Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix: reliability and correctness hardening across messaging, webhooks, ingress, and session lifecycle (#658)
Yudhi Armyndharis071516086343
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a9ca4f87e..22a12a2c2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- **Prometheus counter for terminally-failed webhook deliveries.** `/api/metrics` now exposes `openwa_webhook_delivery_failures_total`, incremented once per delivery that exhausts all its retries (mirroring the durable `webhook_delivery_failures` dead-letter record, on both the queued and the queue-disabled direct path). It is an in-process monotonic counter — cheap, real-time, and resetting only on restart, which Prometheus `rate()`/`increase()` treat as a normal counter reset — so a `COUNT(*)` over the retention-pruned failure table isn't queried per scrape. Operators can now alert on webhook failure rate from the scrape instead of tailing the structured log or querying the dead-letter endpoint.++### Changed++- **Runtime feature flags are centralized in the config layer.** `AUTO_START_SESSIONS`, `STORE_EPHEMERAL_MESSAGES`, `RESOLVE_LID_TO_PHONE`, `SIMULATE_TYPING`, and `SIMULATE_TYPING_MAX_MS` now resolve through a single discoverable `features.*` namespace on `ConfigService` (backed by one `computeFeatureFlags()` source of truth) instead of ad-hoc `process.env` reads scattered across the session and message services. Runtime behavior and defaults are unchanged. The four boolean flags are now validated at boot alongside the existing `QUEUE_ENABLED`/`MCP_ENABLED`/`SERVE_DASHBOARD` checks — ⚠️ **behavior change:** a deployment booting one of them with a non-canonical value (e.g. `SIMULATE_TYPING=1`, `AUTO_START_SESSIONS=yes`) will now fail fast naming the offending key until corrected to `true`/`false`/unset, instead of silently falling back to the default.+- **Coverage floors added for the session, webhook, and hook-manager modules.** Per-directory Jest `coverageThreshold` entries now guard `src/modules/session`, `src/modules/webhook`, and `src/core/hooks` (set just below measured, matching the ratcheted floors already in place for the security, auth, engine-adapter, and integration modules), so a large deletion of these modules' tests fails CI instead of passing under the softer global gate.++### Fixed++- **Inbound integration (ingress) deliveries now retry with backoff instead of failing on the first error.** A queued ingress job was enqueued with no retry policy, so BullMQ ran a single attempt and a transient plugin-handler error (e.g. a 5xx from the sandbox) went straight to the dead-letter table — asymmetric with the webhook queue, which already retries. Ingress jobs now use bounded exponential-backoff retries (default 3 attempts, 5s base delay; configurable via `INGRESS_MAX_ATTEMPTS` and `INGRESS_RETRY_DELAY_MS`), and the dead-letter write still fires exactly once, only after the retries are exhausted. ⚠️ **Ordering caveat:** the per-conversation ordering lock guarantees no two same-conversation dispatches run concurrently, but a retried delivery re-enters the lock after its backoff and can therefore overtake a same-conversation successor that dispatched during the backoff window. Ingress order is best-effort regardless (the provider delivers over unordered HTTP); order-strict plugins must not assume a retried event still arrives in sequence. This trades strict order for throughput — BullMQ releases the worker slot during backoff, where retrying inside the lock would hold it.+- **`/infra/status` now actively probes the databases (`SELECT 1`) instead of trusting `isInitialized`.** The Infrastructure panel's database tile read only `DataSource.isInitialized`, which stays `true` after a PostgreSQL backend dies (until an explicit `.destroy()`), so the tile showed the database healthy while it was actually down. The endpoint now runs a short, timeout-bounded `SELECT 1` on both connections — the same probe `/health/ready` uses — so a post-init outage is reflected. SQLite is effectively always up, so this only changes behavior for a genuinely-down external PostgreSQL.+- **The settings panel reports the real docs and base-URL configuration.** `GET /settings` hardcoded `enableDocs: true` (ignoring `ENABLE_SWAGGER`, so it claimed the API docs were enabled in production where they are disabled by default) and an `http://localhost:<port>` `apiBaseUrl` (ignoring the operator's configured `BASE_URL`). Both now reflect the real values, and `autoReconnect` reports the engine's actual default (on) rather than a hardcoded `false` for a config key that never existed.+- **A reaction no longer clobbers a message's delivery status.** `applyReaction` read the full message row, mutated its `reactions` metadata, then wrote the whole row back — so a delivery ack (`SENT`→`DELIVERED`/`READ`) that committed in the window between that read and write was overwritten with the stale status, permanently regressing the message's state until another ack happened to arrive. The reaction now writes only the `metadata` column via a scoped `UPDATE` keyed on `(sessionId, waMessageId)`, so it can never touch `status` (acks and reactions update disjoint columns). The existing per-message serialization for concurrent reactions is unchanged.+- **`PUT /infra/config` returns the real HTTP status for a rejected configuration.** A validation failure (an unknown engine type, or a value carrying a newline that would inject an extra env var) was caught and returned as HTTP 200 with `{ saved: false }`, so a client branching on the status code alone treated a rejected save as success. Such validation errors now surface as their real 4xx (`BadRequestException`); a genuine persistence fault (e.g. a disk/permission error while writing the env file) still returns `{ saved: false }` with 200, preserving the dashboard's `body.saved` handling.+- **Deleting a session no longer orphans its webhooks, templates, or stored Baileys messages on SQLite.** `webhooks`, `templates`, and `baileys_stored_messages` declare an `ON DELETE CASCADE` foreign key to `sessions`, but the default `data` engine (SQLite) runs with `foreign_keys` OFF, so that cascade never fired — a session delete removed only the session, `messages`, and `message_batches` rows and left the rest behind indefinitely (orphaned `webhooks` rows in particular retain their signing secret and any custom headers). `delete()` now removes all CASCADE-FK child rows explicitly inside the same transaction (children before the parent), which is engine-agnostic — redundant-but-harmless on PostgreSQL, where the real cascade already handles it — and mirrors the ordering the data-restore path already uses.+- **The `message:sending` moderation gate and `message:failed` notification now cover every outbound path.** Both hooks were wired only into the text `sendText` method, so a plugin registered on `message:sending` (the canonical pre-send moderation/compliance gate) saw no image/video/audio/document/sticker/location/contact/poll/reply/forward send and no bulk send at all, and a `message:failed` plugin saw only text-send failures. Every single sender now passes through a shared pre-send gate (a plugin can block or rewrite the payload) and a shared failure emitter, and `BulkMessageService` runs the same per-message gate (a block fails just that message, honoring `stopOnError`) and emits `message:failed` on a failed batch item. ⚠️ **Behavior change:** a `message:sending` plugin now receives — and can block/modify — media, extended, and bulk sends it previously never saw; the hook payload carries a `type` discriminator (`image`/`video`/`poll`/`reply`/… ) so a handler can scope its logic per send type, and its `error` field is sanitized so an SSRF-blocked media fetch does not expose the resolved internal address to plugins. A moderation block on a bulk item fails just that item (honoring `stopOnError`) without emitting `message:failed`, matching single-send where a block is a client error, not a delivery failure. `message:sent` is unchanged (still emitted once from the engine `message_create` path).+- **Sibling webhooks subscribed to the same event now get distinct idempotency keys.** The per-event idempotency key was derived only from the event and its payload, so two _different_ webhook endpoints registered for the same event on the same session received an identical `X-OpenWA-Idempotency-Key`. A receiver sitting behind both (or a shared dedup store) could drop the second endpoint's delivery as a replay of the first. The key is now salted with the destination webhook's id, so each endpoint is dedup'd independently while retries of the _same_ delivery (including the queue-add→direct fallback) keep their stable key.+- **A session with auto-reconnect turned off no longer reports "reconnection failed after 0 attempts".** When a disconnect fired with the reconnect budget set to `0` (auto-reconnect disabled), the session was marked `FAILED` with the exhausted-retries message and a count of `0` — implying a retry loop had run and failed rather than a feature that is simply off. That case now records an explicit "Auto-reconnect is disabled" reason; the genuine exhausted-retries message (with its real attempt count) is unchanged.+- **A failed inbound integration (ingress) delivery is no longer silently dropped on the inline path.** With the queue disabled (or Redis unreachable), an ingress delivery is dispatched inline; if the plugin handler threw, the error was swallowed and the event was stranded — the provider had already received its `202`, and the redrive tooling only scans the dead-letter table, which never got a row. The inline path now persists a dead-letter record (the same shape the queued path writes on its final failed attempt), so the event is redrivable. The write is best-effort: a failure to persist it is logged but never turns the `202` into a `5xx` (the delivery is already dedup-persisted, so the provider won't re-send).+- **Plugin instance session bindings are re-derived on startup, so a binding lost while the plugin was momentarily unloaded self-heals.** Provisioning a plugin instance mirrors its config into the plugin runtime (per-session config + activation) so an ingress handler resolves the right `ctx.config`; if the plugin happened to be unloaded at that moment the bridge was skipped (only an INFO audit), leaving the instance marked enabled but resolving base config only — previously recoverable only by re-saving the instance. A boot-time reconciliation now re-applies every enabled instance's binding from the persisted `plugin_instances` rows (honoring each row's real `enabled` flag), so a restart restores it. The binding logic moved into a dedicated service shared by provisioning and the reconciler.+## [0.8.10] - 2026-07-07### Added@@ -25,7 +48,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **Indexed `webhooks.sessionId`.** The webhook dispatch path looks up a session's active webhooks by `sessionId` on every emitted event, so on a busy session this was a full table scan of the `webhooks` table per event (the foreign-key column carried no index). A cross-dialect index migration — plus the matching entity index — makes the lookup index-backed.- **Boot now rejects a non-canonical boolean feature flag instead of silently disabling the feature.** `QUEUE_ENABLED`, `MCP_ENABLED`, and `SERVE_DASHBOARD` are read with an exact `=== 'true'` / `!== 'false'` comparison, so a typo (`True`, `1`, `yes`) or a stray trailing space/CR (a Windows-edited env file forwarded verbatim by `docker run --env-file`) silently (dis)abled the feature with zero diagnostics. These are now validated at startup and boot fails fast naming the offending key. ⚠️ **Behavior change:** a deployment currently booting with such a value (e.g. `QUEUE_ENABLED=1`) will now refuse to start until corrected to `true`/`false`/unset — including `SERVE_DASHBOARD=0`/`no`, which was silently serving the dashboard and will now correctly disable it once set to `false`.- **A fatal uncaught exception is now written to the structured log** (with its stack and origin) before the process exits, instead of only a raw stack on stderr that the log pipeline missed. This is observe-only: the crash-and-restart posture is unchanged (the container restart policy still fires and the process never continues on corrupted post-exception state).-- **`POST /infra/import-data` no longer swallows a genuine database error while clearing tables.** The table-clearing step tolerated only a genuinely-absent table but previously used a blanket catch, so an I/O/lock error (or an aborted transaction) could let a restore commit a *merged* rather than *replaced* dataset on SQLite. Such errors now surface and roll the whole import back (a real fault returns a `500` carrying the actual cause); the intended tolerance for a missing table is preserved.+- **`POST /infra/import-data` no longer swallows a genuine database error while clearing tables.** The table-clearing step tolerated only a genuinely-absent table but previously used a blanket catch, so an I/O/lock error (or an aborted transaction) could let a restore commit a _merged_ rather than _replaced_ dataset on SQLite. Such errors now surface and roll the whole import back (a real fault returns a `500` carrying the actual cause); the intended tolerance for a missing table is preserved.- **A session no longer schedules a reconnect while the process is shutting down** — a disconnect during the drain window would otherwise launch a fresh Chromium racing the shutdown teardown. The session is left `DISCONNECTED` (a later start / auto-restore re-initializes it cleanly).- **Documentation & config accuracy.** `.env.example` now documents `PORT` (the port the app binds to on bare metal) distinctly from the Compose-only host-published `API_PORT`, and adds the `QUEUE_ENABLED`/`CACHE_ENABLED` toggles. `SECURITY.md`'s supported-versions table and the Java SDK install snippets are refreshed to the current releases. The unused `uuid`/`@types/uuid` dependency was removed, and stale "not yet wired" comments on the plugin ingress-manifest validation (which the loader has called since it shipped) were corrected.- **The bundled Docker Compose stack no longer kills Chromium mid-spawn under multi-session `whatsapp-web.js` workloads (#636).** The per-container `pids_limit` shipped at `512` since the `#243` hardening pass — a fork-bomb guard chosen without accounting for Chromium's multi-process model. `whatsapp-web.js` runs a full Chromium instance per session (browser + renderer + GPU + zygote + utilities), and WhatsApp Web is itself process-heavy, so ~4 concurrent sessions already approached 512 and the next session's Chromium was killed mid-spawn when `fork()` returned `EAGAIN` — surfacing in the API as a `Failed to launch the browser process: Code: null` launch failure with no useful log (the dbus/crashpad noise in the log is non-fatal). The default is now `2048` (fits ~8–10 sessions with startup-spike headroom), exposed as `OPENWA_PIDS_LIMIT` for larger fleets. The limit is a cgroup `pids.max` ceiling, not an allocation — raising it is a no-op for light containers, so this is safe for the `baileys` engine (single-process, no Chromium, a handful of PIDs regardless). The fork-bomb guard stays finite (`-1`/unlimited is explicitly discouraged). A new troubleshooting entry distinguishes the three causes of `Code: null` (PID exhaustion vs OOM-kill vs the XDG/crashpad crash already fixed earlier), since the cause isn't visible in the log without `docker stats` / `dmesg`.@@ -72,7 +95,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed-- **The `engine.getChatHistory` plugin capability (added in 0.8.5) now reaches sandboxed plugins.** It was wired only into the host-side context, not the plugin-worker bridge, so a sandboxed plugin's `ctx.engine.getChatHistory` was `undefined` and the call failed silently. It is now bridged through the worker capability + router like the other engine reads. Historical messages from the whatsapp-web.js engine also carry location coordinates and quoted-message references now, matching the live message path (previously a backfilled location rendered empty and replies lost their thread link). (#609)## [0.8.5] - 2026-07-03@@ -478,7 +500,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed- Sessions (Baileys): when a session is logged out — unlinked from the phone or via the API — the now-invalid on-disk auth state is cleared, so re-linking shows a fresh QR instead of getting stuck silently reloading the dead credentials. (#453 — thanks @ulises2k)-- Webhooks: registering a webhook (`POST /sessions/:id/webhooks`) to a host whose DNS lookup *rejects* (NXDOMAIN, or a transient `EAI_AGAIN`/`ESERVFAIL` under resolver pressure) now returns `400 Could not resolve host: <host> (<code>)` instead of a generic `500 Internal server error`. The SSRF guard's DNS deadline already mapped resolution *timeouts* and empty results to a 4xx; a rejected lookup leaked the raw DNS error, which surfaced as an intermittent 500 during back-to-back session-create → webhook-register flows.+- Webhooks: registering a webhook (`POST /sessions/:id/webhooks`) to a host whose DNS lookup _rejects_ (NXDOMAIN, or a transient `EAI_AGAIN`/`ESERVFAIL` under resolver pressure) now returns `400 Could not resolve host: <host> (<code>)` instead of a generic `500 Internal server error`. The SSRF guard's DNS deadline already mapped resolution _timeouts_ and empty results to a 4xx; a rejected lookup leaked the raw DNS error, which surfaced as an intermittent 500 during back-to-back session-create → webhook-register flows.- Infrastructure: the dashboard config form no longer shows Server, Webhook, and Rate-Limit sections that were never persisted — they returned a fake "saved" while silently discarding every value. The form now exposes only the settings it actually writes (Database, Redis/Queue, Storage, Engine); the removed settings remain configurable via environment variables.- Infrastructure: data export/import (the documented backup and SQLite↔PostgreSQL migration flow) is now complete. It previously exported and restored only sessions, webhooks, messages, and message batches — so a restore silently lost all message templates and stored Baileys messages (cascade-deleted with the old sessions and never re-imported) and dropped every webhook's filters, causing a filtered webhook to come back firing on all events. Templates, stored Baileys messages, and webhook filters now round-trip intact.- Engine selection: pinning the engine from the environment works again after the v0.7.1 compose change. The bundled compose files forward `ENGINE_TYPE` into the container again (`- ENGINE_TYPE=${ENGINE_TYPE:-}`) and the app treats a blank value as unset, so an `.env`/host `ENGINE_TYPE=baileys` is honoured while the dashboard's Infrastructure > Engine selection still wins when no engine is pinned. `.env.example` no longer ships `ENGINE_TYPE` pre-pinned. **Upgrade note:** if you relied on `ENGINE_TYPE=baileys` in your `.env`, confirm the active engine after upgrading. (#453 — thanks @ulises2k)@@ -661,7 +683,7 @@ path (browser-flag parsing + `0600` secret file), and cleaner fresh-install sche- **The contact, group, and chat list endpoints are now paginated (default cap 1000).** ⚠️ Behaviorchange. `GET /sessions/:id/contacts`, `/groups`, and `/chats` previously serialized the operator's- *entire* address book / group / chat set into one response — a heap/GC hazard for very large+ _entire_ address book / group / chat set into one response — a heap/GC hazard for very largeaccounts. They now accept optional `limit` (clamped `[1, 1000]`) and `offset` query params, anddefault to returning at most **1000** items when no `limit` is given. Accounts under 1000 items areunaffected; larger accounts page with `offset`. Chats are returned **most-recent first**, so a@@ -836,7 +858,7 @@ longer floods the screen with error toasts.A reliability, correctness, and dashboard release. **Identity & engine:** Baileys gains a persistent,cross-session `lid -> phone` table (shared resolution that survives restarts) plus a new `from` message-filter, and its contact/chat *listing* ids are now engine-neutral (`@c.us`). **Webhooks:** message+filter, and its contact/chat _listing_ ids are now engine-neutral (`@c.us`). **Webhooks:** messagereactions now also fire as a `message.reaction` webhook (previously WebSocket-only). **Dashboard:**selectable appearance palettes with light/dark/system mode, and a redesigned Templates workspace.**Hardening:** the LibreTranslate client pins its outbound connection, and Baileys group-participant@@ -889,7 +911,7 @@ webhooks subscribed with `*` now also receive `message.reaction`.addressed by a raw engine id), so the conversation view is no longer empty when the stored and querieddialects differ - the same resolution the `from` filter uses. (#375)-- **Baileys engine: contact and chat *listing* ids are now engine-neutral (`@c.us`).** `getContacts` /+- **Baileys engine: contact and chat _listing_ ids are now engine-neutral (`@c.us`).** `getContacts` /`getChats` / `getContactById` previously returned the raw `<phone>@s.whatsapp.net` id (visible in thedashboard, and mismatched against the `@c.us` chatId stored on messages). They now emit the neutral`@c.us` dialect like the message payloads; the read-back paths (`sendSeen` / `deleteChat` / contact@@ -1049,8 +1071,8 @@ of silently falling back to the default.the queue dashboard (Bull Board) auth uses the same trusted-proxy IP model as the API; the productionsecret-guard inspects the canonical S3 variables. (#345)- **Storage import/key hardening.** A `tar.gz` import is bounded against decompression bombs (per-entry byte cap- + entry-count cap); storage-key containment is enforced at the backend-agnostic boundary so the S3 path- inherits it; a plugin's `ctx.storage` is sandbox-contained against `..` traversal. (#346)+ - entry-count cap); storage-key containment is enforced at the backend-agnostic boundary so the S3 path+ inherits it; a plugin's `ctx.storage` is sandbox-contained against `..` traversal. (#346)### Fixed@@ -1207,7 +1229,7 @@ application-code changes.monitoring, and any external reverse-proxy config accordingly. (#275)- The `with-dashboard` and `with-proxy` compose profiles are removed, and the `DASHBOARD_PORT`,`PROXY_ENABLED`, and `DASHBOARD_ENABLED` env vars are gone (silently ignored if still set). `--profile- full` now starts the optional datastores (postgres, redis, minio). If you relied on the bundled Traefik+full` now starts the optional datastores (postgres, redis, minio). If you relied on the bundled Traefikfor TLS, front the API with your own reverse proxy. (#275, #276)## [0.3.0] - 2026-06-18@@ -1467,7 +1489,7 @@ Login language selector legible in dark mode.### Fixed- Chromium no longer hard-crashes at launch (`Trace/breakpoint trap` / `chrome_crashpad_handler:- --database is required`) on hardened `read_only` containers. Chromium resolves its home dir from the+--database is required`) on hardened `read_only` containers. Chromium resolves its home dir from thepasswd entry and ignores `$HOME`, so the home-less `openwa` user pointed it at a nonexistent`/home/openwa`. It is now given writable, pre-created `XDG_CONFIG_HOME`/`XDG_CACHE_HOME` dirs (createdby the entrypoint, owned by `openwa`). This supersedes the ineffective `--crash-dumps-dir` approachdiff --git a/docs/09-testing-strategy.md b/docs/09-testing-strategy.mdindex 3b8afd8db..c8620d2a3 100644--- a/docs/09-testing-strategy.md+++ b/docs/09-testing-strategy.md@@ -1,45 +1,56 @@# 09 - Testing Strategy-## 09.1 Current Status+## 9.1 Current StatusOpenWA now has an active Jest test suite covering the backend core, engine adapters, security helpers,database migrations, plugin hooks, and smoke-level e2e boot paths. This document describes the currenttest layout and the expected testing workflow for contributors.-Status snapshot from the repository state on 2026-06-28:+| 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 |+| 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 |-| Area | Current state |-|------|---------------|-| Backend unit tests | 113 Jest suites / 1481 tests passing with `npm test -- --runInBand` |-| E2E smoke tests | 5 Jest suites / 31 tests passing plus 3 todo with `npm run test:e2e -- --runInBand` |-| Dashboard checks | Dashboard lint, unit tests, i18n parity check, and build |-| Coverage baseline | 66.87% line coverage; active target is 80% (see `docs/superpowers/specs/2025-01-28-test-coverage-improvement-design.md`) |-| Coverage gate | Jest global thresholds plus stricter thresholds for security-sensitive modules |--The exact counts will change as the project evolves. Use the commands below as the source of truth.+The exact counts will change as the project evolves. Use the commands below as the source of truth for+the test inventory, and use the test commands in the next section for pass/fail status.```bash-find src test -name '*.spec.ts' -o -name '*.e2e-spec.ts' | wc -l+rg --files -g '*.spec.ts' src | wc -l+rg --files -g '*.e2e-spec.ts' test | wc -l+rg --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$)' \+ | wc -lnpm test -- --runInBandnpm run test:e2e -- --runInBandnpm --prefix dashboard run test:unit```-## 09.2 Test Commands--| Command | Purpose |-|---------|---------|-| `npm test` | Run backend Jest unit tests from `src/` |-| `npm test -- --runInBand` | Run backend tests serially; useful for local debugging and clean output |-| `npm run test:cov` | Run backend tests with coverage and coverage thresholds |-| `npm run test:e2e` | Run smoke-level e2e tests from `test/` |-| `npm run lint` | Run backend ESLint with type-aware rules |-| `cd dashboard && npm run lint` | Run dashboard ESLint |-| `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 |--## 09.3 Backend Unit Tests+## 9.2 Test Commands++| Command | Purpose |+| ----------------------------------------------------------------- | ----------------------------------------------------------------------- |+| `npm test` | Run backend Jest unit tests from `src/` |+| `npm test -- --runInBand` | Run backend tests serially; useful for local debugging and clean output |+| `npm run test:cov` | Run backend tests with coverage and coverage thresholds |+| `npm run test:e2e` | Run smoke-level e2e tests from `test/` |+| `npm run test:pg-smoke` | Run the PostgreSQL migration and UUID-default smoke test |+| `npm run lint` | Run backend ESLint with type-aware rules |+| `npm run check:versions` | Verify documentation and package version consistency |+| `cd dashboard && npm run lint` | Run dashboard ESLint |+| `cd dashboard && npm run test:unit` | Run dashboard pure utility/unit tests |+| `cd dashboard && npm run i18n:check` | Verify dashboard locale key parity |+| `cd dashboard && npm run build` | Type-check and build the dashboard |+| `cd sdk/javascript && npm test && npm run build && npm run smoke` | Test and package-smoke the JavaScript SDK |+| `cd sdk/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 |++## 9.3 Backend Unit TestsBackend unit tests live next to the source files they cover:@@ -95,7 +106,7 @@ describe('resolveReconnectConfig', () => {});```-## 09.4 E2E Smoke Tests+## 9.4 E2E Smoke TestsE2E smoke tests live in `test/` and use `test/jest-e2e.json`.@@ -103,7 +114,12 @@ E2E smoke tests live in `test/` and use `test/jest-e2e.json`.test/├── app.e2e-spec.ts├── baileys-engine.e2e-spec.ts+├── ingress-instance-throttle.e2e-spec.ts+├── integration-fabric.e2e-spec.ts+├── integration-instance.e2e-spec.ts+├── mcp-auth.e2e-spec.ts├── serve-static.e2e-spec.ts+├── webhooks.e2e-spec.ts├── jest-e2e.json└── setup-e2e.ts```@@ -119,36 +135,52 @@ test/The e2e suite intentionally avoids requiring a live WhatsApp account. It focuses on application boot,authentication plumbing, public health endpoints, engine selection paths, and dashboard static serving behavior.-## 09.5 Coverage Policy+## 9.5 Coverage Policy++Coverage thresholds are defined in `package.json` under the Jest configuration. Treat that file as the+authoritative gate. Current policy:++| Scope | Branches | Functions | Lines | Statements |+| -------------------------- | -------- | --------- | ----- | ---------- |+| Global | 58% | 58% | 66% | 65% |+| `src/common/security/` | 85% | 95% | 90% | 90% |+| `src/modules/auth/` | 62% | 70% | 72% | 72% |+| `src/engine/adapters/` | 63% | 63% | 70% | 70% |+| `src/modules/integration/` | 67% | 68% | 77% | 77% |+| `src/core/hooks/` | 80% | 70% | 82% | 81% |+| `src/modules/session/` | 50% | 63% | 74% | 72% |+| `src/modules/webhook/` | 65% | 83% | 84% | 80% |-Coverage thresholds are defined in `package.json` under the Jest configuration. Current policy:+The stricter scoped gates protect security-sensitive code and high-risk boundary layers. When adding+security, engine-adapter, or integration-fabric behavior, add focused regression tests instead of relying+on broad integration coverage.-| Scope | Branches | Functions | Lines | Statements |-|-------|----------|-----------|-------|------------|-| Global | 30% | 30% | 33% | 33% |-| `src/common/security/` | 85% | 95% | 90% | 90% |-| `src/modules/auth/` | 30% | 50% | 45% | 45% |+## 9.6 CI Checks-These thresholds are intentionally higher for security-sensitive code. When adding security code,-add focused regression tests instead of relying on broad integration coverage.+Main CI is defined in `.github/workflows/ci.yml`.-## 09.6 CI Checks+| Job | Checks |+| --------------- | ----------------------------------------------------------------------------------------------- |+| `lint` | `npm audit --audit-level=critical`, backend ESLint, formatting check, version consistency check |+| `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 |+| `build` | backend build after lint/test/dashboard jobs pass |+| `docker` | multi-arch Docker build and push on branch pushes |-CI is defined in `.github/workflows/ci.yml`.+SDK CI is defined in `.github/workflows/sdk-ci.yml` and is path-filtered to SDK sources plus server+contract surfaces that SDKs mirror (`src/**/dto/**` and the engine interface). It runs:-| Job | Checks |-|-----|--------|-| `lint` | `npm audit --audit-level=critical`, backend ESLint, formatting check |-| `test` | backend coverage run, e2e smoke tests, Codecov upload |-| `dashboard` | dashboard install, lint, unit tests, i18n parity, build |-| `build` | backend build after lint/test/dashboard jobs pass |-| `docker` | multi-arch Docker build and push on branch pushes |+- JavaScript SDK tests, build, and dual CJS/ESM smoke test.+- Python SDK tests with `pytest`.+- PHP SDK tests with PHPUnit.+- Java SDK tests with Maven.-Release tags run `.github/workflows/release.yml`, which gates Docker publishing behind tests and build,-and publishes the GitHub Release only after the image build succeeds — so a tag never ends up with-release notes but no matching multi-arch image.+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+backend, and publishes the GitHub Release only after the Docker image has built and pushed successfully.-## 09.7 Testing Guidelines+## 9.7 Testing Guidelines### Add Tests Near the Risk@@ -184,7 +216,7 @@ covered by a test proving it cannot leak an unhandled rejection.E2E tests should stay smoke-level unless a change specifically needs a full app boot. Prefer unit testsfor business logic and e2e tests for wiring, guards, global pipes, app boot, and route-level behavior.-## 09.8 Manual Smoke Checks+## 9.8 Manual Smoke ChecksUse these checks when changing Docker, Chromium, dashboard serving, or session startup behavior.@@ -214,7 +246,7 @@ Live WhatsApp checks require an operator-owned account and should not be part of5. Send a text message to a test chat.6. Confirm message history, webhook delivery, and WebSocket events.-## 09.9 Known Gaps+## 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.diff --git a/package.json b/package.jsonindex 673ede346..ab796128d 100644--- a/package.json+++ b/package.json@@ -182,6 +182,24 @@"functions": 68,"lines": 77,"statements": 77+ },+ "./src/core/hooks/": {+ "branches": 80,+ "functions": 70,+ "lines": 82,+ "statements": 81+ },+ "./src/modules/session/": {+ "branches": 50,+ "functions": 63,+ "lines": 74,+ "statements": 72+ },+ "./src/modules/webhook/": {+ "branches": 65,+ "functions": 83,+ "lines": 84,+ "statements": 80}},"testEnvironment": "node"diff --git a/src/common/metrics/webhook-delivery-metrics.spec.ts b/src/common/metrics/webhook-delivery-metrics.spec.tsnew file mode 100644index 000000000..efcc7b361--- /dev/null+++ b/src/common/metrics/webhook-delivery-metrics.spec.ts@@ -0,0 +1,17 @@+import { incrementWebhookDeliveryFailures, getWebhookDeliveryFailuresTotal } from './webhook-delivery-metrics';++describe('webhook-delivery-metrics', () => {+ it('monotonically increments the terminal-failure total', () => {+ const before = getWebhookDeliveryFailuresTotal();+ incrementWebhookDeliveryFailures();+ incrementWebhookDeliveryFailures();+ expect(getWebhookDeliveryFailuresTotal()).toBe(before + 2);+ });++ it('never decreases', () => {+ const a = getWebhookDeliveryFailuresTotal();+ incrementWebhookDeliveryFailures();+ const b = getWebhookDeliveryFailuresTotal();+ expect(b).toBeGreaterThan(a);+ });+});diff --git a/src/common/metrics/webhook-delivery-metrics.ts b/src/common/metrics/webhook-delivery-metrics.tsnew file mode 100644index 000000000..dd68596ba--- /dev/null+++ b/src/common/metrics/webhook-delivery-metrics.ts@@ -0,0 +1,20 @@+/**+ * Process-local monotonic counter of webhook deliveries that terminally failed (every retry+ * exhausted), incremented one-for-one alongside the durable `webhook_delivery_failures` dead-letter+ * rows. Kept as a plain in-process counter rather than a `COUNT(*)` over that table because the table+ * is pruned on a retention schedule, which would make its count non-monotonic and therefore invalid+ * as a Prometheus `counter` (a prune would look like a counter reset to `rate()`/`increase()`). An+ * in-process counter only resets on restart, which those functions already handle correctly, and it+ * also captures the failure even when persisting the dead-letter row itself fails.+ */+let terminalFailureTotal = 0;++/** Record one terminal (all-retries-exhausted) webhook delivery failure. */+export function incrementWebhookDeliveryFailures(): void {+ terminalFailureTotal += 1;+}++/** Current process-lifetime total of terminal webhook delivery failures. */+export function getWebhookDeliveryFailuresTotal(): number {+ return terminalFailureTotal;+}diff --git a/src/config/configuration.ts b/src/config/configuration.tsindex 98046be81..b0add4d2b 100644--- a/src/config/configuration.ts+++ b/src/config/configuration.ts@@ -1,6 +1,12 @@+import { computeFeatureFlags } from './feature-flags';+export default () => ({port: parseInt(process.env.PORT || '2785', 10),+ // Runtime feature flags. Single source of truth: src/config/feature-flags.ts. Exposed here so the+ // full set is discoverable via ConfigService (`features.*`) instead of scattered process.env reads.+ features: computeFeatureFlags(),+// Redis configurationredis: {host: process.env.REDIS_HOST || 'localhost',diff --git a/src/config/env.validation.ts b/src/config/env.validation.tsindex d90dc2c34..5d508bf21 100644--- a/src/config/env.validation.ts+++ b/src/config/env.validation.ts@@ -147,7 +147,15 @@ export function validateEnv(config: EnvConfig): EnvConfig {errors.push(`${key} must be "true" or "false" (got ${JSON.stringify(raw)})`);}};- for (const key of ['QUEUE_ENABLED', 'MCP_ENABLED', 'SERVE_DASHBOARD']) {+ for (const key of [+ 'QUEUE_ENABLED',+ 'MCP_ENABLED',+ 'SERVE_DASHBOARD',+ 'AUTO_START_SESSIONS',+ 'STORE_EPHEMERAL_MESSAGES',+ 'RESOLVE_LID_TO_PHONE',+ 'SIMULATE_TYPING',+ ]) {checkBool(key);}diff --git a/src/config/feature-flags.spec.ts b/src/config/feature-flags.spec.tsnew file mode 100644index 000000000..d5519716b--- /dev/null+++ b/src/config/feature-flags.spec.ts@@ -0,0 +1,73 @@+import { computeFeatureFlags, resolveFeatureFlags, FeatureFlags } from './feature-flags';++describe('feature-flags', () => {+ describe('computeFeatureFlags', () => {+ it('applies the documented defaults for an empty environment', () => {+ const flags = computeFeatureFlags({});+ expect(flags).toEqual<FeatureFlags>({+ autoStartSessions: false, // opt-in+ storeEphemeralMessages: true, // opt-out+ resolveLidToPhone: false, // opt-in+ simulateTyping: true, // opt-out+ simulateTypingMaxMs: 5000,+ });+ });++ it('treats opt-in flags (autoStart, resolveLid) as ON only for the exact string "true"', () => {+ expect(computeFeatureFlags({ AUTO_START_SESSIONS: 'true' }).autoStartSessions).toBe(true);+ expect(computeFeatureFlags({ RESOLVE_LID_TO_PHONE: 'true' }).resolveLidToPhone).toBe(true);+ // Anything else stays OFF.+ for (const v of ['false', 'TRUE', '1', 'yes', '']) {+ expect(computeFeatureFlags({ AUTO_START_SESSIONS: v }).autoStartSessions).toBe(false);+ expect(computeFeatureFlags({ RESOLVE_LID_TO_PHONE: v }).resolveLidToPhone).toBe(false);+ }+ });++ it('treats opt-out flags (storeEphemeral, simulateTyping) as OFF only for the exact string "false"', () => {+ expect(computeFeatureFlags({ STORE_EPHEMERAL_MESSAGES: 'false' }).storeEphemeralMessages).toBe(false);+ expect(computeFeatureFlags({ SIMULATE_TYPING: 'false' }).simulateTyping).toBe(false);+ // Anything else stays ON.+ for (const v of ['true', 'FALSE', '0', 'no', '']) {+ expect(computeFeatureFlags({ STORE_EPHEMERAL_MESSAGES: v }).storeEphemeralMessages).toBe(true);+ expect(computeFeatureFlags({ SIMULATE_TYPING: v }).simulateTyping).toBe(true);+ }+ });++ it('parses simulateTypingMaxMs with Number()||5000 semantics (0/negative/non-numeric fall back)', () => {+ expect(computeFeatureFlags({ SIMULATE_TYPING_MAX_MS: '3000' }).simulateTypingMaxMs).toBe(3000);+ // Critical: "0" must fall back to 5000 (Number('0')||5000), NOT stay 0 as parseInt would.+ expect(computeFeatureFlags({ SIMULATE_TYPING_MAX_MS: '0' }).simulateTypingMaxMs).toBe(5000);+ expect(computeFeatureFlags({ SIMULATE_TYPING_MAX_MS: '' }).simulateTypingMaxMs).toBe(5000);+ expect(computeFeatureFlags({ SIMULATE_TYPING_MAX_MS: 'abc' }).simulateTypingMaxMs).toBe(5000);+ expect(computeFeatureFlags({ SIMULATE_TYPING_MAX_MS: undefined }).simulateTypingMaxMs).toBe(5000);+ });+ });++ describe('resolveFeatureFlags', () => {+ const original = process.env.AUTO_START_SESSIONS;+ afterEach(() => {+ if (original === undefined) delete process.env.AUTO_START_SESSIONS;+ else process.env.AUTO_START_SESSIONS = original;+ });++ it('prefers the ConfigService-loaded features object when present', () => {+ const features = computeFeatureFlags({ AUTO_START_SESSIONS: 'true' });+ const configService = { get: jest.fn().mockReturnValue(features) };+ expect(resolveFeatureFlags(configService)).toBe(features);+ expect(configService.get).toHaveBeenCalledWith('features');+ });++ it('falls back to a live process.env read when ConfigService is absent', () => {+ process.env.AUTO_START_SESSIONS = 'true';+ expect(resolveFeatureFlags(undefined).autoStartSessions).toBe(true);+ process.env.AUTO_START_SESSIONS = 'false';+ expect(resolveFeatureFlags(undefined).autoStartSessions).toBe(false);+ });++ it('falls back to process.env when ConfigService has no "features" entry (e.g. a partial mock)', () => {+ process.env.AUTO_START_SESSIONS = 'true';+ const configService = { get: jest.fn().mockImplementation((_k: string, def?: unknown) => def) };+ expect(resolveFeatureFlags(configService).autoStartSessions).toBe(true);+ });+ });+});diff --git a/src/config/feature-flags.ts b/src/config/feature-flags.tsnew file mode 100644index 000000000..6f8fe465c--- /dev/null+++ b/src/config/feature-flags.ts@@ -0,0 +1,52 @@+import { ConfigService } from '@nestjs/config';++/**+ * Runtime feature flags, centralised so every flag's env-var name and default lives in one place+ * instead of being read inline from `process.env` at each call site. Surfaced through+ * `ConfigService` as `features.*` (see `configuration.ts`) and their canonical boolean values are+ * validated at boot (see `env.validation.ts`).+ */+export interface FeatureFlags {+ /** Auto-start previously-authenticated sessions on boot. Opt-in — default OFF. */+ autoStartSessions: boolean;+ /** Persist + dispatch incoming disappearing-message-timer messages. Default ON. */+ storeEphemeralMessages: boolean;+ /** Inline @lid -> phone resolution for inbound privacy-id senders. Opt-in — default OFF. */+ resolveLidToPhone: boolean;+ /** Humanising typing indicator before single (non-bulk) sends. Default ON. */+ simulateTyping: boolean;+ /** Upper bound (ms) on the humanising typing pause. Default 5000. */+ simulateTypingMaxMs: number;+}++/**+ * Derive the feature-flag set from an environment map. Pure and parameterised for testability. The+ * comparisons intentionally mirror the exact semantics of the original inline reads so behaviour is+ * unchanged:+ * - `=== 'true'` → opt-in flag (default false)+ * - `!== 'false'` → opt-out flag (default true)+ * and the max-ms parse mirrors the original `Number(x) || 5000` — 0, negative, empty and non-numeric+ * values all fall back to 5000 (note this differs from `parseInt`, which would keep a literal 0).+ */+export function computeFeatureFlags(env: NodeJS.ProcessEnv = process.env): FeatureFlags {+ return {+ autoStartSessions: env.AUTO_START_SESSIONS === 'true',+ storeEphemeralMessages: env.STORE_EPHEMERAL_MESSAGES !== 'false',+ resolveLidToPhone: env.RESOLVE_LID_TO_PHONE === 'true',+ simulateTyping: env.SIMULATE_TYPING !== 'false',+ simulateTypingMaxMs: Number(env.SIMULATE_TYPING_MAX_MS) || 5000,+ };+}++/**+ * Resolve the flags, preferring the `ConfigService`-loaded set (the boot-time snapshot built by+ * `configuration.ts`) and falling back to a live `process.env` read when `ConfigService` is absent —+ * e.g. a unit test that constructs a service without the global `ConfigModule`. Environment variables+ * do not change during a process's lifetime, so the snapshot and a live read are equivalent in+ * production; the fallback exists purely to preserve the live-read behaviour that unit tests rely on+ * when they mutate `process.env`.+ */+export function resolveFeatureFlags(configService?: Pick<ConfigService, 'get'>): FeatureFlags {+ const fromConfig = configService?.get<FeatureFlags>('features');+ return fromConfig ?? computeFeatureFlags();+}diff --git a/src/core/plugins/sandbox/worker-bootstrap.ts b/src/core/plugins/sandbox/worker-bootstrap.tsindex 2ecfb186f..bb8e93ff9 100644--- a/src/core/plugins/sandbox/worker-bootstrap.ts+++ b/src/core/plugins/sandbox/worker-bootstrap.ts@@ -5,10 +5,16 @@ import { WorkerHookRegistry, WorkerHookHandler, hookConfigStore } from './workerimport { WebhookRegistry, WebhookHandler } from './worker-webhooks';/**- * Worker entry for an untrusted plugin. Loads the plugin module and drives its lifecycle in response- * to host messages. This is the only code that runs alongside untrusted plugin code, so it keeps no- * host references — its sole channel out is `parentPort`, and every capability call round-trips to- * the host (which validates permission + session scope) via the capability client.+ * Worker entry for a plugin. Loads the plugin module and drives its lifecycle in response to host+ * messages, exposing the `ctx.*` capability surface, which round-trips every call to the host (which+ * validates permission + session scope) via the capability client.+ *+ * SECURITY MODEL — read before relying on the sandbox: a `worker_thread` shares the host OS process,+ * filesystem, and network credentials. It provides crash / heap-OOM CONTAINMENT, NOT a security+ * boundary. Plugin code can `require('fs' | 'net' | 'child_process')` and reach the host's files and+ * sockets directly — `parentPort` is NOT the worker's only channel out, and the capability permission+ * model gates only the `ctx.*` verbs, not raw Node access. Load only trusted plugin code, or run+ * OpenWA under an OS-level sandbox (container / seccomp) when untrusted plugins must be supported.*/interface LifecyclePlugin {diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.tsindex 44071d815..6585e4734 100644--- a/src/modules/infra/infra.controller.spec.ts+++ b/src/modules/infra/infra.controller.spec.ts@@ -91,12 +91,42 @@ describe('InfraController.importStorage filePath validation (Vuln 3)', () => {});});-describe('InfraController.getStatus queue job counts (F-18)', () => {+describe('InfraController.getStatus DB health (active SELECT 1 probe, not just isInitialized)', () => {+ const build = (query: jest.Mock) => {+ // engine.type=baileys skips the wa-web-version registry fetch (no network in unit tests).+ const config = { get: (k: string, def?: unknown) => (k === 'engine.type' ? 'baileys' : def) };+ const ds = { isInitialized: true, query };+ const cache = { isAvailable: jest.fn().mockResolvedValue(false), refreshS3Availability: jest.fn() };+ return new InfraController(+ config as never,+ ds as never,+ ds as never,+ { create: jest.fn() } as never,+ { isDockerAvailable: () => false, getRunningBuiltinServices: jest.fn() } as never,+ cache as never,+ { refreshS3Availability: jest.fn() } as never,+ {} as never,+ undefined as never,+ );+ };++ it('reports connected:true when SELECT 1 succeeds', async () => {+ const status = await build(jest.fn().mockResolvedValue([{ '1': 1 }])).getStatus();+ expect(status.database.connected).toBe(true);+ });++ it('reports connected:false when the DB is initialized but SELECT 1 fails (backend died post-init)', async () => {+ const status = await build(jest.fn().mockRejectedValue(new Error('ECONNRESET'))).getStatus();+ expect(status.database.connected).toBe(false);+ });+});++describe('InfraController.getStatus queue job counts', () => {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 dataSource = { isInitialized: true, query: jest.fn().mockResolvedValue([{ '1': 1 }]) } as unknown;const engineFactory = { create: jest.fn() };const dockerService = { isDockerAvailable: () => false, getRunningBuiltinServices: jest.fn() };const cacheService = { isAvailable: jest.fn().mockResolvedValue(false), refreshS3Availability: jest.fn() };@@ -359,9 +389,9 @@ describe('InfraController.saveConfig rejects values that would inject extra env(fs.existsSync as jest.Mock).mockReturnValue(false);(fs.writeFileSync as jest.Mock).mockClear();- const result = newController().saveConfig({ engine: { browserArgs: malicious } });-- expect(result.saved).toBe(false);+ // A newline-injected value is rejected outright with a 4xx (BadRequestException), not masked as a+ // {saved:false} 200 — and nothing is written.+ expect(() => newController().saveConfig({ engine: { browserArgs: malicious } })).toThrow(BadRequestException);expect(fs.writeFileSync as jest.Mock).not.toHaveBeenCalled();});@@ -416,9 +446,8 @@ describe('InfraController.saveConfig engine selection (persist ENGINE_TYPE — Iit('rejects an unknown engine type and writes nothing', () => {(fs.writeFileSync as jest.Mock).mockClear();- const res = newController().saveConfig({ engine: { type: 'bogus' } });- expect(res.saved).toBe(false);- expect(res.message).toMatch(/unknown engine/i);+ // Rejected as a 4xx (BadRequestException naming the bad engine), not a {saved:false} 200.+ expect(() => newController().saveConfig({ engine: { type: 'bogus' } })).toThrow(/unknown engine/i);expect(fs.writeFileSync as jest.Mock).not.toHaveBeenCalled();});});@@ -799,7 +828,7 @@ describe('InfraController.getConfig (#226)', () => {});});-describe('InfraController.getStatus engine (F7 — reads the real engine.puppeteer.* keys)', () => {+describe('InfraController.getStatus engine (reads the real engine.puppeteer.* keys)', () => {// Pin the WA-Web version so getStatus does not fire the wa-version registry fetch (no network in tests).const savedWebVer = process.env.WWEBJS_WEB_VERSION;beforeAll(() => (process.env.WWEBJS_WEB_VERSION = 'off'));@@ -817,7 +846,7 @@ describe('InfraController.getStatus engine (F7 — reads the real engine.puppete};const config = { get: (key: string, def?: unknown) => (key in map ? map[key] : def) };const cache = { isAvailable: () => Promise.resolve(false) };- const ds = { isInitialized: true };+ const ds = { isInitialized: true, query: jest.fn().mockResolvedValue([{ '1': 1 }]) };const controller = new InfraController(config as never,ds as never,@@ -848,7 +877,7 @@ describe('InfraController.getStatus storage (reads the real storage.localPath keconst buildController = (map: Record<string, unknown>) => {const config = { get: (key: string, def?: unknown) => (key in map ? map[key] : def) };const cache = { isAvailable: () => Promise.resolve(false) };- const ds = { isInitialized: true };+ const ds = { isInitialized: true, query: jest.fn().mockResolvedValue([{ '1': 1 }]) };return new InfraController(config as never,ds as never,diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.tsindex f9c866226..069fede84 100644--- a/src/modules/infra/infra.controller.ts+++ b/src/modules/infra/infra.controller.ts@@ -1,4 +1,4 @@-import { Controller, Get, Put, Post, Body, BadRequestException, Optional } from '@nestjs/common';+import { Controller, Get, Put, Post, Body, BadRequestException, HttpException, Optional } from '@nestjs/common';import { ApiTags, ApiOperation, ApiResponse, ApiBody } from '@nestjs/swagger';import { InjectQueue } from '@nestjs/bullmq';import { Queue } from 'bullmq';@@ -249,14 +249,44 @@ export class InfraController {private readonly webhookQueue?: Queue,) {}+ /** Bound the DB liveness probe so a hung connection can't stall the status read. */+ private static readonly DB_PROBE_TIMEOUT_MS = 3000;++ /**+ * Active DB liveness probe: run `SELECT 1`, not just read `DataSource.isInitialized`. A backend+ * (notably Postgres) that dies AFTER init keeps `isInitialized` true until an explicit `.destroy()`,+ * so the old check reported the tile green while the DB was actually down. Bounded by a short+ * timeout; any error or timeout resolves to `false`. Mirrors `/health/ready`'s authoritative probe.+ */+ private async probeDbConnected(ds: DataSource): Promise<boolean> {+ if (!ds.isInitialized) return false;+ let timer: NodeJS.Timeout | undefined;+ try {+ await Promise.race([+ ds.query('SELECT 1'),+ new Promise((_resolve, reject) => {+ timer = setTimeout(() => reject(new Error('db probe timeout')), InfraController.DB_PROBE_TIMEOUT_MS);+ }),+ ]);+ return true;+ } catch {+ return false;+ } finally {+ if (timer) clearTimeout(timer);+ }+ }+@Get('status')@RequireRole(ApiKeyRole.ADMIN)@ApiOperation({ summary: 'Get infrastructure status' })@ApiResponse({ status: 200, description: 'Infrastructure status' })async getStatus(): Promise<InfraStatus> {- // Check both database connections- const mainDbConnected = this.mainDataSource.isInitialized;- const dataDbConnected = this.dataDataSource.isInitialized;+ // Active DB liveness probe (SELECT 1) on both connections in parallel — not just isInitialized,+ // which stays true after a Postgres backend dies until an explicit .destroy() (see probeDbConnected).+ const [mainDbConnected, dataDbConnected] = await Promise.all([+ this.probeDbConnected(this.mainDataSource),+ this.probeDbConnected(this.dataDataSource),+ ]);const dbConnected = mainDbConnected && dataDbConnected;const dbType = this.configService.get<string>('dataDatabase.type', 'sqlite');const dbHost = this.configService.get<string>('dataDatabase.host', 'localhost');@@ -640,6 +670,14 @@ export class InfraController {profiles,};} catch (error) {+ // A validation rejection (unknown engine type, or a newline-injected value) is a BadRequestException+ // and MUST surface as its real 4xx status, not be masked as an HTTP 200 {saved:false} — a client+ // branching on HTTP status alone would otherwise treat rejected input as success. Re-throw any+ // HttpException so the Nest layer maps it. A non-HTTP failure (e.g. a writeSecretFile disk/permission+ // error) stays a {saved:false} 200, preserving the dashboard's body.saved handling for I/O faults.+ if (error instanceof HttpException) {+ throw error;+ }return {message: `Failed to save configuration: ${error instanceof Error ? error.message : 'Unknown error'}`,saved: false,diff --git a/src/modules/integration/ingress-enqueue.service.spec.ts b/src/modules/integration/ingress-enqueue.service.spec.tsindex 31b5c8a73..76c0f7180 100644--- a/src/modules/integration/ingress-enqueue.service.spec.ts+++ b/src/modules/integration/ingress-enqueue.service.spec.ts@@ -1,4 +1,4 @@-import { IngressEnqueueService } from './ingress-enqueue.service';+import { IngressEnqueueService, resolveIngressJobOptions, buildIngressDeadLetterRow } from './ingress-enqueue.service';import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';import { ConfigService } from '@nestjs/config';@@ -28,7 +28,11 @@ describe('IngressEnqueueService', () => {expect(await svc.enqueue(data, 'd1')).toEqual({ outcome: 'queued' });- expect(queue.add).toHaveBeenCalledWith('ingress', data, { jobId: 'd1' });+ expect(queue.add).toHaveBeenCalledWith('ingress', data, {+ jobId: 'd1',+ attempts: 3,+ backoff: { type: 'exponential', delay: 5000 },+ });expect(loader.dispatchWebhookForInstance).not.toHaveBeenCalled();});@@ -56,7 +60,7 @@ describe('IngressEnqueueService', () => {(config.get as jest.Mock).mockReturnValue(false);const svc = new IngressEnqueueService(loader as PluginLoaderService, config as ConfigService, undefined);- expect(await svc.enqueue(data, 'd1')).toEqual({ outcome: 'failed' });+ expect(await svc.enqueue(data, 'd1')).toEqual({ outcome: 'failed', error: 'boom' });});it('falls back to inline dispatch (never throws) when queue.add() fails, e.g. Redis unreachable', async () => {@@ -67,7 +71,54 @@ describe('IngressEnqueueService', () => {const svc = new IngressEnqueueService(loader as PluginLoaderService, config as ConfigService, queue as never);expect(await svc.enqueue(data, 'd1')).toEqual({ outcome: 'dispatched' });- expect(queue.add).toHaveBeenCalledWith('ingress', data, { jobId: 'd1' });+ expect(queue.add).toHaveBeenCalledWith('ingress', data, {+ jobId: 'd1',+ attempts: 3,+ backoff: { type: 'exponential', delay: 5000 },+ });expect(loader.dispatchWebhookForInstance).toHaveBeenCalledWith(data);});++ describe('resolveIngressJobOptions', () => {+ it('defaults to 3 attempts with exponential backoff', () => {+ expect(resolveIngressJobOptions()).toEqual({ attempts: 3, backoff: { type: 'exponential', delay: 5000 } });+ });++ it('honors INGRESS_MAX_ATTEMPTS / INGRESS_RETRY_DELAY_MS overrides', () => {+ const prevA = process.env.INGRESS_MAX_ATTEMPTS;+ const prevD = process.env.INGRESS_RETRY_DELAY_MS;+ try {+ process.env.INGRESS_MAX_ATTEMPTS = '5';+ process.env.INGRESS_RETRY_DELAY_MS = '1000';+ expect(resolveIngressJobOptions()).toEqual({ attempts: 5, backoff: { type: 'exponential', delay: 1000 } });+ } finally {+ if (prevA === undefined) delete process.env.INGRESS_MAX_ATTEMPTS;+ else process.env.INGRESS_MAX_ATTEMPTS = prevA;+ if (prevD === undefined) delete process.env.INGRESS_RETRY_DELAY_MS;+ else process.env.INGRESS_RETRY_DELAY_MS = prevD;+ }+ });+ });++ describe('buildIngressDeadLetterRow', () => {+ it('mirrors the ingress-processor dead-letter shape so a redrive reads it back (attempts=1, redriven=false)', () => {+ expect(buildIngressDeadLetterRow(data, 'boom')).toEqual({+ direction: 'inbound',+ pluginId: 'chatwoot',+ instanceId: 'acct1',+ sessionId: 'sess-1',+ deliveryId: 'd1',+ attempts: 1,+ lastError: 'boom',+ payload: { route: 'chatwoot', providerConversationId: undefined, ingress: data.payload },+ redriven: false,+ });+ });++ it('defaults sessionId to null and supplies a fallback lastError when the error is absent', () => {+ const row = buildIngressDeadLetterRow({ ...data, sessionId: undefined }, undefined);+ expect(row.sessionId).toBeNull();+ expect(row.lastError).toBe('inline ingress dispatch failed');+ });+ });});diff --git a/src/modules/integration/ingress-enqueue.service.ts b/src/modules/integration/ingress-enqueue.service.tsindex 392a2a4cd..a7427e130 100644--- a/src/modules/integration/ingress-enqueue.service.ts+++ b/src/modules/integration/ingress-enqueue.service.ts@@ -4,15 +4,56 @@ import { InjectQueue } from '@nestjs/bullmq';import { Queue } from 'bullmq';import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';import { IngressJobData } from '../queue/processors/ingress.processor';+import { IntegrationDeliveryFailure } from './entities/integration-delivery-failure.entity';import { QUEUE_NAMES } from '../queue/queue-names';import { createLogger } from '../../common/services/logger.service';/*** Outcome of an enqueue attempt. 'queued' = handed to BullMQ; 'dispatched' = delivered inline; 'failed'- * = inline dispatch threw and was swallowed (the row stays durable for a redrive). enqueue() never- * throws, so callers use the outcome (not exceptions) to decide durability follow-up (e.g. redrive).+ * = inline dispatch threw and was swallowed (`error` carries the message). enqueue() never throws, so+ * callers use the outcome (not exceptions) to decide durability follow-up: a LIVE ingress delivery must+ * persist a dead-letter row on 'failed' (see buildIngressDeadLetterRow, wired at the IngressService+ * factory) so RedriveService can replay it; RedriveService itself calls enqueue() directly, because a+ * failed replay must keep its EXISTING dead-letter row redrivable rather than write a second one.*/-export type EnqueueOutcome = { outcome: 'queued' | 'dispatched' | 'failed' };+export type EnqueueOutcome = { outcome: 'queued' | 'dispatched' | 'failed'; error?: string };++/**+ * Retry policy for inbound ingress jobs. Previously the enqueue passed only a jobId, so BullMQ ran a+ * SINGLE attempt — a transient plugin-sandbox 5xx went straight to the DLQ with no retry (asymmetric+ * with the webhook queue). A few exponential-backoff attempts absorb transient failures; the+ * final-attempt DLQ write in ingress.processor is gated on `job.opts.attempts`, so it still fires+ * exactly once, only after these are exhausted. Env-overridable (INGRESS_MAX_ATTEMPTS /+ * INGRESS_RETRY_DELAY_MS); an invalid value falls back to the default.+ */+export function resolveIngressJobOptions(): { attempts: number; backoff: { type: 'exponential'; delay: number } } {+ const attempts = Number(process.env.INGRESS_MAX_ATTEMPTS);+ const delay = Number(process.env.INGRESS_RETRY_DELAY_MS);+ return {+ attempts: Number.isInteger(attempts) && attempts >= 1 ? attempts : 3,+ backoff: { type: 'exponential', delay: Number.isInteger(delay) && delay >= 0 ? delay : 5000 },+ };+}++/**+ * Build the dead-letter row for an ingress delivery whose inline-dispatch fallback failed. The shape+ * mirrors the row IngressProcessor writes on a final-attempt failure (direction / pluginId / instanceId+ * / sessionId / deliveryId / attempts / lastError / payload / redriven), so RedriveService reads either+ * back identically. `attempts` is 1 — the inline path makes a single dispatch attempt (no BullMQ retries).+ */+export function buildIngressDeadLetterRow(data: IngressJobData, error?: string): Partial<IntegrationDeliveryFailure> {+ return {+ direction: 'inbound',+ pluginId: data.pluginId,+ instanceId: data.instanceId,+ sessionId: data.sessionId ?? null,+ deliveryId: data.deliveryId,+ attempts: 1,+ lastError: error ?? 'inline ingress dispatch failed',+ payload: { route: data.route, providerConversationId: data.providerConversationId, ingress: data.payload },+ redriven: false,+ };+}/*** Shared queue-or-inline enqueue for inbound ingress jobs. Extracted out of IngressService's DI@@ -37,8 +78,9 @@ export class IngressEnqueueService {if (useQueue && this.ingressQueue) {try {- // jobId = deliveryId gives BullMQ exactly-once enqueue semantics.- await this.ingressQueue.add('ingress', data, { jobId });+ // jobId = deliveryId gives BullMQ exactly-once enqueue semantics; the retry policy adds bounded+ // exponential-backoff attempts so a transient failure retries before landing in the DLQ.+ await this.ingressQueue.add('ingress', data, { jobId, ...resolveIngressJobOptions() });return { outcome: 'queued' };} catch (err) {// Redis unreachable (enableOfflineQueue:false makes add() reject) — fall through to inline@@ -64,18 +106,20 @@ export class IngressEnqueueService {await this.loader.dispatchWebhookForInstance(data);return { outcome: 'dispatched' };} catch (err) {- // A duplicate delivery already 200s before this point, so a failure here is a real- // dispatch error. Log and swallow: the row is durably persisted for a later redrive,- // and the provider still gets its 202 (at-least-once, like the webhook fallback).- // The 'failed' outcome lets RedriveService avoid marking a DLQ row handled on a silent drop.- this.logger.error('Inline ingress dispatch failed', err instanceof Error ? err.message : String(err), {+ // A duplicate delivery already 200s before this point, so a failure here is a real dispatch error.+ // Log and swallow so the provider still gets its 202 (at-least-once, like the webhook fallback).+ // enqueue() intentionally does NOT write a dead-letter row here — it is shared with RedriveService+ // (a failed replay must not spawn a second DLQ row). The 'failed' outcome + error is returned so the+ // caller decides durability: the live-ingress wiring persists a DLQ row (buildIngressDeadLetterRow).+ const error = err instanceof Error ? err.message : String(err);+ this.logger.error('Inline ingress dispatch failed', error, {pluginId: data.pluginId,instanceId: data.instanceId,route: data.route,deliveryId: data.deliveryId,action: 'ingress_inline_dispatch_failed',});- return { outcome: 'failed' };+ return { outcome: 'failed', error };}}}diff --git a/src/modules/integration/integration-instance.controller.spec.ts b/src/modules/integration/integration-instance.controller.spec.tsindex 467f6930d..a4914253e 100644--- a/src/modules/integration/integration-instance.controller.spec.ts+++ b/src/modules/integration/integration-instance.controller.spec.ts@@ -2,6 +2,7 @@ import { IntegrationInstanceController } from './integration-instance.controllerimport { PluginInstanceService } from './plugin-instance.service';import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';import { AuditService } from '../audit/audit.service';+import { ScopeBindingService } from './scope-binding.service';// The provisioning bridge is what makes a minted instance's config reach the ingress worker: on// create/patch it mirrors the instance config into the plugin's per-session config and activates the@@ -40,7 +41,12 @@ describe('IntegrationInstanceController provisioning bridge', () => {updatedAt: new Date(0),}),} as unknown as PluginInstanceService;- const controller = new IntegrationInstanceController(instances, loader, audit);+ const controller = new IntegrationInstanceController(+ instances,+ loader,+ audit,+ new ScopeBindingService(instances, loader, audit),+ );await controller.create('chatwoot-adapter', {instanceId: 'acct1',@@ -70,7 +76,12 @@ describe('IntegrationInstanceController provisioning bridge', () => {update: jest.fn(),maskedView: (i: unknown) => i,} as unknown as PluginInstanceService;- const controller = new IntegrationInstanceController(instances, loader, audit);+ const controller = new IntegrationInstanceController(+ instances,+ loader,+ audit,+ new ScopeBindingService(instances, loader, audit),+ );await controller.patch('chatwoot-adapter', 'acct1', { enabled: false });@@ -93,7 +104,12 @@ describe('IntegrationInstanceController provisioning bridge', () => {list: jest.fn().mockResolvedValue([{ ...base, enabled: false }]), // only this one, now disabledmaskedView: (i: unknown) => i,} as unknown as PluginInstanceService;- const controller = new IntegrationInstanceController(instances, loader, audit);+ const controller = new IntegrationInstanceController(+ instances,+ loader,+ audit,+ new ScopeBindingService(instances, loader, audit),+ );await controller.patch('chatwoot-adapter', 'acct1', { enabled: false });@@ -118,7 +134,12 @@ describe('IntegrationInstanceController provisioning bridge', () => {]),maskedView: (i: unknown) => i,} as unknown as PluginInstanceService;- const controller = new IntegrationInstanceController(instances, loader, audit);+ const controller = new IntegrationInstanceController(+ instances,+ loader,+ audit,+ new ScopeBindingService(instances, loader, audit),+ );await controller.patch('chatwoot-adapter', 'acct1', { enabled: false });@@ -150,7 +171,12 @@ describe('IntegrationInstanceController provisioning bridge', () => {}),maskedView: (i: unknown) => i,} as unknown as PluginInstanceService;- const controller = new IntegrationInstanceController(instances, loader, audit);+ const controller = new IntegrationInstanceController(+ instances,+ loader,+ audit,+ new ScopeBindingService(instances, loader, audit),+ );await controller.patch('chatwoot-adapter', 'acct1', { sessionScope: 'sess-2' });diff --git a/src/modules/integration/integration-instance.controller.ts b/src/modules/integration/integration-instance.controller.tsindex ccb10e9f0..49fb227c1 100644--- a/src/modules/integration/integration-instance.controller.ts+++ b/src/modules/integration/integration-instance.controller.ts@@ -17,6 +17,7 @@ import { AuditAction } from '../audit/entities/audit-log.entity';import { AuditService } from '../audit/audit.service';import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';import { InstanceExistsError, PluginInstanceService } from './plugin-instance.service';+import { ScopeBindingService } from './scope-binding.service';import { PluginInstance } from './entities/plugin-instance.entity';import { buildIngressUrls } from './ingress-url';import { CreateInstanceDto, InstanceView, UpdateInstanceDto } from './dto/instance.dto';@@ -33,6 +34,7 @@ export class IntegrationInstanceController {private readonly instances: PluginInstanceService,private readonly loader: PluginLoaderService,private readonly audit: AuditService,+ private readonly scopeBinding: ScopeBindingService,) {}@Post()@@ -49,7 +51,7 @@ export class IntegrationInstanceController {void this.audit.logInfo(AuditAction.INTEGRATION_INSTANCE_CREATED, {metadata: { pluginId, instanceId: dto.instanceId },});- await this.applyScopeBinding(pluginId, inst.sessionScope, inst.config ?? {}, inst.enabled);+ await this.scopeBinding.applyScopeBinding(pluginId, inst.sessionScope, inst.config ?? {}, inst.enabled);return this.view(inst, routes, /* reveal */ true);} catch (err) {if (err instanceof InstanceExistsError) throw new ConflictException(err.message);@@ -108,9 +110,9 @@ export class IntegrationInstanceController {// firing with stale config. The new scope is (re)bound right after; teardown runs first with the new// scope already persisted, so the wildcard retirement check sees the current state correctly.if (previousScope !== updated.sessionScope) {- await this.applyScopeBinding(pluginId, previousScope, {}, false);+ await this.scopeBinding.applyScopeBinding(pluginId, previousScope, {}, false);}- await this.applyScopeBinding(pluginId, updated.sessionScope, updated.config ?? {}, updated.enabled);+ await this.scopeBinding.applyScopeBinding(pluginId, updated.sessionScope, updated.config ?? {}, updated.enabled);return this.view(updated, this.pluginRoutes(pluginId), false);}@@ -123,7 +125,7 @@ export class IntegrationInstanceController {// Delete the row FIRST, then tear down its scope: for a wildcard/null scope the teardown lists the// remaining instances to decide whether to retire '*', and that check must not count this instance.await this.instances.remove(pluginId, instanceId);- await this.applyScopeBinding(pluginId, scope, {}, false);+ await this.scopeBinding.applyScopeBinding(pluginId, scope, {}, false);void this.audit.logInfo(AuditAction.INTEGRATION_INSTANCE_DELETED, { metadata: { pluginId, instanceId } });}@@ -167,53 +169,4 @@ export class IntegrationInstanceController {ingressUrls: buildIngressUrls(process.env.BASE_URL, inst.pluginId, inst.instanceId, routes),};}-- // Bind an instance's config to the plugin's runtime so an ingress handler resolves it as ctx.config- // (see PluginLoaderService.dispatchWebhookForInstance) and activate the session — iff `activate` (a- // disabled or removed instance must not keep firing). A concrete scope writes sessionConfig[scope] and- // toggles that session in activeSessions; a null/'*' scope binds the base config + all sessions ('*').- // Best-effort: provisioning must not fail because the plugin is momentarily unloaded.- private async applyScopeBinding(- pluginId: string,- scope: string | null,- config: Record<string, unknown>,- activate: boolean,- ): Promise<void> {- try {- if (!scope || scope === '*') {- // 'all sessions' → base config + activate ['*']. The merged base config cannot be cleanly torn- // down (updatePluginConfig merges, so one instance's keys aren't separable), but the '*'- // activation CAN be retired: on deactivate, drop '*' from activeSessions ONLY when no OTHER- // enabled instance still binds a wildcard/null scope — otherwise disabling/deleting a wildcard- // instance would leave the plugin firing on every session with stale config.- if (activate) {- this.loader.updatePluginConfig(pluginId, config);- this.loader.setPluginSessions(pluginId, ['*']);- return;- }- const anyWildcardLeft = (await this.instances.list(pluginId)).some(- i => i.enabled && (!i.sessionScope || i.sessionScope === '*'),- );- if (!anyWildcardLeft) {- const current = this.loader.getPlugin(pluginId)?.activeSessions ?? [];- this.loader.setPluginSessions(- pluginId,- current.filter(s => s !== '*'),- );- }- return;- }- this.loader.setPluginSessionConfig(pluginId, scope, activate ? config : {});- const current = this.loader.getPlugin(pluginId)?.activeSessions ?? [];- const set = new Set(current.filter(s => s !== '*'));- if (activate) set.add(scope);- else set.delete(scope);- this.loader.setPluginSessions(pluginId, [...set]);- } catch (err) {- // Best-effort: don't fail provisioning if the plugin is momentarily unloaded.- void this.audit.logInfo(AuditAction.INTEGRATION_INSTANCE_UPDATED, {- metadata: { pluginId, scope, bridgeError: String(err) },- });- }- }}diff --git a/src/modules/integration/integration.module.ts b/src/modules/integration/integration.module.tsindex de6f9e6ae..7f1d9b4b9 100644--- a/src/modules/integration/integration.module.ts+++ b/src/modules/integration/integration.module.ts@@ -1,5 +1,6 @@import { Module } from '@nestjs/common';-import { TypeOrmModule } from '@nestjs/typeorm';+import { TypeOrmModule, getRepositoryToken } from '@nestjs/typeorm';+import { Repository } from 'typeorm';import { PluginInstance } from './entities/plugin-instance.entity';import { IngressEvent } from './entities/ingress-event.entity';import { IntegrationDeliveryFailure } from './entities/integration-delivery-failure.entity';@@ -7,11 +8,13 @@ import { PluginInstanceService } from './plugin-instance.service';import { IngressEventService } from './ingress-event.service';import { IngressService, IngressRouteDescriptor } from './ingress.service';import { IngressController } from './ingress.controller';-import { IngressEnqueueService } from './ingress-enqueue.service';+import { IngressEnqueueService, buildIngressDeadLetterRow } from './ingress-enqueue.service';import { RedriveService } from './redrive.service';import { RedriveController } from './redrive.controller';import { IntegrationInstanceController } from './integration-instance.controller';+import { ScopeBindingService } from './scope-binding.service';import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';+import { createLogger } from '../../common/services/logger.service';/*** Wires the @Public ingress HTTP surface: instance/event persistence services and the fast-ack@@ -28,21 +31,49 @@ import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';IngressEventService,IngressEnqueueService,RedriveService,+ ScopeBindingService,{provide: IngressService,- inject: [PluginInstanceService, IngressEventService, PluginLoaderService, IngressEnqueueService],+ inject: [+ PluginInstanceService,+ IngressEventService,+ PluginLoaderService,+ IngressEnqueueService,+ getRepositoryToken(IntegrationDeliveryFailure, 'data'),+ ],useFactory: (instances: PluginInstanceService,events: IngressEventService,loader: PluginLoaderService,ingressEnqueue: IngressEnqueueService,+ failures: Repository<IntegrationDeliveryFailure>,) => {+ const dlqLogger = createLogger('IngressEnqueue');return new IngressService({instances: { resolve: (pluginId, instanceId) => instances.resolve(pluginId, instanceId) },manifestRoute: (pluginId, route): IngressRouteDescriptor | undefined =>loader.getPlugin(pluginId)?.manifest.ingress?.find(r => r.route === route),events: { recordOrSkip: input => events.recordOrSkip(input) },- enqueue: (data, jobId) => ingressEnqueue.enqueue(data, jobId),+ // Live ingress delivery: on a swallowed inline-dispatch failure, persist a dead-letter row so+ // RedriveService can replay it — IngressService.handle() ignores the outcome and always 202s, so+ // nothing else would. RedriveService calls enqueue() directly (it is already replaying a DLQ+ // row) so it never double-writes here. The DLQ save is itself best-effort: a failure must not+ // 500 the ingress request (the delivery is already dedup-persisted, so the provider won't re-send).+ enqueue: async (data, jobId) => {+ const result = await ingressEnqueue.enqueue(data, jobId);+ if (result.outcome === 'failed') {+ try {+ await failures.save(buildIngressDeadLetterRow(data, result.error));+ } catch (err) {+ dlqLogger.error(+ 'Failed to persist ingress dead-letter row after inline dispatch failure',+ err instanceof Error ? err.message : String(err),+ { pluginId: data.pluginId, instanceId: data.instanceId, deliveryId: data.deliveryId },+ );+ }+ }+ return result;+ },now: () => Date.now(),});},diff --git a/src/modules/integration/plugin-instance.service.ts b/src/modules/integration/plugin-instance.service.tsindex 7f9145358..6d0b388a9 100644--- a/src/modules/integration/plugin-instance.service.ts+++ b/src/modules/integration/plugin-instance.service.ts@@ -88,6 +88,11 @@ export class PluginInstanceService {return this.repo.find({ where: { pluginId } });}+ /** Every persisted instance across all plugins — used by the boot-time scope-binding reconciliation. */+ listAll(): Promise<PluginInstance[]> {+ return this.repo.find();+ }+async regenerateSecret(pluginId: string, instanceId: string): Promise<PluginInstance> {const inst = await this.resolve(pluginId, instanceId);if (!inst) throw new Error(`instance ${instanceId} not found for plugin ${pluginId}`);diff --git a/src/modules/integration/scope-binding.service.spec.ts b/src/modules/integration/scope-binding.service.spec.tsnew file mode 100644index 000000000..817fdff14--- /dev/null+++ b/src/modules/integration/scope-binding.service.spec.ts@@ -0,0 +1,123 @@+import { ScopeBindingService } from './scope-binding.service';+import { PluginInstanceService } from './plugin-instance.service';+import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';+import { AuditService } from '../audit/audit.service';++// The boot-time reconciler re-derives each ENABLED instance's runtime scope binding from the persisted+// plugin_instances rows, so a binding lost at provisioning time (plugin momentarily unloaded) is+// restored on the next boot without an operator re-PATCH.+describe('ScopeBindingService.onApplicationBootstrap reconciliation', () => {+ function build(loaded = true) {+ const setPluginSessionConfig = jest.fn();+ const setPluginSessions = jest.fn();+ const updatePluginConfig = jest.fn();+ const loader = {+ getPlugin: jest.fn().mockReturnValue(loaded ? { manifest: { id: 'chatwoot' }, activeSessions: [] } : undefined),+ setPluginSessionConfig,+ setPluginSessions,+ updatePluginConfig,+ } as unknown as PluginLoaderService;+ const audit = { logInfo: jest.fn() } as unknown as AuditService;+ return { loader, audit, setPluginSessionConfig, setPluginSessions, updatePluginConfig };+ }++ it('restores an enabled concrete-scope instance (sessionConfig + activeSessions) on boot', async () => {+ const { loader, audit, setPluginSessionConfig, setPluginSessions } = build();+ const instances = {+ listAll: jest+ .fn()+ .mockResolvedValue([+ { pluginId: 'chatwoot', instanceId: 'a', sessionScope: 'sess-1', config: { baseUrl: 'x' }, enabled: true },+ ]),+ } as unknown as PluginInstanceService;++ await new ScopeBindingService(instances, loader, audit).onApplicationBootstrap();++ expect(setPluginSessionConfig).toHaveBeenCalledWith('chatwoot', 'sess-1', { baseUrl: 'x' });+ expect(setPluginSessions).toHaveBeenCalledWith('chatwoot', ['sess-1']);+ });++ it('restores an enabled wildcard/null-scope instance as base config + ["*"]', async () => {+ const { loader, audit, updatePluginConfig, setPluginSessions } = build();+ const instances = {+ listAll: jest+ .fn()+ .mockResolvedValue([+ { pluginId: 'chatwoot', instanceId: 'a', sessionScope: null, config: { token: 't' }, enabled: true },+ ]),+ } as unknown as PluginInstanceService;++ await new ScopeBindingService(instances, loader, audit).onApplicationBootstrap();++ expect(updatePluginConfig).toHaveBeenCalledWith('chatwoot', { token: 't' });+ expect(setPluginSessions).toHaveBeenCalledWith('chatwoot', ['*']);+ });++ it('does NOT activate a disabled instance (honors the real enabled flag, never force-activates)', async () => {+ const { loader, audit, setPluginSessionConfig, setPluginSessions } = build();+ const instances = {+ listAll: jest+ .fn()+ .mockResolvedValue([+ { pluginId: 'chatwoot', instanceId: 'a', sessionScope: 'sess-1', config: {}, enabled: false },+ ]),+ } as unknown as PluginInstanceService;++ await new ScopeBindingService(instances, loader, audit).onApplicationBootstrap();++ expect(setPluginSessionConfig).not.toHaveBeenCalled();+ expect(setPluginSessions).not.toHaveBeenCalled();+ });++ it('skips an instance whose plugin is not loaded', async () => {+ const { loader, audit, setPluginSessions } = build(/* loaded */ false);+ const instances = {+ listAll: jest+ .fn()+ .mockResolvedValue([{ pluginId: 'ghost', instanceId: 'a', sessionScope: 'sess-1', config: {}, enabled: true }]),+ } as unknown as PluginInstanceService;++ await new ScopeBindingService(instances, loader, audit).onApplicationBootstrap();++ expect(setPluginSessions).not.toHaveBeenCalled();+ });++ it('does not throw when listing instances fails (reconciliation is best-effort)', async () => {+ const { loader, audit } = build();+ const instances = {+ listAll: jest.fn().mockRejectedValue(new Error('db down')),+ } as unknown as PluginInstanceService;++ await expect(new ScopeBindingService(instances, loader, audit).onApplicationBootstrap()).resolves.toBeUndefined();+ });++ it('ends at ["*"] for a plugin with a wildcard + concrete instance regardless of DB row order (order-independent)', async () => {+ // Simulate the real loader, where setPluginSessions MUTATES the plugin's activeSessions so a later+ // applyScopeBinding reads the prior write — the exact shared-state mutation that made the old+ // unordered loop order-dependent (a concrete scope processed after a wildcard used to strip '*').+ const plugin = { manifest: { id: 'chatwoot' }, activeSessions: [] as string[] };+ const loader = {+ getPlugin: jest.fn(() => plugin),+ setPluginSessionConfig: jest.fn(),+ setPluginSessions: jest.fn((_id: string, sessions: string[]) => {+ plugin.activeSessions = sessions;+ }),+ updatePluginConfig: jest.fn(),+ } as unknown as PluginLoaderService;+ const audit = { logInfo: jest.fn() } as unknown as AuditService;++ const wildcard = { pluginId: 'chatwoot', instanceId: 'wild', sessionScope: null, config: {}, enabled: true };+ const concrete = { pluginId: 'chatwoot', instanceId: 'conc', sessionScope: 'sess-1', config: {}, enabled: true };++ for (const rowOrder of [+ [wildcard, concrete], // the order that used to lose '*'+ [concrete, wildcard],+ ] as const) {+ plugin.activeSessions = [];+ const instances = { listAll: jest.fn().mockResolvedValue(rowOrder) } as unknown as PluginInstanceService;+ await new ScopeBindingService(instances, loader, audit).onApplicationBootstrap();+ // The wildcard activation must survive in both row orders ('*' subsumes the concrete scope).+ expect(plugin.activeSessions).toContain('*');+ }+ });+});diff --git a/src/modules/integration/scope-binding.service.ts b/src/modules/integration/scope-binding.service.tsnew file mode 100644index 000000000..dda909ad6--- /dev/null+++ b/src/modules/integration/scope-binding.service.ts@@ -0,0 +1,128 @@+import { Injectable, OnApplicationBootstrap } from '@nestjs/common';+import { AuditAction } from '../audit/entities/audit-log.entity';+import { AuditService } from '../audit/audit.service';+import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';+import { PluginInstanceService } from './plugin-instance.service';+import { PluginInstance } from './entities/plugin-instance.entity';+import { createLogger } from '../../common/services/logger.service';++/**+ * Owns the provisioning bridge that makes a persisted plugin instance's config reach the ingress+ * worker: it mirrors the instance config into the plugin's per-session config and toggles the bound+ * session in activeSessions, so `dispatchWebhookForInstance` resolves it as `ctx.config`. Extracted+ * from IntegrationInstanceController so the SAME binding runs both on provisioning (create/patch/remove)+ * and as a boot-time reconciliation over the authoritative `plugin_instances` rows.+ */+@Injectable()+export class ScopeBindingService implements OnApplicationBootstrap {+ private readonly logger = createLogger('ScopeBindingService');++ constructor(+ private readonly instances: PluginInstanceService,+ private readonly loader: PluginLoaderService,+ private readonly audit: AuditService,+ ) {}++ /**+ * Re-derive every ENABLED instance's runtime scope binding from the persisted `plugin_instances`+ * rows, so a binding lost at provisioning time (the plugin was momentarily unloaded, so+ * applyScopeBinding was swallowed as an INFO audit) is restored on the next boot without an operator+ * re-PATCH — otherwise the row shows `enabled` but the ingress handler resolves base config only.+ * Runs after every module's onModuleInit (so PluginLoaderService has loaded all plugins).+ *+ * Only enabled rows are (re)activated: a disabled instance must never be force-activated, and issuing+ * its deactivate here could clear a scope a sibling ENABLED instance still binds. applyScopeBinding+ * already no-ops/logs for an unloaded plugin, and its internal try/catch means one instance's failure+ * cannot abort the rest.+ */+ async onApplicationBootstrap(): Promise<void> {+ let rows: PluginInstance[];+ try {+ rows = await this.instances.listAll();+ } catch (err) {+ this.logger.error('Scope-binding reconciliation skipped (failed to list instances)', String(err));+ return;+ }++ // Order-independent reconciliation: listAll() is repo.find() with no ORDER BY, so its row order+ // is DB/restart-dependent (differs between SQLite and Postgres). applyScopeBinding mutates the+ // SAME in-memory plugin.activeSessions each iteration — the concrete-scope path strips '*' while+ // the wildcard path overwrites with ['*'] — so for a plugin with BOTH a wildcard and a concrete+ // instance the final set would otherwise depend on row order (a concrete processed after a+ // wildcard drops the '*'). Sort concrete scopes before wildcard/null so the wildcard's ['*'] is+ // the last write (correct: '*' subsumes every concrete scope), making the result stable across+ // DBs and restarts. instanceId is the deterministic tiebreak among same-rank rows.+ rows.sort((a, b) => {+ const rank = (i: PluginInstance) => (!i.sessionScope || i.sessionScope === '*' ? 1 : 0);+ if (rank(a) !== rank(b)) return rank(a) - rank(b);+ return String(a.instanceId).localeCompare(String(b.instanceId));+ });++ let count = 0;+ for (const inst of rows) {+ if (!inst.enabled) continue;+ // Skip instances whose plugin isn't loaded — applyScopeBinding would only no-op/log for them.+ if (!this.loader.getPlugin(inst.pluginId)) continue;+ await this.applyScopeBinding(inst.pluginId, inst.sessionScope, inst.config ?? {}, true);+ count++;+ }++ if (count > 0) {+ this.logger.log(`Reconciled scope bindings for ${count} enabled plugin instance(s)`, {+ action: 'scope_bindings_reconciled',+ count,+ });+ }+ }++ /**+ * Bind an instance's config to the plugin's runtime so an ingress handler resolves it as ctx.config+ * (see PluginLoaderService.dispatchWebhookForInstance) and activate the session — iff `activate` (a+ * disabled or removed instance must not keep firing). A concrete scope writes sessionConfig[scope] and+ * toggles that session in activeSessions; a null/'*' scope binds the base config + all sessions ('*').+ * Best-effort: provisioning must not fail because the plugin is momentarily unloaded.+ */+ async applyScopeBinding(+ pluginId: string,+ scope: string | null,+ config: Record<string, unknown>,+ activate: boolean,+ ): Promise<void> {+ try {+ if (!scope || scope === '*') {+ // 'all sessions' → base config + activate ['*']. The merged base config cannot be cleanly torn+ // down (updatePluginConfig merges, so one instance's keys aren't separable), but the '*'+ // activation CAN be retired: on deactivate, drop '*' from activeSessions ONLY when no OTHER+ // enabled instance still binds a wildcard/null scope — otherwise disabling/deleting a wildcard+ // instance would leave the plugin firing on every session with stale config.+ if (activate) {+ this.loader.updatePluginConfig(pluginId, config);+ this.loader.setPluginSessions(pluginId, ['*']);+ return;+ }+ const anyWildcardLeft = (await this.instances.list(pluginId)).some(+ i => i.enabled && (!i.sessionScope || i.sessionScope === '*'),+ );+ if (!anyWildcardLeft) {+ const current = this.loader.getPlugin(pluginId)?.activeSessions ?? [];+ this.loader.setPluginSessions(+ pluginId,+ current.filter(s => s !== '*'),+ );+ }+ return;+ }+ this.loader.setPluginSessionConfig(pluginId, scope, activate ? config : {});+ const current = this.loader.getPlugin(pluginId)?.activeSessions ?? [];+ const set = new Set(current.filter(s => s !== '*'));+ if (activate) set.add(scope);+ else set.delete(scope);+ this.loader.setPluginSessions(pluginId, [...set]);+ } catch (err) {+ // Best-effort: don't fail provisioning if the plugin is momentarily unloaded.+ void this.audit.logInfo(AuditAction.INTEGRATION_INSTANCE_UPDATED, {+ metadata: { pluginId, scope, bridgeError: String(err) },+ });+ }+ }+}diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.tsindex f9fc9d678..a2e43dc36 100644--- a/src/modules/message/bulk-message.service.spec.ts+++ b/src/modules/message/bulk-message.service.spec.ts@@ -7,6 +7,7 @@ import { MessageStatus } from './entities/message.entity';import { SendBulkMessageDto } from './dto/bulk-message.dto';import { SessionService } from '../session/session.service';import { MessageService } from './message.service';+import { HookManager } from '../../core/hooks';import { SsrfBlockedError } from '../../common/security/ssrf-guard';/** Regression lock for the terminal-status decision (cancel-clobber + stopOnError overwrite bugs). */@@ -49,6 +50,14 @@ describe('BulkMessageService.onApplicationBootstrap', () => {{ provide: getRepositoryToken(MessageBatch, 'data'), useValue: repo },{ provide: SessionService, useValue: { getEngine: jest.fn() } },{ provide: MessageService, useValue: { saveOutgoingMessage: jest.fn() } },+ {+ provide: HookManager,+ useValue: {+ execute: jest+ .fn()+ .mockImplementation((_e: string, d: unknown) => Promise.resolve({ continue: true, data: d })),+ },+ },],}).compile();service = module.get<BulkMessageService>(BulkMessageService);@@ -99,6 +108,7 @@ describe('BulkMessageService.processBatch', () => {sendAudioMessage?: jest.Mock;};let sessionService: { getEngine: jest.Mock; findOne: jest.Mock };+ let hookManager: { execute: jest.Mock };const makeBatch = (messageCount: number): MessageBatch =>({@@ -124,6 +134,9 @@ describe('BulkMessageService.processBatch', () => {findOne: jest.fn().mockResolvedValue({ phone: '628' }),};messageService = { saveOutgoingMessage: jest.fn().mockResolvedValue(undefined) };+ hookManager = {+ execute: jest.fn().mockImplementation((_e: string, data: unknown) => Promise.resolve({ continue: true, data })),+ };repo = { findOne: jest.fn(), save: jest.fn().mockImplementation(b => Promise.resolve(b)) };const module: TestingModule = await Test.createTestingModule({providers: [@@ -131,6 +144,7 @@ describe('BulkMessageService.processBatch', () => {{ provide: getRepositoryToken(MessageBatch, 'data'), useValue: repo },{ provide: SessionService, useValue: sessionService },{ provide: MessageService, useValue: messageService },+ { provide: HookManager, useValue: hookManager },],}).compile();service = module.get<BulkMessageService>(BulkMessageService);@@ -191,6 +205,53 @@ describe('BulkMessageService.processBatch', () => {);});+ it('runs the message:sending gate for each bulk message (bulk no longer bypasses moderation)', async () => {+ repo.findOne.mockResolvedValue(makeBatch(1));++ await runProcessBatch();++ expect(hookManager.execute).toHaveBeenCalledWith(+ 'message:sending',+ expect.objectContaining({ type: 'text', sessionId: 's1' }),+ expect.objectContaining({ source: 'BulkMessageService' }),+ );+ expect(engine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'hi');+ });++ it('fails just the plugin-blocked message (continue:false) without calling the engine for it', async () => {+ repo.findOne.mockResolvedValue(makeBatch(1));+ hookManager.execute.mockResolvedValueOnce({ continue: false, data: {} }); // block message 0++ await runProcessBatch();++ expect(engine.sendTextMessage).not.toHaveBeenCalled();+ });++ it('fires message:failed when a bulk send fails (bulk failures were previously invisible to plugins)', async () => {+ repo.findOne.mockResolvedValue(makeBatch(1));+ engine.sendTextMessage.mockRejectedValueOnce(new Error('boom'));++ await runProcessBatch();++ expect(hookManager.execute).toHaveBeenCalledWith(+ 'message:failed',+ expect.objectContaining({ type: 'text', error: 'boom' }),+ expect.objectContaining({ source: 'BulkMessageService' }),+ );+ });++ it('does NOT fire message:failed when the gate blocks a bulk item (a block is a moderation decision, not a delivery failure)', async () => {+ repo.findOne.mockResolvedValue(makeBatch(1));+ hookManager.execute.mockResolvedValueOnce({ continue: false, data: {} }); // block message 0++ await runProcessBatch();++ expect(engine.sendTextMessage).not.toHaveBeenCalled();+ // A moderation block must not be reported as a delivery failure — matches single send, where a+ // block is a 400 with no message:failed.+ expect(hookManager.execute).not.toHaveBeenCalledWith('message:failed', expect.anything(), expect.anything());+ });+it('sends a bulk audio item with ptt as a voice note and persists type "voice"', async () => {engine.sendAudioMessage = jest.fn().mockResolvedValue({ id: 'wa2', timestamp: 222 });const batch = {@@ -320,6 +381,14 @@ describe('BulkMessageService.createBatch base64 media cap', () => {{ provide: getRepositoryToken(MessageBatch, 'data'), useValue: repo },{ provide: SessionService, useValue: { getEngine: jest.fn().mockReturnValue({}) } },{ provide: MessageService, useValue: { saveOutgoingMessage: jest.fn() } },+ {+ provide: HookManager,+ useValue: {+ execute: jest+ .fn()+ .mockImplementation((_e: string, d: unknown) => Promise.resolve({ continue: true, data: d })),+ },+ },],}).compile();service = module.get<BulkMessageService>(BulkMessageService);diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.tsindex 3c76f2ef3..eb11c8251 100644--- a/src/modules/message/bulk-message.service.ts+++ b/src/modules/message/bulk-message.service.ts@@ -13,6 +13,7 @@ import { SendBulkMessageDto } from './dto/bulk-message.dto';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 { SsrfBlockedError, SSRF_BLOCKED_CLIENT_MESSAGE } from '../../common/security/ssrf-guard';import { renderTemplate } from '../../common/utils/template-render';@@ -81,6 +82,7 @@ export class BulkMessageService implements OnApplicationBootstrap {private readonly batchRepository: Repository<MessageBatch>,private readonly sessionService: SessionService,private readonly messageService: MessageService,+ private readonly hookManager: HookManager,) {}/**@@ -259,9 +261,30 @@ export class BulkMessageService implements OnApplicationBootstrap {status: BatchMessageStatus.PENDING,};+ // Hoisted so the failure hook below can report the exact (variable-applied / plugin-modified)+ // content that was attempted, even when applyVariables or the send throws.+ let content: BulkMessageContent = msg.content;+ // Set when the message:sending gate blocked this item, so the catch treats it as a moderation+ // decision (not a delivery failure) and skips message:failed — matching the single-send path,+ // where a block is a 400 with no failure hook.+ let blockedByPlugin = false;try {// Apply template variables- const content: BulkMessageContent = this.applyVariables(msg.content, msg.variables);+ content = this.applyVariables(msg.content, msg.variables);++ // Per-message moderation gate — the SAME message:sending hook single sends use, so a+ // compliance/moderation plugin sees bulk traffic too (bulk previously bypassed it entirely).+ // A block fails just THIS message (honouring stopOnError below); a plugin may also rewrite it.+ const gate = await this.hookManager.execute(+ 'message:sending',+ { sessionId: batch.sessionId, input: content, type: msg.type },+ { sessionId: batch.sessionId, source: 'BulkMessageService' },+ );+ if (!gate.continue) {+ blockedByPlugin = true;+ throw new BadRequestException('Message sending blocked by plugin');+ }+ content = (gate.data as { input: BulkMessageContent }).input;// Send message based on typeconst messageResult = await this.sendMessage(engine, msg.chatId, msg.type, content);@@ -286,6 +309,17 @@ export class BulkMessageService implements OnApplicationBootstrap {batch.progress.failed++;batch.progress.pending--;+ // Fire message:failed so alerting/analytics plugins observe bulk failures too (previously+ // none) — but NOT for a plugin gate-block, which is a moderation decision, not a delivery+ // failure (matches single send, where a block is a 400 with no message:failed).+ if (!blockedByPlugin) {+ await this.hookManager.execute(+ 'message:failed',+ { sessionId: batch.sessionId, error: sanitized.message, input: content, type: msg.type },+ { sessionId: batch.sessionId, source: 'BulkMessageService' },+ );+ }+this.logger.warn(`Batch ${batch.batchId}: Failed message ${i + 1} to ${msg.chatId}: ${sanitized.message}`);if (batch.options.stopOnError) {diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.tsindex d8074e75c..cbae076ff 100644--- a/src/modules/message/message.service.spec.ts+++ b/src/modules/message/message.service.spec.ts@@ -70,10 +70,11 @@ describe('MessageService', () => {};hookManager = {- execute: jest.fn().mockResolvedValue({- continue: true,- data: { sessionId: 'sess-1', input: { chatId: '[email protected]', text: 'Hello' }, type: 'text' },- }),+ // Echo the input straight back so the message:sending gate is a pass-through by default; specific+ // tests override with continue:false (block) or a modified input.+ execute: jest+ .fn()+ .mockImplementation((_event: string, data: unknown) => Promise.resolve({ continue: true, data })),};templateService = {@@ -290,6 +291,64 @@ describe('MessageService', () => {});});+ // ── send-hook chokepoint ──────────────────────────────────────────++ describe('send-hook chokepoint (message:sending gate + message:failed across all senders)', () => {+ it('runs the message:sending gate for a media send (sendImage) tagged with the media type', async () => {+ await service.sendImage('sess-1', { chatId: '[email protected]', url: 'https://e.com/i.jpg', caption: 'hi' });+ expect(hookManager.execute).toHaveBeenCalledWith(+ 'message:sending',+ expect.objectContaining({ type: 'image' }),+ expect.any(Object),+ );+ });++ it('runs the message:sending gate for an extended send (sendPoll)', async () => {+ await service.sendPoll('sess-1', { chatId: '[email protected]', name: 'Q?', options: ['a', 'b'] });+ expect(hookManager.execute).toHaveBeenCalledWith(+ 'message:sending',+ expect.objectContaining({ type: 'poll' }),+ expect.any(Object),+ );+ });++ it('lets a plugin block a media send (continue:false) before the engine is called', async () => {+ (hookManager.execute as jest.Mock).mockResolvedValueOnce({ continue: false, data: {} });+ await expect(service.sendImage('sess-1', { chatId: '[email protected]', url: 'https://e.com/i.jpg' })).rejects.toThrow(+ 'Message sending blocked by plugin',+ );+ expect(mockEngine.sendImageMessage).not.toHaveBeenCalled();+ });++ it('threads a plugin-modified media input through to the engine', async () => {+ (hookManager.execute as jest.Mock).mockResolvedValueOnce({+ continue: true,+ data: {+ sessionId: 'sess-1',+ type: 'image',+ input: { chatId: '[email protected]', url: 'https://e.com/mod.jpg', caption: 'edited' },+ },+ });+ await service.sendImage('sess-1', { chatId: '[email protected]', url: 'https://e.com/i.jpg', caption: 'orig' });+ expect(mockEngine.sendImageMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ data: 'https://e.com/mod.jpg', caption: 'edited' }),+ );+ });++ it('fires message:failed when a media send fails (previously only sendText did)', async () => {+ mockEngine.sendImageMessage.mockRejectedValueOnce(new Error('engine down'));+ await expect(service.sendImage('sess-1', { chatId: '[email protected]', url: 'https://e.com/i.jpg' })).rejects.toThrow(+ 'engine down',+ );+ expect(hookManager.execute).toHaveBeenCalledWith(+ 'message:failed',+ expect.objectContaining({ type: 'image', error: 'engine down' }),+ expect.any(Object),+ );+ });+ });+// ── sendImage ─────────────────────────────────────────────────────describe('sendImage', () => {@@ -345,6 +404,24 @@ describe('MessageService', () => {).rejects.toMatchObject({ response: { message: 'Destination address is not allowed' } });});+ it('does not leak the SSRF internal address into the message:failed hook payload (media sends now route there)', async () => {+ mockEngine.sendImageMessage.mockRejectedValueOnce(+ new SsrfBlockedError('Host x resolves to a blocked internal address: 169.254.169.254'),+ );++ await expect(+ service.sendImage('sess-1', { chatId: '[email protected]', url: 'http://127.0.0.1/x.png' }),+ ).rejects.toThrow();++ const calls = (hookManager.execute as jest.Mock).mock.calls as [string, { error?: string }, unknown][];+ const failedCall = calls.find(c => c[0] === 'message:failed');+ expect(failedCall).toBeDefined();+ // The hook payload (now delivered to plugins for media sends) carries the generic message, NOT+ // the resolved internal IP that the raw SsrfBlockedError.message contains.+ expect(failedCall![1].error).toBe('Destination address is not allowed');+ expect(failedCall![1].error).not.toContain('169.254.169.254');+ });+it('rejects a base64 image over the media cap before sending or persisting', async () => {process.env.MEDIA_DOWNLOAD_MAX_BYTES = '1024';try {@@ -566,6 +643,24 @@ describe('MessageService', () => {expect(repository.create).toHaveBeenCalledWith(expect.objectContaining({ type: 'voice' }));});+ it('labels the message:sending gate "voice" for a voice note (matches the persisted/failed type)', async () => {+ await service.sendAudio('sess-1', { chatId: '[email protected]', url: 'https://example.com/voice', ptt: true });+ expect(hookManager.execute).toHaveBeenCalledWith(+ 'message:sending',+ expect.objectContaining({ type: 'voice' }),+ expect.any(Object),+ );+ });++ it('labels the message:sending gate "audio" for a plain (non-ptt) audio send', async () => {+ await service.sendAudio('sess-1', { chatId: '[email protected]', url: 'https://example.com/audio.ogg' });+ expect(hookManager.execute).toHaveBeenCalledWith(+ 'message:sending',+ expect.objectContaining({ type: 'audio' }),+ expect.any(Object),+ );+ });+it('persists a plain audio send (no ptt) as type "audio"', async () => {await service.sendAudio('sess-1', { chatId: '[email protected]', url: 'https://example.com/audio.ogg' });expect(repository.create).toHaveBeenCalledWith(expect.objectContaining({ type: 'audio' }));diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex 6856c3be9..a1dd6ceec 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -1,4 +1,5 @@-import { Injectable, BadRequestException } from '@nestjs/common';+import { Injectable, BadRequestException, Optional } from '@nestjs/common';+import { ConfigService } from '@nestjs/config';import { InjectRepository } from '@nestjs/typeorm';import { Repository } from 'typeorm';import { SessionService } from '../session/session.service';@@ -13,6 +14,7 @@ import { renderTemplate } from '../../common/utils/template-render';import { createLogger } from '../../common/services/logger.service';import { SsrfBlockedError, SSRF_BLOCKED_CLIENT_MESSAGE } from '../../common/security/ssrf-guard';import { userPart } from '../../engine/identity/wa-id';+import { resolveFeatureFlags } from '../../config/feature-flags';import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';export interface GetMessagesOptions {@@ -34,22 +36,12 @@ export class MessageService {private readonly hookManager: HookManager,private readonly templateService: TemplateService,private readonly lidMappingStore: LidMappingStoreService,+ @Optional()+ private readonly configService?: ConfigService,) {}async sendText(sessionId: string, dto: SendTextMessageDto): Promise<MessageResponseDto> {- // Execute hook before sending - plugins can modify or block- const { continue: shouldContinue, data: hookData } = await this.hookManager.execute(- 'message:sending',- { sessionId, input: dto, type: 'text' },- { sessionId, source: 'MessageService' },- );-- if (!shouldContinue) {- throw new BadRequestException('Message sending blocked by plugin');- }-- // Use potentially modified input- const finalDto = (hookData as { input: SendTextMessageDto }).input;+ const finalDto = await this.applySendingGate(sessionId, 'text', dto);const engine = this.getEngine(sessionId);@@ -70,16 +62,9 @@ export class MessageService {? await engine.sendTextMessage(finalDto.chatId, finalDto.text, finalDto.mentions): await engine.sendTextMessage(finalDto.chatId, finalDto.text);} catch (error) {- // The SEND itself failed — mark FAILED and fire the failure hook (a post-send persistence fault is+ // The SEND itself failed — mark FAILED + fire message:failed (a post-send persistence fault is// handled separately by persistSentState and must NOT land here).- message.status = MessageStatus.FAILED;- await this.messageRepository.save(message);- await this.hookManager.execute(- 'message:failed',- { sessionId, error: error instanceof Error ? error.message : String(error), input: finalDto },- { sessionId, source: 'MessageService' },- );- throw error;+ return this.failSend(sessionId, 'text', message, finalDto, error);}// Note: the `message:sent` hook is emitted solely by SessionService.onMessageCreate (engine@@ -88,6 +73,59 @@ export class MessageService {return this.persistSentState(message, result);}+ /**+ * Run the pre-send `message:sending` plugin gate for one outbound message and return the+ * (possibly plugin-modified) input, or throw BadRequestException if a plugin blocked the send.+ * Centralised so EVERY public sender — text, media, and extended (location/contact/poll/sticker/+ * reply/forward) — passes through the same moderation chokepoint, instead of only `sendText`.+ */+ private async applySendingGate<T extends object>(sessionId: string, type: string, input: T): Promise<T> {+ const { continue: shouldContinue, data: hookData } = await this.hookManager.execute(+ 'message:sending',+ { sessionId, input, type },+ { sessionId, source: 'MessageService' },+ );+ if (!shouldContinue) {+ throw new BadRequestException('Message sending blocked by plugin');+ }+ // Use the potentially plugin-modified input.+ return (hookData as { input: T }).input;+ }++ /**+ * Mark a send as FAILED, fire the `message:failed` plugin hook, then throw a client-facing error.+ * Centralised so failure notifications cover every sender (previously only `sendText` fired+ * `message:failed`; media/extended sends failed silently to plugins). The post-send persistence-fault+ * path (persistSentState) deliberately does NOT route here — a message the engine already accepted+ * must never be reported as a send failure.+ */+ private async failSend(+ sessionId: string,+ type: string,+ message: Message,+ input: unknown,+ error: unknown,+ ): Promise<never> {+ await this.saveFailedMessage(message);+ // Sanitize the hook payload: an SSRF block's raw .message names the resolved internal address+ // (a recon/DNS-rebind oracle) — the client-facing throw below already maps it to a generic+ // message via toClientFacingError, and the message:failed hook must not expose more than the+ // client sees. Now that every media/extended sender routes here, this is the chokepoint that+ // keeps SSRF detail out of plugin hands (bulk does the same via sanitizeBatchError).+ const hookError =+ error instanceof SsrfBlockedError+ ? SSRF_BLOCKED_CLIENT_MESSAGE+ : error instanceof Error+ ? error.message+ : String(error);+ await this.hookManager.execute(+ 'message:failed',+ { sessionId, error: hookError, input, type },+ { sessionId, source: 'MessageService' },+ );+ throw this.toClientFacingError(error);+ }+/*** Resolve a stored template, render its body (with optional header/footer* flattened using newlines) using the supplied variables, and delegate to the@@ -111,102 +149,106 @@ export class MessageService {}async sendImage(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {+ const finalDto = await this.applySendingGate(sessionId, 'image', dto);const engine = this.getEngine(sessionId);- const media = this.buildMediaInput(dto);+ const media = this.buildMediaInput(finalDto);// Save message as pending BEFORE sendingconst message = await this.saveOutgoingMessage(sessionId, {- chatId: dto.chatId,- body: dto.caption || '',+ chatId: finalDto.chatId,+ body: finalDto.caption || '',type: 'image',metadata: {- media: { mimetype: dto.mimetype, filename: dto.filename, data: dto.base64 || dto.url },+ media: { mimetype: finalDto.mimetype, filename: finalDto.filename, data: finalDto.base64 || finalDto.url },},});let result: MessageResult;try {- result = await engine.sendImageMessage(dto.chatId, media);+ result = await engine.sendImageMessage(finalDto.chatId, media);} catch (error) {- await this.saveFailedMessage(message);- throw this.toClientFacingError(error);+ return this.failSend(sessionId, 'image', message, finalDto, error);}return this.persistSentState(message, result);}async sendVideo(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {+ const finalDto = await this.applySendingGate(sessionId, 'video', dto);const engine = this.getEngine(sessionId);- const media = this.buildMediaInput(dto);+ const media = this.buildMediaInput(finalDto);// Save message as pending BEFORE sendingconst message = await this.saveOutgoingMessage(sessionId, {- chatId: dto.chatId,- body: dto.caption || '',+ chatId: finalDto.chatId,+ body: finalDto.caption || '',type: 'video',metadata: {- media: { mimetype: dto.mimetype, filename: dto.filename, data: dto.base64 || dto.url },+ media: { mimetype: finalDto.mimetype, filename: finalDto.filename, data: finalDto.base64 || finalDto.url },},});let result: MessageResult;try {- result = await engine.sendVideoMessage(dto.chatId, media);+ result = await engine.sendVideoMessage(finalDto.chatId, media);} catch (error) {- await this.saveFailedMessage(message);- throw this.toClientFacingError(error);+ return this.failSend(sessionId, 'video', message, finalDto, error);}return this.persistSentState(message, result);}async sendAudio(sessionId: string, dto: SendAudioMessageDto): Promise<MessageResponseDto> {+ // Label a PTT send 'voice' in the gate (not 'audio') so message:sending, message:failed, and the+ // persisted row all carry the same type for one outbound voice note — failSend and the saved row+ // already use `finalDto.ptt ? 'voice' : 'audio'`.+ const finalDto = await this.applySendingGate(sessionId, dto.ptt ? 'voice' : 'audio', dto);const engine = this.getEngine(sessionId);// Voice notes need a real audio codec; default to ogg/opus when the caller omits a mimetype so the// wire message and the persisted record agree. Resolved BEFORE buildMediaInput so its base64// mimetype guard sees the effective type. buildMediaInput itself stays generic (shared by all media).- const audioDto = dto.ptt && !dto.mimetype ? { ...dto, mimetype: 'audio/ogg; codecs=opus' } : dto;+ const audioDto =+ finalDto.ptt && !finalDto.mimetype ? { ...finalDto, mimetype: 'audio/ogg; codecs=opus' } : finalDto;const media = this.buildMediaInput(audioDto);- media.ptt = dto.ptt;+ media.ptt = finalDto.ptt;// Save message as pending BEFORE sending. A PTT send is a 'voice' note (matches inbound// classification, the outbound webhook echo, stats, and the dashboard), not a plain 'audio' file.const message = await this.saveOutgoingMessage(sessionId, {- chatId: dto.chatId,- type: dto.ptt ? 'voice' : 'audio',+ chatId: finalDto.chatId,+ type: finalDto.ptt ? 'voice' : 'audio',metadata: {- media: { mimetype: audioDto.mimetype, filename: dto.filename, data: dto.base64 || dto.url },+ media: { mimetype: audioDto.mimetype, filename: finalDto.filename, data: finalDto.base64 || finalDto.url },},});let result: MessageResult;try {- result = await engine.sendAudioMessage(dto.chatId, media);+ result = await engine.sendAudioMessage(finalDto.chatId, media);} catch (error) {- await this.saveFailedMessage(message);- throw this.toClientFacingError(error);+ return this.failSend(sessionId, finalDto.ptt ? 'voice' : 'audio', message, finalDto, error);}return this.persistSentState(message, result);}async sendDocument(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {+ const finalDto = await this.applySendingGate(sessionId, 'document', dto);const engine = this.getEngine(sessionId);- const media = this.buildMediaInput(dto);+ const media = this.buildMediaInput(finalDto);// Save message as pending BEFORE sendingconst message = await this.saveOutgoingMessage(sessionId, {- chatId: dto.chatId,- body: dto.caption || dto.filename || '',+ chatId: finalDto.chatId,+ body: finalDto.caption || finalDto.filename || '',type: 'document',metadata: {- media: { mimetype: dto.mimetype, filename: dto.filename, data: dto.base64 || dto.url },+ media: { mimetype: finalDto.mimetype, filename: finalDto.filename, data: finalDto.base64 || finalDto.url },},});let result: MessageResult;try {- result = await engine.sendDocumentMessage(dto.chatId, media);+ result = await engine.sendDocumentMessage(finalDto.chatId, media);} catch (error) {- await this.saveFailedMessage(message);- throw this.toClientFacingError(error);+ return this.failSend(sessionId, 'document', message, finalDto, error);}return this.persistSentState(message, result);}@@ -272,26 +314,26 @@ export class MessageService {sessionId: string,dto: { chatId: string; latitude: number; longitude: number; description?: string; address?: string },): Promise<MessageResponseDto> {+ const finalDto = await this.applySendingGate(sessionId, 'location', dto);const engine = this.getEngine(sessionId);// Save message as pending BEFORE sendingconst message = await this.saveOutgoingMessage(sessionId, {- chatId: dto.chatId,- body: `📍 ${dto.description || 'Location'}`,+ chatId: finalDto.chatId,+ body: `📍 ${finalDto.description || 'Location'}`,type: 'location',});let result: MessageResult;try {- result = await engine.sendLocationMessage(dto.chatId, {- latitude: dto.latitude,- longitude: dto.longitude,- description: dto.description,- address: dto.address,+ result = await engine.sendLocationMessage(finalDto.chatId, {+ latitude: finalDto.latitude,+ longitude: finalDto.longitude,+ description: finalDto.description,+ address: finalDto.address,});} catch (error) {- await this.saveFailedMessage(message);- throw this.toClientFacingError(error);+ return this.failSend(sessionId, 'location', message, finalDto, error);}return this.persistSentState(message, result);}@@ -300,24 +342,24 @@ export class MessageService {sessionId: string,dto: { chatId: string; contactName: string; contactNumber: string },): Promise<MessageResponseDto> {+ const finalDto = await this.applySendingGate(sessionId, 'contact', dto);const engine = this.getEngine(sessionId);// Save message as pending BEFORE sendingconst message = await this.saveOutgoingMessage(sessionId, {- chatId: dto.chatId,- body: `📇 ${dto.contactName}`,+ chatId: finalDto.chatId,+ body: `📇 ${finalDto.contactName}`,type: 'contact',});let result: MessageResult;try {- result = await engine.sendContactMessage(dto.chatId, {- name: dto.contactName,- number: dto.contactNumber,+ result = await engine.sendContactMessage(finalDto.chatId, {+ name: finalDto.contactName,+ number: finalDto.contactNumber,});} catch (error) {- await this.saveFailedMessage(message);- throw this.toClientFacingError(error);+ return this.failSend(sessionId, 'contact', message, finalDto, error);}return this.persistSentState(message, result);}@@ -326,49 +368,49 @@ export class MessageService {sessionId: string,dto: { chatId: string; name: string; options: string[]; allowMultipleAnswers?: boolean },): Promise<MessageResponseDto> {+ const finalDto = await this.applySendingGate(sessionId, 'poll', dto);const engine = this.getEngine(sessionId);// Save message as pending BEFORE sending. A poll has no plain-text body, so store the// question — that keeps the message history readable.const message = await this.saveOutgoingMessage(sessionId, {- chatId: dto.chatId,- body: `📊 ${dto.name}`,+ chatId: finalDto.chatId,+ body: `📊 ${finalDto.name}`,type: 'poll',});let result: MessageResult;try {- result = await engine.sendPollMessage(dto.chatId, {- name: dto.name,- options: dto.options,- allowMultipleAnswers: dto.allowMultipleAnswers === true,+ result = await engine.sendPollMessage(finalDto.chatId, {+ name: finalDto.name,+ options: finalDto.options,+ allowMultipleAnswers: finalDto.allowMultipleAnswers === true,});} catch (error) {- await this.saveFailedMessage(message);- throw this.toClientFacingError(error);+ return this.failSend(sessionId, 'poll', message, finalDto, error);}return this.persistSentState(message, result);}async sendSticker(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {+ const finalDto = await this.applySendingGate(sessionId, 'sticker', dto);const engine = this.getEngine(sessionId);- const media = this.buildMediaInput(dto);+ const media = this.buildMediaInput(finalDto);// Save message as pending BEFORE sendingconst message = await this.saveOutgoingMessage(sessionId, {- chatId: dto.chatId,+ chatId: finalDto.chatId,type: 'sticker',metadata: {- media: { mimetype: dto.mimetype, filename: dto.filename, data: dto.base64 || dto.url },+ media: { mimetype: finalDto.mimetype, filename: finalDto.filename, data: finalDto.base64 || finalDto.url },},});let result: MessageResult;try {- result = await engine.sendStickerMessage(dto.chatId, media);+ result = await engine.sendStickerMessage(finalDto.chatId, media);} catch (error) {- await this.saveFailedMessage(message);- throw this.toClientFacingError(error);+ return this.failSend(sessionId, 'sticker', message, finalDto, error);}return this.persistSentState(message, result);}@@ -377,35 +419,35 @@ export class MessageService {sessionId: string,dto: { chatId: string; quotedMessageId: string; text: string },): Promise<MessageResponseDto> {+ const finalDto = await this.applySendingGate(sessionId, 'reply', dto);const engine = this.getEngine(sessionId);// Resolve the quoted message body (best-effort) so the dashboard can render the reply preview.let quotedBody = '';try {const quoted = await this.messageRepository.findOne({- where: { sessionId, waMessageId: dto.quotedMessageId },+ where: { sessionId, waMessageId: finalDto.quotedMessageId },});quotedBody = quoted?.body || '';} catch (err) {- this.logger.warn(`Failed to resolve quoted message ${dto.quotedMessageId}`, { error: String(err) });+ this.logger.warn(`Failed to resolve quoted message ${finalDto.quotedMessageId}`, { error: String(err) });}// Save message as pending BEFORE sendingconst message = await this.saveOutgoingMessage(sessionId, {- chatId: dto.chatId,- body: dto.text,+ chatId: finalDto.chatId,+ body: finalDto.text,type: 'text',metadata: {- quotedMessage: { id: dto.quotedMessageId, body: quotedBody },+ quotedMessage: { id: finalDto.quotedMessageId, body: quotedBody },},});let result: MessageResult;try {- result = await engine.replyToMessage(dto.chatId, dto.quotedMessageId, dto.text);+ result = await engine.replyToMessage(finalDto.chatId, finalDto.quotedMessageId, finalDto.text);} catch (error) {- await this.saveFailedMessage(message);- throw this.toClientFacingError(error);+ return this.failSend(sessionId, 'reply', message, finalDto, error);}return this.persistSentState(message, result);}@@ -414,21 +456,21 @@ export class MessageService {sessionId: string,dto: { fromChatId: string; toChatId: string; messageId: string },): Promise<MessageResponseDto> {+ const finalDto = await this.applySendingGate(sessionId, 'forward', dto);const engine = this.getEngine(sessionId);// Save message as pending BEFORE sendingconst message = await this.saveOutgoingMessage(sessionId, {- chatId: dto.toChatId,+ chatId: finalDto.toChatId,body: '[Forwarded]',type: 'forward',});let result: MessageResult;try {- result = await engine.forwardMessage(dto.fromChatId, dto.toChatId, dto.messageId);+ result = await engine.forwardMessage(finalDto.fromChatId, finalDto.toChatId, finalDto.messageId);} catch (error) {- await this.saveFailedMessage(message);- throw this.toClientFacingError(error);+ return this.failSend(sessionId, 'forward', message, finalDto, 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.@@ -587,10 +629,11 @@ export class MessageService {* Note: this covers single sends only; bulk sends use their own `delayBetweenMessages` throttle.*/private async simulateTypingIfEnabled(engine: IWhatsAppEngine, chatId: string, text: string): Promise<void> {- if (process.env.SIMULATE_TYPING === 'false') return;+ const { simulateTyping, simulateTypingMaxMs } = resolveFeatureFlags(this.configService);+ if (!simulateTyping) return;try {await engine.sendChatState(chatId, 'typing');- const maxMs = Number(process.env.SIMULATE_TYPING_MAX_MS) || 5000;+ const maxMs = simulateTypingMaxMs;const planned = Math.min(maxMs, 500 + text.length * 45);const jittered = Math.round(planned * (0.85 + Math.random() * 0.3)); // ±15% so it isn't metronomicawait new Promise(resolve => setTimeout(resolve, jittered));diff --git a/src/modules/metrics/metrics.service.spec.ts b/src/modules/metrics/metrics.service.spec.tsindex c5ac6e09a..8cd2eca4c 100644--- a/src/modules/metrics/metrics.service.spec.ts+++ b/src/modules/metrics/metrics.service.spec.ts@@ -2,6 +2,7 @@ import { NotFoundException, UnauthorizedException } from '@nestjs/common';import { ConfigService } from '@nestjs/config';import { MetricsService, METRICS_RENDER_TTL_MS } from './metrics.service';import { StatsService, OverviewStats } from '../stats/stats.service';+import { getWebhookDeliveryFailuresTotal } from '../../common/metrics/webhook-delivery-metrics';describe('MetricsService', () => {const overview: OverviewStats = {@@ -57,6 +58,9 @@ describe('MetricsService', () => {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');+ // 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()}`);expect(out.endsWith('\n')).toBe(true);});diff --git a/src/modules/metrics/metrics.service.ts b/src/modules/metrics/metrics.service.tsindex eb0fe1d9e..1c3f974de 100644--- a/src/modules/metrics/metrics.service.ts+++ b/src/modules/metrics/metrics.service.ts@@ -2,6 +2,7 @@ import { Injectable, NotFoundException, UnauthorizedException } from '@nestjs/coimport { ConfigService } from '@nestjs/config';import { timingSafeEqual } from 'crypto';import { StatsService } from '../stats/stats.service';+import { getWebhookDeliveryFailuresTotal } from '../../common/metrics/webhook-delivery-metrics';/*** Prometheus exposition for OpenWA. Kept dependency-free (no prom-client) — the@@ -97,6 +98,12 @@ export class MetricsService {lines.push('# TYPE openwa_messages_failed_total counter');lines.push(`openwa_messages_failed_total ${overview.messages.failed}`);+ lines.push(+ '# HELP openwa_webhook_delivery_failures_total Webhook deliveries that terminally failed (all retries exhausted) since process start.',+ );+ lines.push('# TYPE openwa_webhook_delivery_failures_total counter');+ lines.push(`openwa_webhook_delivery_failures_total ${getWebhookDeliveryFailuresTotal()}`);+const text = lines.join('\n') + '\n';this.cachedRender = { at: now, text };return text;diff --git a/src/modules/queue/processors/ingress.processor.ts b/src/modules/queue/processors/ingress.processor.tsindex a9058628f..a0f528795 100644--- a/src/modules/queue/processors/ingress.processor.ts+++ b/src/modules/queue/processors/ingress.processor.ts@@ -23,9 +23,16 @@ export interface IngressJobData {payload: { headers: Record<string, string>; query: Record<string, string>; body: string; rawBody: string };}-// Ordering within a conversation is guaranteed by the KeyedAsyncLock wrapping dispatch below, so the-// worker no longer needs concurrency 1 to stay correct-by-default; raising it parallelizes unrelated-// conversations instead of head-of-line-blocking every inbound event behind the slowest one.+// The KeyedAsyncLock wrapping dispatch below guarantees no two dispatches for the SAME conversation+// run concurrently (mutual exclusion + in-order START for events as they reach the worker), so the+// worker no longer needs concurrency 1 — raising it parallelizes UNRELATED conversations instead of+// head-of-line-blocking every inbound event behind the slowest one. Strict end-to-end order is NOT+// preserved across a BullMQ retry: a retried job re-enters lock.run() after its backoff and chains at+// the conversation's CURRENT tail, so it can overtake a same-conversation successor that dispatched+// during the backoff window. This is a deliberate tradeoff — BullMQ retries release the worker slot+// during backoff (better throughput under transient failure), where retrying inside the lock would+// hold it — and is acceptable because ingress order is best-effort regardless: the provider delivers+// over unordered HTTP. Order-strict plugins must not assume retry-involved events arrive in sequence.@Processor(QUEUE_NAMES.INGRESS, { connection: workerConnectionOptions(), concurrency: ingressWorkerConcurrency() })export class IngressProcessor extends WorkerHost {private readonly logger = createLogger('IngressProcessor');diff --git a/src/modules/queue/processors/webhook.processor.spec.ts b/src/modules/queue/processors/webhook.processor.spec.tsindex 9e0f8b906..acd931632 100644--- a/src/modules/queue/processors/webhook.processor.spec.ts+++ b/src/modules/queue/processors/webhook.processor.spec.ts@@ -44,7 +44,6 @@ describe('WebhookProcessor', () => {deliveryId: 'd',data: {},},- signature: '',headers: { 'Content-Type': 'application/json' },attempt: 1,maxRetries: 3,diff --git a/src/modules/queue/processors/webhook.processor.ts b/src/modules/queue/processors/webhook.processor.tsindex f01597e25..a36a326d0 100644--- a/src/modules/queue/processors/webhook.processor.ts+++ b/src/modules/queue/processors/webhook.processor.ts@@ -12,6 +12,7 @@ import { WebhookDeliveryFailure } from '../../webhook/entities/webhook-delivery-import { recordWebhookDeliveryFailure, statusCodeFromError } from '../../webhook/utils/record-delivery-failure';import { HookManager } from '../../../core/hooks';import { withSafeFetch, isSsrfProtectionEnabled } from '../../../common/security/ssrf-guard';+import { incrementWebhookDeliveryFailures } from '../../../common/metrics/webhook-delivery-metrics';export interface WebhookJobResult {statusCode: number;@@ -158,6 +159,7 @@ export class WebhookProcessor extends WorkerHost {lastStatusCode: statusCodeFromError(errorMessage),lastError: errorMessage,});+ incrementWebhookDeliveryFailures();}// Re-throw to trigger BullMQ retrydiff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 4f4c7963e..b52324828 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -7,6 +7,9 @@ import { SessionService, ACK_RECONCILE_DELAY_MS } from './session.service';import { Session, SessionStatus } from './entities/session.entity';import { Message, MessageStatus } from '../message/entities/message.entity';import { MessageBatch } from '../message/entities/message-batch.entity';+import { Webhook } from '../webhook/entities/webhook.entity';+import { Template } from '../template/entities/template.entity';+import { BaileysStoredMessage } from '../../engine/adapters/baileys-stored-message.entity';import { EngineFactory } from '../../engine/engine.factory';import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';import { EventsGateway } from '../events/events.gateway';@@ -484,7 +487,7 @@ describe('SessionService', () => {expect(mockEngine.forceDestroy).toHaveBeenCalled();});- it('removes the session messages and bulk batches in the same transaction (no orphaned rows)', async () => {+ it('removes the session and all its child rows explicitly in one transaction (SQLite cascade is off)', async () => {const session = createMockSession();(repository.findOne as jest.Mock).mockResolvedValue(session);@@ -496,9 +499,14 @@ describe('SessionService', () => {await service.delete('sess-uuid-1');- // These tables carry sessionId but have no FK cascade, so delete() must clean them explicitly.+ // messages/message_batches have no FK; webhooks/templates/baileys_stored_messages declare an+ // ON DELETE CASCADE FK, but SQLite runs with foreign_keys OFF so it never fires — delete() must+ // clear ALL of them explicitly or a session delete orphans them (webhooks retain the secret).expect(managerDelete).toHaveBeenCalledWith(Message, { sessionId: 'sess-uuid-1' });expect(managerDelete).toHaveBeenCalledWith(MessageBatch, { sessionId: 'sess-uuid-1' });+ expect(managerDelete).toHaveBeenCalledWith(Webhook, { sessionId: 'sess-uuid-1' });+ expect(managerDelete).toHaveBeenCalledWith(Template, { sessionId: 'sess-uuid-1' });+ expect(managerDelete).toHaveBeenCalledWith(BaileysStoredMessage, { sessionId: 'sess-uuid-1' });expect(managerRemove).toHaveBeenCalledWith(session);});});@@ -613,6 +621,24 @@ describe('SessionService', () => {});});+ describe('scheduleReconnect (max attempts)', () => {+ it('reports "auto-reconnect disabled" (not "failed after 0 attempts") when maxAttempts is 0', async () => {+ const i = service as unknown as {+ reconnectStates: Map<string, { attempts: number; timer: null; maxAttempts: number; baseDelay: number }>;+ sessionErrors: Map<string, string>;+ scheduleReconnect: (id: string, session: Session) => void;+ };+ i.reconnectStates.set('sess-uuid-1', { attempts: 0, timer: null, maxAttempts: 0, baseDelay: 5000 });+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });++ i.scheduleReconnect('sess-uuid-1', createMockSession());+ await new Promise(resolve => setImmediate(resolve));++ // maxAttempts:0 means auto-reconnect is OFF, not that 0 attempts were tried and failed.+ expect(i.sessionErrors.get('sess-uuid-1')).toMatch(/auto-reconnect is disabled/i);+ });+ });+describe('reconnect/stop race', () => {interface Internals {executeReconnect: (id: string, session: Session, state: unknown) => Promise<void>;@@ -1216,16 +1242,16 @@ describe('SessionService', () => {it('serializes concurrent reactions on the same message so neither sender is clobbered', async () => {const callbacks = await startAndCaptureCallbacks();- // Simulate a real DB: each findOne returns a FRESH snapshot of the persisted row, and save- // writes it back. Without per-message serialization the two handlers read the same empty- // snapshot and the second save clobbers the first sender's reaction.+ // Simulate a real DB: each findOne returns a FRESH snapshot of the persisted row, and the scoped+ // update writes the new metadata back. Without per-message serialization the two handlers read the+ // same empty snapshot and the second write clobbers the first sender's reaction.type Row = { metadata?: Record<string, unknown> };const clone = (r: Row): Row => JSON.parse(JSON.stringify(r)) as Row;let stored: Row = { metadata: {} };(messageRepository.findOne as jest.Mock).mockImplementation(() => Promise.resolve(clone(stored)));- (messageRepository.save as jest.Mock).mockImplementation((m: Row) => {- stored = clone(m);- return Promise.resolve(m);+ (messageRepository.update as jest.Mock).mockImplementation((_c: unknown, patch: Row) => {+ stored = clone({ ...stored, ...patch });+ return Promise.resolve({ affected: 1 });});callbacks.onMessageReaction!({ messageId: 'wa-1', chatId: 'c', senderId: 'alice', reaction: '👍' });@@ -1236,15 +1262,34 @@ describe('SessionService', () => {expect(stored.metadata?.reactions).toEqual({ alice: '👍', bob: '🎉' });});+ it('persists a reaction via a scoped metadata update, never a full-row save (protects ack status)', async () => {+ const callbacks = await startAndCaptureCallbacks();+ // The row was already advanced to DELIVERED by a concurrent ack. A full-row save(msg) would+ // re-persist the stale status read at findOne time and clobber it; the write must be scoped to+ // the metadata column only, keyed by (sessionId, waMessageId).+ (messageRepository.findOne as jest.Mock).mockResolvedValue({ status: 'delivered', metadata: {} });+ (messageRepository.save as jest.Mock).mockClear();+ (messageRepository.update as jest.Mock).mockClear().mockResolvedValue({ affected: 1 });++ callbacks.onMessageReaction!({ messageId: 'wa-1', chatId: 'c', senderId: 'alice', reaction: '👍' });+ for (let i = 0; i < 3; i++) await flush();++ expect(messageRepository.save).not.toHaveBeenCalled();+ expect(messageRepository.update).toHaveBeenCalledWith(+ { sessionId: 'sess-uuid-1', waMessageId: 'wa-1' },+ { metadata: { reactions: { alice: '👍' } } },+ );+ });+it('removes a sender reaction on a cleared reaction event (delete branch)', async () => {const callbacks = await startAndCaptureCallbacks();type Row = { metadata?: Record<string, unknown> };const clone = (r: Row): Row => JSON.parse(JSON.stringify(r)) as Row;let stored: Row = { metadata: { reactions: { alice: '👍', bob: '🎉' } } };(messageRepository.findOne as jest.Mock).mockImplementation(() => Promise.resolve(clone(stored)));- (messageRepository.save as jest.Mock).mockImplementation((m: Row) => {- stored = clone(m);- return Promise.resolve(m);+ (messageRepository.update as jest.Mock).mockImplementation((_c: unknown, patch: Row) => {+ stored = clone({ ...stored, ...patch });+ return Promise.resolve({ affected: 1 });});callbacks.onMessageReaction!({ messageId: 'wa-1', chatId: 'c', senderId: 'alice', reaction: '' });@@ -1260,11 +1305,11 @@ describe('SessionService', () => {const clone = (r: Row): Row => JSON.parse(JSON.stringify(r)) as Row;let stored: Row = { metadata: {} };(messageRepository.findOne as jest.Mock).mockImplementation(() => Promise.resolve(clone(stored)));- (messageRepository.save as jest.Mock)+ (messageRepository.update as jest.Mock).mockRejectedValueOnce(new Error('write blip')) // alice's write fails- .mockImplementation((m: Row) => {- stored = clone(m);- return Promise.resolve(m);+ .mockImplementation((_c: unknown, patch: Row) => {+ stored = clone({ ...stored, ...patch });+ return Promise.resolve({ affected: 1 });});callbacks.onMessageReaction!({ messageId: 'wa-1', chatId: 'c', senderId: 'alice', reaction: '👍' });@@ -1278,7 +1323,7 @@ describe('SessionService', () => {it('cleans up the per-message serialization entry after the chain drains (no leak)', async () => {const callbacks = await startAndCaptureCallbacks();(messageRepository.findOne as jest.Mock).mockResolvedValue({ metadata: {} });- (messageRepository.save as jest.Mock).mockResolvedValue(undefined);+ (messageRepository.update as jest.Mock).mockResolvedValue({ affected: 1 });callbacks.onMessageReaction!({ messageId: 'wa-1', chatId: 'c', senderId: 'alice', reaction: '👍' });@@ -1294,9 +1339,9 @@ describe('SessionService', () => {const clone = (r: Row): Row => JSON.parse(JSON.stringify(r)) as Row;let stored: Row = { metadata: {} };(messageRepository.findOne as jest.Mock).mockImplementation(() => Promise.resolve(clone(stored)));- (messageRepository.save as jest.Mock).mockImplementation((m: Row) => {- stored = clone(m);- return Promise.resolve(m);+ (messageRepository.update as jest.Mock).mockImplementation((_c: unknown, patch: Row) => {+ stored = clone({ ...stored, ...patch });+ return Promise.resolve({ affected: 1 });});callbacks.onMessageReaction!({ messageId: 'wa-1', chatId: 'c', senderId: 'alice', reaction: '👍' });diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex f4378ffea..2cf687445 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -15,12 +15,16 @@ import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntityimport { Session, SessionStatus } from './entities/session.entity';import { Message, MessageDirection, MessageStatus } from '../message/entities/message.entity';import { MessageBatch } from '../message/entities/message-batch.entity';+import { Webhook } from '../webhook/entities/webhook.entity';+import { Template } from '../template/entities/template.entity';+import { BaileysStoredMessage } from '../../engine/adapters/baileys-stored-message.entity';import { CreateSessionDto } from './dto';import { EngineFactory } from '../../engine/engine.factory';import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';import { userPart } from '../../engine/identity/wa-id';import { paginate, ListOptions, resolveListWindow } from '../../common/utils/paginate';import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';+import { resolveFeatureFlags } from '../../config/feature-flags';import {IWhatsAppEngine,EngineStatus,@@ -184,7 +188,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat}async onApplicationBootstrap(): Promise<void> {- if (process.env.AUTO_START_SESSIONS !== 'true') return;+ if (!resolveFeatureFlags(this.configService).autoStartSessions) return;const sessions = await this.sessionRepository.find({where: { phone: Not(IsNull()), status: SessionStatus.DISCONNECTED },@@ -404,12 +408,19 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat);// DB removal is NOT best-effort: a genuine failure must surface (500) rather than be swallowed.- // messages and message_batches carry a sessionId but have no FK cascade to sessions (unlike- // webhooks/templates/baileys_stored_messages), so remove them explicitly in the same transaction- // — otherwise deleting a session leaves its full history orphaned forever.+ // Delete every child row explicitly, in one transaction, children before the parent. messages/+ // message_batches carry a plain sessionId with no FK. webhooks/templates/baileys_stored_messages+ // DO declare an ON DELETE CASCADE FK, but the default `data` engine (SQLite) runs with+ // foreign_keys OFF, so that cascade never fires there — a session delete would otherwise orphan+ // them forever (webhooks in particular retain the signing secret + custom headers). Deleting them+ // explicitly is engine-agnostic (redundant-but-harmless on Postgres, where the cascade finds+ // nothing left) and mirrors the restore path's explicit-clear ordering.await this.dataSource.transaction(async manager => {await manager.delete(Message, { sessionId: id });await manager.delete(MessageBatch, { sessionId: id });+ await manager.delete(Webhook, { sessionId: id });+ await manager.delete(Template, { sessionId: id });+ await manager.delete(BaileysStoredMessage, { sessionId: id });await manager.remove(session);});this.logger.log(`Session deleted: ${session.name}`, {@@ -701,7 +712,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// Ephemeral/disappearing messages: skip persist + dispatch when the operator opted out.// A message is ephemeral when its chat has a disappearing-messages timer (ephemeralDuration > 0).if (- process.env.STORE_EPHEMERAL_MESSAGES === 'false' &&+ !resolveFeatureFlags(this.configService).storeEphemeralMessages &&message.ephemeralDuration &&message.ephemeralDuration > 0) {@@ -742,7 +753,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// Inline @lid -> phone resolution (#263), opt-in via RESOLVE_LID_TO_PHONE. Best-effort:// attaches senderPhone (digits or null) before persist/dispatch so webhook/ws consumers// get it in a single pass. Only for privacy-id senders, so no lookup for normal numbers.- if (process.env.RESOLVE_LID_TO_PHONE === 'true' && incoming.isLidSender && !incoming.fromMe) {+ if (resolveFeatureFlags(this.configService).resolveLidToPhone && incoming.isLidSender && !incoming.fromMe) {incoming.senderPhone = await this.resolveSenderPhone(id, incoming.author ?? incoming.from);}@@ -1094,8 +1105,14 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatreactions[event.senderId] = event.reaction;}metadata.reactions = reactions;- msg.metadata = metadata;- await this.messageRepository.save(msg);+ // Scoped update of ONLY the metadata column. A full-row save(msg) would re-persist the `status`+ // read at findOne time, clobbering a concurrent ack UPDATE (SENT→DELIVERED/READ) that committed in+ // the window between this findOne and the write — reactionChains serializes reaction-vs-reaction+ // but NOT reaction-vs-ack, so scoping the write to metadata is what keeps delivery state monotonic+ // (#220). Other metadata fields are carried through untouched (they were read into `metadata`).+ await this.messageRepository.update({ sessionId: id, waMessageId: event.messageId }, {+ metadata,+ } as QueryDeepPartialEntity<Message>);this.eventsGateway.emitMessageReaction(id, { ...event, reactions });// Webhook parity with the WebSocket broadcast: same payload (event + post-apply snapshot), so a@@ -1127,7 +1144,14 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat});// Don't leave the session silently stuck DISCONNECTED — mark it terminally FAILED with a reason// so findOne/findAll surface it via `lastError` and the dashboard shows it needs a restart.- this.sessionErrors.set(id, `Reconnection failed after ${state.attempts} attempts — restart the session.`);+ // maxAttempts:0 means auto-reconnect is disabled, not that N attempts were tried and failed — say+ // so instead of the misleading "failed after 0 attempts".+ this.sessionErrors.set(+ id,+ state.maxAttempts === 0+ ? 'Auto-reconnect is disabled (max attempts set to 0); the session was left disconnected — restart it manually.'+ : `Reconnection failed after ${state.attempts} attempts — restart the session.`,+ );void this.updateStatus(id, SessionStatus.FAILED);return;}diff --git a/src/modules/settings/settings.controller.spec.ts b/src/modules/settings/settings.controller.spec.tsindex e6ffdf3ba..fdc2c89bb 100644--- a/src/modules/settings/settings.controller.spec.ts+++ b/src/modules/settings/settings.controller.spec.ts@@ -18,6 +18,30 @@ describe('SettingsController', () => {expect(settings).toHaveProperty('notifications');});+ it('reports enableDocs from the real ENABLE_SWAGGER gate, not a hardcoded true', () => {+ const prev = process.env.ENABLE_SWAGGER;+ try {+ process.env.ENABLE_SWAGGER = 'false';+ expect(new SettingsController(configStub).get().api.enableDocs).toBe(false);+ process.env.ENABLE_SWAGGER = 'true';+ expect(new SettingsController(configStub).get().api.enableDocs).toBe(true);+ } finally {+ if (prev === undefined) delete process.env.ENABLE_SWAGGER;+ else process.env.ENABLE_SWAGGER = prev;+ }+ });++ it('reports apiBaseUrl from BASE_URL when the operator configured one', () => {+ const prev = process.env.BASE_URL;+ try {+ process.env.BASE_URL = 'https://wa.example.com';+ expect(new SettingsController(configStub).get().general.apiBaseUrl).toBe('https://wa.example.com');+ } finally {+ if (prev === undefined) delete process.env.BASE_URL;+ else process.env.BASE_URL = prev;+ }+ });+// The previous PUT mutated an in-memory field and returned 200 'updated' while persisting// nothing and applying nothing to the runtime — a false success. Settings are env-derived and// read-only at runtime, so the write path must say so (501) rather than fake success.diff --git a/src/modules/settings/settings.controller.ts b/src/modules/settings/settings.controller.tsindex 7ed111549..d0ea664ff 100644--- a/src/modules/settings/settings.controller.ts+++ b/src/modules/settings/settings.controller.ts@@ -3,6 +3,7 @@ import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';import { ConfigService } from '@nestjs/config';import { RequireRole } from '../auth/decorators/auth.decorators';import { ApiKeyRole } from '../auth/entities/api-key.entity';+import { isSwaggerEnabled } from '../../config/bootstrap-security';interface Settings {general: {@@ -34,15 +35,22 @@ export class SettingsController {this.settings = {general: {- apiBaseUrl: `http://localhost:${port}`,+ // 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),- autoReconnect: this.configService.get<boolean>('engine.autoReconnect', false),+ // 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.+ autoReconnect: true,debugMode: this.configService.get<boolean>('database.logging', false),},api: {rateLimit: this.configService.get<number>('api.rateLimit.mediumLimit', 100),rateLimitWindow: this.configService.get<number>('api.rateLimit.mediumTtl', 60000),- enableDocs: true, // Swagger docs always enabled+ // Reflect the REAL ENABLE_SWAGGER gate (off by default in production), not a hardcoded `true`+ // — otherwise the panel reports docs enabled in production where they are actually disabled.+ enableDocs: isSwaggerEnabled(process.env.ENABLE_SWAGGER, process.env.NODE_ENV),},notifications: {emailEnabled: false,diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.tsindex 15042e4d2..60f46fccb 100644--- a/src/modules/webhook/webhook.service.spec.ts+++ b/src/modules/webhook/webhook.service.spec.ts@@ -26,6 +26,7 @@ import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.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';function createMockWebhook(overrides: Partial<Webhook> = {}): Webhook {return {@@ -383,6 +384,28 @@ describe('WebhookService', () => {await dispatchP;});+ 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'] });+ (repository.find as jest.Mock).mockResolvedValue([wA, wB]);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });+ mockFetch.mockResolvedValue({ ok: true, status: 200 });++ await service.dispatch('sess-1', 'message.received', { from: '[email protected]' });++ const keyByUrl = new Map<string, string>();+ for (const call of mockFetch.mock.calls as [string, { headers: Record<string, string> }][]) {+ keyByUrl.set(call[0], call[1].headers['X-OpenWA-Idempotency-Key']);+ }+ const keyA = keyByUrl.get('https://a.example/hook');+ const keyB = keyByUrl.get('https://b.example/hook');+ // Same event + payload, but two distinct endpoints must not collide on the dedupe header.+ expect(keyA).toBeTruthy();+ expect(keyB).toBeTruthy();+ expect(keyA).not.toBe(keyB);+ });+it('falls back to the original payload when a before-hook omits payload (no undefined body)', async () => {const webhook = createMockWebhook({ events: ['message.received'] });(repository.find as jest.Mock).mockResolvedValue([webhook]);@@ -944,6 +967,7 @@ describe('WebhookService', () => {const mockFetch = undiciFetch as jest.Mock;mockFetch.mockResolvedValue({ ok: false, status: 500, statusText: 'Server Error' });+ const failuresBefore = getWebhookDeliveryFailuresTotal();await service.dispatch('sess-1', 'message.received', {});expect(failureRepository.insert).toHaveBeenCalledWith(@@ -954,6 +978,8 @@ describe('WebhookService', () => {lastError: 'HTTP 500: Server Error',}),);+ // The terminal failure also bumps the Prometheus counter exactly once.+ expect(getWebhookDeliveryFailuresTotal()).toBe(failuresBefore + 1);mockFetch.mockReset();});diff --git a/src/modules/webhook/webhook.service.ts b/src/modules/webhook/webhook.service.tsindex 28c16f65f..85ffd24a3 100644--- a/src/modules/webhook/webhook.service.ts+++ b/src/modules/webhook/webhook.service.ts@@ -17,6 +17,7 @@ import { WebhookDeliveryFailure } from './entities/webhook-delivery-failure.entiimport { recordWebhookDeliveryFailure, statusCodeFromError } from './utils/record-delivery-failure';import { CreateWebhookDto, UpdateWebhookDto } from './dto';import { createLogger } from '../../common/services/logger.service';+import { incrementWebhookDeliveryFailures } from '../../common/metrics/webhook-delivery-metrics';import { ListOptions, resolveListWindow } from '../../common/utils/paginate';import { QUEUE_NAMES } from '../queue/queue-names';import { generateIdempotencyKey, generateDeliveryId } from './utils/idempotency.util';@@ -46,7 +47,6 @@ export interface WebhookJobData {url: string;event: string;payload: WebhookPayload;- signature: string;headers: Record<string, string>;attempt: number;maxRetries: number;@@ -294,11 +294,11 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {w => (w.events.includes(event) || w.events.includes('*')) && evaluateFilters(w.filters, event, data, resolveLid),);- // Generate idempotency key (same for all webhooks receiving this event). occurredAt is captured- // once here and reused for every retry of this dispatch, so recurring lifecycle events get a- // distinct-per-occurrence key while retries of the same event stay stable.+ // Base idempotency key for this event occurrence. occurredAt is captured once here and reused for+ // every retry of this dispatch, so recurring lifecycle events get a distinct-per-occurrence key+ // while retries of the same event stay stable. It is salted PER WEBHOOK below.const occurredAt = new Date().toISOString();- const idempotencyKey = generateIdempotencyKey(event, { ...data, sessionId }, occurredAt);+ 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@@ -307,6 +307,12 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {// Generate unique delivery ID for each webhookconst 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(),@@ -373,7 +379,6 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {url: webhook.url,event,payload: finalPayload,- signature,headers,attempt: 1,maxRetries: webhook.retryCount,@@ -559,6 +564,7 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {lastStatusCode: statusCodeFromError(errMessage),lastError: errMessage,});+ incrementWebhookDeliveryFailures();throw error;}}diff --git a/test/integration-fabric.e2e-spec.ts b/test/integration-fabric.e2e-spec.tsindex c1a31a801..4d55c38a1 100644--- a/test/integration-fabric.e2e-spec.ts+++ b/test/integration-fabric.e2e-spec.ts@@ -15,6 +15,7 @@ import { json, urlencoded, Request } from 'express';import { AppModule } from './../src/app.module';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';/*** Byte-exact HTTP coverage for the Integration SDK v1 ingress contract, over the seam the@@ -149,4 +150,32 @@ describe('Integration Fabric ingress (e2e)', () => {expect(res.status).toBe(401);expect(dispatchWebhookForInstance).not.toHaveBeenCalled();});++ it('persists a redrivable dead-letter row (still 202) when inline dispatch fails', async () => {+ const failureRepo = app.get<Repository<IntegrationDeliveryFailure>>(+ getRepositoryToken(IntegrationDeliveryFailure, 'data'),+ );+ // The plugin handler throws — the inline-dispatch fallback fails and is swallowed. Without a+ // dead-letter row the event would be stranded: handle() still 202s, and RedriveService only scans+ // this table (never ingress_events). The live-ingress wiring must therefore persist the failure here.+ dispatchWebhookForInstance.mockRejectedValueOnce(new Error('sandbox handler 5xx'));++ const res = await request(app.getHttpServer())+ .post(INGRESS_PATH)+ .set('X-Chatwoot-Signature', sig)+ .set('X-Chatwoot-Delivery', 'delivery-dlq-1')+ .set('Content-Type', 'application/json')+ .send(raw);++ // Provider still gets its 202 (at-least-once) — the failure is captured durably, not surfaced as 5xx.+ expect(res.status).toBe(202);+ const rows = await failureRepo.find({ where: { deliveryId: 'delivery-dlq-1', direction: 'inbound' } });+ expect(rows).toHaveLength(1);+ expect(rows[0]).toMatchObject({+ pluginId: 'chatwoot',+ instanceId: 'acct1',+ redriven: false,+ lastError: 'sandbox handler 5xx',+ });+ });});