Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix: send-vs-persist reliability, live queue panel, and MCP pre-auth rate limit (#549)
Yudhi Armyndharis0915b6b32dcd
diff --git a/.env.example b/.env.exampleindex bded9a9c1..44b8c1d66 100644--- a/.env.example+++ b/.env.example@@ -236,6 +236,10 @@ RATE_LIMIT_MEDIUM_LIMIT=100 # max requests per window# Any blank/non-positive/non-numeric value falls back to the default.# MCP_RATE_LIMIT_MAX=60 # max tool calls per key per window (default 60)# MCP_RATE_LIMIT_WINDOW_MS=60000 # window size in ms (default 60000 = 1 min)+# Pre-auth, per-IP sliding-window throttle for the /mcp mount (gates invalid-key requests before+# key validation, since the raw mount bypasses the global throttler). Same fallback rules.+# MCP_IP_RATE_LIMIT_MAX=120 # max requests per IP per window (default 120)+# MCP_IP_RATE_LIMIT_WINDOW_MS=60000 # window size in ms (default 60000 = 1 min)# =============================================================================# PLUGINSdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7c013c1d6..3ec3d8970 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **The Infrastructure queue panel shows real webhook-queue depth.** It now reports live BullMQ job counts (pending = waiting + active + delayed, plus completed/failed) instead of hard-coded zeros, drops the phantom "Message Queue" card (no such queue exists), removes the dead "Clear Failed Jobs" button (it had no handler and no backend), and makes "View Bull MQ Dashboard" copy the URL with a hint — a plain browser tab can't send the required ADMIN `X-API-Key` header, so opening one only 401'd. (#549)+- **A message that was sent is no longer reported as failed when only its persistence hiccups.** After the engine accepts a message, a transient database fault while saving the `SENT` state is now logged and the call still returns success — instead of marking the already-delivered message permanently `FAILED` (and, for text sends, firing `message:failed`) and returning an error. Genuine send failures are unchanged. (#549)- **Incoming call messages show their real detail in the dashboard.** Call detail (`video` / `missed`) is now attached on the live whatsapp-web.js inbound path — as it already was on history — so an incoming call renders a specific labeled bubble instead of a generic "Call". (#548)- **Location messages no longer dump a base64 thumbnail in the chat list.** Both the live dashboard handler and the engine's chat summary now show a "📍 Location" label as the last-message preview instead of the multi-KB base64 map thumbnail. (#548)- **Logs pagination can reach every page.** The numbered pager was frozen at pages 1–5 (pages 6+ were only reachable by repeated "Next" clicks and the active highlight was lost); it now slides a centered, clamped window around the current page. (#548)@@ -47,6 +49,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Security+- **The MCP endpoint has a pre-authentication per-IP rate limit.** The `/mcp` mount is raw Express and bypasses the global REST throttler, and the per-key limiter only fires after key validation — so a flood of missing/invalid/revoked keys reached a database lookup unthrottled. A sliding-window per-IP throttle now runs before key validation (keyed on the resolved client IP, honoring `TRUSTED_PROXIES`), tunable via `MCP_IP_RATE_LIMIT_MAX` (default 120) / `MCP_IP_RATE_LIMIT_WINDOW_MS` (default 60000). (#549)- **Contact-card names escape vCard structural characters.** A contact whose name contained a backslash, semicolon, or comma could alter the structure of the generated vCard's `FN` field; those characters are now escaped per the vCard spec, complementing the existing CR/LF stripping. (#545)- **Request inputs are bounded against oversized payloads.** Several endpoints accepted unbounded strings or arrays: bulk message `text`/`caption` now match the single-send caps (4096 / 1024), bulk `variables` must be an object, the `mentions` array is capped in size and per-entry length, group name/subject/description, status text/caption, contact name/number, reply text, and reaction emoji now have length limits, and `POST /infra/storage/import` validates its body through a DTO so the global whitelist applies. (#545)diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.jsonindex f5d0bb01a..673639e84 100644--- a/dashboard/src/i18n/locales/ar.json+++ b/dashboard/src/i18n/locales/ar.json@@ -611,16 +611,16 @@"queueTitle": "تفعيل نظام قوائم BullMQ","queueDesc": "استخدام قوائم الرسائل لتوصيل موثوق للرسائل والويب هوك","statsTitle": "إحصائيات القوائم",- "messageQueue": "قائمة الرسائل","webhookQueue": "قائمة الويب هوك","pending": "في الانتظار","completed": "مكتمل","failed": "فشل",- "clearFailed": "مسح المهام الفاشلة","viewBullMq": "عرض لوحة Bull MQ","disabledTitle": "Redis معطّل","disabledDesc": "فعّل Redis للتخزين المؤقت وتخزين الجلسات وقوائم رسائل BullMQ.",- "passwordOptional": "(اختياري)"+ "passwordOptional": "(اختياري)",+ "bullMqUrlCopied": "تم نسخ رابط لوحة Bull MQ",+ "bullMqUrlHint": "افتحه باستخدام مفتاح API بصلاحية ADMIN — لا يمكن لعلامة تبويب المتصفح المصادقة."},"storage": {"title": "إعدادات التخزين",diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.jsonindex cf583512b..019721794 100644--- a/dashboard/src/i18n/locales/en.json+++ b/dashboard/src/i18n/locales/en.json@@ -607,16 +607,16 @@"queueTitle": "Enable BullMQ Queue System","queueDesc": "Use message queues for reliable message and webhook delivery","statsTitle": "Queue Statistics",- "messageQueue": "Message Queue","webhookQueue": "Webhook Queue","pending": "Pending","completed": "Completed","failed": "Failed",- "clearFailed": "Clear Failed Jobs","viewBullMq": "View Bull MQ Dashboard","disabledTitle": "Redis is Disabled","disabledDesc": "Enable Redis for caching, session storage, and BullMQ message queues.",- "passwordOptional": "(optional)"+ "passwordOptional": "(optional)",+ "bullMqUrlCopied": "Bull MQ dashboard URL copied",+ "bullMqUrlHint": "Open it with an ADMIN API key — a browser tab can't authenticate."},"storage": {"title": "Storage Configuration",diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.jsonindex abf08f6c5..a17629ab2 100644--- a/dashboard/src/i18n/locales/es.json+++ b/dashboard/src/i18n/locales/es.json@@ -607,16 +607,16 @@"queueTitle": "Habilitar sistema de colas BullMQ","queueDesc": "Usa colas de mensajes para entrega fiable de mensajes y webhooks","statsTitle": "Estadísticas de colas",- "messageQueue": "Cola de mensajes","webhookQueue": "Cola de webhooks","pending": "Pendiente","completed": "Completado","failed": "Fallido",- "clearFailed": "Limpiar trabajos fallidos","viewBullMq": "Ver panel BullMQ","disabledTitle": "Redis está deshabilitado","disabledDesc": "Habilita Redis para caché, almacenamiento de sesiones y colas de mensajes BullMQ.",- "passwordOptional": "(opcional)"+ "passwordOptional": "(opcional)",+ "bullMqUrlCopied": "URL del panel de Bull MQ copiada",+ "bullMqUrlHint": "Ábrelo con una clave de API ADMIN: una pestaña del navegador no puede autenticarse."},"storage": {"title": "Configuración de almacenamiento",diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.jsonindex 9ceef2aa1..ac148f8f0 100644--- a/dashboard/src/i18n/locales/fr.json+++ b/dashboard/src/i18n/locales/fr.json@@ -607,16 +607,16 @@"queueTitle": "Activer le système de file d'attente BullMQ","queueDesc": "Utiliser des files d'attente pour une livraison fiable des messages et des webhooks","statsTitle": "Statistiques de la file d'attente",- "messageQueue": "File d'attente des messages","webhookQueue": "File d'attente des webhooks","pending": "En attente","completed": "Terminé","failed": "Échoué",- "clearFailed": "Effacer les tâches échouées","viewBullMq": "Voir le tableau de bord Bull MQ","disabledTitle": "Redis est désactivé","disabledDesc": "Activez Redis pour le cache, le stockage des sessions et les files d'attente de messages BullMQ.",- "passwordOptional": "(optionnel)"+ "passwordOptional": "(optionnel)",+ "bullMqUrlCopied": "URL du tableau de bord Bull MQ copiée",+ "bullMqUrlHint": "Ouvrez-le avec une clé d'API ADMIN — un onglet de navigateur ne peut pas s'authentifier."},"storage": {"title": "Configuration du stockage",diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.jsonindex ed974720b..a3fd2c847 100644--- a/dashboard/src/i18n/locales/he.json+++ b/dashboard/src/i18n/locales/he.json@@ -608,16 +608,16 @@"queueTitle": "הפעלת מערכת התורים BullMQ","queueDesc": "שימוש בתורי הודעות לאספקה אמינה של הודעות ו-Webhooks","statsTitle": "סטטיסטיקות תור",- "messageQueue": "תור הודעות","webhookQueue": "תור Webhooks","pending": "בהמתנה","completed": "הושלמו","failed": "נכשלו",- "clearFailed": "ניקוי משימות שנכשלו","viewBullMq": "פתיחת Bull MQ Dashboard","disabledTitle": "Redis מושבת","disabledDesc": "יש להפעיל את Redis למטמון, אחסון Sessions ותורי הודעות BullMQ.",- "passwordOptional": "(אופציונלי)"+ "passwordOptional": "(אופציונלי)",+ "bullMqUrlCopied": "כתובת לוח Bull MQ הועתקה",+ "bullMqUrlHint": "פתח אותו עם מפתח API מסוג ADMIN — לשונית דפדפן אינה יכולה לאמת."},"storage": {"title": "הגדרות אחסון",diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.jsonindex 70c954a55..1b852dde7 100644--- a/dashboard/src/i18n/locales/it.json+++ b/dashboard/src/i18n/locales/it.json@@ -607,16 +607,16 @@"queueTitle": "Abilita Sistema di Code BullMQ","queueDesc": "Usa le code di messaggi per una consegna affidabile di messaggi e webhook","statsTitle": "Statistiche delle Code",- "messageQueue": "Coda Messaggi","webhookQueue": "Coda Webhook","pending": "In attesa","completed": "Completati","failed": "Falliti",- "clearFailed": "Cancella Processi Falliti","viewBullMq": "Visualizza Dashboard BullMQ","disabledTitle": "Redis è Disabilitato","disabledDesc": "Abilita Redis per la cache, lo storage delle sessioni e le code di messaggi BullMQ.",- "passwordOptional": "(opzionale)"+ "passwordOptional": "(opzionale)",+ "bullMqUrlCopied": "URL della dashboard Bull MQ copiato",+ "bullMqUrlHint": "Aprilo con una chiave API ADMIN: una scheda del browser non può autenticarsi."},"storage": {"title": "Configurazione di Archiviazione",diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.jsonindex 4f54c03e8..b75ef4e1a 100644--- a/dashboard/src/i18n/locales/pt-BR.json+++ b/dashboard/src/i18n/locales/pt-BR.json@@ -607,16 +607,16 @@"queueTitle": "Habilitar sistema de filas BullMQ","queueDesc": "Use filas de mensagens para entrega confiável de mensagens e webhooks","statsTitle": "Estatísticas das filas",- "messageQueue": "Fila de mensagens","webhookQueue": "Fila de webhooks","pending": "Pendente","completed": "Concluído","failed": "Falhou",- "clearFailed": "Limpar trabalhos com falha","viewBullMq": "Ver painel BullMQ","disabledTitle": "Redis está desabilitado","disabledDesc": "Habilite o Redis para cache, armazenamento de sessões e filas de mensagens BullMQ.",- "passwordOptional": "(opcional)"+ "passwordOptional": "(opcional)",+ "bullMqUrlCopied": "URL do painel do Bull MQ copiada",+ "bullMqUrlHint": "Abra com uma chave de API ADMIN — uma aba do navegador não consegue autenticar."},"storage": {"title": "Configuração de armazenamento",diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.jsonindex fa0256eb5..35db8ce81 100644--- a/dashboard/src/i18n/locales/te.json+++ b/dashboard/src/i18n/locales/te.json@@ -607,16 +607,16 @@"queueTitle": "BullMQ క్యూ సిస్టమ్ను ప్రారంభించండి","queueDesc": "నమ్మకమైన సందేశం మరియు వెబ్హుక్ డెలివరీ కోసం సందేశ క్యూలను ఉపయోగించండి","statsTitle": "క్యూ గణాంకాలు",- "messageQueue": "సందేశ క్యూ","webhookQueue": "వెబ్హుక్ క్యూ","pending": "పెండింగ్","completed": "పూర్తయింది","failed": "విఫలమైంది",- "clearFailed": "విఫలమైన జాబ్స్ను క్లియర్ చేయి","viewBullMq": "Bull MQ డ్యాష్బోర్డ్ను చూడండి","disabledTitle": "Redis నిలిపివేయబడింది","disabledDesc": "క్యాషింగ్, సెషన్ స్టోరేజ్ మరియు BullMQ సందేశ క్యూల కోసం Redisని ప్రారంభించండి.",- "passwordOptional": "(ఐచ్ఛికం)"+ "passwordOptional": "(ఐచ్ఛికం)",+ "bullMqUrlCopied": "Bull MQ డాష్బోర్డ్ URL కాపీ చేయబడింది",+ "bullMqUrlHint": "దాన్ని ADMIN API కీతో తెరవండి — బ్రౌజర్ ట్యాబ్ ప్రామాణీకరించలేదు."},"storage": {"title": "స్టోరేజ్ కాన్ఫిగరేషన్",diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.jsonindex e9681fb90..35490aefd 100644--- a/dashboard/src/i18n/locales/zh-CN.json+++ b/dashboard/src/i18n/locales/zh-CN.json@@ -607,16 +607,16 @@"queueTitle": "启用 BullMQ 队列系统","queueDesc": "使用消息队列可靠地投递消息和 Webhook","statsTitle": "队列统计",- "messageQueue": "消息队列","webhookQueue": "Webhook 队列","pending": "待处理","completed": "已完成","failed": "失败",- "clearFailed": "清除失败任务","viewBullMq": "查看 Bull MQ 仪表盘","disabledTitle": "Redis 已禁用","disabledDesc": "启用 Redis 以使用缓存、会话存储和 BullMQ 消息队列。",- "passwordOptional": "(可选)"+ "passwordOptional": "(可选)",+ "bullMqUrlCopied": "已复制 Bull MQ 仪表板网址",+ "bullMqUrlHint": "请使用 ADMIN API 密钥打开 — 浏览器标签页无法进行身份验证。"},"storage": {"title": "存储配置",diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.jsonindex 0850cd1de..1ddadb420 100644--- a/dashboard/src/i18n/locales/zh-HK.json+++ b/dashboard/src/i18n/locales/zh-HK.json@@ -607,16 +607,16 @@"queueTitle": "啟用 BullMQ 佇列系統","queueDesc": "使用訊息佇列可靠地傳遞訊息和 Webhook","statsTitle": "佇列統計",- "messageQueue": "訊息佇列","webhookQueue": "Webhook 佇列","pending": "待處理","completed": "已完成","failed": "失敗",- "clearFailed": "清除失敗任務","viewBullMq": "查看 Bull MQ 控制面板","disabledTitle": "Redis 已停用","disabledDesc": "啟用 Redis 以使用快取、工作階段儲存及 BullMQ 訊息佇列。",- "passwordOptional": "(選填)"+ "passwordOptional": "(選填)",+ "bullMqUrlCopied": "已複製 Bull MQ 儀表板網址",+ "bullMqUrlHint": "請使用 ADMIN API 金鑰開啟 — 瀏覽器分頁無法進行身份驗證。"},"storage": {"title": "儲存空間設定",diff --git a/dashboard/src/pages/Infrastructure.tsx b/dashboard/src/pages/Infrastructure.tsxindex 008ef57f8..dcf3e1abb 100644--- a/dashboard/src/pages/Infrastructure.tsx+++ b/dashboard/src/pages/Infrastructure.tsx@@ -8,13 +8,13 @@ import {ExternalLink,Loader2,CheckCircle,- Trash2,Cpu,AlertTriangle,Download,Upload,} from 'lucide-react';import { infraApi, API_BASE_URL } from '../services/api';+import { copyToClipboard } from '../utils/clipboard';import { useDocumentTitle } from '../hooks/useDocumentTitle';import {useInfraStatusQuery,@@ -123,7 +123,6 @@ export function Infrastructure() {});const [queueStats, setQueueStats] = useState({- messages: { pending: 0, completed: 0, failed: 0 } as QueueStats,webhooks: { pending: 0, completed: 0, failed: 0 } as QueueStats,});@@ -157,7 +156,7 @@ export function Infrastructure() {useEffect(() => {if (!infraStatus) return;setRedisConfig(prev => ({ ...prev, connected: infraStatus.redis.connected }));- setQueueStats({ messages: infraStatus.queue.messages, webhooks: infraStatus.queue.webhooks });+ setQueueStats({ webhooks: infraStatus.queue.webhooks });}, [infraStatus]);// Seed the EDITABLE selections from live /status ONCE (the running selection), guarded so a refetch@@ -869,23 +868,6 @@ export function Infrastructure() {<div className="queue-stats"><h3>{t('infrastructure.redis.statsTitle')}</h3><div className="stats-row">- <div className="queue-stat-card">- <h4>{t('infrastructure.redis.messageQueue')}</h4>- <div className="stat-values">- <div className="stat-item pending">- <span className="value">{queueStats.messages.pending}</span>- <span className="label">{t('infrastructure.redis.pending')}</span>- </div>- <div className="stat-item completed">- <span className="value">{queueStats.messages.completed.toLocaleString()}</span>- <span className="label">{t('infrastructure.redis.completed')}</span>- </div>- <div className="stat-item failed">- <span className="value">{queueStats.messages.failed}</span>- <span className="label">{t('infrastructure.redis.failed')}</span>- </div>- </div>- </div><div className="queue-stat-card"><h4>{t('infrastructure.redis.webhookQueue')}</h4><div className="stat-values">@@ -905,13 +887,24 @@ export function Infrastructure() {</div></div><div className="queue-actions">- <button className="btn-danger-outline">- <Trash2 size={16} />- {t('infrastructure.redis.clearFailed')}- </button><buttonclassName="btn-outline"- onClick={() => window.open(`${API_BASE_URL}/admin/queues`, '_blank')}+ onClick={() => {+ // The BullBoard route requires an ADMIN API key in the X-API-Key header — a plain+ // browser tab can't send one, so copy the URL for use with an authenticated client+ // / reverse proxy instead of opening a tab that 401s.+ const base = API_BASE_URL.startsWith('http')+ ? API_BASE_URL+ : `${window.location.origin}${API_BASE_URL}`;+ void copyToClipboard(`${base}/admin/queues`).then(ok => {+ if (ok) {+ toast.success(+ t('infrastructure.redis.bullMqUrlCopied'),+ t('infrastructure.redis.bullMqUrlHint'),+ );+ }+ });+ }}><ExternalLink size={16} />{t('infrastructure.redis.viewBullMq')}diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex a0068f955..6f55958f9 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -212,7 +212,6 @@ export interface InfraStatus {redis: { enabled: boolean; connected: boolean; host: string; port: number; builtIn: boolean };queue: {enabled: boolean;- messages: { pending: number; completed: number; failed: number };webhooks: { pending: number; completed: number; failed: number };};storage: { type: 'local' | 's3'; path?: string; bucket?: string; builtIn: boolean; s3Available?: boolean };diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 78ee9a3b1..a776ccb11 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -3646,7 +3646,6 @@ Aggregate infrastructure status (database, Redis, queue, storage, engine)."redis": { "enabled": false, "connected": false, "host": "localhost", "port": 6379 },"queue": {"enabled": false,- "messages": { "pending": 0, "completed": 0, "failed": 0 },"webhooks": { "pending": 0, "completed": 0, "failed": 0 }},"storage": { "type": "local", "path": "./data/media" },@@ -3659,7 +3658,7 @@ Aggregate infrastructure status (database, Redis, queue, storage, engine).}```-The `queue.messages`/`queue.webhooks` counters are hardcoded to zeros (not live job counts); `redis.connected` is a live probe. `storage` only ever returns `type`+`path` here (no `bucket`).+The `queue.webhooks` counters are live BullMQ job counts (`pending` = waiting + active + delayed; plus `completed`/`failed`), degrading to zeros when the queue is disabled or Redis is unreachable. `redis.connected` is a live probe. `storage` only ever returns `type`+`path` here (no `bucket`).**Errors:** `401` missing/invalid key · `403` key role < ADMINdiff --git a/docs/24-mcp-integration.md b/docs/24-mcp-integration.mdindex 7081e0bcd..05acbaf5b 100644--- a/docs/24-mcp-integration.md+++ b/docs/24-mcp-integration.md@@ -152,7 +152,12 @@ posture when an agent only needs to observe.calls. Buckets are pruned when idle. This is independent of the REST throttler.Tune with `MCP_RATE_LIMIT_MAX` (default `60`) and `MCP_RATE_LIMIT_WINDOW_MS`(default `60000`). Any missing, blank, non-positive, or non-numeric value falls back- to the default.+ to the default. A **second, pre-auth per-IP throttle** runs on the `/mcp` mount *before*+ key validation (the raw Express mount bypasses the global REST throttler, so a+ missing/invalid key would otherwise reach a DB lookup unthrottled). It keys on the+ resolved client IP (honoring `TRUSTED_PROXIES`) and is tuned with `MCP_IP_RATE_LIMIT_MAX`+ (default `120`) and `MCP_IP_RATE_LIMIT_WINDOW_MS` (default `60000`), with the same+ fallback rules — independent of the per-key vars.- **Response parity.** Tools reuse the REST response DTOs, so sensitive fields the RESTAPI strips (e.g. webhook HMAC secrets and custom headers, session proxy URLs and engineconfig) are **not** exposed over MCP.@@ -168,6 +173,8 @@ MCP_ENABLED=true npm run start:prod # or set MCP_ENABLED in your .env / composMCP_READONLY=true # read tools onlyMCP_RATE_LIMIT_MAX=60 # max tool calls per key per window (default 60)MCP_RATE_LIMIT_WINDOW_MS=60000 # sliding window in ms (default 60000 = 1 min)+MCP_IP_RATE_LIMIT_MAX=120 # pre-auth per-IP request cap per window (default 120)+MCP_IP_RATE_LIMIT_WINDOW_MS=60000 # per-IP window in ms (default 60000 = 1 min)```Point an MCP client at `POST /mcp`. For Claude Code, a `.mcp.json` at your project rootdiff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.tsindex 49f0187ff..8879f94c1 100644--- a/src/modules/infra/infra.controller.spec.ts+++ b/src/modules/infra/infra.controller.spec.ts@@ -91,6 +91,51 @@ describe('InfraController.importStorage filePath validation (Vuln 3)', () => {});});+describe('InfraController.getStatus queue job counts (F-18)', () => {+ function buildStatusController(opts: { queueEnabled: boolean; queue?: { getJobCounts: jest.Mock } }) {+ const configService = {+ get: (key: string, def?: unknown) => (key === 'queue.enabled' ? opts.queueEnabled : def),+ };+ const dataSource = { isInitialized: true } as unknown;+ const engineFactory = { create: jest.fn() };+ const dockerService = { isDockerAvailable: () => false, getRunningBuiltinServices: jest.fn() };+ const cacheService = { isAvailable: jest.fn().mockResolvedValue(false), refreshS3Availability: jest.fn() };+ const storageService = { refreshS3Availability: jest.fn() };+ const shutdownService = {};+ return new InfraController(+ configService as never,+ dataSource as never,+ dataSource as never,+ engineFactory as never,+ dockerService as never,+ cacheService as never,+ storageService as never,+ shutdownService as never,+ opts.queue as never,+ );+ }++ it('reports live webhook job counts when the queue is enabled (pending = wait+active+delayed)', async () => {+ const getJobCounts = jest.fn().mockResolvedValue({ wait: 2, active: 1, delayed: 3, completed: 10, failed: 1 });+ const controller = buildStatusController({ queueEnabled: true, queue: { getJobCounts } });++ const status = await controller.getStatus();++ expect(getJobCounts).toHaveBeenCalledWith('wait', 'active', 'delayed', 'completed', 'failed');+ expect(status.queue).toEqual({ enabled: true, webhooks: { pending: 6, completed: 10, failed: 1 } });+ });++ it('reports zeros (and does not touch the queue) when the queue is disabled', async () => {+ const getJobCounts = jest.fn();+ const controller = buildStatusController({ queueEnabled: false, queue: { getJobCounts } });++ const status = await controller.getStatus();++ expect(getJobCounts).not.toHaveBeenCalled();+ expect(status.queue).toEqual({ enabled: false, webhooks: { pending: 0, completed: 0, failed: 0 } });+ });+});+describe('InfraController.saveConfig SSL reject-unauthorized', () => {function writtenEnv(config: unknown): string {const spy = jest.spyOn(fs, 'writeFileSync').mockImplementation(() => undefined);diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.tsindex fc33bcfc9..1c211e9fe 100644--- a/src/modules/infra/infra.controller.ts+++ b/src/modules/infra/infra.controller.ts@@ -1,5 +1,8 @@-import { Controller, Get, Put, Post, Body, BadRequestException } from '@nestjs/common';+import { Controller, Get, Put, Post, Body, BadRequestException, Optional } from '@nestjs/common';import { ApiTags, ApiOperation, ApiResponse, ApiBody } from '@nestjs/swagger';+import { InjectQueue } from '@nestjs/bullmq';+import { Queue } from 'bullmq';+import { QUEUE_NAMES } from '../queue/queue-names';import { ConfigService } from '@nestjs/config';import { DataSource } from 'typeorm';import { InjectDataSource } from '@nestjs/typeorm';@@ -28,7 +31,6 @@ interface InfraStatus {redis: { enabled: boolean; connected: boolean; host: string; port: number; builtIn: boolean };queue: {enabled: boolean;- messages: { pending: number; completed: number; failed: number };webhooks: { pending: number; completed: number; failed: number };};storage: { type: 'local' | 's3'; path?: string; bucket?: string; builtIn: boolean; s3Available?: boolean };@@ -239,6 +241,9 @@ export class InfraController {private readonly cacheService: CacheService,private readonly storageService: StorageService,private readonly shutdownService: ShutdownService,+ @Optional()+ @InjectQueue(QUEUE_NAMES.WEBHOOK)+ private readonly webhookQueue?: Queue,) {}@Get('status')@@ -308,6 +313,22 @@ export class InfraController {// Re-probe (throttled) so a MinIO/S3 that came up after boot is reflected, not latched unreachable.const s3Available = storageType === 's3' ? await this.storageService.refreshS3Availability() : undefined;+ // Live webhook-queue depth (the only real queue). pending = waiting + active + delayed. Degrades to+ // zeros when the queue is disabled or Redis is unreachable, so the panel never errors the status read.+ let webhooks = { pending: 0, completed: 0, failed: 0 };+ if (queueEnabled && this.webhookQueue) {+ try {+ const counts = await this.webhookQueue.getJobCounts('wait', 'active', 'delayed', 'completed', 'failed');+ webhooks = {+ pending: (counts.wait ?? 0) + (counts.active ?? 0) + (counts.delayed ?? 0),+ completed: counts.completed ?? 0,+ failed: counts.failed ?? 0,+ };+ } catch (error) {+ this.logger.warn('Failed to read webhook queue job counts', { error: String(error) });+ }+ }+return {database: { connected: dbConnected, type: dbType, host: dbHost, builtIn: dbBuiltIn },redis: {@@ -319,8 +340,7 @@ export class InfraController {},queue: {enabled: queueEnabled,- messages: { pending: 0, completed: 0, failed: 0 },- webhooks: { pending: 0, completed: 0, failed: 0 },+ webhooks,},storage: {type: storageType,diff --git a/src/modules/infra/infra.module.ts b/src/modules/infra/infra.module.tsindex 00a0d97e2..9a8a6068f 100644--- a/src/modules/infra/infra.module.ts+++ b/src/modules/infra/infra.module.ts@@ -1,10 +1,19 @@-import { Module } from '@nestjs/common';+import { Module, DynamicModule, Type } from '@nestjs/common';import { InfraController } from './infra.controller';import { EngineModule } from '../../engine/engine.module';import { DockerModule } from '../docker';+// Only import QueueModule if explicitly enabled to avoid Redis connection errors. It registers and+// exports the webhook queue, which the controller injects (@Optional) to report live job counts.+const queueModules: Array<Type | DynamicModule> = [];+if (process.env.QUEUE_ENABLED === 'true') {+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const queueModule = require('../queue/queue.module') as { QueueModule: Type };+ queueModules.push(queueModule.QueueModule);+}+@Module({- imports: [EngineModule, DockerModule],+ imports: [EngineModule, DockerModule, ...queueModules],controllers: [InfraController],})export class InfraModule {}diff --git a/src/modules/mcp/mcp-rate-limit.spec.ts b/src/modules/mcp/mcp-rate-limit.spec.tsindex af70ac138..dcece8b53 100644--- a/src/modules/mcp/mcp-rate-limit.spec.ts+++ b/src/modules/mcp/mcp-rate-limit.spec.ts@@ -1,4 +1,4 @@-import { KeyRateLimiter, readRateLimitConfig } from './mcp-rate-limit';+import { KeyRateLimiter, readRateLimitConfig, readIpRateLimitConfig } from './mcp-rate-limit';describe('readRateLimitConfig', () => {it('returns defaults for an empty env', () => {@@ -61,6 +61,34 @@ describe('readRateLimitConfig', () => {});});+describe('readIpRateLimitConfig', () => {+ it('returns the IP defaults for an empty env (more generous than the per-key budget)', () => {+ expect(readIpRateLimitConfig({})).toEqual({ max: 120, windowMs: 60_000 });+ });++ it('parses valid numeric env values', () => {+ expect(readIpRateLimitConfig({ MCP_IP_RATE_LIMIT_MAX: '500', MCP_IP_RATE_LIMIT_WINDOW_MS: '30000' })).toEqual({+ max: 500,+ windowMs: 30_000,+ });+ });++ it('falls back to the IP defaults for non-numeric / zero / negative / blank values', () => {+ expect(readIpRateLimitConfig({ MCP_IP_RATE_LIMIT_MAX: 'abc' }).max).toBe(120);+ expect(readIpRateLimitConfig({ MCP_IP_RATE_LIMIT_MAX: '0' }).max).toBe(120);+ expect(readIpRateLimitConfig({ MCP_IP_RATE_LIMIT_MAX: '-5' }).max).toBe(120);+ expect(readIpRateLimitConfig({ MCP_IP_RATE_LIMIT_MAX: '' }).max).toBe(120);+ expect(readIpRateLimitConfig({ MCP_IP_RATE_LIMIT_WINDOW_MS: '0.5' }).windowMs).toBe(60_000);+ });++ it('is independent of the per-key vars (they must not bleed into the IP budget)', () => {+ expect(readIpRateLimitConfig({ MCP_RATE_LIMIT_MAX: '5', MCP_RATE_LIMIT_WINDOW_MS: '5' })).toEqual({+ max: 120,+ windowMs: 60_000,+ });+ });+});+describe('KeyRateLimiter', () => {it('allows up to max per window, then throws 429', () => {let now = 1_000;diff --git a/src/modules/mcp/mcp-rate-limit.ts b/src/modules/mcp/mcp-rate-limit.tsindex ddf4d4fff..521aa4502 100644--- a/src/modules/mcp/mcp-rate-limit.ts+++ b/src/modules/mcp/mcp-rate-limit.ts@@ -2,26 +2,40 @@ import { HttpException, HttpStatus } from '@nestjs/common';const DEFAULT_MAX = 60;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 parsePositiveInt = (raw: string | undefined, fallback: number): number => {+ if (!raw || raw.trim() === '') return fallback;+ const n = Number(raw);+ if (!Number.isFinite(n)) return fallback;+ const i = Math.floor(n);+ return i >= 1 ? i : fallback;+};/*** Read MCP rate-limit configuration from the environment.* Falls back to the default for any missing, blank, non-positive, or non-numeric value.*/export function readRateLimitConfig(env: NodeJS.ProcessEnv = process.env): { max: number; windowMs: number } {- const parsePositiveInt = (raw: string | undefined, fallback: number): number => {- if (!raw || raw.trim() === '') return fallback;- const n = Number(raw);- if (!Number.isFinite(n)) return fallback;- const i = Math.floor(n);- return i >= 1 ? i : fallback;- };-return {max: parsePositiveInt(env['MCP_RATE_LIMIT_MAX'], DEFAULT_MAX),windowMs: parsePositiveInt(env['MCP_RATE_LIMIT_WINDOW_MS'], DEFAULT_WINDOW_MS),};}+/**+ * Read the PRE-AUTH per-IP MCP throttle config. Independent of the per-key vars above (which must not+ * bleed in), with the same blank/non-positive/non-numeric fallback.+ */+export function readIpRateLimitConfig(env: NodeJS.ProcessEnv = process.env): { max: number; windowMs: number } {+ return {+ max: parsePositiveInt(env['MCP_IP_RATE_LIMIT_MAX'], DEFAULT_IP_MAX),+ windowMs: parsePositiveInt(env['MCP_IP_RATE_LIMIT_WINDOW_MS'], DEFAULT_WINDOW_MS),+ };+}+/*** Per-API-key sliding window rate limiter.* The inherited IP-keyed throttler collapses all MCP calls into one 127.0.0.1 bucket,diff --git a/src/modules/mcp/mcp.module.ts b/src/modules/mcp/mcp.module.tsindex a0b6c4f38..f542d9b05 100644--- a/src/modules/mcp/mcp.module.ts+++ b/src/modules/mcp/mcp.module.ts@@ -2,7 +2,7 @@ import { type DynamicModule, Module, type MiddlewareConsumer, type NestModule }import { HttpAdapterHost } from '@nestjs/core';import { ToolRegistryService } from '../../core/agent-tools/tool-registry.service';import { AuthService } from '../auth/auth.service';-import { KeyRateLimiter, readRateLimitConfig } from './mcp-rate-limit';+import { KeyRateLimiter, readRateLimitConfig, readIpRateLimitConfig } from './mcp-rate-limit';import { mountMcpServer } from './mcp.server';export interface McpModuleOptions {@@ -41,6 +41,8 @@ export class McpModule implements NestModule {const { basePath, serverInfo } = _moduleOptions;const { max, windowMs } = readRateLimitConfig();const rateLimiter = new KeyRateLimiter(max, windowMs);- mountMcpServer(httpAdapter, this.registry, this.authService, rateLimiter, { basePath, serverInfo });+ const ipCfg = readIpRateLimitConfig();+ const ipRateLimiter = new KeyRateLimiter(ipCfg.max, ipCfg.windowMs);+ mountMcpServer(httpAdapter, this.registry, this.authService, rateLimiter, ipRateLimiter, { basePath, serverInfo });}}diff --git a/src/modules/mcp/mcp.server.spec.ts b/src/modules/mcp/mcp.server.spec.tsnew file mode 100644index 000000000..f4e9dbc16--- /dev/null+++ b/src/modules/mcp/mcp.server.spec.ts@@ -0,0 +1,48 @@+import type { Request, Response } from 'express';+import { createIpThrottle } from './mcp.server';+import { KeyRateLimiter } from './mcp-rate-limit';++// The MCP mount is raw Express (outside the Nest guard pipeline) and the per-key limiter only fires+// after key validation, so a missing/invalid-key flood would otherwise reach a DB lookup unthrottled.+// createIpThrottle gates by resolved client IP BEFORE auth and answers with a JSON-RPC 429.+describe('createIpThrottle (pre-auth per-IP MCP throttle)', () => {+ const makeReq = (ip: string): Request => ({ socket: { remoteAddress: ip }, headers: {} }) as unknown as Request;++ type ResMock = { status: jest.Mock; json: jest.Mock; statusCode?: number; body?: unknown };+ const makeRes = (): ResMock => {+ const res: ResMock = { status: jest.fn(), json: jest.fn() };+ res.status.mockImplementation((code: number) => {+ res.statusCode = code;+ return res;+ });+ res.json.mockImplementation((b: unknown) => {+ res.body = b;+ return res;+ });+ return res;+ };++ it('passes the first request from an IP and rejects the second with a 429', () => {+ const throttle = createIpThrottle(new KeyRateLimiter(1, 60_000));++ const next1 = jest.fn();+ throttle(makeReq('1.2.3.4'), makeRes() as unknown as Response, next1);+ expect(next1).toHaveBeenCalledWith(); // allowed through, no error++ const next2 = jest.fn();+ const res2 = makeRes();+ throttle(makeReq('1.2.3.4'), res2 as unknown as Response, next2);+ expect(next2).not.toHaveBeenCalled(); // short-circuited+ expect(res2.status).toHaveBeenCalledWith(429);+ expect((res2.body as { error?: { code?: number } }).error?.code).toBe(-32000);+ });++ it('buckets per IP — a different IP is not throttled', () => {+ const throttle = createIpThrottle(new KeyRateLimiter(1, 60_000));+ throttle(makeReq('1.1.1.1'), makeRes() as unknown as Response, jest.fn());++ const next = jest.fn();+ throttle(makeReq('2.2.2.2'), makeRes() as unknown as Response, next);+ expect(next).toHaveBeenCalledWith();+ });+});diff --git a/src/modules/mcp/mcp.server.ts b/src/modules/mcp/mcp.server.tsindex 002479604..cb96b2db2 100644--- a/src/modules/mcp/mcp.server.ts+++ b/src/modules/mcp/mcp.server.ts@@ -1,4 +1,4 @@-import { Logger } from '@nestjs/common';+import { HttpException, Logger } from '@nestjs/common';import type { HttpAdapterHost } from '@nestjs/core';import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';@@ -10,6 +10,7 @@ import type { ToolRegistryService } from '../../core/agent-tools/tool-registry.simport type { AuthService } from '../auth/auth.service';import { handleToolError, jsonToolResult, smartToolResult } from './tool-result';import type { KeyRateLimiter } from './mcp-rate-limit';+import { resolveClientIp } from '../../common/utils/ip';const logger = new Logger('McpServer');@@ -96,11 +97,39 @@ export interface MountMcpServerOptions {* Creating a new McpServer per request is safe and avoids the single-transport constraint;* tool registration is O(n) pure function calls with no I/O overhead.*/+/**+ * Pre-auth, per-IP throttle for the raw-Express /mcp mount. The global Nest throttler doesn't cover this+ * mount (it bypasses the guard pipeline) and the per-key limiter only fires AFTER key validation — so a+ * missing/invalid/revoked key otherwise reaches a DB lookup unthrottled. This gates by resolved client IP+ * first and returns a JSON-RPC 429 directly (raw Express wouldn't convert a thrown HttpException).+ */+export function createIpThrottle(ipRateLimiter: KeyRateLimiter): RequestHandler {+ return (req, res, next) => {+ const trustedProxies = (process.env.TRUSTED_PROXIES ?? '')+ .split(',')+ .map(s => s.trim())+ .filter(Boolean);+ const ip = resolveClientIp(req, trustedProxies);+ try {+ ipRateLimiter.check(ip);+ next();+ } catch (err) {+ const status = err instanceof HttpException ? err.getStatus() : 429;+ res.status(status).json({+ jsonrpc: '2.0',+ error: { code: -32000, message: err instanceof Error ? err.message : 'MCP rate limit exceeded' },+ id: null,+ });+ }+ };+}+export function mountMcpServer(httpAdapter: HttpAdapter,registry: ToolRegistryService,authService: AuthService,rateLimiter: KeyRateLimiter,+ ipRateLimiter: KeyRateLimiter,options: MountMcpServerOptions = {},): void {const basePath = (options.basePath ?? '/mcp').replace(/\/$/, '') || '/mcp';@@ -132,5 +161,7 @@ export function mountMcpServer(};const adapter = httpAdapter as unknown as { post: (path: string, ...handlers: RequestHandler[]) => unknown };- adapter.post(basePath, express.json(), handler);+ // ipThrottle runs BEFORE express.json()/handler so an unauthenticated flood is rejected before any body+ // parsing or DB lookup.+ adapter.post(basePath, createIpThrottle(ipRateLimiter), express.json(), handler);}diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.tsindex f8eb7ab03..151d30938 100644--- a/src/modules/message/message.service.spec.ts+++ b/src/modules/message/message.service.spec.ts@@ -157,6 +157,20 @@ describe('MessageService', () => {expect(repository.save).toHaveBeenCalledTimes(2);});+ it('returns success (not FAILED) when persisting the SENT state fails after a successful send', async () => {+ // 1st save (PENDING) ok; 2nd save (SENT-state, after WhatsApp already accepted the message) throws.+ (repository.save as jest.Mock)+ .mockImplementationOnce((msg: unknown) => Promise.resolve(msg))+ .mockRejectedValueOnce(new Error('transient db fault'));++ const result = await service.sendText('sess-1', { chatId: '[email protected]', text: 'Hello' });++ // The send succeeded, so it is reported as success — not rethrown, not marked FAILED.+ expect(result.messageId).toBe('wa-msg-1');+ expect(result.timestamp).toBe(1706868000);+ expect(hookManager.execute).not.toHaveBeenCalledWith('message:failed', expect.anything(), expect.anything());+ });+it('executes the message:sending hook (message:sent now fires once from the engine message_create path)', async () => {await service.sendText('sess-1', {chatId: '[email protected]',diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex 0400407e8..4c7d3311c 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -5,7 +5,7 @@ import { SessionService } from '../session/session.service';import { SendTextMessageDto, SendMediaMessageDto, MessageResponseDto } from './dto';import { SendTemplateMessageDto } from './dto/send-template.dto';import { assertBase64WithinMediaCap } from './media-cap.util';-import { MediaInput, IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';+import { MediaInput, IWhatsAppEngine, MessageResult } from '../../engine/interfaces/whatsapp-engine.interface';import { Message, MessageDirection, MessageStatus } from './entities/message.entity';import { HookManager } from '../../core/hooks';import { TemplateService } from '../template/template.service';@@ -63,39 +63,29 @@ export class MessageService {// Opt-in humanising "typing…" pause before the actual send (anti-automation signal).await this.simulateTypingIfEnabled(engine, finalDto.chatId, finalDto.text);+ let result: MessageResult;try {// Keep the 2-arg call shape for plain sends; only pass mentions when the caller supplied any.- const result = finalDto.mentions?.length+ result = finalDto.mentions?.length? await engine.sendTextMessage(finalDto.chatId, finalDto.text, finalDto.mentions): await engine.sendTextMessage(finalDto.chatId, finalDto.text);-- // Update with actual WhatsApp message ID and status- message.waMessageId = result.id;- message.status = MessageStatus.SENT;- message.timestamp = result.timestamp;- await this.messageRepository.save(message);-- // Note: the `message:sent` hook is emitted solely by SessionService.onMessageCreate (engine- // `message_create`) with a consistent IncomingMessage payload for ALL sends (text, media,- // and phone-composed), so it is intentionally not fired here to avoid a double dispatch.- return {- messageId: result.id,- timestamp: result.timestamp,- };} catch (error) {- // Mark as failed+ // The SEND itself failed — mark FAILED and fire the failure hook (a post-send persistence fault is+ // handled separately by persistSentState and must NOT land here).message.status = MessageStatus.FAILED;await this.messageRepository.save(message);-- // Execute hook on failureawait this.hookManager.execute('message:failed',{ sessionId, error: error instanceof Error ? error.message : String(error), input: finalDto },{ sessionId, source: 'MessageService' },);-throw error;}++ // Note: the `message:sent` hook is emitted solely by SessionService.onMessageCreate (engine+ // `message_create`) with a consistent IncomingMessage payload for ALL sends (text, media,+ // and phone-composed), so it is intentionally not fired here to avoid a double dispatch.+ return this.persistSentState(message, result);}/**@@ -134,23 +124,14 @@ export class MessageService {},});+ let result: MessageResult;try {- const result = await engine.sendImageMessage(dto.chatId, media);-- // Update with actual WhatsApp message ID and status- message.waMessageId = result.id;- message.status = MessageStatus.SENT;- message.timestamp = result.timestamp;- await this.messageRepository.save(message);-- return {- messageId: result.id,- timestamp: result.timestamp,- };+ result = await engine.sendImageMessage(dto.chatId, media);} catch (error) {await this.saveFailedMessage(message);throw this.toClientFacingError(error);}+ return this.persistSentState(message, result);}async sendVideo(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {@@ -167,23 +148,14 @@ export class MessageService {},});+ let result: MessageResult;try {- const result = await engine.sendVideoMessage(dto.chatId, media);-- // Update with actual WhatsApp message ID and status- message.waMessageId = result.id;- message.status = MessageStatus.SENT;- message.timestamp = result.timestamp;- await this.messageRepository.save(message);-- return {- messageId: result.id,- timestamp: result.timestamp,- };+ result = await engine.sendVideoMessage(dto.chatId, media);} catch (error) {await this.saveFailedMessage(message);throw this.toClientFacingError(error);}+ return this.persistSentState(message, result);}async sendAudio(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {@@ -199,23 +171,14 @@ export class MessageService {},});+ let result: MessageResult;try {- const result = await engine.sendAudioMessage(dto.chatId, media);-- // Update with actual WhatsApp message ID and status- message.waMessageId = result.id;- message.status = MessageStatus.SENT;- message.timestamp = result.timestamp;- await this.messageRepository.save(message);-- return {- messageId: result.id,- timestamp: result.timestamp,- };+ result = await engine.sendAudioMessage(dto.chatId, media);} catch (error) {await this.saveFailedMessage(message);throw this.toClientFacingError(error);}+ return this.persistSentState(message, result);}async sendDocument(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {@@ -232,23 +195,14 @@ export class MessageService {},});+ let result: MessageResult;try {- const result = await engine.sendDocumentMessage(dto.chatId, media);-- // Update with actual WhatsApp message ID and status- message.waMessageId = result.id;- message.status = MessageStatus.SENT;- message.timestamp = result.timestamp;- await this.messageRepository.save(message);-- return {- messageId: result.id,- timestamp: result.timestamp,- };+ result = await engine.sendDocumentMessage(dto.chatId, media);} catch (error) {await this.saveFailedMessage(message);throw this.toClientFacingError(error);}+ return this.persistSentState(message, result);}/**@@ -321,28 +275,19 @@ export class MessageService {type: 'location',});+ let result: MessageResult;try {- const result = await engine.sendLocationMessage(dto.chatId, {+ result = await engine.sendLocationMessage(dto.chatId, {latitude: dto.latitude,longitude: dto.longitude,description: dto.description,address: dto.address,});-- // Update with actual WhatsApp message ID and status- message.waMessageId = result.id;- message.status = MessageStatus.SENT;- message.timestamp = result.timestamp;- await this.messageRepository.save(message);-- return {- messageId: result.id,- timestamp: result.timestamp,- };} catch (error) {await this.saveFailedMessage(message);throw this.toClientFacingError(error);}+ return this.persistSentState(message, result);}async sendContact(@@ -358,26 +303,17 @@ export class MessageService {type: 'contact',});+ let result: MessageResult;try {- const result = await engine.sendContactMessage(dto.chatId, {+ result = await engine.sendContactMessage(dto.chatId, {name: dto.contactName,number: dto.contactNumber,});-- // Update with actual WhatsApp message ID and status- message.waMessageId = result.id;- message.status = MessageStatus.SENT;- message.timestamp = result.timestamp;- await this.messageRepository.save(message);-- return {- messageId: result.id,- timestamp: result.timestamp,- };} catch (error) {await this.saveFailedMessage(message);throw this.toClientFacingError(error);}+ return this.persistSentState(message, result);}async sendSticker(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {@@ -393,23 +329,14 @@ export class MessageService {},});+ let result: MessageResult;try {- const result = await engine.sendStickerMessage(dto.chatId, media);-- // Update with actual WhatsApp message ID and status- message.waMessageId = result.id;- message.status = MessageStatus.SENT;- message.timestamp = result.timestamp;- await this.messageRepository.save(message);-- return {- messageId: result.id,- timestamp: result.timestamp,- };+ result = await engine.sendStickerMessage(dto.chatId, media);} catch (error) {await this.saveFailedMessage(message);throw this.toClientFacingError(error);}+ return this.persistSentState(message, result);}async reply(@@ -439,23 +366,14 @@ export class MessageService {},});+ let result: MessageResult;try {- const result = await engine.replyToMessage(dto.chatId, dto.quotedMessageId, dto.text);-- // Update with actual WhatsApp message ID and status- message.waMessageId = result.id;- message.status = MessageStatus.SENT;- message.timestamp = result.timestamp;- await this.messageRepository.save(message);-- return {- messageId: result.id,- timestamp: result.timestamp,- };+ result = await engine.replyToMessage(dto.chatId, dto.quotedMessageId, dto.text);} catch (error) {await this.saveFailedMessage(message);throw this.toClientFacingError(error);}+ return this.persistSentState(message, result);}async forward(@@ -471,26 +389,16 @@ export class MessageService {type: 'forward',});+ let result: MessageResult;try {- const result = await engine.forwardMessage(dto.fromChatId, dto.toChatId, dto.messageId);-- // Update with actual WhatsApp message ID and status. A forward whose engine could not recover the- // sent copy's real id returns an empty id — leave waMessageId unset (NULL) so no ack mis-matches it.- if (result.id) {- message.waMessageId = result.id;- }- message.status = MessageStatus.SENT;- message.timestamp = result.timestamp;- await this.messageRepository.save(message);-- return {- messageId: result.id,- timestamp: result.timestamp,- };+ result = await engine.forwardMessage(dto.fromChatId, dto.toChatId, dto.messageId);} catch (error) {await this.saveFailedMessage(message);throw this.toClientFacingError(error);}+ // persistSentState preserves the empty-id rule: a forward whose engine couldn't recover the sent+ // copy's id leaves waMessageId NULL so no ack mis-matches it.+ return this.persistSentState(message, result);}/**@@ -553,6 +461,28 @@ export class MessageService {await this.messageRepository.save(message);}+ /**+ * Persist the SENT state AFTER the engine has already accepted the message. The send already+ * succeeded, so a failure to write the SENT row must NOT be surfaced as a send failure — a transient+ * DB fault would otherwise mark a delivered message permanently FAILED and (for text) fire+ * `message:failed`. Log and return success instead.+ */+ private async persistSentState(message: Message, result: MessageResult): Promise<MessageResponseDto> {+ // A forward whose engine couldn't recover the sent copy's id returns an empty id — leave waMessageId+ // unset (NULL) so no ack mis-matches it. Every other send path carries a real id.+ if (result.id) message.waMessageId = result.id;+ message.status = MessageStatus.SENT;+ message.timestamp = result.timestamp;+ try {+ await this.messageRepository.save(message);+ } catch (persistError) {+ this.logger.warn(`Persisting SENT state failed after a successful send (id=${result.id})`, {+ error: persistError instanceof Error ? persistError.message : String(persistError),+ });+ }+ return { messageId: result.id, timestamp: result.timestamp };+ }+// ========== Phase 3: Reactions ==========async reactToMessage(sessionId: string, dto: { chatId: string; messageId: string; emoji: string }): Promise<void> {