Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(config,http,auth,engine): resolve env precedence at save time, price in-flight bodies by real bytes, and confine the admin invariant (#971)
Yudhi Armyndharisac9170c60017
diff --git a/.env.example b/.env.exampleindex 539871ff3..1ff1e921e 100644--- a/.env.example+++ b/.env.example@@ -325,7 +325,8 @@ WEBHOOK_SSRF_PROTECT=true# STORAGE_EXPORT_SWEEP_MAX_AGE_MS=86400000 # boot sweep deletes export archives orphaned by a restart, older than this (default 24h)# Outbound rows stuck PENDING (process died between the pre-send save and the final save) are marked# FAILED with a `reapedAt` metadata marker by a periodic reaper, which also re-emits-# `message:persisted` so hook-driven search providers reconcile. Interval <= 0 disables the reaper.+# `message:persisted` so hook-driven search providers reconcile. Set the interval to 0 to disable+# the reaper; a blank or unparseable value falls back to the default instead of disabling it.# MESSAGE_REAPER_INTERVAL_MS=600000 # how often the reaper sweeps (default 10min)# MESSAGE_REAPER_GRACE_MS=3600000 # only rows older than this are reaped (default 1h)# MESSAGE_REAPER_BATCH_SIZE=50 # max rows reaped per sweep (default 50)diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 6855c7e95..93dea69a0 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -231,7 +231,7 @@ jobs:name: Shell scriptsruns-on: ubuntu-lateststeps:- - uses: actions/checkout@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7- name: Install sqlite3# smoke-test-backup-restore.sh skips its sqlite3 .backup roundtrip case (with a notice) whendiff --git a/CHANGELOG.md b/CHANGELOG.mdindex ae5072db5..525826529 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,30 +21,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed-- **S3 storage no longer silently stays on the local fallback after a boot-time miss, the Baileys- engine no longer reports READY while its socket is in reconnect backoff, and the dashboard no- longer serves cached state across logout.** Four correctness fixes: if S3 was unreachable at boot,- `StorageService` fell back to local and never re-probed, so after S3 recovered writes kept landing- in `./data/media` while reads hit S3 `NoSuchKey` — a silent split-brain; it now re-probes on a- 60s interval (`S3_REPROBE_INTERVAL_MS`), WARNs while degraded, self-clears the timer on recovery,- and the recovery is strictly one-way (false→true) so a transient flake cannot drop a healthy- deployment to local. When the Baileys socket entered reconnect backoff after a transient close,- the adapter kept reporting `READY` for up to the 60s backoff cap while the socket was dead, so- `probeLiveness()` returned true and `ensureReady()` let sends through against a dead socket — it- now sets `INITIALIZING` immediately on the transient close (matching the whatsapp-web.js engine)- and restores `READY` on the next `open`. The dashboard's React Query cache survived logout (a- re-login showed the previous user's sessions/messages), the startup re-validation did not check- `res.ok` (a 401/revoked key kept the cached role), the WebSocket client dropped `subscribed`/- `error` frames (a scoped-key `FORBIDDEN_SESSION` was invisible), and `markChatRead` fired per- call without a debounce; all four are fixed (`queryClient.clear()` on logout, state-machine+- **S3 storage no longer silently stays on the local fallback after a boot-time miss, the Baileys engine no+ longer reports READY while its socket is in reconnect backoff, and the dashboard no longer serves cached+ state across logout.** Four correctness fixes: if S3 was unreachable at boot, `StorageService` fell back+ to local and never re-probed, so after S3 recovered writes kept landing in `./data/media` while reads hit+ S3 `NoSuchKey` — a silent split-brain; it now re-probes on a 60s interval (`S3_REPROBE_INTERVAL_MS`),+ WARNs while degraded, self-clears the timer on recovery, and the recovery is strictly one-way (false→true)+ so a transient flake cannot drop a healthy deployment to local; while S3 is active, enumeration and the+ storage totals also cover the local fallback directory and deletes go to both backends, so bytes written+ during an outage stay visible to listings and reclaimable instead of being stranded. When the Baileys+ socket entered reconnect backoff after a transient close, the adapter kept reporting `READY` for up to the+ 60s backoff cap while the socket was dead, so `probeLiveness()` returned true and `ensureReady()` let+ sends through against a dead socket — it now sets `INITIALIZING` immediately on the transient close+ (matching the whatsapp-web.js engine) and restores `READY` on the next `open`. The dashboard's React Query+ cache survived logout (a re-login showed the previous user's sessions/messages), the startup re-validation+ did not check `res.ok` (a 401/revoked key kept the cached role), the WebSocket client dropped+ `subscribed`/ `error` frames (a scoped-key `FORBIDDEN_SESSION` was invisible), and `markChatRead` fired+ per call without a debounce; all four are fixed (`queryClient.clear()` on logout, state-machinevalidation, frame routing, a 750ms trailing coalescer). Separately, the `tecnativa/docker-socket-proxy`- compose entry set `DELETE: 1` which is dead config on the pinned v0.4.2 image (its method gate- admits on `POST` alone), so the SECURITY.md "least-privilege" claim oversold the boundary — the- dead directive is dropped, the README/SECURITY now document the real threat model (a compromised- API container with `POST=1` is host-root-equivalent), and the managed-profile teardown switched- from `remove({ v: true })` (which discarded anonymous volumes the disable/re-enable flow assumes)- to a stop-only path that reports per-profile errors honestly instead of claiming success on a 403.- (#945, #944, #938, #934)+ compose entry set `DELETE: 1` which is dead config on the pinned v0.4.2 image (its method gate admits on+ `POST` alone), so the SECURITY.md "least-privilege" claim oversold the boundary — the dead directive is+ dropped, the README/SECURITY now document the real threat model (a compromised API container with `POST=1`+ is host-root-equivalent), and the managed-profile teardown switched from `remove({ v: true })` (which+ discarded anonymous volumes the disable/re-enable flow assumes) to a stop-only path that reports+ per-profile errors honestly instead of claiming success on a 403. (#945, #944, #938, #934)- **The data export/import path and the backup/restore scripts no longer silently lose data, crashthe process, or write databases the app never opens.** Five integrity gaps in the export/import@@ -120,23 +120,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`pending`, and masked the real delivery failures and the `message:failed` events that had alreadyfired. FAILED is now in the terminal-status guard, so each terminal status stays exclusive.-- **The ingress queue now actually queues when `QUEUE_ENABLED=true`, persisted ingress events are- reconciled after silent-loss windows, and disabling one instance no longer tears down an enabled- sibling sharing its session scope.** The IntegrationModule never imported the QueueModule, so the- `@Optional()` ingress queue injection was always `undefined` and every delivery dispatched inline- despite the operator-facing queued contract (fast-ack, retries, ordering, DLQ) — the module now- imports it conditionally (mirroring the webhook module) and the boot fail-fast tripwire crashes- startup loudly if the wiring ever regresses. `ingress_events` was a dedup log but never a- durability handle: a crash between persist and dispatch, a failed fire-and-forget response route,- or a swallowed inline failure lost the event while the provider's honest retry deduped to a no-op.- Rows now carry `dispatchState`/`dispatchAttempts`/`lastDispatchAt` (legacy rows excluded), the- enqueue path records outcomes, and a 60s reconciler (`INGRESS_RECONCILE_*`) replays stuck- deliveries with their original delivery id, retiring them terminally (plus a DLQ row) after five- attempts instead of looping forever. Separately, disabling, deleting, or re-scoping an instance- unconditionally stripped its session from the plugin's `activeSessions` and wiped the per-session- config even when another ENABLED instance shared that scope; the teardown now checks for an- enabled sibling first, and concrete activation preserves `'*'` while a wildcard sibling is still- enabled. (#921, #924, #922)+- **The ingress queue now actually queues when `QUEUE_ENABLED=true`, persisted ingress events are reconciled+ after silent-loss windows, and disabling one instance no longer tears down an enabled sibling sharing its+ session scope.** The IntegrationModule never imported the QueueModule, so the `@Optional()` ingress queue+ injection was always `undefined` and every delivery dispatched inline despite the operator-facing queued+ contract (fast-ack, retries, ordering, DLQ) — the module now imports it conditionally (mirroring the+ webhook module) and the boot fail-fast tripwire crashes startup loudly if the wiring ever regresses.+ `ingress_events` was a dedup log but never a durability handle: a crash between persist and dispatch, a+ failed fire-and-forget response route, or a swallowed inline failure lost the event while the provider's+ honest retry deduped to a no-op. Rows now carry `dispatchState`/`dispatchAttempts`/`lastDispatchAt`+ (legacy rows excluded), the enqueue path records outcomes, and a 60s reconciler (`INGRESS_RECONCILE_*`)+ replays stuck deliveries with their original delivery id, retiring them terminally (plus a DLQ row) after+ five attempts instead of looping forever; a replay first re-applies the eligibility check the live path+ makes at the door, so an instance disabled or deleted after the persist is never handed the event.+ Separately, disabling, deleting, or re-scoping an instance unconditionally stripped its session from the+ plugin's `activeSessions` and wiped the per-session config even when another ENABLED instance shared that+ scope; the teardown now checks for an enabled sibling first, and concrete activation preserves `'*'` while+ a wildcard sibling is still enabled. (#921, #924, #922)- **Search-provider plugins now receive the finalized state of every outbound message, and tworunnable cURL examples in the API collection no longer 404.** The `message:persisted` hook fired@@ -168,59 +168,75 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0re-purges both engines' auth dirs (gated by a by-name re-check so delete+recreate keeps its freshdir) on the start and reconnect paths alike. (#949, #961, #952)-- **Infra config writes are section-scoped, mode-aware, and strictly coerced, and the bootstrap- config guards cover the paths the app actually uses.** Saving config used to clobber sections- absent from the payload and carry stale secrets across mode flips (built-in `minioadmin`/`openwa`- credentials surviving into an external-blank config, which the production secret guard then- rejected at the next boot — a crash-loop with the dashboard dead); writes now merge per key,- drop the old mode's secrets on a builtin→external flip (`S3_ENDPOINT` clearable), and re-run the- production default-secret assertion at save time (400 before anything hits disk). Controller-local- DTOs moved to `dto/` with strict coercion, so a form-encoded `'false'` can no longer persist as- `'true'` for the boolean flags. The SQLite main/data path-collision guard now resolves paths- exactly like the runtime (and also fires for CLI migration invocations), `REDIS_ENABLED` is- strictly validated (a typo fails boot instead of silently downgrading the throttler and cache to- in-memory), and a boot sweep deletes `storage-export-*` archives orphaned by a restart after- `STORAGE_EXPORT_SWEEP_MAX_AGE_MS` (default 24h). **Breaking (behavior):** partial config payloads- now preserve omitted fields instead of resetting them (the dashboard's full payload is- byte-identical), and non-canonical `REDIS_ENABLED` values now fail boot. (#946, #960)--- **Bulk batches re-validate rendered payloads and cancel terminally, and outbound rows stuck- PENDING after a crash are reaped.** Media presence/size was only checked at batch creation, so- `{{variables}}` and the `message:sending` hook could grow a payload past the cap afterwards —- every item is now re-validated post-gate (violations fail the item, honoring `stopOnError`). A- cancel landing before the first item could be fully overwritten by the cadence/final writes and- send the whole batch anyway; all status transitions are now DB-conditional on the current status,- so CANCELLED stays terminal (duplicate chatIds are deduped first-wins at creation). Rows left- PENDING when the process dies between the pre-send save and the final save previously stayed- PENDING forever (in the DB and in plugin search indexes); a periodic reaper- (`MESSAGE_REAPER_INTERVAL_MS`/`_GRACE_MS`/`_BATCH_SIZE`, defaults 10min/1h/50) marks them FAILED- with a `reapedAt` marker and re-emits `message:persisted` so hook-driven providers reconcile.- (#955, #958)--- **API-key usage accounting no longer loses deltas, and the queue dashboard leaves an audit- trail.** A failed `pendingUsage` save dropped the accumulated delta and 500'd the request (the- delta now merges back and the request stands); nothing flushed on shutdown, so the last window's- usage vanished (a bounded `onModuleDestroy` flush now writes it). Bull Board rejected requests- with no audit record and queue-mutating UI actions left none either — 401/403s now write the- standard failed-auth row (429s are left to the limiter), and authenticated non-GET requests write- a new `QUEUE_BOARD_MUTATED` action with actor/method/path. The bootstrap `data/.api-key` file and- boot banner pointed at keys after rotation/revoke; the file is now removed when its key no- longer validates (checked by hash at boot, and on the revoke/delete paths). (#963)--- **Group participant batches, template renders, and status media are bounded and reconciled, and- the Postgres FTS probe reads the active schema.** Participant arrays accept at most 256 entries- (the engine works them serially) and a partially-failing settings patch now names the failed- field instead of silently half-applying. Rendered templates are capped at- `TEMPLATE_RENDER_MAX_CHARS` (default 64 KiB) instead of growing unbounded. Status media used to- write the file before its row (a crash between them left a permanent orphan) and purge deleted- the row even when the file delete failed; ingest is now row-first with `write_failed` recorded on- attachment failure, purge keeps the row for the next sweep when the file delete fails, and a- periodic sweep reclaims `statuses/` files no row references after a grace period. The search FTS- probe queried `information_schema` unscoped, so a `POSTGRES_SCHEMA` deployment could read a- namesake table in another schema and pick the wrong availability posture in degraded states; it- now resolves the table through the session `search_path` via `to_regclass('messages')` and probe- errors fail closed without caching. **Breaking (behavior):** batches over 256 participants and- renders over the cap are now 400s. (#964, #966)+- **Infra config writes are section-scoped, mode-aware, and strictly coerced, and the bootstrap config+ guards cover the paths the app actually uses.** Saving config used to clobber sections absent from the+ payload and carry stale secrets across mode flips (built-in `minioadmin`/`openwa` credentials surviving+ into an external-blank config, which the production secret guard then rejected at the next boot — a+ crash-loop with the dashboard dead); writes now merge per key, drop the old mode's secrets on a+ builtin→external flip (`S3_ENDPOINT` clearable), keep a re-keyed built-in Postgres password instead of+ re-stamping the bundled default on every save (it is reset only when switching in from an external+ database), and re-run the production default-secret assertion at save time (400 before anything hits+ disk). That assertion judges the configuration the next boot would actually see: a value supplied by the+ host or orchestrator (compose `environment:`) takes precedence over the saved file just as it does at+ boot, with a blank forward counting as unset, while values the loader itself merged in from `.env` and+ `data/.env.generated` do not — so a save is judged on the config being written rather than on the one it+ replaces. Controller-local DTOs moved to `dto/` with strict coercion, so a form-encoded `'false'` can no+ longer persist as `'true'` for the boolean flags. The SQLite main/data path-collision guard now resolves+ paths exactly like the runtime (and also fires for CLI migration invocations), `REDIS_ENABLED` is strictly+ validated (a typo fails boot instead of silently downgrading the throttler and cache to in-memory), the+ numeric env checks accept plain decimal digits only — an exponent or hex spelling (`1e6`, `0x100`) now+ fails boot instead of validating as one number while the app, which reads these back with `parseInt`,+ configures another — `WEBHOOK_MAX_PAYLOAD_BYTES` is validated positive-only (a `0` cap would reject every+ webhook dispatch), and a boot sweep deletes `storage-export-*` archives orphaned by a restart after+ `STORAGE_EXPORT_SWEEP_MAX_AGE_MS` (default 24h). Numeric knobs whose `0` is a documented opt-out now read+ a blank or whitespace-only value — exactly what a compose `${KEY:-}` forward renders — as unset and fall+ back to their default instead of parsing it as `0`: a blank `INGRESS_INSTANCE_LIMIT` used to mean a limit+ of zero, which 429'd every inbound ingress webhook, and a blank `BULK_MAX_CONCURRENT_BATCHES` silently+ meant unlimited. **Breaking (behavior):** partial config payloads now preserve omitted fields instead of+ resetting them (the dashboard's full payload is byte-identical), and non-canonical `REDIS_ENABLED` values+ — along with numeric variables spelled in exponent or hex notation — now fail boot. (#946, #960)++- **Bulk batches re-validate rendered payloads and cancel terminally, and outbound rows stuck PENDING after+ a crash are reaped.** Media presence/size was only checked at batch creation, so `{{variables}}` and the+ `message:sending` hook could grow a payload past the cap afterwards — every item is now re-validated+ post-gate (violations fail the item, honoring `stopOnError`). A cancel landing before the first item could+ be fully overwritten by the cadence/final writes and send the whole batch anyway; all status transitions+ are now DB-conditional on the current status, so CANCELLED stays terminal (only exact duplicate entries+ are deduped first-wins at creation). Rows left PENDING when the process dies between the pre-send save and+ the final save previously stayed PENDING forever (in the DB and in plugin search indexes); a periodic+ reaper (`MESSAGE_REAPER_INTERVAL_MS`/`_GRACE_MS`/`_BATCH_SIZE`, defaults 10min/1h/50) marks them FAILED+ with a `reapedAt` marker and re-emits `message:persisted` so hook-driven providers reconcile. The reap+ write is itself conditional on the row still being PENDING, so a send that resolves between the sweep's+ scan and its write keeps its own SENT outcome and engine message id. (#955, #958)++- **API-key usage accounting no longer loses deltas, and the queue dashboard leaves an audit trail.** A+ failed `pendingUsage` save dropped the accumulated delta and 500'd the request (the delta now merges back+ and the request stands); nothing flushed on shutdown, so the last window's usage vanished (a bounded+ `onModuleDestroy` flush now writes it). Bull Board rejected requests with no audit record and+ queue-mutating UI actions left none either — 401/403s now write the standard failed-auth row (429s are+ left to the limiter), and authenticated non-GET requests write a new `QUEUE_BOARD_MUTATED` action with+ actor/method/path. The bootstrap `data/.api-key` file and boot banner pointed at keys after+ rotation/revoke; the file is now removed when its key no longer validates (checked by hash at boot, and on+ the revoke/delete paths) — unless a key row still carries the file's prefix, which means the hash miss+ came from a changed `API_KEY_PEPPER` rather than a dead key: the file then survives and a WARN names the+ repair (restore the original pepper, or rotate the key). (#963)++- **Group participant batches, template renders, and status media are bounded and reconciled, and the+ Postgres FTS probe reads the active schema.** Participant arrays accept at most 256 entries (the engine+ works them serially) and a partially-failing settings patch now names the failed field instead of silently+ half-applying. Rendered templates are capped at `TEMPLATE_RENDER_MAX_CHARS` (default 64 KiB) instead of+ growing unbounded. Status media used to write the file before its row (a crash between them left a+ permanent orphan) and purge deleted the row even when the file delete failed; ingest is now row-first with+ `write_failed` recorded whenever the media ends up unattached — a failed file write or a failed post-write+ row update — so the `status.received` webhook always names the reason for a missing attachment, purge+ keeps the row for the next sweep when the file delete fails (and reports nothing purged when that is every+ expired row), and a periodic sweep reclaims `statuses/` files no row references after a grace period,+ walking that prefix in the store directly so a store larger than a single listing leaves no orphan+ stranded. The search FTS probe queried `information_schema` unscoped, so a `POSTGRES_SCHEMA` deployment+ could read a namesake table in another schema and pick the wrong availability posture in degraded states;+ it now resolves the table through the session `search_path` via `to_regclass('messages')` and probe errors+ fail closed without caching. **Breaking (behavior):** batches over 256 participants and renders over the+ cap are now 400s. (#964, #966)- **Contract and documentation drift corrections.** `POST /api/sessions` returned the raw entity(leaking `config`/`proxyUrl`) instead of the documented DTO — it now maps through@@ -238,34 +254,44 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Security- **The HTTP body parser, the WebSocket gateway, and the plugin install path are now bounded against- memory-exhaustion and supply-chain attacks, and the dashboard's plugin frame and CSV export no- longer leak or inject.** Five hardening fixes: the bootstrap only enforced a **per-request**- `BODY_SIZE_LIMIT`, so N concurrent near-limit bodies pinned N×limit bytes before any guard ran- (the throttler sits behind the body parser) — a new aggregate in-flight body budget- (`INFLIGHT_BODY_BUDGET_BYTES`, default 4× the per-request cap) reserves `Content-Length` at- admission and counts chunked bytes per `data` event, rejecting over-budget requests with 503 +- `Retry-After` + `Connection: close` (exactly-once release across finish/close/error/abort).- The WebSocket gateway had no rate limit on handshakes (every connect did a DB lookup), no per-key- socket cap, and no per-frame throttle — an unauthenticated connection flood, a valid-key frame- flood, or socket exhaustion were all open; it now enforces three independent limits (per-IP- handshake window, per-key socket cap, per-token frame bucket), all memory-bounded by LRU maps- with re-insertion-on-touch so an active abuser cannot drift to the LRU head, and a new- `RATE_LIMIT_EXCEEDED` audit action is sampled at 1/min/kind+subject so the audit writes cannot- themselves become the flood. Plugin install accepted `http://` URLs with no integrity check- (MITM-substitutable executable code); the DTO now requires `https` and an optional sha256 pin- carried via URL fragment (`#sha256=…`, never sent to the server so a catalog download link can- carry it) or query, fail-closed on mismatch/malformed/conflict. The dashboard plugin config UI+ memory-exhaustion and supply-chain attacks, and the dashboard's plugin frame and CSV export no longer leak+ or inject.** Five hardening fixes: the bootstrap only enforced a **per-request** `BODY_SIZE_LIMIT`, so N+ concurrent near-limit bodies pinned N×limit bytes before any guard ran (the throttler sits behind the body+ parser) — a new aggregate in-flight body budget (`INFLIGHT_BODY_BUDGET_BYTES`, default 4× the per-request+ cap) reserves `Content-Length` at admission, rejecting over-budget requests with 503 + `Retry-After` ++ `Connection: close` (exactly-once release across finish/close/error/abort). A chunk-encoded body declares+ no length, so it takes a small opening reservation that is then reconciled against the bytes actually read+ off the socket — a tiny chunked upload never costs a whole request slot, and one that grows past the+ aggregate is aborted mid-stream. Reservations cannot be squatted on either: a sender that ships headers+ and then goes silent is dropped after 15s without new body bytes rather than holding its declared size+ until Node's request timeout, while any progress resets that clock and a fully-received request is never+ reaped no matter how long its handler runs. The request stream is never tapped, so consumers that attach+ late — the multipart parser, running after the async guards — still see every chunk. The WebSocket gateway+ had no rate limit on handshakes (every connect did a DB lookup), no per-key socket cap, and no per-frame+ throttle — an unauthenticated connection flood, a valid-key frame flood, or socket exhaustion were all+ open; it now enforces three independent limits (per-IP handshake window, per-key socket cap, per-token+ frame bucket). The handshake window is charged before authentication, so a flood never reaches the key+ lookup, and refunded once the handshake proves authentic — it therefore bounds **failed** handshakes,+ while authenticated volume stays bounded by the socket cap and clients sharing one NAT or reverse-proxy+ address cannot shut each other out of the dashboard. All three are memory-bounded by LRU maps with+ re-insertion-on-touch so an active abuser cannot drift to the LRU head, and a new `RATE_LIMIT_EXCEEDED`+ audit action is sampled at 1/min/kind+subject so the audit writes cannot themselves become the flood.+ Plugin install accepted `http://` URLs with no integrity check (MITM-substitutable executable code); the+ DTO now requires `https` and an optional sha256 pin carried via URL fragment (`#sha256=…`, never sent to+ the server so a catalog download link can carry it), fail-closed on a malformed marker or a digest+ mismatch — the fragment is the only honored marker, since a `sha256`/`checksum` query parameter belongs to+ the download host and seizing it would mis-verify an unrelated URL. The dashboard plugin config UIrendered in an `allow-scripts` sandbox that inherits the dashboard CSP (which allows any `https:`- `img-src`/`media-src`) — a meta-CSP (`img-src 'self' data:`, `media-src 'self' data:`,- `connect-src 'none'`) is now injected as the frame's first `<head>` element, closing the egress- channel `sandbox` alone cannot block. The audit-log CSV export quoted only `,`/`\n`/`"`, so an- attacker-influenced string starting with `=`/`+`/`@`/`-` became a formula when an operator opened- the export in a spreadsheet — cells are now apostrophe-prefixed before structural quoting.- **Breaking (behavior):** legitimate concurrent sends that together exceed the aggregate body- budget now get a transient 503 (raise `INFLIGHT_BODY_BUDGET_BYTES`); a frame/handshake/socket- that exceeds its limit is closed with a `RATE_LIMIT_EXCEEDED` audit row; a plugin install over- `http://` is now rejected (use `https://`); a config-UI plugin that hot-links remote media will- render broken until its CSP-compliant equivalent is used. (#936, #937, #942, #939)+ `img-src`/`media-src`) — a meta-CSP (`img-src 'self' data:`, `media-src 'self' data:`, `connect-src+ 'none'`) is now injected as the frame's first `<head>` element, closing the egress channel `sandbox` alone+ cannot block. The audit-log CSV export quoted only `,`/`\n`/`"`, so an attacker-influenced string starting+ with `=`/`+`/`@`/`-` became a formula when an operator opened the export in a spreadsheet — cells are now+ apostrophe-prefixed before structural quoting. **Breaking (behavior):** legitimate concurrent sends that+ together exceed the aggregate body budget now get a transient 503 (raise `INFLIGHT_BODY_BUDGET_BYTES`),+ and a client that sends request headers and then transmits nothing for 15s has its connection dropped; a+ frame/handshake/socket that exceeds its limit is closed with a `RATE_LIMIT_EXCEEDED` audit row; a plugin+ install over `http://` is now rejected (use `https://`); a config-UI plugin that hot-links remote media+ will render broken until its CSP-compliant equivalent is used. (#936, #937, #942, #939)- **Release workflows now pin every GitHub Action to a commit SHA and stop re-pointing `:latest` onevery main push, and the production Docker build context no longer leaks `.git/`, agent@@ -293,28 +319,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0moves the tag — only a tagged release does; `npm install` now fails where it previously reportedsuccess over a broken dashboard/patch. (#940, #943)-- **The create-instance and regenerate-secret responses no longer echo plaintext values for- secret-flagged config fields, and the whatsapp-web.js engine no longer reports phantom success- for operations it never performed.** Two related honesty fixes:- `(POST /integration/plugins/:pluginId/instances, …/regenerate-secret)` rendered the raw instance- row when `reveal=true`, bypassing `maskedView` — so any config field flagged `secret: true` at any- nesting depth (a nested `credentials.apiToken`, an array-row `webhooks[].signingKey`) was returned- in plaintext alongside the one-time ingress secret/verifyToken reveal. The view builder now always- starts from `maskedView` (fail-closed when the schema is unavailable) and unmasks only the two- documented "revealed once" fields. Separately, several whatsapp-web.js adapter methods reported- success for work that never happened: `subscribeToChannel` fabricated `{id:"undefined"}` from a- boolean return, `add/remove/promote/demoteParticipants` discarded the per-participant outcome- (so a 403 not-admin / 404 not-registered / 409 already-member was a plain 2xx), the catalog reads- (`getCatalog/getProducts/getProduct`) were phantom stubs returning `null`/`[]`, and a dead- Chromium page was folded into a 404/400 not-found. These now answer honestly: 501 for the- unwired catalog/subscribe paths, 403 on a total participant refusal or a discarded `false` boolean- (subject/description/unsubscribe), 503 with `EngineTransportError` for a transport death, and an- additive `results` field on the four participant endpoints carrying the per-participant outcome.- `getProfilePicture` received the same transport-death treatment for consistency. **Breaking- (behavior):** callers that previously read their own config secret back from the create response- now receive `***`, and any client that programmed against a phantom 2xx for the engine operations- above will see the new 4xx/5xx where the operation genuinely cannot succeed. Response envelopes- are otherwise additive only. (#929, #925)+- **The create-instance and regenerate-secret responses no longer echo plaintext values for secret-flagged+ config fields, and the whatsapp-web.js engine no longer reports phantom success for operations it never+ performed.** Two related honesty fixes: `(POST /integration/plugins/:pluginId/instances,+ …/regenerate-secret)` rendered the raw instance row when `reveal=true`, bypassing `maskedView` — so any+ config field flagged `secret: true` at any nesting depth (a nested `credentials.apiToken`, an array-row+ `webhooks[].signingKey`) was returned in plaintext alongside the one-time ingress secret/verifyToken+ reveal. The view builder now always starts from `maskedView` (fail-closed when the schema is unavailable)+ and unmasks only the two documented "revealed once" fields. Separately, several whatsapp-web.js adapter+ methods reported success for work that never happened: `subscribeToChannel` fabricated `{id:"undefined"}`+ from a boolean return, `add/remove/promote/demoteParticipants` discarded the per-participant outcome (so a+ 403 not-admin / 404 not-registered / 409 already-member was a plain 2xx), the catalog reads+ (`getCatalog/getProducts/getProduct`) were phantom stubs returning `null`/`[]`, and a dead Chromium page+ was folded into a 404/400 not-found. These now answer honestly: 501 for the unwired catalog/subscribe+ paths, 403 on a total participant refusal or a discarded `false` boolean+ (subject/description/unsubscribe), 503 with `EngineTransportError` for a transport death, and an additive+ `results` field on the four participant endpoints carrying the per-participant outcome. Where+ whatsapp-web.js delivered a private group invite instead of adding the member, that entry is a success+ carrying the 403 status and an invite-sent message, so an all-invite batch resolves rather than reading as+ a total refusal; the remove/promote/demote entries, which the library only confirms as a whole batch, say+ so in their message instead of implying an individually confirmed outcome. `getProfilePicture` received+ the same transport-death treatment for consistency. **Breaking (behavior):** callers that previously read+ their own config secret back from the create response now receive `***`, and any client that programmed+ against a phantom 2xx for the engine operations above will see the new 4xx/5xx where the operation+ genuinely cannot succeed. Response envelopes are otherwise additive only. (#929, #925)- **Plugin ingress routes with `signature.scheme: 'none'` now require an explicit opt-in.** A `none`-schemeroute is an unauthenticated `@Public()` endpoint that, once an integration instance is provisioned@@ -351,52 +379,63 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0into `node:22-slim` — and the arm64-only `chromium` packages — that the source-tree `npm audit`gate cannot see. Runs at release time only, so it never touches fork-PR token permissions.-- **Session-scoped API keys can no longer escape their fence through key management or integration- instance management, and plugin `conversation.send` now verifies the mapping belongs to the- envelope's session.** The guard enforces `allowedSessions` only against the `:sessionId` route- param, so surfaces without one slipped through: every `/api/auth/api-keys` route (a scoped ADMIN- could mint an unrestricted ADMIN key, clear another key's scope, or enumerate all credentials —- a total, persistent escape) and the integration instance routes (whose `sessionScope` travels in- the request body and persisted rows the guard never sees). A new `@RequireUnscopedKey()` marker- rejects any allowlisted key on the key-lifecycle controller (403, audited via the existing- failed-auth trail), and instance create/patch/redrive now intersect the requested and persisted- scopes with the caller's allowlist — out-of-scope instances answer 404 (indistinguishable from- missing, so they cannot be probed), and an all-sessions scope is uncreatable by scoped keys.- Separately, `conversation.send` resolved a provider-conversation mapping without comparing its- `sessionId` to the envelope session, so a stale mapping after a scope move could send on the- wrong WhatsApp session; the lookup now fails closed on any mismatch (an explicit `chatId` in the- envelope is unaffected). **Breaking (behavior):** session-scoped ADMIN keys now get 403 on all- key-management routes and can only manage instances bound inside their own sessions; unrestricted- keys (including the bootstrap key) are unchanged. (#916, #920)--- **The last-admin guard is race-safe, and webhook media fan-out is bounded.** The- last-usable-admin check ran check-then-act across an `await`, so two concurrent demote/delete- requests against the last two admins both passed and produced a total management lockout; the- check and its mutation now share one in-process mutex (a DB transaction cannot provide this- atomicity on the better-sqlite3 driver), entered only when an operation can actually strip admin- capability. On the webhook side, one inbound media message cloned its full base64 payload per- registered webhook (with no per-session webhook cap) and retained it in Redis on failure: new- registrations above `WEBHOOK_MAX_PER_SESSION` (default 16; existing webhooks grandfathered) are- rejected, media above `WEBHOOK_MEDIA_INLINE_MAX_BYTES` (default 1 MiB) travels as an omitted- marker instead of inline base64, oversized serialized bodies shed their media before enqueue- (delivering the event as a marker rather than dropping it), and the serialized bytes are built- once per delivery for both signing and posting. **Breaking (behavior):** media above the inline- threshold now arrives as a marker (fetch it via history or raise the knob), and webhook- registration past the cap returns 400. (#950, #948)--- **The plugin sandbox runtime is bounded and no longer fails silently.** A hung plugin could pin- all 32 in-flight capability slots forever — capability RPCs now time out- (`PLUGIN_CAP_TIMEOUT_MS`, default 30s), freeing the slot and logging late settles as warnings- (worker work already running is not cancelled, by design). Hook handler errors inside the sandbox- were swallowed wholesale; the first handler error per hook now surfaces as a rate-limited- structured host log and in the plugin's health check. Per-plugin storage writes are quota-bounded- (`PLUGIN_STORAGE_MAX_BYTES`, default 50 MiB) and the log relay truncates and caps throughput per- plugin. Plugin search-provider responses are validated at the host boundary — malformed- hits/totals now fail with 502 instead of a bogus 200/500. `conversation.send` with- `type: 'location'` fell through to an empty text message; coordinates are now part of the- envelope and send a real location (invalid ranges are rejected). **Breaking (behavior):**- malformed plugin search results now 502, and plugins relying on the empty-text fallthrough get an- explicit error. (#954)+- **Session-scoped API keys can no longer escape their fence through key management or integration instance+ management, and plugin `conversation.send` now verifies the mapping belongs to the envelope's session.**+ The guard enforces `allowedSessions` only against the `:sessionId` route param, so surfaces without one+ slipped through: every `/api/auth/api-keys` route (a scoped ADMIN could mint an unrestricted ADMIN key,+ clear another key's scope, or enumerate all credentials — a total, persistent escape) and the integration+ instance routes (whose `sessionScope` travels in the request body and persisted rows the guard never+ sees). A new `@RequireUnscopedKey()` marker rejects any allowlisted key on the key-lifecycle controller+ (403, audited via the existing failed-auth trail), and instance create/patch/redrive now intersect the+ requested and persisted scopes with the caller's allowlist — out-of-scope instances answer 404+ (indistinguishable from missing, so they cannot be probed), and an all-sessions scope is uncreatable by+ scoped keys. Separately, `conversation.send` resolved a provider-conversation mapping without comparing+ its `sessionId` to the envelope session, so a stale mapping after a scope move could send on the wrong+ WhatsApp session; the lookup now fails closed on any mismatch (an explicit `chatId` in the envelope is+ unaffected) — except when the mapping's own session no longer exists, which means the operator deleted and+ re-paired it: the row is stale rather than cross-session, so it is rebound to the envelope's (already+ activation-gated) session and the send proceeds, and a mapping upsert that collides with such a dead+ session's row supersedes it instead of failing forever. Without that repair a deleted session's rows+ bricked `conversation.send` for that conversation permanently. A mapping owned by another live session is+ still a genuine violation and still fails closed. **Breaking (behavior):** session-scoped ADMIN keys now+ get 403 on all key-management routes and can only manage instances bound inside their own sessions;+ unrestricted keys (including the bootstrap key) are unchanged. (#916, #920)++- **The last-admin guard is race-safe, and webhook media fan-out is bounded.** The last-usable-admin check+ ran check-then-act across an `await`, so two concurrent demote/delete requests against the last two admins+ both passed and produced a total management lockout; the check and its mutation now share one in-process+ mutex (a DB transaction cannot provide this atomicity on the better-sqlite3 driver), entered whenever the+ target key is an ADMIN and the operation can strip its capability, with the target re-read inside the+ critical section so the decision never runs against a pre-lock snapshot. A usable admin is an active,+ unexpired ADMIN key with no session scope: the key-lifecycle routes are fenced behind+ `@RequireUnscopedKey()`, so a session-scoped admin can authenticate but can never manage keys, and+ counting it as a survivor would bless the removal of the last key that can — a lockout with no in-band+ recovery, since the boot seed only re-seeds an empty key table. Applying a session scope to the last+ unscoped admin is therefore refused with **409 Conflict**, exactly like demoting, revoking, deleting, or+ expiring it. On the webhook side, one inbound media message cloned its full base64 payload per registered+ webhook (with no per-session webhook cap) and retained it in Redis on failure: new registrations above+ `WEBHOOK_MAX_PER_SESSION` (default 16; existing webhooks grandfathered) are rejected, media above+ `WEBHOOK_MEDIA_INLINE_MAX_BYTES` (default 1 MiB) travels as an omitted marker instead of inline base64,+ oversized serialized bodies shed their media before enqueue (delivering the event as a marker rather than+ dropping it), and the serialized bytes are built once per delivery for both signing and posting.+ **Breaking (behavior):** media above the inline threshold now arrives as a marker (fetch it via history or+ raise the knob), and webhook registration past the cap returns 400. (#950, #948)++- **The plugin sandbox runtime is bounded and no longer fails silently.** A hung plugin could pin all 32+ in-flight capability slots forever — capability RPCs now time out (`PLUGIN_CAP_TIMEOUT_MS`, default 30s),+ freeing the slot and logging late settles as warnings (worker work already running is not cancelled, by+ design). Hook handler errors inside the sandbox were swallowed wholesale; the first handler error per hook+ now surfaces as a rate-limited structured host log and in the plugin's health check, and a plugin whose+ load fails at boot has its registry entry reconciled to ERROR instead of still reporting installed/enabled+ (the operator config is preserved, and a later successful load restores the status). Per-plugin storage+ writes are quota-bounded (`PLUGIN_STORAGE_MAX_BYTES`, default 50 MiB) and the log relay truncates, caps+ throughput per plugin, and flushes its dropped-line count on worker exit so a plugin that goes quiet+ before the window rolls over still reports what it dropped. Plugin search-provider responses are validated+ at the host boundary — malformed hits/totals now fail with 502 instead of a bogus 200/500.+ `conversation.send` with `type: 'location'` fell through to an empty text message; coordinates are now+ part of the envelope and send a real location (invalid ranges are rejected). **Breaking (behavior):**+ malformed plugin search results now 502, and plugins relying on the empty-text fallthrough get an explicit+ error. (#954)### Changed@@ -448,11 +487,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **Ten operator-tunable environment variables are now documented in `.env.example`.**`INGRESS_MAX_ATTEMPTS`, `INGRESS_RETRY_DELAY_MS`, `INGRESS_RETENTION_DAYS`, `SSRF_DNS_TIMEOUT_MS`,`INGRESS_WORKER_CONCURRENCY`, `WEBHOOK_WORKER_CONCURRENCY`, `INBOUND_MEDIA_CONCURRENCY`,- `STATUS_MEDIA_MAX_BYTES`, `PLUGIN_DOWNLOAD_MAX_BYTES`, and `BULK_MAX_CONCURRENT_BATCHES` are read- from the environment with sensible defaults but were absent from the configuration reference. Each- is now documented next to its related block, with the exact default and the parse semantics- (`INGRESS_RETENTION_DAYS <= 0` disables pruning, `BULK_MAX_CONCURRENT_BATCHES = 0` is unlimited, the- DoS trade-off on `SSRF_DNS_TIMEOUT_MS`).+ `STATUS_MEDIA_MAX_BYTES`, `PLUGIN_DOWNLOAD_MAX_BYTES`, and `BULK_MAX_CONCURRENT_BATCHES` are read from the+ environment with sensible defaults but were absent from the configuration reference. Each is now+ documented next to its related block, with the exact default and the parse semantics+ (`INGRESS_RETENTION_DAYS <= 0` disables pruning, `BULK_MAX_CONCURRENT_BATCHES = 0` is unlimited, the DoS+ trade-off on `SSRF_DNS_TIMEOUT_MS`). The numeric knobs whose `0` is a documented opt-out also share one+ parse rule now: the value must be plain decimal digits, an explicit `0` selects that knob's opt-out+ (unlimited for `BULK_MAX_CONCURRENT_BATCHES` and `LID_MAPPING_CACHE_MAX`, sweep-off for+ `MESSAGE_REAPER_INTERVAL_MS` and `INGRESS_RECONCILE_INTERVAL_MS`), and a blank or otherwise unparseable+ value falls back to the documented default rather than the opt-out — a compose `${KEY:-}` forward or a+ stray typo can no longer silently disable a cap, a sweep, or a retry backoff.- **Dockerfile `apt-get install` invocations now use `--no-install-recommends`**(build-stage build deps and production-stage Chromium/Puppeteer deps).@@ -498,26 +542,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **The peer-fed Baileys session maps and chat-history inline media are now bounded, and an RFC forwa-version content integrity is open for a maintainer decision.** `BaileysSessionStore` held five- unbounded maps fed by peer traffic (contacts, chats, lastMessages, lid, ephemeral markers); all- are now LRU-capped at `BAILEYS_SESSION_STORE_MAX_ENTRIES` (default 5000, `0` restores unbounded)- with defined fallbacks on eviction. `getChatHistory(includeMedia=true)` accumulated up to ~100 ×- 50 MiB of base64 in one response with no way to cancel — an aggregate budget- (`CHAT_HISTORY_MEDIA_BUDGET_BYTES`, default 25 MiB) now omits further media behind the existing- `omitted` marker, and the loop honors request abort. `docs/plans/2026-07-27-wa-version-integrity-options.md`- analyzes the structural options for integrity-checking the pinned WhatsApp Web HTML (per-release- hash allowlist, signed hash channel/mirror, documented accepted-risk, operator pins) and asks the- maintainer for a decision; the transparency layer (warn log, accurate docs, dashboard source- badge) already shipped. (#951, #962)--- **MCP tool inputs now enforce the same caps as the REST DTOs, and the dashboard's catalogs and- modals are complete.** Nine MCP tool fields (location description/address, contact name/number,- reply text, reaction emoji, group name/subject/description) accepted values the equivalent REST- endpoints reject — the Zod schemas now share the DTOs' cap constants. On the dashboard, 15- `plugins.*` keys used by the Plugins page are translated in all 12 locales, count badges use real- plural forms (including the Arabic and Hebrew category sets), `failed`/`authenticating` session- statuses render localized in both status renderers, and all 13 hand-written modals moved to the- shared Modal with `role="dialog"`, focus trap + restore-to-trigger, Escape-to-close, and- background scroll-lock. (#959, #965)+ unbounded maps fed by peer traffic (contacts, chats, lastMessages, lid, ephemeral markers); all are now+ LRU-capped at `BAILEYS_SESSION_STORE_MAX_ENTRIES` (default 5000, `0` restores unbounded) with defined+ fallbacks on eviction. `getChatHistory(includeMedia=true)` accumulated up to ~100 × 50 MiB of base64 in+ one response with no way to cancel — an aggregate budget (`CHAT_HISTORY_MEDIA_BUDGET_BYTES`, default 25+ MiB) now omits further media behind the existing `omitted` marker, and the loop honors request abort. A+ caller that ingests into a store rather than into one HTTP response — the status seed, which passes its+ own per-item media cap — is budgeted from that cap instead of the response default, so a story feed+ carrying several full-size videos is stored whole while the pass stays bounded.+ `docs/plans/2026-07-27-wa-version-integrity-options.md` analyzes the structural options for+ integrity-checking the pinned WhatsApp Web HTML (per-release hash allowlist, signed hash channel/mirror,+ documented accepted-risk, operator pins) and asks the maintainer for a decision; the transparency layer+ (warn log, accurate docs, dashboard source badge) already shipped. (#951, #962)++- **MCP tool inputs now enforce the same caps as the REST DTOs, and the dashboard's catalogs and modals are+ complete.** Nine MCP tool fields (location description/address, contact name/number, reply text, reaction+ emoji, group name/subject/description) accepted values the equivalent REST endpoints reject — the Zod+ schemas now share the DTOs' cap constants, including the 256-entry participant cap on the group create/add+ tools. `GroupAddParticipants` also returns the per-participant `results` and derives its `success` flag+ from them, so a batch in which every participant was refused (not registered, already a member) no longer+ reports success to the caller; a partial refusal reports how many were added rather than failing the+ batch. On the dashboard, 15 `plugins.*` keys used by the Plugins page are translated in all 12 locales,+ count badges use real plural forms (including the Arabic and Hebrew category sets),+ `failed`/`authenticating` session statuses render localized in both status renderers, and all 13+ hand-written modals moved to the shared Modal with `role="dialog"`, focus trap + restore-to-trigger,+ Escape-to-close, and background scroll-lock. (#959, #965)- **CI now boots the queued dispatch path against a real Redis, and the Docker managed profilesmatch compose.** A new `queue-on` e2e suite starts the app with `QUEUE_ENABLED=true` against adiff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsxindex 70ff83f17..09455cad4 100644--- a/dashboard/src/App.tsx+++ b/dashboard/src/App.tsx@@ -82,7 +82,7 @@ function AppContent() {headers: { 'X-API-Key': savedKey },}).then(async res => {- const decision = resolveStartupValidation(res.ok, await res.json().catch(() => null));+ const decision = resolveStartupValidation(res.status, await res.json().catch(() => null));if (decision.action === 'logout') {handleLogout();} else if (decision.action === 'role') {@@ -91,7 +91,7 @@ function AppContent() {}).catch(() => {// Network failure (API unreachable): keep the cached role so a transient outage at- // page load doesn't eject the user — an explicit non-ok answer above still logs out.+ // page load doesn't eject the user — an explicit 401/403 above still logs out.});}, [savedKey, setRole, handleLogout]);diff --git a/dashboard/src/hooks/useWebSocket.ts b/dashboard/src/hooks/useWebSocket.tsindex b8ff45d35..a102468ce 100644--- a/dashboard/src/hooks/useWebSocket.ts+++ b/dashboard/src/hooks/useWebSocket.ts@@ -133,8 +133,11 @@ warnIfInsecureHttpUrl(SOCKET_URL, 'VITE_WS_URL');export function useWebSocket(events: WebSocketEvents = {}) {const socketRef = useRef<Socket | null>(null);const [isConnected, setIsConnected] = useState(false);- // True once Socket.IO exhausts its reconnection attempts and permanently gives up — lets the- // UI show a "connection lost" indicator + a manual retry instead of silently going stale.+ // True when the connection is dead until the user retries: Socket.IO either exhausted its+ // reconnection attempts, or the server itself closed the socket (rate limit, auth rejection,+ // key eviction — a server-initiated close sets skipReconnect, so no auto-reconnect runs and+ // `reconnect_failed` never fires). Lets the UI show a "connection lost" indicator + a manual+ // retry instead of silently going stale.const [connectionFailed, setConnectionFailed] = useState(false);const connect = useCallback(() => {@@ -168,8 +171,16 @@ export function useWebSocket(events: WebSocketEvents = {}) {setConnectionFailed(false);});- socketRef.current.on('disconnect', () => {+ socketRef.current.on('disconnect', reason => {setIsConnected(false);+ // A server-initiated close (handshake rate limit, auth rejection, key eviction) sets+ // Socket.IO's skipReconnect: no auto-reconnect runs, so `reconnect_failed` never fires+ // and without this the tab would silently stop receiving events. Surface the same+ // recoverable failure state — the banner's manual retry opens a fresh socket, which+ // skipReconnect does not block.+ if (reason === 'io server disconnect') {+ setConnectionFailed(true);+ }});socketRef.current.on('connect_error', error => {diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsxindex 47a49c953..bfbbfa0e5 100644--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@ -602,9 +602,12 @@ export function Chats() {[selectedSessionId, t, showWarningToast],);- // Drop pending trailing calls on unmount / session switch so a late fire never targets an- // unmounted component or the previous session.- useEffect(() => () => markReadCoalescer.cancel(), [markReadCoalescer]);+ // Flush pending trailing calls on unmount / session switch: the mark-as-read POST is+ // fire-and-forget (a failure only raises a warning toast), so firing on the way out is safe —+ // and dropping the pending call would leave the last messages of a quickly-exited chat unread.+ // The flush closure still references the PREVIOUS session on a session switch, which is exactly+ // where those queued reads belong.+ useEffect(() => () => markReadCoalescer.flush(), [markReadCoalescer]);const markChatRead = useCallback((chatId: string) => {diff --git a/dashboard/src/pages/Infrastructure.tsx b/dashboard/src/pages/Infrastructure.tsxindex b6a7c2766..d59a72847 100644--- a/dashboard/src/pages/Infrastructure.tsx+++ b/dashboard/src/pages/Infrastructure.tsx@@ -377,6 +377,50 @@ export function Infrastructure() {}};+ // POST the replace-all restore and fold the backend's orphan-engine contract into the UI. A 409+ // means live engines exist for sessions the backup would remove (the server message lists them);+ // the contract's preferred retry is stopOrphans=true, which stops those engines inside the+ // request, so offer it as a confirm. force=true is deliberately not offered (the api client does+ // not even send it): it leaves the engines running until a restart.+ const runImport = async (tables: Record<string, unknown[]>, stopOrphans = false): Promise<void> => {+ try {+ const res = await infraApi.importData(tables, stopOrphans ? { stopOrphans: true } : undefined);+ if (res.imported) {+ // notices carry non-fatal operator messages (orphan teardown details); restartRequired+ // means a teardown failed and only a restart guarantees cleanup — surface both on success.+ if (res.restartRequired || (res.notices && res.notices.length > 0)) {+ toast.warning(t('infrastructure.migration.importOk'), (res.notices ?? []).join('; ') || undefined);+ } else {+ toast.success(t('infrastructure.migration.importOk'));+ }+ } else {+ toast.error(+ t('infrastructure.migration.importFailed'),+ (res.warnings || []).slice(0, 3).join('; ') || res.message,+ );+ }+ } catch (err) {+ const status = (err as { status?: number } | null)?.status;+ if (status === 409 && !stopOrphans && err instanceof Error) {+ // The confirm doubles as the refusal display: OK retries with stopOrphans=true, Cancel+ // leaves the engines (and the current data) untouched. A 409 on the retry itself (an+ // engine started mid-import) falls through to the plain error toast — no confirm loop.+ if (window.confirm(err.message)) await runImport(tables, true);+ else toast.error(t('infrastructure.migration.importFailed'), err.message);+ return;+ }+ // A large backup can exceed the request body cap (default 25mb) — give an actionable message+ // instead of a bare "Payload Too Large". The status is carried on the Error by the api client.+ const detail =+ status === 413+ ? t('infrastructure.migration.importTooLarge')+ : err instanceof Error+ ? err.message+ : t('common.unknownError');+ toast.error(t('infrastructure.migration.importFailed'), detail);+ }+ };+// Restore a previously-exported backup into the CURRENT database (use after switching + restart).// Import REPLACES all current data, so validate + confirm (showing the row count) before any call.const handleImportBackup = async (file: File) => {@@ -395,24 +439,7 @@ export function Infrastructure() {if (!window.confirm(t('infrastructure.migration.importConfirm', { rows }))) return;setMigrating(true);try {- const res = await infraApi.importData(parsed.tables);- if (res.imported) toast.success(t('infrastructure.migration.importOk'));- else- toast.error(- t('infrastructure.migration.importFailed'),- (res.warnings || []).slice(0, 3).join('; ') || res.message,- );- } catch (err) {- // A large backup can exceed the request body cap (default 25mb) — give an actionable message- // instead of a bare "Payload Too Large". The status is carried on the Error by the api client.- const status = (err as { status?: number } | null)?.status;- const detail =- status === 413- ? t('infrastructure.migration.importTooLarge')- : err instanceof Error- ? err.message- : t('common.unknownError');- toast.error(t('infrastructure.migration.importFailed'), detail);+ await runImport(parsed.tables);} finally {setMigrating(false);}diff --git a/dashboard/src/pages/Sessions.tsx b/dashboard/src/pages/Sessions.tsxindex c274adc33..9faa83bfa 100644--- a/dashboard/src/pages/Sessions.tsx+++ b/dashboard/src/pages/Sessions.tsx@@ -130,6 +130,13 @@ export function Sessions() {}}, [isConnected, subscribe]);+ // Rooms are per-socket on the backend: a reconnect lands on a fresh socket with no+ // subscriptions, so the per-session dedup set must be forgotten or the join effect+ // above would skip every already-listed id and no feed frame would arrive again.+ useEffect(() => {+ if (!isConnected) feedStateRef.current.subscribedIds.clear();+ }, [isConnected]);+// In per-session mode, sessions loaded/created after the fallback still need their rooms.useEffect(() => {if (isConnected && feedStateRef.current.scope === 'per-session') {diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex d403c82a7..61133c153 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -1004,14 +1004,26 @@ export const infraApi = {tables: Record<string, unknown[]>;counts: Record<string, number>;}>('/infra/export-data'),- importData: (tables: Record<string, unknown[]>) =>- request<{ imported: boolean; counts?: Record<string, number>; message?: string; warnings?: string[] }>(- '/infra/import-data',- {- method: 'POST',- body: JSON.stringify({ tables }),- },- ),+ // 200 contract includes the orphan-engine reconciliation result (restartRequired / notices /+ // stopped+failed ids). A 409 (live engines exist for sessions the backup would remove; the error+ // message lists them) is retried by the caller with stopOrphans=true, which stops those engines+ // inside the request. force is deliberately NOT exposed: it leaves the engines writing into the+ // restored tables until a restart — the window stopOrphans exists to close.+ importData: (tables: Record<string, unknown[]>, options?: { stopOrphans?: boolean }) =>+ request<{+ imported: boolean;+ counts?: Record<string, number>;+ message?: string;+ warnings?: string[];+ notices?: string[];+ restartRequired?: boolean;+ orphanedEngines?: string[];+ stoppedOrphanEngines?: string[];+ failedOrphanEngines?: string[];+ }>('/infra/import-data', {+ method: 'POST',+ body: JSON.stringify({ tables, ...options }),+ }),};// =============================================================================diff --git a/dashboard/src/utils/authLifecycle.test.ts b/dashboard/src/utils/authLifecycle.test.tsindex b26595a6f..9d7344f22 100644--- a/dashboard/src/utils/authLifecycle.test.ts+++ b/dashboard/src/utils/authLifecycle.test.ts@@ -23,20 +23,29 @@ test('logout cleanup calls clear() on every provided cache', () => {assert.deepEqual(calls, ['a', 'b']);});-test('startup validation: non-ok response (revoked/demoted key) → logout', () => {- assert.deepEqual(resolveStartupValidation(false, null), { action: 'logout' });- assert.deepEqual(resolveStartupValidation(false, { valid: true, role: 'admin' }), { action: 'logout' });+test('startup validation: 401/403 (revoked/demoted/restricted key) → logout', () => {+ assert.deepEqual(resolveStartupValidation(401, null), { action: 'logout' });+ assert.deepEqual(resolveStartupValidation(401, { valid: true, role: 'admin' }), { action: 'logout' });+ assert.deepEqual(resolveStartupValidation(403, null), { action: 'logout' });+});++test('startup validation: 429/5xx keeps the cached role (transient failure, not a revoked key)', () => {+ for (const status of [429, 500, 502, 503]) {+ assert.deepEqual(resolveStartupValidation(status, null), { action: 'keep' }, `status ${status}`);+ // Even a stray valid-looking body cannot upgrade a non-ok answer to a role refresh.+ assert.deepEqual(resolveStartupValidation(status, { valid: true, role: 'admin' }), { action: 'keep' });+ }});test('startup validation: ok + role refreshes the cached role from the server', () => {- assert.deepEqual(resolveStartupValidation(true, { valid: true, role: 'viewer' }), {+ assert.deepEqual(resolveStartupValidation(200, { valid: true, role: 'viewer' }), {action: 'role',role: 'viewer',});});test('startup validation: ok without a usable role keeps the cached role', () => {- assert.deepEqual(resolveStartupValidation(true, { valid: false }), { action: 'keep' });- assert.deepEqual(resolveStartupValidation(true, { valid: true, role: 'superuser' }), { action: 'keep' });- assert.deepEqual(resolveStartupValidation(true, null), { action: 'keep' });+ assert.deepEqual(resolveStartupValidation(200, { valid: false }), { action: 'keep' });+ assert.deepEqual(resolveStartupValidation(200, { valid: true, role: 'superuser' }), { action: 'keep' });+ assert.deepEqual(resolveStartupValidation(200, null), { action: 'keep' });});diff --git a/dashboard/src/utils/authLifecycle.ts b/dashboard/src/utils/authLifecycle.tsindex 2cb4875ae..d31acf023 100644--- a/dashboard/src/utils/authLifecycle.ts+++ b/dashboard/src/utils/authLifecycle.ts@@ -29,17 +29,21 @@ export type StartupValidation =/*** Fold the startup /auth/validate answer into an auth decision:- * - non-ok (401 for a revoked/deleted/expired key) → full logout; the cached role is a lie.+ * - 401/403 (a revoked/deleted/expired key, or one whose restrictions reject this client) → full+ * logout; the cached role is a lie.+ * - any other non-ok status (429 rate limit, 5xx, a proxy error page) → keep the cached role:+ * a transient failure proves nothing about the key, so it must not eject the user.* - ok + role → refresh the cached role from the server (a demoted key must lose its old powers).* - anything else (unexpected body shape) → keep the cached role.* A network throw never reaches this function; the caller keeps the cached role for that case* so a transient outage at page load doesn't eject the user.*/export function resolveStartupValidation(- ok: boolean,+ status: number,body: { valid?: boolean; role?: string } | null,): StartupValidation {- if (!ok) return { action: 'logout' };+ if (status === 401 || status === 403) return { action: 'logout' };+ if (status < 200 || status >= 300) return { action: 'keep' };if (body?.valid && isUserRole(body.role)) return { action: 'role', role: body.role };return { action: 'keep' };}diff --git a/dashboard/src/utils/chatMessages.test.ts b/dashboard/src/utils/chatMessages.test.tsindex 32da99329..f4f56d8d7 100644--- a/dashboard/src/utils/chatMessages.test.ts+++ b/dashboard/src/utils/chatMessages.test.ts@@ -330,6 +330,13 @@ test('capMediaPayloads: under the limit the list is returned untouched (stable rassert.equal(capMediaPayloads(list), list);});+test('the media cap covers the whole fetch window (no dead-end placeholder inside it)', () => {+ // useChatMessages fetches a 100-message slice WITH media and caches it at staleTime: Infinity.+ // A cap below the window strips payloads the user can scroll to, with no refetch path — the+ // stripped rows render the 📎 placeholder forever even though the payload was fetched.+ assert.ok(MEDIA_PAYLOAD_CACHE_LIMIT >= 100);+});+test('capMediaPayloads: past the limit the OLDEST payloads strip to the omitted marker, newest stay', () => {// One over the cap, so exactly the oldest payload must go.const list = Array.from({ length: MEDIA_PAYLOAD_CACHE_LIMIT + 1 }, (_, i) => mediaMsg(`m-${i}`, `PAYLOAD_${i}`));diff --git a/dashboard/src/utils/chatMessages.ts b/dashboard/src/utils/chatMessages.tsindex fb433b8cd..f1b778c6f 100644--- a/dashboard/src/utils/chatMessages.ts+++ b/dashboard/src/utils/chatMessages.ts@@ -64,8 +64,12 @@ export function mergeChatMessages(db: ChatMessage[], history: ChatMessage[]): Ch* the same 📎 placeholder as a history row fetched without media; the newest `keep` stay* renderable (thread + lightbox). Count-based (not byte-based): payloads are bounded upstream* by the backend's media size cap.+ *+ * The cap must cover the fetch window: useChatMessages loads a 100-message slice with media, so a+ * smaller cap strips payloads INSIDE the window the user can scroll to — and with staleTime:+ * Infinity there is no refetch path, leaving a dead-end 📎 placeholder for media that was fetched.*/-export const MEDIA_PAYLOAD_CACHE_LIMIT = 25;+export const MEDIA_PAYLOAD_CACHE_LIMIT = 100;/*** Enforce MEDIA_PAYLOAD_CACHE_LIMIT on an ascending message list, stripping the oldest payloadsdiff --git a/dashboard/src/utils/modalA11y.test.ts b/dashboard/src/utils/modalA11y.test.tsindex 6baaf5648..668f799e3 100644--- a/dashboard/src/utils/modalA11y.test.ts+++ b/dashboard/src/utils/modalA11y.test.ts@@ -168,3 +168,39 @@ test('cleanup removes the keydown listener (no stray closes after unmount)', ()doc.dispatchKey(makeKeyEvent('Escape'));assert.equal(closed, 0);});++test('nested dialogs: Escape closes only the topmost; the parent closes once it is topmost again', () => {+ const { doc, card } = makeWorld();+ let parentClosed = 0;+ let nestedClosed = 0;+ const unbindParent = bindModalA11y(doc as never, card as never, () => parentClosed++);+ const unbindNested = bindModalA11y(doc as never, card as never, () => nestedClosed++);++ const first = makeKeyEvent('Escape');+ doc.dispatchKey(first);+ assert.equal(nestedClosed, 1);+ assert.equal(parentClosed, 0); // the parent's form input survives the nested Escape+ assert.equal(first.propagationStopped, true);++ // React unmounts the closed nested dialog (running its cleanup) — now the parent owns Escape.+ unbindNested();+ doc.dispatchKey(makeKeyEvent('Escape'));+ assert.equal(parentClosed, 1);+ unbindParent();+});++test('a nested dialog still owns Escape when the parent unmounts first', () => {+ const { doc, card } = makeWorld();+ let parentClosed = 0;+ let nestedClosed = 0;+ const unbindParent = bindModalA11y(doc as never, card as never, () => parentClosed++);+ const unbindNested = bindModalA11y(doc as never, card as never, () => nestedClosed++);++ // The parent was closed by an overlay click, unmounting its subtree — including this nested+ // dialog's container in the real DOM; its binder may outlive the parent's.+ unbindParent();+ doc.dispatchKey(makeKeyEvent('Escape'));+ assert.equal(nestedClosed, 1);+ assert.equal(parentClosed, 0);+ unbindNested();+});diff --git a/dashboard/src/utils/modalA11y.ts b/dashboard/src/utils/modalA11y.tsindex dfdf6375e..eb85dcefa 100644--- a/dashboard/src/utils/modalA11y.ts+++ b/dashboard/src/utils/modalA11y.ts@@ -9,6 +9,12 @@const FOCUSABLE ='button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';+// Stack of currently-open dialogs, most recently opened last. Every binder listens for keydown on+// the same document in the capture phase, and stopPropagation() does NOT stop same-target+// listeners — so without this stack, Escape inside a nested dialog also closes the parent and+// loses its form input. Only the topmost entry owns Escape.+const modalStack: object[] = [];+function visibleFocusables(card: HTMLElement): HTMLElement[] {return Array.from(card.querySelectorAll<HTMLElement>(FOCUSABLE)).filter(el => el.offsetParent !== null);}@@ -28,8 +34,13 @@ export function bindModalA11y(doc: Document, card: HTMLElement, onClose: () => vconst previouslyFocused =active && typeof (active as HTMLElement).focus === 'function' ? (active as HTMLElement) : null;+ const stackEntry = {};+ modalStack.push(stackEntry);+const onKeyDown = (event: KeyboardEvent) => {if (event.key === 'Escape') {+ // A nested dialog is open above this one — it owns Escape (see modalStack).+ if (modalStack[modalStack.length - 1] !== stackEntry) return;// Capture phase: nested widgets (selects, menus) may also listen for Escape — the dialog// owns dismissal while it is open.event.stopPropagation();@@ -57,6 +68,8 @@ export function bindModalA11y(doc: Document, card: HTMLElement, onClose: () => v(visibleFocusables(card)[0] ?? card).focus();return () => {+ const stackIndex = modalStack.indexOf(stackEntry);+ if (stackIndex !== -1) modalStack.splice(stackIndex, 1);doc.removeEventListener('keydown', onKeyDown, true);doc.body.style.overflow = previousOverflow;// Restore focus to the trigger — unless it left the document while the dialog was opendiff --git a/dashboard/src/utils/trailingCoalescer.test.ts b/dashboard/src/utils/trailingCoalescer.test.tsindex 36950a9d9..80eac8157 100644--- a/dashboard/src/utils/trailingCoalescer.test.ts+++ b/dashboard/src/utils/trailingCoalescer.test.ts@@ -48,7 +48,7 @@ test('different keys coalesce independently', t => {coalescer.cancel();});-test('cancel() drops pending calls (unmount) so nothing fires late', t => {+test('cancel() drops pending calls so nothing fires late', t => {t.mock.timers.enable({ apis: ['setTimeout'] });const sent: string[] = [];const coalescer = createTrailingCoalescer<string>(key => sent.push(key), 750);@@ -60,3 +60,29 @@ test('cancel() drops pending calls (unmount) so nothing fires late', t => {t.mock.timers.tick(10_000);assert.deepEqual(sent, []);});++test('flush() fires every pending key immediately (unmount/navigation does not lose the call)', t => {+ t.mock.timers.enable({ apis: ['setTimeout'] });+ const sent: string[] = [];+ const coalescer = createTrailingCoalescer<string>(key => sent.push(key), 750);++ coalescer.call('chat-A');+ coalescer.call('chat-B');+ coalescer.flush();++ assert.deepEqual(sent.sort(), ['chat-A', 'chat-B']);+ // Nothing is left pending: a later tick must not re-fire, and cancel() is a no-op.+ coalescer.cancel();+ t.mock.timers.tick(10_000);+ assert.deepEqual(sent.sort(), ['chat-A', 'chat-B']);+});++test('flush() with nothing pending is a no-op', t => {+ t.mock.timers.enable({ apis: ['setTimeout'] });+ const sent: string[] = [];+ const coalescer = createTrailingCoalescer<string>(key => sent.push(key), 750);++ coalescer.flush();+ t.mock.timers.tick(10_000);+ assert.deepEqual(sent, []);+});diff --git a/dashboard/src/utils/trailingCoalescer.ts b/dashboard/src/utils/trailingCoalescer.tsindex dced48960..e15265d0b 100644--- a/dashboard/src/utils/trailingCoalescer.ts+++ b/dashboard/src/utils/trailingCoalescer.ts@@ -3,11 +3,13 @@//// Used for the mark-as-read RPC: every incoming message in the visible chat raises a read// event, and a per-event POST sprays the gateway into 429s. Keys are independent (each chat-// gets its own quiet window), and `cancel()` drops every pending call so a late fire never-// targets an unmounted component.+// gets its own quiet window). `flush()` fires every pending key immediately — used on+// unmount/navigation so a queued mark-as-read isn't lost when the user leaves mid-window —+// while `cancel()` drops pending calls without firing them.export interface TrailingCoalescer<K> {call(key: K): void;+ flush(): void;cancel(): void;}@@ -25,6 +27,12 @@ export function createTrailingCoalescer<K>(send: (key: K) => void, delayMs: numb}, delayMs),);},+ flush() {+ const pending = [...timers.keys()];+ for (const timer of timers.values()) clearTimeout(timer);+ timers.clear();+ for (const key of pending) send(key);+ },cancel() {for (const timer of timers.values()) clearTimeout(timer);timers.clear();diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 0d6c7811c..ec8ae9722 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -4326,7 +4326,7 @@ Install a plugin from an uploaded `.zip` package.Install a plugin by downloading its `.zip` from an HTTPS URL (SSRF-guarded fetch: host validated, redirects refused, size-capped at `plugins.downloadMaxBytes`, default 5 MB). Plain `http://` is rejected — the package is executable code and must be integrity-protected in transit; private-network targets remain subject to the SSRF guard.-Optional content pinning: append `#sha256=<64 hex>` (URL fragment — never sent to the server) or `?sha256=<64 hex>` (`checksum=` also accepted) to require the downloaded bytes to match that digest. A mismatch, a malformed marker, or conflicting markers fail the install closed; no marker means no verification (HTTPS + the SSRF guard are the baseline).+Optional content pinning: append `#sha256=<64 hex>` (URL fragment — never sent to the server) to require the downloaded bytes to match that digest; the fragment is the only honored marker — query params are deliberately ignored. A mismatch or a malformed marker fails the install closed; no marker means no verification (HTTPS + the SSRF guard are the baseline).**Auth:** API key (ADMIN)@@ -4334,7 +4334,7 @@ Optional content pinning: append `#sha256=<64 hex>` (URL fragment — never sent| Field | Type | Required | Constraints | Description || --- | --- | --- | --- | --- |-| `url` | string | Yes | `@IsUrl({ protocols:['https'], require_protocol:true })` | Absolute https URL of the package; optional `#sha256=` / `?sha256=` digest pin |+| `url` | string | Yes | `@IsUrl({ protocols:['https'], require_protocol:true })` | Absolute https URL of the package; optional `#sha256=` digest pin |```json{ "url": "https://github.com/openwa-plugins/chat-flow/releases/download/v1.0.0/chat-flow.zip" }@@ -4491,7 +4491,7 @@ A session-restricted key requesting `"*"` or out-of-scope sessions gets `403 API#### POST /api/plugins/:id/update-Update an installed plugin in place from a URL, preserving config + enabled state. The new package is written to a staging sibling and validated BEFORE the running plugin is stopped, then swapped in with two renames (live → backup, staging → live); a failure before or during the swap restores the previous version, and a process crash mid-swap is reconciled at boot (the backup is restored when the live directory is missing), so an interrupted update can never make the plugin silently vanish. Accepts the same optional `#sha256=` / `?sha256=` digest pin as `install-url` (fail-closed on mismatch).+Update an installed plugin in place from a URL, preserving config + enabled state. The new package is written to a staging sibling and validated BEFORE the running plugin is stopped, then swapped in with two renames (live → backup, staging → live); a failure before or during the swap restores the previous version, and a process crash mid-swap is reconciled at boot (the backup is restored when the live directory is missing), so an interrupted update can never make the plugin silently vanish. Accepts the same optional `#sha256=` digest pin as `install-url` (fail-closed on mismatch).**Auth:** API key (ADMIN)@@ -4505,7 +4505,7 @@ Update an installed plugin in place from a URL, preserving config + enabled stat| Field | Type | Required | Constraints | Description || --- | --- | --- | --- | --- |-| `url` | string | Yes | `@IsUrl({ protocols:['https'], require_protocol:true })` | Absolute https URL of the new `.zip` (SSRF-guarded download); optional `#sha256=` / `?sha256=` digest pin |+| `url` | string | Yes | `@IsUrl({ protocols:['https'], require_protocol:true })` | Absolute https URL of the new `.zip` (SSRF-guarded download); optional `#sha256=` digest pin |```json{ "url": "https://example.com/plugins/chat-flow-1.1.0.zip" }diff --git a/docs/25-integration-fabric.md b/docs/25-integration-fabric.mdindex 6b4471f40..a06fb306d 100644--- a/docs/25-integration-fabric.md+++ b/docs/25-integration-fabric.md@@ -197,7 +197,8 @@ at-least-once HTTP, so plugin handlers must be idempotent and treat ingress as aPersist-before-acknowledge alone is not delivery: a crash between the persist and the enqueue, or afire-and-forget enqueue on a `response` route whose outcome is never recorded, would strand the rowwith the provider already acknowledged. The **ingress reconciler** closes that window: every-`INGRESS_RECONCILE_INTERVAL_MS` (default 60s, `<= 0` disables) it re-dispatches a bounded batch+`INGRESS_RECONCILE_INTERVAL_MS` (default 60s, `0` disables; a blank or unparseable value falls+back to the default rather than disabling the sweep) it re-dispatches a bounded batch(`INGRESS_RECONCILE_BATCH_SIZE`, default 50) of `pending` rows whose last activity is older than agrace period (`INGRESS_RECONCILE_GRACE_MS`, default 60s), through the same queue-or-inline enqueue thelive path uses and with the original delivery id as job id, so a replay is idempotent against a jobdiff --git a/openapi.json b/openapi.jsonindex 7c9fc9d33..648a3eb78 100644--- a/openapi.json+++ b/openapi.json@@ -7141,7 +7141,7 @@"description": "Custom batch ID (auto-generated if not provided)"},"messages": {- "description": "Array of messages (max 100 per request; duplicate chatIds are collapsed — first occurrence wins)",+ "description": "Array of messages (max 100 per request; exact duplicate entries are collapsed — first occurrence wins)","type": "array","items": {"$ref": "#/components/schemas/BulkMessageItemDto"@@ -7766,7 +7766,7 @@"properties": {"url": {"type": "string",- "description": "HTTPS URL of the plugin .zip to download and install. Plain http:// is rejected: the package is executable code, so it must be integrity-protected in transit (hosts on private networks remain subject to the SSRF guard). Optional content pinning: append `#sha256=<64 hex>` (fragment — never sent to the server) or `?sha256=<64 hex>` to require the downloaded archive to match that digest; a mismatch fails the install."+ "description": "HTTPS URL of the plugin .zip to download and install. Plain http:// is rejected: the package is executable code, so it must be integrity-protected in transit (hosts on private networks remain subject to the SSRF guard). Optional content pinning: append `#sha256=<64 hex>` (fragment — never sent to the server; query params are ignored) to require the downloaded archive to match that digest; a mismatch fails the install."}},"required": [diff --git a/src/common/storage/storage.service.s3-reprobe.spec.ts b/src/common/storage/storage.service.s3-reprobe.spec.tsindex 95defaaef..b0ebcabf6 100644--- a/src/common/storage/storage.service.s3-reprobe.spec.ts+++ b/src/common/storage/storage.service.s3-reprobe.spec.ts@@ -25,7 +25,7 @@ jest.mock('@aws-sdk/client-s3', () => {};});-import { GetObjectCommand } from '@aws-sdk/client-s3';+import { DeleteObjectCommand, GetObjectCommand, ListObjectsV2Command } from '@aws-sdk/client-s3';import { DEFAULT_S3_REPROBE_INTERVAL_MS, StorageService } from './storage.service';const ENV_KEYS = [@@ -218,4 +218,91 @@ describe('StorageService S3 re-probe and recovery', () => {const data = await svc.getFile('present.bin');expect(data.toString()).toBe('from-s3');});++ it('deleteFile removes the local fallback copy as well as the S3 object', async () => {+ mockSend.mockResolvedValue({}); // HeadBucket at boot, DeleteObject later+ const svc = new StorageService(makeConfig());+ await flush();+ expect(svc.isS3Available()).toBe(true);++ // Gap media: written to the local fallback dir while S3 was down, never uploaded. Without the+ // delete-through, deleting the (missing) S3 key would leave these bytes orphaned forever.+ fs.writeFileSync(path.join(localPath, 'gap.bin'), 'gap-media');++ await svc.deleteFile('gap.bin');++ expect(fs.existsSync(path.join(localPath, 'gap.bin'))).toBe(false);+ const deleteCalls = mockSend.mock.calls.filter(([cmd]) => cmd instanceof DeleteObjectCommand);+ expect(deleteCalls.length).toBe(1);+ });++ it('deleteFile still resolves for an S3-only key (no local copy — ENOENT stays success)', async () => {+ mockSend.mockResolvedValue({});+ const svc = new StorageService(makeConfig());+ await flush();++ await expect(svc.deleteFile('s3-only.bin')).resolves.toBeUndefined();+ const deleteCalls = mockSend.mock.calls.filter(([cmd]) => cmd instanceof DeleteObjectCommand);+ expect(deleteCalls.length).toBe(1);+ });++ it('listFiles unions S3 objects with the local fallback dir (each key once)', async () => {+ mockSend.mockImplementation((cmd: unknown) => {+ if (cmd instanceof ListObjectsV2Command) {+ return Promise.resolve({ Contents: [{ Key: 'media/s3-only.bin' }, { Key: 'media/shared.bin' }] });+ }+ return Promise.resolve({});+ });+ const svc = new StorageService(makeConfig());+ await flush();++ fs.writeFileSync(path.join(localPath, 'local-only.bin'), 'x');+ fs.writeFileSync(path.join(localPath, 'shared.bin'), 'stale-local-copy');++ const files = await svc.listFiles();+ expect(files.sort()).toEqual(['local-only.bin', 's3-only.bin', 'shared.bin']);+ });++ it('getFileCount counts local-only fallback files S3 does not know about', async () => {+ mockSend.mockImplementation((cmd: unknown) => {+ if (cmd instanceof ListObjectsV2Command) {+ return Promise.resolve({+ Contents: [+ { Key: 'media/s3.bin', Size: 1000 },+ { Key: 'media/shared.bin', Size: 10 },+ ],+ });+ }+ return Promise.resolve({});+ });+ const svc = new StorageService(makeConfig());+ await flush();++ fs.writeFileSync(path.join(localPath, 'local.bin'), Buffer.alloc(500));+ fs.writeFileSync(path.join(localPath, 'shared.bin'), Buffer.alloc(99999)); // S3 size wins for a shared key++ const result = await svc.getFileCount();+ expect(result.count).toBe(3);+ expect(result.sizeBytes).toBe(1000 + 10 + 500);+ });++ it('iterateFiles paginates S3 and unions the local fallback dir (each key once)', async () => {+ const pages = [+ { Contents: [{ Key: 'media/p1.bin' }], NextContinuationToken: 'tok' },+ { Contents: [{ Key: 'media/p2.bin' }] },+ ];+ mockSend.mockImplementation((cmd: unknown) => {+ if (cmd instanceof ListObjectsV2Command) return Promise.resolve(pages.shift() ?? {});+ return Promise.resolve({});+ });+ const svc = new StorageService(makeConfig());+ await flush();++ fs.writeFileSync(path.join(localPath, 'local.bin'), 'x');+ fs.writeFileSync(path.join(localPath, 'p2.bin'), 'stale-copy');++ const seen: string[] = [];+ for await (const file of svc.iterateFiles()) seen.push(file);+ expect(seen.sort()).toEqual(['local.bin', 'p1.bin', 'p2.bin']);+ });});diff --git a/src/common/storage/storage.service.spec.ts b/src/common/storage/storage.service.spec.tsindex 8b325339c..35c1e1b26 100644--- a/src/common/storage/storage.service.spec.ts+++ b/src/common/storage/storage.service.spec.ts@@ -286,4 +286,15 @@ describe('StorageService local traversal (async + bounded)', () => {const files = await service.listFiles();expect(files.length).toBe(5); // capped, not 20});++ it('iterateFiles enumerates the full tree, ignoring the STORAGE_LIST_MAX_FILES per-call cap', async () => {+ process.env.STORAGE_LIST_MAX_FILES = '5';+ for (let i = 0; i < 20; i++) {+ await service.putFile(`file${i}.txt`, Buffer.from('x'));+ }++ const seen: string[] = [];+ for await (const file of service.iterateFiles()) seen.push(file);+ expect(seen.length).toBe(20); // complete where listFiles() above truncates at 5+ });});diff --git a/src/common/storage/storage.service.ts b/src/common/storage/storage.service.tsindex cad7611ea..04f684172 100644--- a/src/common/storage/storage.service.ts+++ b/src/common/storage/storage.service.ts@@ -211,11 +211,43 @@ export class StorageService implements OnModuleDestroy {async listFiles(): Promise<string[]> {if (this.storageType === 's3' && this.s3Client && this.s3Available) {- return this.listS3Files();+ // Union with the local fallback dir: media written locally while S3 was down is otherwise+ // invisible to enumeration — getFile reads through to it, so a listing that omits it+ // contradicts what reads serve, and a sweep reconciling against this listing could never+ // reclaim it.+ const files = new Set(await this.listS3Files());+ for (const file of await this.listLocalFiles()) files.add(file);+ return [...files];}return this.listLocalFiles();}+ /**+ * Enumerate every file in the store (all S3 pages unioned with the local fallback dir, each key+ * once) as a stream — unlike listFiles(), whose STORAGE_LIST_MAX_FILES truncation is a per-call+ * DoS guard, not a completeness contract. Callers that must reconcile against the full store+ * (e.g. the status-media orphan sweep) should iterate this instead of a single capped listing.+ *+ * `prefix` narrows the walk at the source — the S3 ListObjectsV2 prefix and the local traversal+ * root — so a caller reconciling one subtree neither pages the whole store nor holds every key+ * of it in the dedupe Set. Removing the per-call cap must not trade one unbounded read for+ * another.+ */+ async *iterateFiles(prefix = ''): AsyncGenerator<string> {+ if (this.storageType === 's3' && this.s3Client && this.s3Available) {+ const seen = new Set<string>();+ for await (const file of this.iterateS3Files(prefix)) {+ seen.add(file);+ yield file;+ }+ for await (const file of this.iterateLocalFiles(prefix)) {+ if (!seen.has(file)) yield file;+ }+ return;+ }+ yield* this.iterateLocalFiles(prefix);+ }+async getFile(filePath: string): Promise<Buffer> {// Mirror putFile: getLocalFile has its own isPathWithin guard, but getS3File builds// `media/${filePath}` with none — contain both read backends at this boundary.@@ -242,16 +274,19 @@ export class StorageService implements OnModuleDestroy {/*** Delete a file previously written via `putFile`. Same unsafe-key guard as `getFile`/`putFile` (both- * backends key off it, S3's has no host filesystem to check `isPathWithin` against). Missing-file is- * treated as success on both backends (local: ENOENT is swallowed; S3 DeleteObject is idempotent by- * design) so a caller doesn't have to special-case "already gone".+ * backends key off it, S3's has no host filesystem to check `isPathWithin` against). When S3 is+ * active the key is deleted from BOTH backends — delete-through, symmetric with getFile's+ * read-through: the key may exist only in the local fallback dir (written during an S3 outage),+ * and deleting just the S3 object would orphan those bytes permanently once the caller drops its+ * DB reference. Missing-file is treated as success on both backends (local: ENOENT is swallowed;+ * S3 DeleteObject is idempotent by design) so a caller doesn't have to special-case "already gone".*/async deleteFile(filePath: string): Promise<void> {if (!isSafeStorageKey(filePath)) {throw new Error(`Refusing to delete an unsafe storage key: ${filePath}`);}if (this.storageType === 's3' && this.s3Client && this.s3Available) {- return this.deleteS3File(filePath);+ await this.deleteS3File(filePath);}return this.deleteLocalFile(filePath);}@@ -260,7 +295,21 @@ export class StorageService implements OnModuleDestroy {if (this.storageType === 's3' && this.s3Client && this.s3Available) {// ListObjectsV2 already returns each object's Size, so report the real total instead of a// 100KB-per-file estimate — no extra API calls beyond the listing we'd do anyway.- return this.getS3CountAndSize();+ const s3 = await this.getS3CountAndSize();+ // Union with the local fallback dir (same split-brain gap as listFiles): a local-only file+ // counts with its real on-disk size; for a key present in both, the S3 copy is authoritative.+ const s3Keys = new Set(s3.keys);+ let { count, sizeBytes } = s3;+ for await (const file of this.iterateLocalFiles()) {+ if (s3Keys.has(file)) continue;+ count += 1;+ try {+ sizeBytes += fs.statSync(path.join(this.localPath, file)).size;+ } catch (error) {+ this.logger.debug(`Failed to stat file: ${file}`, { error: String(error) });+ }+ }+ return { count, sizeBytes };}const files = await this.listFiles();@@ -278,9 +327,12 @@ export class StorageService implements OnModuleDestroy {return { count: files.length, sizeBytes };}- private async getS3CountAndSize(): Promise<{ count: number; sizeBytes: number }> {+ private async getS3CountAndSize(): Promise<{ count: number; sizeBytes: number; keys: string[] }> {let count = 0;let sizeBytes = 0;+ // Keys (prefix-stripped) are kept so getFileCount can union the local fallback dir without a+ // second listing.+ const keys: string[] = [];let continuationToken: string | undefined;do {@@ -295,12 +347,13 @@ export class StorageService implements OnModuleDestroy {for (const obj of response.Contents ?? []) {count += 1;sizeBytes += obj.Size ?? 0;+ if (obj.Key) keys.push(obj.Key.replace(/^media\//, ''));}continuationToken = response.NextContinuationToken;} while (continuationToken);- return { count, sizeBytes };+ return { count, sizeBytes, keys };}// ============================================================================@@ -449,16 +502,31 @@ export class StorageService implements OnModuleDestroy {// ============================================================================/**- * Enumerate local files under the storage root. Async + iterative (a work queue, not recursion)- * so a deep/wide media tree can't block the event loop or stack-overflow. Bounded by a max file- * count and a max directory depth; a tree exceeding either is truncated rather than enumerated in- * full (these are defense-in-depth caps — a healthy media store stays well under both).+ * Enumerate local files under the storage root, capped at STORAGE_LIST_MAX_FILES — a per-call+ * DoS guard (a healthy media store stays well under it), NOT a completeness contract. Callers+ * that must see the whole tree use iterateFiles().*/private async listLocalFiles(): Promise<string[]> {const maxFiles = positiveIntFromEnv('STORAGE_LIST_MAX_FILES', DEFAULT_LIST_MAX_FILES);const files: string[] = [];- // Iterative BFS: a queue of [relativeDir, depth] avoids unbounded call-stack growth.- const queue: Array<{ dir: string; depth: number }> = [{ dir: '', depth: 0 }];+ for await (const file of this.iterateLocalFiles()) {+ files.push(file);+ if (files.length >= maxFiles) break; // cap reached — stop early+ }+ return files;+ }++ /**+ * Full local enumeration as a stream — no count cap. Async + iterative (a work queue, not+ * recursion) so a deep/wide media tree can't block the event loop or stack-overflow; still+ * bounded by the max directory depth so a pathological tree can't descend unbounded.+ */+ private async *iterateLocalFiles(prefix = ''): AsyncGenerator<string> {+ // Iterative BFS: a queue of [relativeDir, depth] avoids unbounded call-stack growth. A prefix+ // ending in '/' names a subtree, so start the walk there instead of filtering afterwards.+ const root = prefix.endsWith('/') ? prefix.slice(0, -1) : '';+ if (root && !isPathWithin(this.localPath, root)) return;+ const queue: Array<{ dir: string; depth: number }> = [{ dir: root, depth: 0 }];while (queue.length > 0) {const { dir, depth } = queue.shift()!;@@ -477,13 +545,10 @@ export class StorageService implements OnModuleDestroy {if (entry.isDirectory()) {queue.push({ dir: relativePath, depth: depth + 1 });} else if (entry.isFile()) {- files.push(relativePath);- if (files.length >= maxFiles) return files; // cap reached — stop early+ yield relativePath;}}}-- return files;}private getLocalFile(filePath: string): Promise<Buffer> {@@ -525,33 +590,35 @@ export class StorageService implements OnModuleDestroy {// ============================================================================private async listS3Files(): Promise<string[]> {- if (!this.s3Client) return [];-const files: string[] = [];+ for await (const file of this.iterateS3Files()) files.push(file);+ return files;+ }++ /** Stream every S3 object key (prefix-stripped), following the ListObjectsV2 pagination token. */+ private async *iterateS3Files(prefix = ''): AsyncGenerator<string> {+ if (!this.s3Client) return;+let continuationToken: string | undefined;do {const response = await this.s3Client.send(new ListObjectsV2Command({Bucket: this.s3Bucket,- Prefix: 'media/',+ Prefix: `media/${prefix}`,ContinuationToken: continuationToken,}),);- if (response.Contents) {- for (const obj of response.Contents) {- if (obj.Key) {- // Remove 'media/' prefix- files.push(obj.Key.replace(/^media\//, ''));- }+ for (const obj of response.Contents ?? []) {+ if (obj.Key) {+ // Remove 'media/' prefix+ yield obj.Key.replace(/^media\//, '');}}continuationToken = response.NextContinuationToken;} while (continuationToken);-- return files;}private async getS3File(filePath: string): Promise<Buffer> {diff --git a/src/common/utils/db-errors.spec.ts b/src/common/utils/db-errors.spec.tsindex 5bd266978..2582a1166 100644--- a/src/common/utils/db-errors.spec.ts+++ b/src/common/utils/db-errors.spec.ts@@ -31,6 +31,24 @@ describe('isMissingTableError', () => {expect(isMissingTableError(raw)).toBe(true);});+ it('classifies a cross-realm-shaped error by name + message (NOT an Error instance)', () => {+ // better-sqlite3's native addon is cached process-wide, so under a multi-registry jest run a genuine+ // SqliteError can arrive rooted in another realm's Error — `instanceof` must not decide this. A plain+ // object with the right shape classifies exactly like the real thing, and so does a QueryFailedError+ // from a second copy of typeorm.+ const rawSqlite = { name: 'SqliteError', message: 'no such table: templates', code: 'SQLITE_ERROR' };+ expect(isMissingTableError(rawSqlite)).toBe(true);+ const wrappedPg = {+ name: 'QueryFailedError',+ message: 'relation "templates" does not exist',+ driverError: { code: '42P01', message: 'relation "templates" does not exist' },+ };+ expect(isMissingTableError(wrappedPg)).toBe(true);+ expect(+ isUniqueViolation({ name: 'QueryFailedError', message: 'duplicate key', driverError: { code: '23505' } }),+ ).toBe(true);+ });+it('does NOT treat a genuine SQLite failure as missing-table (it must surface)', () => {// A lock/IO error and a syntax error both need to propagate — swallowing them is the very bug this// classifier exists to prevent. Note the syntax error shares the generic SQLITE_ERROR code.diff --git a/src/common/utils/db-errors.ts b/src/common/utils/db-errors.tsindex d96d3ee53..70f7a6fb0 100644--- a/src/common/utils/db-errors.ts+++ b/src/common/utils/db-errors.ts@@ -1,5 +1,22 @@import { QueryFailedError } from 'typeorm';+/** Structural view of the driver errors these predicates classify, so classification survives realms. */+type DriverErrorShape = { code?: string; message?: string };+type DriverErrorWrapperShape = { name?: unknown; message?: string; driverError?: DriverErrorShape };++// These predicates must not rely on `instanceof` alone: the errors they classify can arrive from+// another realm — better-sqlite3's native addon is cached process-wide and builds its SqliteError from+// whichever realm (jest module registry / vm context) loaded it first, and each copy of typeorm carries+// a distinct QueryFailedError class. Both classes set a stable `name` (better-sqlite3 via a prototype+// descriptor, TypeORM via TypeORMError's `get name()`), so classify on that.+function isNamedError(err: unknown, name: string): err is DriverErrorWrapperShape {+ return typeof err === 'object' && err !== null && (err as DriverErrorWrapperShape).name === name;+}++function isQueryFailedErrorLike(err: unknown): err is DriverErrorWrapperShape {+ return err instanceof QueryFailedError || isNamedError(err, 'QueryFailedError');+}+/*** Cross-dialect unique-constraint-violation check by driver code/message, for the two dialects we ship* (sqlite dev, postgres prod). Lets insert-or-converge (RMW) paths distinguish a real duplicate from an@@ -7,8 +24,8 @@ import { QueryFailedError } from 'typeorm';* supported.*/export function isUniqueViolation(err: unknown): boolean {- if (!(err instanceof QueryFailedError)) return false;- const driver = err.driverError as { code?: string; message?: string } | undefined;+ if (!isQueryFailedErrorLike(err)) return false;+ const driver = err.driverError;const code = driver?.code ?? '';const message = driver?.message ?? err.message ?? '';return code === '23505' /* postgres */ || /UNIQUE constraint failed|SQLITE_CONSTRAINT/i.test(message);@@ -23,8 +40,8 @@ export function isUniqueViolation(err: unknown): boolean {* QueryFailedError so a future TypeORM change to the nesting fails toward the regex still matching.*/export function isMissingTableError(err: unknown): boolean {- if (err instanceof QueryFailedError) {- const driver = err.driverError as { code?: string; message?: string } | undefined;+ if (isQueryFailedErrorLike(err)) {+ const driver = err.driverError;if (driver?.code === '42P01') return true; // postgres undefined_tableconst message = `${driver?.message ?? ''} ${err.message ?? ''}`;return /no such table/i.test(message);@@ -33,5 +50,5 @@ export function isMissingTableError(err: unknown): boolean {// statement OUTSIDE its try/catch — so a missing-table error surfaces as the RAW SqliteError, never// wrapped in QueryFailedError. Recognize that exact shape (class name + message); a plain Error whose// text happens to mention a missing table must still NOT classify.- return err instanceof Error && err.name === 'SqliteError' && /no such table/i.test(err.message);+ return isNamedError(err, 'SqliteError') && /no such table/i.test(err.message ?? '');}diff --git a/src/config/configuration.spec.ts b/src/config/configuration.spec.tsindex d2c29ab8f..948859310 100644--- a/src/config/configuration.spec.ts+++ b/src/config/configuration.spec.ts@@ -1,4 +1,4 @@-import configuration from './configuration';+import configuration, { resolveNonNegativeIntEnv } from './configuration';describe('configuration — main DB synchronize', () => {const orig = process.env.MAIN_DATABASE_SYNCHRONIZE;@@ -238,3 +238,72 @@ describe('configuration stats namespace', () => {expect(configuration().stats.cacheTtlMs).toBe(60000);});});++describe('configuration — webhook payload cap is fail-safe', () => {+ const orig = process.env.WEBHOOK_MAX_PAYLOAD_BYTES;+ afterEach(() => {+ if (orig === undefined) delete process.env.WEBHOOK_MAX_PAYLOAD_BYTES;+ else process.env.WEBHOOK_MAX_PAYLOAD_BYTES = orig;+ });++ it('defaults to 1 MiB and honors a valid positive override', () => {+ delete process.env.WEBHOOK_MAX_PAYLOAD_BYTES;+ expect(configuration().webhook.maxPayloadBytes).toBe(1024 * 1024);+ process.env.WEBHOOK_MAX_PAYLOAD_BYTES = '2097152';+ expect(configuration().webhook.maxPayloadBytes).toBe(2097152);+ });++ it('falls back to the default on empty, garbage, zero, or negative values', () => {+ // 0 is NOT an opt-out here (a 0-byte cap rejects every dispatch — a total webhook outage),+ // and a NaN would silently disable the cap (`payloadBytes > NaN` is always false).+ for (const bad of ['', 'abc', '0', '-1']) {+ process.env.WEBHOOK_MAX_PAYLOAD_BYTES = bad;+ expect(configuration().webhook.maxPayloadBytes).toBe(1024 * 1024);+ }+ });+});++describe('configuration — webhook shutdown drain is fail-safe', () => {+ const orig = process.env.WEBHOOK_SHUTDOWN_DRAIN_MS;+ afterEach(() => {+ if (orig === undefined) delete process.env.WEBHOOK_SHUTDOWN_DRAIN_MS;+ else process.env.WEBHOOK_SHUTDOWN_DRAIN_MS = orig;+ });++ it('defaults to 5000 and honors a valid override, incl. an explicit 0 (no wait)', () => {+ delete process.env.WEBHOOK_SHUTDOWN_DRAIN_MS;+ expect(configuration().webhook.shutdownDrainMs).toBe(5000);+ process.env.WEBHOOK_SHUTDOWN_DRAIN_MS = '10000';+ expect(configuration().webhook.shutdownDrainMs).toBe(10000);+ process.env.WEBHOOK_SHUTDOWN_DRAIN_MS = '0';+ expect(configuration().webhook.shutdownDrainMs).toBe(0);+ });++ it('falls back to the default on blank or garbage (a NaN would remove the drain deadline)', () => {+ for (const bad of ['', ' ', 'abc', '1e4']) {+ process.env.WEBHOOK_SHUTDOWN_DRAIN_MS = bad;+ expect(configuration().webhook.shutdownDrainMs).toBe(5000);+ }+ });+});++describe('resolveNonNegativeIntEnv', () => {+ it('treats blank/whitespace as unset and falls back (never the 0 opt-out sentinel)', () => {+ // Number('') is 0, which would otherwise pass a finite && >= 0 guard and silently land on+ // the documented 0 = unlimited/disabled sentinel.+ expect(resolveNonNegativeIntEnv(undefined, 5000)).toBe(5000);+ expect(resolveNonNegativeIntEnv('', 5000)).toBe(5000);+ expect(resolveNonNegativeIntEnv(' ', 5000)).toBe(5000);+ });++ it('reserves 0 for an explicit opt-out and honors valid values', () => {+ expect(resolveNonNegativeIntEnv('0', 5000)).toBe(0);+ expect(resolveNonNegativeIntEnv('250', 5000)).toBe(250);+ });++ it('falls back on garbage and non-decimal spellings (matching the boot validator)', () => {+ for (const bad of ['abc', '-1', '1.5', '1e6', '0x100']) {+ expect(resolveNonNegativeIntEnv(bad, 5000)).toBe(5000);+ }+ });+});diff --git a/src/config/configuration.ts b/src/config/configuration.tsindex 190c894a1..7a7368c9f 100644--- a/src/config/configuration.ts+++ b/src/config/configuration.ts@@ -2,6 +2,21 @@ import { computeFeatureFlags } from './feature-flags';import { resolveInflightBodyBudgetBytes } from './inflight-body-budget';import { readWsRateLimitConfig } from '../modules/events/ws-rate-limit';+/**+ * Shared parser for numeric env knobs whose 0 is a documented opt-out (unlimited / disabled).+ * `Number('')` is 0, so a blank or whitespace-only value — exactly what a compose `${KEY:-}`+ * forward renders — would otherwise pass every `Number.isFinite(x) && x >= 0` guard and land+ * silently on the opt-out sentinel (disabling a memory cap, a reaper, a retry backoff). Blank+ * means "unset": fall back to the default; 0 stays reserved for an explicit opt-out. The value+ * must be a plain decimal integer — the same rule env.validation.ts enforces — so the validated+ * and the parsed value always agree (`parseInt('1e6', 10)` would silently read 1).+ */+export function resolveNonNegativeIntEnv(raw: string | undefined, fallback: number): number {+ const trimmed = raw?.trim();+ if (!trimmed || !/^\d+$/.test(trimmed)) return fallback;+ return Number(trimmed);+}+export default () => ({port: parseInt(process.env.PORT || '2785', 10),@@ -156,8 +171,15 @@ export default () => ({// webhook_delivery_failures instead of retaining payload closures without limit.dispatchMaxQueued: parseInt(process.env.WEBHOOK_DISPATCH_MAX_QUEUED || '1000', 10),// Upper bound on the serialized webhook body after webhook:before hooks ran; oversize payloads- // are recorded as undelivered instead of being sent/persisted. Default 1 MiB.- maxPayloadBytes: parseInt(process.env.WEBHOOK_MAX_PAYLOAD_BYTES || '1048576', 10),+ // are recorded as undelivered instead of being sent/persisted. Default 1 MiB. Fail-safe like the+ // other byte caps: a non-numeric or non-positive value falls back to the default. 0 is NOT an+ // opt-out here — a 0-byte cap rejects every dispatch (a total webhook outage), and a NaN would+ // silently disable the cap (`payloadBytes > NaN` is always false). env.validation rejects+ // non-decimal / non-positive values at boot.+ maxPayloadBytes: (() => {+ const n = parseInt(process.env.WEBHOOK_MAX_PAYLOAD_BYTES ?? '', 10);+ return Number.isFinite(n) && n > 0 ? n : 1024 * 1024;+ })(),// Max webhooks registered per session. One inbound event fans out to every registered webhook// of the session, so an unbounded count multiplies per-event copies of the payload. Creating a// NEW webhook above the cap is rejected with 400; existing ones are grandfathered (never@@ -176,7 +198,9 @@ export default () => ({return Number.isFinite(n) && n >= 0 ? n : 1024 * 1024;})(),// How long shutdown waits for in-flight direct deliveries to finish before abandoning them.- shutdownDrainMs: parseInt(process.env.WEBHOOK_SHUTDOWN_DRAIN_MS || '5000', 10),+ // 0 = don't wait (explicit opt-out); blank/garbage falls back to the default — a NaN here would+ // silently remove the drain deadline downstream (Math.max(0, NaN) is NaN).+ shutdownDrainMs: resolveNonNegativeIntEnv(process.env.WEBHOOK_SHUTDOWN_DRAIN_MS, 5000),},// API configurationdiff --git a/src/config/env-precedence.ts b/src/config/env-precedence.tsindex 064cdb1ac..d0ee1be44 100644--- a/src/config/env-precedence.ts+++ b/src/config/env-precedence.ts@@ -68,3 +68,29 @@ export function clearBlankEnv(env: NodeJS.ProcessEnv, keys: string[]): void {}}}++/**+ * Keys that were already in `process.env` before load-env merged `.env` and `data/.env.generated`+ * into it — i.e. genuinely supplied by the host/orchestrator.+ *+ * Needed because after boot the two file layers are indistinguishable from a real host override:+ * both simply sit in `process.env`. Any check that asks "what will the next boot see for this key?"+ * must not read a file value back out of `process.env` and mistake it for an override — for the+ * save-config guard that would mean validating the config being REPLACED instead of the one being+ * written.+ */+let osEnvKeys: Set<string> | null = null;++/** Snapshot the host-supplied keys. Called by load-env after blank-clearing, before any dotenv load. */+export function recordOsEnvKeys(env: NodeJS.ProcessEnv = process.env): void {+ osEnvKeys = new Set(Object.keys(env));+}++/**+ * True when `key` came from the host rather than a loaded env file. With no snapshot taken (a unit+ * test that never boots), every key counts as host-supplied — the caller's own `process.env` is then+ * the only source there is.+ */+export function isOsProvidedEnv(key: string): boolean {+ return osEnvKeys === null || osEnvKeys.has(key);+}diff --git a/src/config/env.validation.spec.ts b/src/config/env.validation.spec.tsindex 62804ec25..44853c338 100644--- a/src/config/env.validation.spec.ts+++ b/src/config/env.validation.spec.ts@@ -107,6 +107,25 @@ describe('validateEnv', () => {expect(() => validateEnv({ WEBHOOK_MAX_PER_SESSION: '0', WEBHOOK_MEDIA_INLINE_MAX_BYTES: '0' })).not.toThrow();});+ it('rejects a non-positive / non-integer WEBHOOK_MAX_PAYLOAD_BYTES (0 would reject every dispatch)', () => {+ expect(() => validateEnv({ WEBHOOK_MAX_PAYLOAD_BYTES: '0' })).toThrow(/WEBHOOK_MAX_PAYLOAD_BYTES/);+ expect(() => validateEnv({ WEBHOOK_MAX_PAYLOAD_BYTES: 'abc' })).toThrow(/WEBHOOK_MAX_PAYLOAD_BYTES/);+ expect(() => validateEnv({ WEBHOOK_MAX_PAYLOAD_BYTES: '-5' })).toThrow(/WEBHOOK_MAX_PAYLOAD_BYTES/);+ expect(() => validateEnv({ WEBHOOK_MAX_PAYLOAD_BYTES: '1048576' })).not.toThrow();+ });++ it('rejects non-decimal integer spellings that parseInt would silently truncate', () => {+ // Number('1e6') is a valid integer, but the config readers use parseInt(raw, 10) — which reads+ // `1e6` as 1 and `0x100` as 0. Validation must reject these so the validated value and the+ // parsed value can never disagree.+ expect(() => validateEnv({ WEBHOOK_MEDIA_INLINE_MAX_BYTES: '1e6' })).toThrow(/WEBHOOK_MEDIA_INLINE_MAX_BYTES/);+ expect(() => validateEnv({ WEBHOOK_MEDIA_INLINE_MAX_BYTES: '0x100' })).toThrow(/WEBHOOK_MEDIA_INLINE_MAX_BYTES/);+ expect(() => validateEnv({ PORT: '0x50' })).toThrow(/PORT/);+ expect(() => validateEnv({ RATE_LIMIT_SHORT_TTL: '1e3' })).toThrow(/RATE_LIMIT_SHORT_TTL/);+ // Plain decimal integers still pass.+ expect(() => validateEnv({ WEBHOOK_MEDIA_INLINE_MAX_BYTES: '1048576', PORT: '2785' })).not.toThrow();+ });+it('rejects a non-canonical boolean feature flag instead of silently disabling the feature', () => {// QUEUE_ENABLED / MCP_ENABLED / SERVE_DASHBOARD are read at module-eval with `=== 'true'` /// `!== 'false'`, so a typo silently (dis)ables the feature with zero diagnostics. Boot must reject it.diff --git a/src/config/env.validation.ts b/src/config/env.validation.tsindex 6ac86b784..620e49fee 100644--- a/src/config/env.validation.ts+++ b/src/config/env.validation.ts@@ -127,10 +127,16 @@ export function validateEnv(config: EnvConfig): EnvConfig {}}+ // Plain decimal digits only: these numeric knobs are read downstream with parseInt(raw, 10),+ // which silently truncates spellings Number() would accept (`1e6` → 1, `0x100` → 0) — the boot+ // would validate one value and then configure another. Requiring digits keeps the validated+ // value identical to the parsed one.+ const DECIMAL_INTEGER = /^\d+$/;+const checkPort = (key: string): void => {const raw = str(key);if (raw === undefined) return;- const n = Number(raw);+ const n = DECIMAL_INTEGER.test(raw) ? Number(raw) : NaN;if (!Number.isInteger(n) || n < 1 || n > 65535) {errors.push(`${key} must be an integer port in [1, 65535] (got "${raw}")`);}@@ -144,7 +150,7 @@ export function validateEnv(config: EnvConfig): EnvConfig {const checkNonNegativeInt = (key: string): void => {const raw = str(key);if (raw === undefined) return;- const n = Number(raw);+ const n = DECIMAL_INTEGER.test(raw) ? Number(raw) : NaN;if (!Number.isInteger(n) || n < 0) {errors.push(`${key} must be a non-negative integer (got "${raw}")`);}@@ -175,7 +181,7 @@ export function validateEnv(config: EnvConfig): EnvConfig {const checkPositiveInt = (key: string): void => {const raw = str(key);if (raw === undefined) return;- const n = Number(raw);+ const n = DECIMAL_INTEGER.test(raw) ? Number(raw) : NaN;if (!Number.isInteger(n) || n < 1) {errors.push(`${key} must be a positive integer (got "${raw}")`);}@@ -196,6 +202,8 @@ export function validateEnv(config: EnvConfig): EnvConfig {'HEADERS_TIMEOUT_MS','KEEPALIVE_TIMEOUT_MS','WEBHOOK_DISPATCH_CONCURRENCY',+ // 0 would reject every webhook dispatch (a total, silent webhook outage).+ 'WEBHOOK_MAX_PAYLOAD_BYTES',// 0 would refuse every request carrying a body (a self-DoS), so the budget is positive-only.'INFLIGHT_BODY_BUDGET_BYTES',]) {diff --git a/src/config/inflight-body-budget.spec.ts b/src/config/inflight-body-budget.spec.tsindex bb2170ae3..0a4bd850b 100644--- a/src/config/inflight-body-budget.spec.ts+++ b/src/config/inflight-body-budget.spec.ts@@ -13,6 +13,8 @@ const MB = 1024 * 1024;const makeReq = (headers: Record<string, string> = {}): Request & EventEmitter => {const req = new EventEmitter() as unknown as Request & EventEmitter;(req as unknown as { headers: Record<string, string> }).headers = headers;+ (req as unknown as { socket: { bytesRead: number } }).socket = { bytesRead: 0 };+ (req as unknown as { destroy: jest.Mock }).destroy = jest.fn();return req;};@@ -20,6 +22,8 @@ const makeRes = () => {const state = { code: 0, payload: undefined as unknown };const headers: Record<string, string> = {};const res = Object.assign(new EventEmitter(), {+ headersSent: false,+ writableEnded: false,status(code: number) {state.code = code;return res;@@ -180,48 +184,69 @@ describe('createInflightBodyBudget middleware', () => {expect(budget.currentBytes()).toBe(0);});- it('counts actual bytes for requests without a Content-Length and releases on completion', () => {+ it('takes only an opening placeholder for chunk-encoded bodies and releases it on completion', () => {const budget = createInflightBodyBudget(1000);- const req = makeReq(); // chunked / close-delimited: nothing declared+ const req = makeReq({ 'transfer-encoding': 'chunked' });const { res, next } = run(budget, req);expect(next).toHaveBeenCalledTimes(1);- expect(budget.currentBytes()).toBe(0);-- req.emit('data', Buffer.alloc(300));- expect(budget.currentBytes()).toBe(300);- req.emit('data', Buffer.alloc(300));- expect(budget.currentBytes()).toBe(600);+ // Capped by the budget here (1 MiB placeholder > the 1000-byte test budget); the poller+ // reconciles it against real bytes, so a chunked body is never priced at a full slot.+ expect(budget.currentBytes()).toBe(1000);+ // The middleware must never tap the stream: a 'data' listener would switch it to flowing+ // mode and eat chunks before a late consumer (busboy attaches only after async guards).+ expect(req.listenerCount('data')).toBe(0);res.emit('finish');expect(budget.currentBytes()).toBe(0);});- it('aborts an un-declared upload mid-stream when it pushes the aggregate over budget', () => {- const budget = createInflightBodyBudget(1000);+ it('does not price a small chunked body at a whole per-request slot', () => {+ // Regression: reserving budget/4 up front turned the byte budget into a concurrency limit of 4+ // for chunked senders — four 6-byte uploads refused every further body-carrying request.+ const budget = createInflightBodyBudget(64 * 1024 * 1024);+ for (let i = 0; i < 8; i++) {+ const { next } = run(budget, makeReq({ 'transfer-encoding': 'chunked' }));+ expect(next).toHaveBeenCalledTimes(1);+ }+ expect(budget.currentBytes()).toBe(8 * 1024 * 1024); // 8 × the 1 MiB placeholder, not 8 × 16 MiB+ });- const reqA = makeReq();- const { res: resA } = run(budget, reqA);- reqA.emit('data', Buffer.alloc(600));- expect(budget.currentBytes()).toBe(600);+ it('still refuses an un-declared body once the aggregate is exhausted', () => {+ const budget = createInflightBodyBudget(2 * 1024 * 1024);+ for (let i = 0; i < 2; i++) {+ expect(run(budget, makeReq({ 'transfer-encoding': 'chunked' })).next).toHaveBeenCalledTimes(1);+ }+ const third = run(budget, makeReq({ 'transfer-encoding': 'chunked' }));+ expect(third.next).not.toHaveBeenCalled();+ expect(third.state.code).toBe(503);+ });- const reqB = makeReq();- const { res: resB, headers: headersB, state: stateB } = run(budget, reqB);- reqB.emit('data', Buffer.alloc(500)); // 600 + 500 > 1000 → abort B, keep A's accounting+ it('reserves nothing for requests with neither Content-Length nor Transfer-Encoding', () => {+ const budget = createInflightBodyBudget(1000);+ run(budget, makeReq({ 'content-length': '1000' }));+ // No body expected (health checks, GETs): admitted even with the budget fully reserved.+ const req = makeReq();+ const { next } = run(budget, req);+ expect(next).toHaveBeenCalledTimes(1);+ expect(budget.currentBytes()).toBe(1000);+ expect(req.listenerCount('data')).toBe(0);+ });- expect(stateB.code).toBe(503);- expect(headersB['retry-after']).toBe('1');- expect(budget.currentBytes()).toBe(600);+ it('drops the socket instead of writing a 503 when the response is already flushing', () => {+ const budget = createInflightBodyBudget(1000);+ run(budget, makeReq({ 'content-length': '800' }));- // After the abort, B is fully released: more incoming bytes are not counted and B's later- // terminal events cannot decrement a second time.- reqB.emit('data', Buffer.alloc(100));- resB.emit('finish');- reqB.emit('close');- expect(budget.currentBytes()).toBe(600);+ const req = makeReq({ 'content-length': '300' });+ const mock = makeRes();+ (mock.res as unknown as { headersSent: boolean }).headersSent = true;+ const next = jest.fn();- resA.emit('finish');- expect(budget.currentBytes()).toBe(0);+ expect(() => budget.middleware(req, mock.res, next)).not.toThrow();+ expect(next).not.toHaveBeenCalled();+ expect((req as unknown as { destroy: jest.Mock }).destroy).toHaveBeenCalledTimes(1);+ expect(mock.state.code).toBe(0); // no second response attempted+ expect(budget.currentBytes()).toBe(800); // nothing reserved for the rejected request});it('reuses freed budget for the next request (no leak across a full lifecycle)', () => {@@ -235,3 +260,133 @@ describe('createInflightBodyBudget middleware', () => {}});});++describe('stall reaper', () => {+ beforeEach(() => jest.useFakeTimers());+ afterEach(() => jest.useRealTimers());++ const destroyMock = (req: Request): jest.Mock => (req as unknown as { destroy: jest.Mock }).destroy;++ it('reaps a stalled declared-length connection and releases its reservation', () => {+ const budget = createInflightBodyBudget(1000);+ const req = makeReq({ 'content-length': '400' });+ run(budget, req);+ expect(budget.currentBytes()).toBe(400);++ // Headers sent, then silence: the reservation must not survive the stall timeout.+ jest.advanceTimersByTime(60_000);+ expect(destroyMock(req)).toHaveBeenCalledTimes(1);+ expect(budget.currentBytes()).toBe(0);++ // The freed budget is immediately usable again.+ const { next } = run(budget, makeReq({ 'content-length': '400' }));+ expect(next).toHaveBeenCalledTimes(1);+ expect(budget.currentBytes()).toBe(400);+ });++ it('reaps a stalled chunk-encoded connection the same way', () => {+ const budget = createInflightBodyBudget(1000);+ const req = makeReq({ 'transfer-encoding': 'chunked' });+ run(budget, req);+ expect(budget.currentBytes()).toBe(1000);++ jest.advanceTimersByTime(60_000);+ expect(destroyMock(req)).toHaveBeenCalledTimes(1);+ expect(budget.currentBytes()).toBe(0);+ });++ it('does not reap a connection that keeps making progress, however slow', () => {+ const budget = createInflightBodyBudget(1000);+ const req = makeReq({ 'content-length': '400' });+ run(budget, req);+ const socket = (req as unknown as { socket: { bytesRead: number } }).socket;++ // Well past the stall timeout in total, but never idle for a whole timeout window.+ for (let i = 0; i < 20; i++) {+ jest.advanceTimersByTime(4_000);+ socket.bytesRead += 10; // stays below the declared 400, so only progress keeps it alive+ }+ expect(destroyMock(req)).not.toHaveBeenCalled();+ expect(budget.currentBytes()).toBe(400);+ });++ it('stops reaping once the declared body has fully arrived', () => {+ const budget = createInflightBodyBudget(1000);+ const req = makeReq({ 'content-length': '400' });+ const { res } = run(budget, req);+ (req as unknown as { socket: { bytesRead: number } }).socket.bytesRead = 400;++ jest.advanceTimersByTime(120_000); // body arrived; a slow handler is not a stalled sender+ expect(destroyMock(req)).not.toHaveBeenCalled();+ expect(budget.currentBytes()).toBe(400);++ res.emit('finish');+ expect(budget.currentBytes()).toBe(0);+ });++ it('stops reaping once the downstream consumer finished reading (end)', () => {+ const budget = createInflightBodyBudget(1000);+ const req = makeReq({ 'transfer-encoding': 'chunked' });+ const { res } = run(budget, req);++ req.emit('end');+ jest.advanceTimersByTime(120_000);+ expect(destroyMock(req)).not.toHaveBeenCalled();+ expect(budget.currentBytes()).toBe(1000);++ res.emit('finish');+ expect(budget.currentBytes()).toBe(0);+ });++ it('reconciles a chunked reservation with the bytes that actually arrive', () => {+ const budget = createInflightBodyBudget(64 * 1024 * 1024);+ const req = makeReq({ 'transfer-encoding': 'chunked' });+ run(budget, req);+ expect(budget.currentBytes()).toBe(1024 * 1024); // opening placeholder++ const socket = (req as unknown as { socket: { bytesRead: number } }).socket;+ socket.bytesRead = 5 * 1024 * 1024;+ jest.advanceTimersByTime(5_000);+ expect(budget.currentBytes()).toBe(5 * 1024 * 1024); // now priced at its real weight+ });++ it('aborts an un-declared body that streams past the aggregate budget', () => {+ const budget = createInflightBodyBudget(2 * 1024 * 1024);+ const req = makeReq({ 'transfer-encoding': 'chunked' });+ run(budget, req);++ (req as unknown as { socket: { bytesRead: number } }).socket.bytesRead = 3 * 1024 * 1024;+ jest.advanceTimersByTime(5_000);+ expect(destroyMock(req)).toHaveBeenCalledTimes(1);+ expect(budget.currentBytes()).toBe(0);+ });++ it('does not reap a fully-received request whose body no parser consumed', () => {+ // The body can arrive in the same segment as the headers, so socket.bytesRead never moves again+ // and 'end' never fires when no parser reads the stream. Killing that request at the stall+ // timeout would drop a healthy connection mid-handler.+ const budget = createInflightBodyBudget(1000);+ const req = makeReq({ 'content-length': '400' });+ const { res } = run(budget, req);+ (req as unknown as { complete: boolean }).complete = true;++ jest.advanceTimersByTime(120_000);+ expect(destroyMock(req)).not.toHaveBeenCalled();+ expect(budget.currentBytes()).toBe(400);++ res.emit('finish');+ expect(budget.currentBytes()).toBe(0);+ });++ it('never arms the reaper for requests without a body', () => {+ const budget = createInflightBodyBudget(1000);+ const getReq = makeReq();+ const emptyReq = makeReq({ 'content-length': '0' });+ run(budget, getReq);+ run(budget, emptyReq);++ jest.advanceTimersByTime(120_000);+ expect(destroyMock(getReq)).not.toHaveBeenCalled();+ expect(destroyMock(emptyReq)).not.toHaveBeenCalled();+ });+});diff --git a/src/config/inflight-body-budget.ts b/src/config/inflight-body-budget.tsindex f00648825..77b64c01f 100644--- a/src/config/inflight-body-budget.ts+++ b/src/config/inflight-body-budget.ts@@ -9,11 +9,13 @@* push a 2 GiB container out of memory.** This middleware closes the gap. It tracks the aggregate body bytes currently in flight across- * ALL connections — the declared Content-Length where present, the actual received bytes- * otherwise — and refuses NEW requests with 503 + Retry-After once the budget is exhausted,- * without reading a single byte of the rejected body. Requests with no Content-Length (chunked /- * close-delimited) are admitted, counted as their bytes actually arrive, and aborted mid-stream- * if they push the aggregate over the budget, so un-declared tricklers cannot bypass the cap.+ * ALL connections — the declared Content-Length where present, one budget slot otherwise — and+ * refuses NEW requests with 503 + Retry-After once the budget is exhausted, without reading a+ * single byte of the rejected body. A stalled sender (headers, then silence) holds its+ * reservation only until the stall reaper drops the socket after STALL_TIMEOUT_MS without any+ * new body bytes, so a handful of silent connections cannot pin the whole budget. The request+ * stream itself is never tapped — no 'data' listener — so downstream consumers (the body+ * parser, busboy) see every chunk exactly as it arrives, even when they attach late.** Extracted from main.ts so the accounting — notably the exactly-once release across every* terminal path — is unit-tested without booting the app.@@ -40,6 +42,26 @@ const UNIT_BYTES: Record<string, number> = {const FALLBACK_LIMIT_BYTES = 25 * UNIT_BYTES.mb;+/**+ * Stall reaper. A reservation is normally released when the response finishes or the connection+ * dies — but a socket that sends headers and then goes silent fires NEITHER, so without a reaper+ * it would hold its declared bytes until Node's requestTimeout (5 minutes by default), and four+ * such connections at the per-request cap would pin the entire default budget, renewable forever.+ * Any admitted request expecting a body is therefore polled: if no new body bytes arrive for+ * STALL_TIMEOUT_MS the socket is destroyed and the reservation released. Polling (rather than one+ * fixed deadline) lets any progress reset the clock, so slow-but-moving uploads are untouched.+ */+const STALL_TIMEOUT_MS = 15_000;+const STALL_POLL_MS = 5_000;++/**+ * What a chunked (undeclared-length) body reserves before any of it has arrived. The same poll that+ * watches for a stall also reconciles this against `socket.bytesRead`, so the reservation converges+ * on the real size within one interval — this only has to be big enough that admission control is+ * not a free-for-all, not big enough to price a small upload out of the budget.+ */+const UNDECLARED_OPENING_RESERVATION_BYTES = 1024 * 1024;+/*** Parse a body-limit string ('25mb', '1024', '1.5gb') into bytes. Only the formats* resolveBodyLimit accepts are supported, which keeps this module self-contained (no extra@@ -80,11 +102,24 @@ export interface InflightBodyBudget {export function createInflightBodyBudget(budgetBytes: number, options?: InflightBodyBudgetOptions): InflightBodyBudget {let inFlightBytes = 0;const retryAfter = String(options?.retryAfterSeconds ?? 1);+ // Opening reservation for a body with no declared length (chunked). It is only a placeholder:+ // the poller below reconciles it against the bytes that actually arrive, so a small chunked+ // request ends up costing what it really weighs. Reserving a whole per-request cap up front+ // instead would make the budget a concurrency limit of DEFAULT_BUDGET_MULTIPLIER for chunked+ // senders — four 6-byte uploads would refuse every further body-carrying request.+ const undeclaredReservation = Math.max(1, Math.min(UNDECLARED_OPENING_RESERVATION_BYTES, budgetBytes));// The rejected request's body is deliberately NEVER read. 'Connection: close' tells the client// (and Node) this socket dies with the response, so the unread bytes are discarded with the// socket instead of being misread as the next pipelined request on a keep-alive connection.- const rejectBusy = (res: Response): void => {+ const rejectBusy = (req: Request, res: Response): void => {+ // Another listener may already have started an early response (e.g. a guard's 401 flushing+ // while the body still streams in); writing the 503 then throws ERR_HTTP_HEADERS_SENT from+ // inside a raw listener. Dropping the socket is the only safe rejection left.+ if (res.headersSent || res.writableEnded) {+ req.destroy();+ return;+ }res.status(503).set('Retry-After', retryAfter)@@ -94,25 +129,36 @@ export function createInflightBodyBudget(budgetBytes: number, options?: Inflightconst middleware = (req: Request, res: Response, next: NextFunction): void => {const declared = parseDeclaredLength(req.headers['content-length']);+ // A body with no declared length is expected only when the request is chunk-encoded (Node+ // ignores close-delimited request bodies on keep-alive HTTP/1.1). Anything else — GETs,+ // health checks, Content-Length: 0 — reserves nothing and is never reaped.+ let reserved = declared ?? (req.headers['transfer-encoding'] !== undefined ? undeclaredReservation : 0);- // Admission control on the DECLARED size: a request that would push the aggregate past the+ // Admission control on the RESERVED size: a request that would push the aggregate past the// budget is refused before a single byte of its body is buffered.- if (declared !== undefined && inFlightBytes + declared > budgetBytes) {- rejectBusy(res);+ if (inFlightBytes + reserved > budgetBytes) {+ rejectBusy(req, res);return;}- let counted = declared ?? 0;- inFlightBytes += counted;+ inFlightBytes += reserved;++ let released = false;+ let stallTimer: ReturnType<typeof setInterval> | undefined;+ const disarmStallReaper = (): void => {+ if (stallTimer === undefined) return;+ clearInterval(stallTimer);+ stallTimer = undefined;+ };// Exactly-once release: the first terminal event wins — normal completion (res 'finish'),// client/socket abort (req/res 'close'), stream failure (req/res 'error'). An aborted upload// typically fires several of these; the flag guarantees the aggregate is decremented once.- let released = false;const release = (): void => {if (released) return;released = true;- inFlightBytes -= counted;+ disarmStallReaper();+ inFlightBytes -= reserved;};res.on('finish', release);res.on('close', release);@@ -120,20 +166,57 @@ export function createInflightBodyBudget(budgetBytes: number, options?: Inflightreq.on('close', release);req.on('error', release);- if (declared === undefined) {- // No Content-Length (chunked / close-delimited): nothing to reserve up front, so count- // bytes as they actually arrive. The mid-stream abort keeps the aggregate bounded even- // when every sender avoids declaring a length. The stream stays intact for the downstream- // body parser — 'data' listeners observe the same chunks, they do not consume them away.- req.on('data', (chunk: Buffer) => {- if (released) return; // already aborted below — stop counting, the 503 is on its way- counted += chunk.length;- inFlightBytes += chunk.length;+ if (reserved > 0) {+ // Stall reaper (see STALL_TIMEOUT_MS above). Progress is measured on the SOCKET byte+ // counter, never on the request stream: attaching a 'data' listener would switch the+ // stream to flowing mode and eat chunks before a late consumer (the async guards run+ // before busboy/body-parser attach) ever sees them. 'end' is safe to observe — it does+ // not start the flow — and disarms the reaper once the real consumer finished reading.+ const socket = req.socket;+ const startBytes = socket.bytesRead;+ let lastBytes = startBytes;+ let lastProgress = Date.now();++ // Undeclared length: replace the opening placeholder with what has actually arrived, so a+ // small chunked upload stops holding a big reservation and a large one is accounted honestly.+ // Crossing the budget mid-stream aborts the request — the same bound a declared length gets+ // at admission, applied to a sender that declined to declare one.+ const reconcileUndeclared = (readNow: number): void => {+ const actual = Math.max(undeclaredReservation, readNow - startBytes);+ if (actual === reserved) return;+ inFlightBytes += actual - reserved;+ reserved = actual;if (inFlightBytes > budgetBytes) {release();- rejectBusy(res);+ req.destroy();+ }+ };++ stallTimer = setInterval(() => {+ // The whole message is in (Node parsed it to the end) — there is nothing left to stall on,+ // whether or not any consumer has read it. Without this a body that arrived in one segment+ // before this middleware ran would keep the reaper armed on a byte counter that can no+ // longer move, and a handler slower than STALL_TIMEOUT_MS would be killed mid-work.+ if (req.complete) {+ disarmStallReaper();+ return;+ }+ const readNow = socket.bytesRead;+ if (readNow !== lastBytes) {+ if (declared === undefined) reconcileUndeclared(readNow);+ lastBytes = readNow;+ lastProgress = Date.now();+ // The whole declared body has arrived; nothing left to stall on.+ if (declared !== undefined && readNow - startBytes >= declared) disarmStallReaper();+ return;+ }+ if (Date.now() - lastProgress >= STALL_TIMEOUT_MS) {+ release();+ req.destroy();}- });+ }, STALL_POLL_MS);+ stallTimer.unref();+ req.on('end', disarmStallReaper);}next();@@ -142,7 +225,7 @@ export function createInflightBodyBudget(budgetBytes: number, options?: Inflightreturn { middleware, currentBytes: () => inFlightBytes };}-/** A well-formed Content-Length, or undefined when absent/unusable (then count actual bytes). */+/** A well-formed Content-Length, or undefined when absent/unusable (then reserve one slot if chunk-encoded). */function parseDeclaredLength(raw: string | undefined): number | undefined {if (raw === undefined) return undefined;const n = Number(raw.trim());diff --git a/src/config/load-env.ts b/src/config/load-env.tsindex a5db93213..cc5831816 100644--- a/src/config/load-env.ts+++ b/src/config/load-env.ts@@ -2,7 +2,7 @@ import * as dotenv from 'dotenv';import * as fs from 'fs';import * as path from 'path';import { writeSecretFile } from '../common/utils/secret-file';-import { clearBlankEnv, BLANK_SHADOWED_ENV_KEYS } from './env-precedence';+import { clearBlankEnv, recordOsEnvKeys, BLANK_SHADOWED_ENV_KEYS } from './env-precedence';/*** Load configuration into process.env BEFORE any application module is imported.@@ -49,6 +49,11 @@ export function loadEnvironment(): void {// selection and the external-Postgres password).clearBlankEnv(process.env, BLANK_SHADOWED_ENV_KEYS);+ // Snapshot what the HOST supplied, before the two file layers below are merged in. Afterwards a+ // file value is indistinguishable from an orchestrator override — both just sit in process.env —+ // so anything asking "is this key overridden?" (the save-config boot guard) needs this record.+ recordOsEnvKeys(process.env);+// 2. User-managed .env (does not override real process env)if (fs.existsSync(userEnvPath)) {console.log('[Bootstrap] Loading .env from:', userEnvPath);diff --git a/src/core/agent-tools/tools/group.tools.spec.ts b/src/core/agent-tools/tools/group.tools.spec.tsnew file mode 100644index 000000000..f2fb157be--- /dev/null+++ b/src/core/agent-tools/tools/group.tools.spec.ts@@ -0,0 +1,73 @@+import { invokeTool } from '../tool-invoker';+import { groupTools } from './group.tools';+import type { GroupService } from '../../../modules/group/group.service';+import type { AuthService } from '../../../modules/auth/auth.service';+import type { ParticipantOperationResult } from '../../../engine/interfaces/whatsapp-engine.interface';++function makeAuth(): Pick<AuthService, 'validateApiKey' | 'hasPermission'> {+ return {+ validateApiKey: jest.fn().mockResolvedValue({ id: 'k1', allowedSessions: null }),+ hasPermission: jest.fn().mockReturnValue(true),+ };+}++describe('GroupAddParticipants', () => {+ it('returns the engine per-participant results instead of a blanket success', async () => {+ const results: ParticipantOperationResult[] = [+ { id: '[email protected]', success: true, status: 200 },+ { id: '[email protected]', success: false, status: 403, message: 'invite-only' },+ ];+ const addParticipants = jest.fn().mockResolvedValue(results);+ const groupSvc = { addParticipants } as unknown as GroupService;++ const tool = groupTools(groupSvc).find(t => t.name === 'GroupAddParticipants')!;+ const out = (await invokeTool(+ tool,+ { sessionId: 's1', groupId: '[email protected]', participants: ['[email protected]', '[email protected]'] },+ 'key',+ makeAuth() as unknown as AuthService,+ )) as { success: boolean; message: string; results: ParticipantOperationResult[] };++ expect(addParticipants).toHaveBeenCalledWith('s1', '[email protected]', ['[email protected]', '[email protected]']);+ // Partial batch: success stays true (one did join) but the message must not claim a clean run.+ expect(out.success).toBe(true);+ expect(out.message).toContain('1/2');+ expect(out.results).toEqual(results);+ });++ it('reports failure when every participant was refused', async () => {+ // An agent reading only the top-level fields was previously told "Participants added" even when+ // nothing happened.+ const results: ParticipantOperationResult[] = [+ { id: '[email protected]', success: false, status: 404, message: 'not registered' },+ { id: '[email protected]', success: false, status: 409, message: 'already a member' },+ ];+ const groupSvc = { addParticipants: jest.fn().mockResolvedValue(results) } as unknown as GroupService;++ const tool = groupTools(groupSvc).find(t => t.name === 'GroupAddParticipants')!;+ const out = (await invokeTool(+ tool,+ { sessionId: 's1', groupId: '[email protected]', participants: ['[email protected]', '[email protected]'] },+ 'key',+ makeAuth() as unknown as AuthService,+ )) as { success: boolean; message: string };++ expect(out.success).toBe(false);+ expect(out.message).toContain('0/2');+ });++ it('reports a clean success when every participant joined', async () => {+ const results: ParticipantOperationResult[] = [{ id: '[email protected]', success: true, status: 200 }];+ const groupSvc = { addParticipants: jest.fn().mockResolvedValue(results) } as unknown as GroupService;++ const tool = groupTools(groupSvc).find(t => t.name === 'GroupAddParticipants')!;+ const out = (await invokeTool(+ tool,+ { sessionId: 's1', groupId: '[email protected]', participants: ['[email protected]'] },+ 'key',+ makeAuth() as unknown as AuthService,+ )) as { success: boolean; message: string };++ expect(out).toEqual({ success: true, message: 'Participants added', results });+ });+});diff --git a/src/core/agent-tools/tools/group.tools.ts b/src/core/agent-tools/tools/group.tools.tsindex 83f415642..b74002996 100644--- a/src/core/agent-tools/tools/group.tools.ts+++ b/src/core/agent-tools/tools/group.tools.ts@@ -1,7 +1,11 @@import { z } from 'zod';import { ApiKeyRole } from '../../../modules/auth/entities/api-key.entity';import type { GroupService } from '../../../modules/group/group.service';-import { GROUP_DESCRIPTION_MAX_LENGTH, GROUP_NAME_MAX_LENGTH } from '../../../modules/group/dto/group.dto';+import {+ GROUP_DESCRIPTION_MAX_LENGTH,+ GROUP_NAME_MAX_LENGTH,+ GROUP_PARTICIPANTS_MAX,+} from '../../../modules/group/dto/group.dto';import type { ToolDescriptor } from '../tool-descriptor';const sessionId = z.string().min(1).describe('Session UUID (the session id, not the name)');@@ -55,25 +59,45 @@ export function groupTools(group: GroupService): ToolDescriptor[] {inputSchema: z.object({sessionId,name: z.string().min(1).max(GROUP_NAME_MAX_LENGTH).describe('Group subject/name'),- participants: z.array(z.string()).min(1).describe('Participant WhatsApp JIDs (e.g. [email protected])'),+ participants: z+ .array(z.string())+ .min(1)+ .max(GROUP_PARTICIPANTS_MAX)+ .describe('Participant WhatsApp JIDs (e.g. [email protected])'),}),handler: (input: { sessionId: string; name: string; participants: string[] }) =>group.createGroup(input.sessionId, input.name, input.participants),},{name: 'GroupAddParticipants',- description: 'Add participants to an existing group. Requires OPERATOR role.',+ description:+ 'Add participants to an existing group. The returned `results` carry the per-participant outcome (a partial refusal does not fail the batch). Requires OPERATOR role.',tier: 'write',requiredRole: ApiKeyRole.OPERATOR,sessionScoped: true,inputSchema: z.object({sessionId,groupId: z.string().describe('Group JID (e.g. [email protected])'),- participants: z.array(z.string()).min(1).describe('Participant WhatsApp JIDs to add'),+ participants: z+ .array(z.string())+ .min(1)+ .max(GROUP_PARTICIPANTS_MAX)+ .describe('Participant WhatsApp JIDs to add'),}),handler: async (input: { sessionId: string; groupId: string; participants: string[] }) => {- await group.addParticipants(input.sessionId, input.groupId, input.participants);- return { success: true, message: 'Participants added' };+ const results = await group.addParticipants(input.sessionId, input.groupId, input.participants);+ // Derive the verdict from the per-participant outcomes instead of asserting it: a batch in+ // which every participant was refused (not registered, already a member) must not report+ // success to an agent that only reads the top-level fields.+ const added = results.filter(r => r.success).length;+ return {+ success: added > 0,+ message:+ added === results.length+ ? 'Participants added'+ : `${added}/${results.length} participants added; see results for per-participant outcomes`,+ results,+ };},},{diff --git a/src/core/agent-tools/tools/tool-input-caps.spec.ts b/src/core/agent-tools/tools/tool-input-caps.spec.tsindex 52e480896..2adff1aa5 100644--- a/src/core/agent-tools/tools/tool-input-caps.spec.ts+++ b/src/core/agent-tools/tools/tool-input-caps.spec.ts@@ -17,8 +17,10 @@ import {CreateGroupDto,GROUP_DESCRIPTION_MAX_LENGTH,GROUP_NAME_MAX_LENGTH,+ GROUP_PARTICIPANTS_MAX,GroupDescriptionDto,GroupSubjectDto,+ ParticipantsDto,} from '../../../modules/group/dto/group.dto';import type { ToolDescriptor } from '../tool-descriptor';import { messageTools } from './message.tools';@@ -133,7 +135,30 @@ const CASES: CapCase[] = [},];-async function dtoFieldErrors(c: CapCase, value: string): Promise<boolean> {+// Same parity idea as the string caps above, for the participants arrays: the Zod schemas had+// min(1) but no max while the REST DTOs enforce ArrayMaxSize(GROUP_PARTICIPANTS_MAX).+const PARTICIPANT_CASES: CapCase[] = [+ {+ label: 'GroupCreate.participants ↔ CreateGroupDto.participants',+ toolName: 'GroupCreate',+ field: 'participants',+ cap: GROUP_PARTICIPANTS_MAX,+ toolInput: { sessionId: 's1', name: 'weekend' },+ dtoClass: CreateGroupDto,+ dtoPayload: { name: 'weekend' },+ },+ {+ label: 'GroupAddParticipants.participants ↔ ParticipantsDto.participants',+ toolName: 'GroupAddParticipants',+ field: 'participants',+ cap: GROUP_PARTICIPANTS_MAX,+ toolInput: { sessionId: 's1', groupId: '[email protected]' },+ dtoClass: ParticipantsDto,+ dtoPayload: {},+ },+];++async function dtoFieldErrors(c: CapCase, value: unknown): Promise<boolean> {const instance = plainToInstance(c.dtoClass, { ...c.dtoPayload, [c.field]: value }, PIPE_TRANSFORM_OPTS);const errors = await validate(instance);return errors.some(e => e.property === c.field);@@ -156,4 +181,21 @@ describe('agent-tool input caps (parity with the REST DTOs)', () => {}expect(await dtoFieldErrors(c, overCap)).toBe(true);});++ it.each(PARTICIPANT_CASES)('$label: accepts a list at the cap in both MCP and REST', async c => {+ const atCap = Array.from({ length: c.cap }, () => '[email protected]');+ const parsed = tool(c.toolName).inputSchema.safeParse({ ...c.toolInput, [c.field]: atCap });+ expect(parsed.success).toBe(true);+ expect(await dtoFieldErrors(c, atCap)).toBe(false);+ });++ it.each(PARTICIPANT_CASES)('$label: rejects a list above the cap in both MCP and REST', async c => {+ const overCap = Array.from({ length: c.cap + 1 }, () => '[email protected]');+ const parsed = tool(c.toolName).inputSchema.safeParse({ ...c.toolInput, [c.field]: overCap });+ expect(parsed.success).toBe(false);+ if (!parsed.success) {+ expect(parsed.error.issues.some(i => i.path.includes(c.field) && i.code === 'too_big')).toBe(true);+ }+ expect(await dtoFieldErrors(c, overCap)).toBe(true);+ });});diff --git a/src/core/plugins/plugin-loader-conversation-repair.spec.ts b/src/core/plugins/plugin-loader-conversation-repair.spec.tsnew file mode 100644index 000000000..71e150acc--- /dev/null+++ b/src/core/plugins/plugin-loader-conversation-repair.spec.ts@@ -0,0 +1,166 @@+import { NotFoundException } from '@nestjs/common';+import { ConfigService } from '@nestjs/config';+import { ModuleRef } from '@nestjs/core';+import { PluginLoaderService } from './plugin-loader.service';+import { PluginStorageService } from './plugin-storage.service';+import { HookManager } from '../hooks';+import { PluginContext, PluginInstance, PluginManifest, PluginStatus, PluginType } from './plugin.interfaces';+import { SessionService } from '../../modules/session/session.service';+import {+ ConversationMappingConflict,+ ConversationMappingService,+} from '../../modules/integration/conversation-mapping.service';++/**+ * Stale-mapping repair after a session is deleted and re-paired under a new id. The cross-session+ * fence in resolveChatId must still reject a mapping owned by a LIVE session, but a mapping whose+ * session no longer exists is rebound to the envelope's session — otherwise the dead session's rows+ * brick conversation.send and mappings.upsert for that instance permanently.+ */+describe('PluginLoaderService — stale conversation-mapping repair', () => {+ let loader: PluginLoaderService;+ let mappingService: { getByProvider: jest.Mock; rebindSession: jest.Mock; delete: jest.Mock; upsert: jest.Mock };+ let messageService: { sendText: jest.Mock; reply: jest.Mock };+ let sessionService: { findOne: jest.Mock };++ beforeEach(() => {+ mappingService = {+ getByProvider: jest.fn(),+ rebindSession: jest.fn().mockResolvedValue(undefined),+ delete: jest.fn().mockResolvedValue(undefined),+ upsert: jest.fn().mockResolvedValue(undefined),+ };+ messageService = {+ sendText: jest.fn().mockResolvedValue({ messageId: 'wamid', timestamp: 1 }),+ reply: jest.fn().mockResolvedValue({ messageId: 'wamid', timestamp: 1 }),+ };+ sessionService = { findOne: jest.fn() };+ const moduleRef = {+ get: jest.fn().mockImplementation((token: unknown) => {+ if (token === ConversationMappingService) return mappingService;+ if (token === SessionService) return sessionService;+ return messageService;+ }),+ };+ const configService = { get: jest.fn().mockReturnValue(undefined) } as unknown as ConfigService;+ const pluginStorage = {+ createPluginStorage: jest.fn().mockReturnValue({}),+ } as unknown as PluginStorageService;+ loader = new PluginLoaderService(+ configService,+ new HookManager(),+ pluginStorage,+ moduleRef as unknown as ModuleRef,+ );+ });++ function contextFor(plugin: PluginInstance): PluginContext {+ return (loader as unknown as { createPluginContext: (p: PluginInstance) => PluginContext }).createPluginContext(+ plugin,+ );+ }++ function makePlugin(activeSessions?: string[]): PluginInstance {+ const manifest: PluginManifest = {+ id: 'test-ext',+ name: 'Test Extension',+ version: '1.0.0',+ type: PluginType.EXTENSION,+ main: 'index.ts',+ permissions: ['conversation:send'],+ };+ return { manifest, status: PluginStatus.INSTALLED, config: {}, instance: null, activeSessions };+ }++ const sendEnv = {+ type: 'text' as const,+ text: 'hi',+ instanceId: 'inst-1',+ source: { provider: 'chatwoot', externalConversationId: 'conv-42' },+ };+ const mapping = (sessionId: string) => ({+ id: 'm-1',+ sessionId,+ chatId: '[email protected]',+ pluginId: 'test-ext',+ instanceId: 'inst-1',+ providerConversationId: 'conv-42',+ });+ const upsertKey = { sessionId: 'sess-new', chatId: 'chat-1', instanceId: 'inst-1' };+ const conflict = () =>+ new ConversationMappingConflict(+ { sessionId: 'sess-new', chatId: 'chat-1', pluginId: 'test-ext', instanceId: 'inst-1' },+ 'conv-42',+ );++ it('rebinds a mapping whose session was deleted, then conversation.send succeeds', async () => {+ mappingService.getByProvider.mockResolvedValue(mapping('sess-dead'));+ sessionService.findOne.mockRejectedValue(new NotFoundException("Session with id 'sess-dead' not found"));+ const ctx = contextFor(makePlugin());++ await ctx.conversations.send({ ...sendEnv, sessionId: 'sess-new' });++ expect(sessionService.findOne).toHaveBeenCalledWith('sess-dead');+ expect(mappingService.rebindSession).toHaveBeenCalledWith('m-1', 'sess-new');+ expect(messageService.sendText).toHaveBeenCalledWith('sess-new', { chatId: '[email protected]', text: 'hi' });+ });++ it('still rejects a mapping owned by another LIVE session and never sends', async () => {+ // The plugin is activated for both sessions, so the activation gate passes — only the mapping's+ // own (live) sessionId stops sess-new's envelope from routing out through sess-live's chat.+ mappingService.getByProvider.mockResolvedValue(mapping('sess-live'));+ sessionService.findOne.mockResolvedValue({ id: 'sess-live' });+ const ctx = contextFor(makePlugin(['sess-new', 'sess-live']));++ await expect(ctx.conversations.send({ ...sendEnv, sessionId: 'sess-new' })).rejects.toThrow(+ /belongs to session sess-live, not sess-new/,+ );+ expect(mappingService.rebindSession).not.toHaveBeenCalled();+ expect(messageService.sendText).not.toHaveBeenCalled();+ expect(messageService.reply).not.toHaveBeenCalled();+ });++ it('keeps the fence closed when the session lookup fails for a non-NotFound reason (fail-closed)', async () => {+ mappingService.getByProvider.mockResolvedValue(mapping('sess-maybe'));+ sessionService.findOne.mockRejectedValue(new Error('database is locked'));+ const ctx = contextFor(makePlugin());++ await expect(ctx.conversations.send({ ...sendEnv, sessionId: 'sess-new' })).rejects.toThrow(+ /belongs to session sess-maybe, not sess-new/,+ );+ expect(mappingService.rebindSession).not.toHaveBeenCalled();+ expect(messageService.sendText).not.toHaveBeenCalled();+ });++ it('mappings.upsert supersedes a reverse-key row whose session is gone, then converges', async () => {+ mappingService.upsert.mockRejectedValueOnce(conflict()).mockResolvedValueOnce(undefined);+ mappingService.getByProvider.mockResolvedValue(mapping('sess-dead'));+ sessionService.findOne.mockRejectedValue(new NotFoundException());+ const ctx = contextFor(makePlugin());++ await expect(ctx.mappings.upsert(upsertKey, 'conv-42')).resolves.toBeUndefined();++ expect(mappingService.delete).toHaveBeenCalledWith('m-1');+ expect(mappingService.upsert).toHaveBeenCalledTimes(2);+ });++ it('mappings.upsert rethrows ConversationMappingConflict when the reverse-key row is owned by a live session', async () => {+ mappingService.upsert.mockRejectedValue(conflict());+ mappingService.getByProvider.mockResolvedValue(mapping('sess-live'));+ sessionService.findOne.mockResolvedValue({ id: 'sess-live' });+ const ctx = contextFor(makePlugin());++ await expect(ctx.mappings.upsert(upsertKey, 'conv-42')).rejects.toBeInstanceOf(ConversationMappingConflict);+ expect(mappingService.delete).not.toHaveBeenCalled();+ expect(mappingService.upsert).toHaveBeenCalledTimes(1);+ });++ it('mappings.upsert propagates a non-conflict failure untouched', async () => {+ mappingService.upsert.mockRejectedValue(new Error('disk i/o'));+ const ctx = contextFor(makePlugin());++ await expect(ctx.mappings.upsert(upsertKey, 'conv-42')).rejects.toThrow('disk i/o');+ expect(mappingService.getByProvider).not.toHaveBeenCalled();+ expect(mappingService.delete).not.toHaveBeenCalled();+ });+});diff --git a/src/core/plugins/plugin-loader-sandbox-routing.spec.ts b/src/core/plugins/plugin-loader-sandbox-routing.spec.tsindex 22228e5aa..0abff0050 100644--- a/src/core/plugins/plugin-loader-sandbox-routing.spec.ts+++ b/src/core/plugins/plugin-loader-sandbox-routing.spec.ts@@ -20,14 +20,19 @@ class TestableLoader extends PluginLoaderService {readonly hosts: FakeHost[] = [];capturedOnHookSubscribe?: (event: string, priority?: number) => void;capturedOnLog?: (level: PluginLogLevel, message: string, meta?: Record<string, unknown>) => void;+ capturedOnWorkerExit?: (code: number, intentional: boolean) => void;protected createSandboxHost(_capDispatcher?: (verb: string, args: unknown[]) => Promise<unknown>,onHookSubscribe?: (event: string, priority?: number) => void,_onWebhookSubscribe?: (route: string) => void,onLog?: (level: PluginLogLevel, message: string, meta?: Record<string, unknown>) => void,+ _runWithHookGuard?: (inFlightEvents: string[], run: () => Promise<unknown>) => Promise<unknown>,+ _onSearchProviderRegister?: () => void,+ onWorkerExit?: (code: number, intentional: boolean) => void,): PluginWorkerHost {this.capturedOnHookSubscribe = onHookSubscribe;this.capturedOnLog = onLog;+ this.capturedOnWorkerExit = onWorkerExit;const host: FakeHost = {load: jest.fn().mockResolvedValue(undefined),runLifecycle: jest.fn().mockResolvedValue(undefined),@@ -267,6 +272,30 @@ describe('PluginLoaderService — sandbox log relay bounds', () => {}});+ it('flushes the pending drop count on worker exit, so a quiet plugin loses nothing', async () => {+ const loader = makeLoader();+ seed(loader, { builtIn: false, instance: null });+ await loader.enablePlugin('p1');+ const logSpy = jest.spyOn(loggerOf(loader), 'log').mockImplementation(() => undefined);+ const warnSpy = jest.spyOn(loggerOf(loader), 'warn').mockImplementation(() => undefined);++ const onLog = loader.capturedOnLog!;+ for (let i = 0; i < 250; i++) onLog('log', `line ${i}`);+ expect(logSpy).toHaveBeenCalledTimes(200);+ expect(warnSpy).not.toHaveBeenCalled(); // the plugin went quiet before any window rollover++ // Disable/crash tears the worker down first: the pending count surfaces as a final burst.+ loader.capturedOnWorkerExit!(0, true);+ expect(warnSpy).toHaveBeenCalledWith(+ expect.stringContaining('Dropped 50 log messages from sandboxed plugin p1'),+ expect.objectContaining({ action: 'sandbox_log_relay_dropped', pluginId: 'p1', dropped: 50 }),+ );++ // The flush is one-shot: a repeated exit callback must not re-report the same count.+ loader.capturedOnWorkerExit!(0, true);+ expect(warnSpy).toHaveBeenCalledTimes(1);+ });+it('truncates an oversized worker log line before relaying it', async () => {const loader = makeLoader();seed(loader, { builtIn: false, instance: null });diff --git a/src/core/plugins/plugin-loader.service.spec.ts b/src/core/plugins/plugin-loader.service.spec.tsindex 0eadd7a1a..8089c03f6 100644--- a/src/core/plugins/plugin-loader.service.spec.ts+++ b/src/core/plugins/plugin-loader.service.spec.ts@@ -466,6 +466,76 @@ describe('PluginLoaderService — prunes registry ghosts of removed built-ins',});});+describe('PluginLoaderService — boot reconciles the registry entry of a plugin it drops', () => {+ let tmpDir: string;+ let pluginsDir: string;+ let storage: PluginStorageService;++ const config = () =>+ ({+ get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? tmpDir : undefined),+ }) as unknown as ConfigService;++ beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-drop-'));+ pluginsDir = path.join(tmpDir, 'plugins');+ fs.mkdirSync(pluginsDir, { recursive: true });+ storage = new PluginStorageService(config());+ });+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));++ const makeLoader = (): PluginLoaderService =>+ new PluginLoaderService(config(), new HookManager(), storage, {} as unknown as ModuleRef);++ const writePlugin = (id: string, manifest: Record<string, unknown>): void => {+ const dir = path.join(pluginsDir, id);+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify(manifest));+ fs.writeFileSync(path.join(dir, 'index.js'), 'module.exports = class {};');+ };++ it('marks the persisted entry ERROR when boot-time manifest validation drops a previously-installed plugin', () => {+ // Boot 1: a valid hand-placed plugin loads and gets its registry entry.+ writePlugin('hand-placed', {+ id: 'hand-placed',+ name: 'Hand',+ version: '1.0.0',+ type: 'extension',+ main: 'index.js',+ });+ makeLoader().onModuleInit();+ expect(storage.getPluginEntry('hand-placed')?.status).toBe(PluginStatus.INSTALLED);+ // The operator's config + standing enable decision live in that entry.+ storage.setPluginConfig('hand-placed', { apiKey: 'keep-me' });+ storage.setPluginEnabledByOperator('hand-placed', true);++ // Boot 2: the manifest was hand-edited into something the installer would have rejected+ // (missing required field) — the plugin is dropped from the runtime...+ writePlugin('hand-placed', { id: 'hand-placed', name: 'Hand', type: 'extension', main: 'index.js' });+ const loader2 = makeLoader();+ loader2.onModuleInit();+ expect(loader2.getPlugin('hand-placed')).toBeUndefined();++ // ...and the registry no longer claims it installed. The entry itself (config,+ // enabledByOperator) survives, so fixing the manifest and rebooting re-enables it.+ const entry = storage.getPluginEntry('hand-placed');+ expect(entry?.status).toBe(PluginStatus.ERROR);+ expect(entry?.config).toEqual({ apiKey: 'keep-me' });+ expect(entry?.enabledByOperator).toBe(true);+ });++ it('a hand-placed plugin that fails validation without a registry entry simply does not load', () => {+ writePlugin('never-installed', { id: 'never-installed', name: 'Nope', type: 'extension', main: 'index.js' });++ const loader = makeLoader();+ loader.onModuleInit();++ expect(loader.getPlugin('never-installed')).toBeUndefined();+ // No entry existed, so the ERROR reconciliation is a no-op — none is invented either.+ expect(storage.getPluginEntry('never-installed')).toBeUndefined();+ });+});+describe('PluginLoaderService — loadPlugin seeds configSchema defaults', () => {let tmpDir: string;let pluginsDir: string;diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.tsindex 3b6889eaa..7c5140453 100644--- a/src/core/plugins/plugin-loader.service.ts+++ b/src/core/plugins/plugin-loader.service.ts@@ -1,4 +1,11 @@-import { Injectable, OnApplicationBootstrap, OnModuleInit, OnModuleDestroy, Optional } from '@nestjs/common';+import {+ Injectable,+ NotFoundException,+ OnApplicationBootstrap,+ OnModuleInit,+ OnModuleDestroy,+ Optional,+} from '@nestjs/common';import { ConfigService } from '@nestjs/config';import { ModuleRef } from '@nestjs/core';import { toNeutralJid, userPart } from '../../engine/identity/wa-id';@@ -45,7 +52,10 @@ import { INGRESS_DISPATCH_TIMEOUT_MS } from '../../modules/integration/integratiimport type { MessageService } from '../../modules/message/message.service';import type { SessionService } from '../../modules/session/session.service';import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';-import type { ConversationMappingService } from '../../modules/integration/conversation-mapping.service';+import {+ ConversationMappingConflict,+ type ConversationMappingService,+} from '../../modules/integration/conversation-mapping.service';import type { PluginInstanceService } from '../../modules/integration/plugin-instance.service';import type { IngressJobData } from '../../modules/queue/processors/ingress.processor';import type { SearchProviderRegistry } from '../../modules/search/search-provider.registry';@@ -351,6 +361,13 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstraperror instanceof Error ? error.message : String(error),{ pluginPath, action: 'plugin_load_failed' },);+ // The runtime just dropped this plugin, but a registry entry from a previous successful+ // load still claims it installed/enabled — reconcile the persisted state to ERROR so the+ // mismatch surfaces instead of silently persisting. The entry itself (operator config,+ // enabledByOperator) is preserved: fix the manifest/main and the next boot loads and+ // re-enables it (ensureRegistryEntry resets the status on a successful load). No-op when+ // no entry exists (a hand-placed dir that never loaded).+ this.pluginStorage.setPluginStatus(entry.name, PluginStatus.ERROR);}}}@@ -1061,6 +1078,22 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrapreturn this.resolveEngine(plugin, sessionId);}+ /**+ * Definitive "this session row no longer exists" probe for the stale-mapping repair paths below.+ * True ONLY on a clean not-found from the sessions table; any other failure (service unresolvable,+ * DB error) returns false, so the cross-session fences stay fail-CLOSED when the answer is+ * indeterminate. The runtime engine map can't answer this — a stopped session has no engine but+ * still owns its mappings.+ */+ private async isSessionGone(sessionId: string): Promise<boolean> {+ try {+ await this.getSessionService().findOne(sessionId);+ return false;+ } catch (error) {+ return error instanceof NotFoundException;+ }+ }+/*** Build a worker host for a sandboxed (untrusted) plugin. Overridable so tests can inject a fake* instead of spawning a real OS thread. Production loads the compiled worker bootstrap from dist.@@ -1246,8 +1279,9 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap// uses, so sandboxed plugins log identically (prefixed + structured) instead of bare stdout. The// relay is bounded: oversized lines are truncated and throughput is capped per window — a chatty// or buggy plugin must not flood the host log. Dropped lines are counted and surfaced as one warn- // per window (never one line per drop, or the bound itself would be a flood vector). State is local- // to this enable call, so it resets on disable.+ // per window (never one line per drop, or the bound itself would be a flood vector), plus a final+ // flush on worker exit so a plugin that goes quiet first doesn't silently lose the count. State is+ // local to this enable call, so it resets on disable.let logWindowStart = Date.now();let logCount = 0;let logDropped = 0;@@ -1300,6 +1334,16 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap// provider ACTIVE). Mirrors the enable-failure cleanup. Broader crash-lifecycle cleanup (status, hooks)// is a pre-existing gap for all bridges and out of scope here.const onWorkerExit = (code: number, intentional: boolean): void => {+ // Final log-relay flush: the per-window drop warn above only fires when a new line arrives in a+ // later window, so without this a plugin that goes quiet (or is disabled) before the rollover+ // silently discards its pending count. The worker is gone, so no further lines can arrive.+ if (logDropped > 0) {+ this.logger.warn(+ `Dropped ${logDropped} log messages from sandboxed plugin ${pluginId} (log relay rate limit)`,+ { pluginId, action: 'sandbox_log_relay_dropped', dropped: logDropped },+ );+ logDropped = 0;+ }// Always release the search-provider slot so the registry can fall back to builtin-fts. On a crash// this is the only cleanup; on a deliberate disable/enable-failure the explicit unregister already// ran, making this a harmless no-op.@@ -1495,8 +1539,23 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap// providerConversationId) only, so a stale row can resolve to a chat owned by a DIFFERENT// session than the envelope's. Parity with the assertSessionActive(m.sessionId) check on// mappings.getByProvider below — never send through a session the mapping does not belong to.- // (mapping.sessionId is NOT NULL in the entity, so a plain inequality check suffices.)- if (mapping.sessionId !== env.sessionId) {+ // (mapping.sessionId is NOT NULL in the entity, so a plain inequality check suffices. The+ // env.sessionId guard is for the type only — the facade rejects a missing sessionId first.)+ if (env.sessionId && mapping.sessionId !== env.sessionId) {+ // Repair path: the mapping's session was DELETED (operator re-paired under a new id), so+ // the row is stale rather than cross-session. Rebind it to the envelope's session —+ // already activation-gated by the facade — and let the send proceed; without this the+ // dead session's rows bricked conversation.send permanently. A mapping owned by another+ // EXISTING session is a genuine cross-session violation and still throws.+ if (await this.isSessionGone(mapping.sessionId)) {+ await this.getConversationMappingService().rebindSession(mapping.id, env.sessionId);+ this.logger.warn(+ `Rebound conversation mapping for instance ${env.instanceId} / ${env.source.externalConversationId} ` ++ `from deleted session ${mapping.sessionId} to ${env.sessionId}`,+ { pluginId: plugin.manifest.id, action: 'conversation_mapping_rebound' },+ );+ return mapping.chatId;+ }throw new PluginCapabilityError(`Plugin ${plugin.manifest.id}: conversation mapping for instance ${env.instanceId} / ${env.source.externalConversationId} belongs to session ${mapping.sessionId}, not ${env.sessionId}`,);@@ -1541,10 +1600,30 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrapupsert: async (key, providerConversationId) => {this.assertPermission(plugin.manifest, PluginCapabilityPermission.CONVERSATION_SEND);this.assertSessionActive(plugin, key.sessionId);- await this.getConversationMappingService().upsert(- { sessionId: key.sessionId, chatId: key.chatId, pluginId: plugin.manifest.id, instanceId: key.instanceId },- providerConversationId,- );+ const mappingKey = {+ sessionId: key.sessionId,+ chatId: key.chatId,+ pluginId: plugin.manifest.id,+ instanceId: key.instanceId,+ };+ try {+ await this.getConversationMappingService().upsert(mappingKey, providerConversationId);+ } catch (error) {+ if (!(error instanceof ConversationMappingConflict)) throw error;+ // The reverse unique key is held by another row. If that row's session was DELETED+ // (operator re-paired under a new id), the adapter can never converge — the forward key+ // carries the new sessionId, so every upsert bricks on the dead session's row. Supersede+ // the stale row and retry once. A row owned by an EXISTING session is a genuine conflict+ // and rethrows.+ const stale = await this.getConversationMappingService().getByProvider(+ plugin.manifest.id,+ key.instanceId,+ providerConversationId,+ );+ if (!stale || !(await this.isSessionGone(stale.sessionId))) throw error;+ await this.getConversationMappingService().delete(stale.id);+ await this.getConversationMappingService().upsert(mappingKey, providerConversationId);+ }},get: async key => {this.assertPermission(plugin.manifest, PluginCapabilityPermission.CONVERSATION_SEND);diff --git a/src/core/plugins/sandbox/plugin-worker-host.spec.ts b/src/core/plugins/sandbox/plugin-worker-host.spec.tsindex 26c2afd9d..34ec90069 100644--- a/src/core/plugins/sandbox/plugin-worker-host.spec.ts+++ b/src/core/plugins/sandbox/plugin-worker-host.spec.ts@@ -213,7 +213,7 @@ describe('PluginWorkerHost', () => {// maxInFlightCaps = 1 (7th arg) so the freed slot is observable; capTimeoutMs = 100 (10th arg).new PluginWorkerHost(ch, dispatcher, undefined, undefined, onLog, undefined, 1, undefined, undefined, 100);- ch.reply({ kind: 'cap', id: 1, verb: 'messages.sendText', args: [] });+ ch.reply({ kind: 'cap', id: 1, verb: 'engine.getContacts', args: [] });await microFlush();expect(dispatcher).toHaveBeenCalledTimes(1);@@ -227,7 +227,7 @@ describe('PluginWorkerHost', () => {expect(timedOut?.error).toMatch(/timed out after 100ms/);// The slot is freed: a fresh call dispatches immediately and resolves normally.- ch.reply({ kind: 'cap', id: 2, verb: 'messages.sendText', args: [] });+ ch.reply({ kind: 'cap', id: 2, verb: 'engine.getContacts', args: [] });await microFlush();expect(dispatcher).toHaveBeenCalledTimes(2);expect(ch.sent.find(m => m.kind === 'cap-result' && m.id === 2)).toMatchObject({ ok: true });@@ -240,13 +240,86 @@ describe('PluginWorkerHost', () => {expect(onLog).toHaveBeenCalledWith('warn',expect.stringMatching(/late result was discarded/),- expect.objectContaining({ action: 'sandbox_cap_late_settle', verb: 'messages.sendText' }),+ expect.objectContaining({ action: 'sandbox_cap_late_settle', verb: 'engine.getContacts' }),);} finally {jest.useRealTimers();}});+ it('gives a send verb a wider budget: a send outrunning the base budget still reports success', async () => {+ jest.useFakeTimers();+ try {+ const ch = new FakeChannel();+ // A send that runs longer than the base budget but inside the send budget must NOT be+ // reported as failed to the worker (the send would still land → a retry would duplicate it).+ let settleSend: (v: unknown) => void = () => undefined;+ const dispatcher = jest.fn().mockImplementation(() => new Promise(r => (settleSend = r)));+ const onLog = jest.fn();+ // capTimeoutMs = 100 (10th arg) → send budget 400.+ new PluginWorkerHost(+ ch,+ dispatcher,+ undefined,+ undefined,+ onLog,+ undefined,+ undefined,+ undefined,+ undefined,+ 100,+ );++ ch.reply({ kind: 'cap', id: 1, verb: 'conversation.send', args: [{ type: 'image' }] });+ await microFlush();+ jest.advanceTimersByTime(100); // a lookup would be timed out here+ await microFlush();+ expect(ch.sent.find(m => m.kind === 'cap-result' && m.id === 1)).toBeUndefined();++ settleSend({ messageId: 'wamid' }); // lands at ~100ms, inside the send budget+ await microFlush();+ expect(ch.sent.find(m => m.kind === 'cap-result' && m.id === 1)).toMatchObject({+ ok: true,+ result: { messageId: 'wamid' },+ });+ jest.advanceTimersByTime(1000); // the timer was cleared — no late timeout, no warn+ await microFlush();+ expect(onLog).not.toHaveBeenCalled();+ } finally {+ jest.useRealTimers();+ }+ });++ it('still bounds a wedged send — it times out at the send budget and frees the slot', async () => {+ jest.useFakeTimers();+ try {+ const ch = new FakeChannel();+ const dispatcher = jest.fn().mockImplementation(() => new Promise(() => undefined)); // never settles+ const onLog = jest.fn();+ // maxInFlightCaps = 1 (7th arg) so the freed slot is observable; capTimeoutMs = 100 → send budget 400.+ new PluginWorkerHost(ch, dispatcher, undefined, undefined, onLog, undefined, 1, undefined, undefined, 100);++ ch.reply({ kind: 'cap', id: 1, verb: 'messages.sendText', args: ['s1', 'c1', 'hi'] });+ await microFlush();+ jest.advanceTimersByTime(399);+ await microFlush();+ expect(ch.sent.find(m => m.kind === 'cap-result' && m.id === 1)).toBeUndefined();++ jest.advanceTimersByTime(1); // 400: the send budget elapses+ await microFlush();+ const timedOut = ch.sent.find(m => m.kind === 'cap-result' && m.id === 1) as+ { ok: boolean; error?: string } | undefined;+ expect(timedOut?.ok).toBe(false);+ expect(timedOut?.error).toMatch(/timed out after 400ms/);++ ch.reply({ kind: 'cap', id: 2, verb: 'engine.getContacts', args: [] });+ await microFlush();+ expect(dispatcher).toHaveBeenCalledTimes(2); // slot freed at the send timeout+ } finally {+ jest.useRealTimers();+ }+ });+it('warns (not crashes) when the hung work fails after the timeout', async () => {jest.useFakeTimers();try {diff --git a/src/core/plugins/sandbox/plugin-worker-host.ts b/src/core/plugins/sandbox/plugin-worker-host.tsindex 6c7581be8..eab13299f 100644--- a/src/core/plugins/sandbox/plugin-worker-host.ts+++ b/src/core/plugins/sandbox/plugin-worker-host.ts@@ -7,6 +7,20 @@ import {} from './protocol';import type { SearchQuery, SearchResults } from '../../../modules/search/search.types';+/**+ * Capability verbs whose host-side work IS an outbound message send. A media send (the URL+ * download — itself bounded at 30s by MEDIA_DOWNLOAD_TIMEOUT_MS — then the WhatsApp upload) can+ * legitimately outrun the lookup-oriented capTimeoutMs, and a cap timeout does NOT cancel the+ * underlying work: the worker would record a failure while the message still lands, and a plugin+ * retrying on that error would deliver a duplicate. These verbs therefore get+ * SEND_CAP_TIMEOUT_FACTOR × the base budget (see withCapTimeout), so the timeout stays a "wedged+ * call" signal instead of firing inside normal execution. The in-flight bound is unchanged.+ */+const SEND_CAP_VERBS: ReadonlySet<string> = new Set(['messages.sendText', 'messages.reply', 'conversation.send']);++/** Send-verb budget as a multiple of capTimeoutMs (default 30s → 120s: the 30s media download + upload headroom). */+const SEND_CAP_TIMEOUT_FACTOR = 4;+/*** Host-side driver for a single untrusted plugin running in a worker. Owns the request/response* correlation over a {@link PluginWorkerChannel}: it posts `load`/`lifecycle` messages and resolves@@ -448,11 +462,12 @@ export class PluginWorkerHost {* token — so when it eventually settles the outcome is only logged as a WARN and its result is* discarded (never a second cap-result). This is a robustness bound, not an atomicity guarantee: a* timed-out call may still complete its side effect late (e.g. a message send that lands after the- * caller already saw the timeout error).+ * caller already saw the timeout error). To keep that late-settle window small where a duplicate is+ * user-visible, send verbs (SEND_CAP_VERBS) run on a wider budget that covers normal execution.*/private withCapTimeout(verb: string, work: Promise<unknown>): Promise<unknown> {if (this.capTimeoutMs === undefined) return work;- const timeoutMs = this.capTimeoutMs;+ const timeoutMs = SEND_CAP_VERBS.has(verb) ? this.capTimeoutMs * SEND_CAP_TIMEOUT_FACTOR : this.capTimeoutMs;return new Promise((resolve, reject) => {const timer = setTimeout(() => {// Late settle: warn exactly once, whichever way the work ends. These handlers also keep adiff --git a/src/engine/adapters/baileys-session-store.spec.ts b/src/engine/adapters/baileys-session-store.spec.tsindex ef0eb3565..e7bed67ce 100644--- a/src/engine/adapters/baileys-session-store.spec.ts+++ b/src/engine/adapters/baileys-session-store.spec.ts@@ -478,5 +478,11 @@ describe('BaileysSessionStore', () => {expect(s.findContact('[email protected]')).toBeNull(); // the oldest went firstexpect(s.findContact('[email protected]')).not.toBeNull();});++ it('treats a blank override as unset, not as 0 (unbounded)', () => {+ const s = storeWithCap('');+ s.upsertContacts(Array.from({ length: 5001 }, (_, i) => ({ id: `62${100000 + i}@s.whatsapp.net` })));+ expect(s.listContacts()).toHaveLength(5000);+ });});});diff --git a/src/engine/adapters/baileys-session-store.ts b/src/engine/adapters/baileys-session-store.tsindex 9984f5037..9ba882958 100644--- a/src/engine/adapters/baileys-session-store.ts+++ b/src/engine/adapters/baileys-session-store.ts@@ -2,6 +2,7 @@ import type { Chat, Contact as BaileysContact, WAMessage, WAMessageKey } from '@import { ChatSummary, Contact } from '../interfaces/whatsapp-engine.interface';import { chatKind, parseWaId, toNeutralJid as canonicalizeWaId, userPart } from '../identity/wa-id';import type { LidMappingStore } from '../identity/lid-mapping-store.service';+import { resolveNonNegativeIntEnv } from '../../config/configuration';interface LastMessage {key: WAMessageKey;@@ -98,8 +99,10 @@ export class BaileysSessionStore {private readonly sessionId?: string,) {// Mirrors LidMappingStoreService: a finite default, 0 opts back into unbounded, garbage falls back.- const parsed = Number(process.env.BAILEYS_SESSION_STORE_MAX_ENTRIES ?? SESSION_STORE_MAP_CAP_DEFAULT);- const maxEntries = Number.isFinite(parsed) && parsed >= 0 ? Math.floor(parsed) : SESSION_STORE_MAP_CAP_DEFAULT;+ const maxEntries = resolveNonNegativeIntEnv(+ process.env.BAILEYS_SESSION_STORE_MAX_ENTRIES,+ SESSION_STORE_MAP_CAP_DEFAULT,+ );this.contacts = new LruMap(maxEntries);this.chats = new LruMap(maxEntries);this.lastMessages = new LruMap(maxEntries);diff --git a/src/engine/adapters/inbound-media-cap.spec.ts b/src/engine/adapters/inbound-media-cap.spec.tsindex 5ab2a720e..c532c8e1b 100644--- a/src/engine/adapters/inbound-media-cap.spec.ts+++ b/src/engine/adapters/inbound-media-cap.spec.ts@@ -7,6 +7,7 @@ import {withInboundDownloadTimeout,coerceDeclaredSize,isMediaDownloadEnabled,+ ingestMediaBudgetBytes,} from './inbound-media-cap';describe('inbound media cap', () => {@@ -231,3 +232,26 @@ describe('inbound media cap', () => {});});});++describe('ingestMediaBudgetBytes', () => {+ // An ingest caller (the status seed) needs more headroom than one HTTP response, but "more" must+ // never mean unbounded: at a 10 MiB per-item cap a 50-item seed would otherwise stack ~650 MiB of+ // base64 on the heap at connect time.+ it('stays finite and scales with the per-item cap', () => {+ const budget = ingestMediaBudgetBytes(10 * 1024 * 1024);+ expect(Number.isFinite(budget)).toBe(true);+ expect(budget).toBeGreaterThan(ingestMediaBudgetBytes(1024));+ });++ it('leaves room for several full-size items (the two-videos case that motivated it)', () => {+ const perItem = 10 * 1024 * 1024;+ // ~1.37x accounts for base64 inflation of the decoded cap.+ expect(ingestMediaBudgetBytes(perItem)).toBeGreaterThan(2 * perItem * 1.37);+ });++ it('never drops below the response budget, and falls back to it for a garbage cap', () => {+ expect(ingestMediaBudgetBytes(1)).toBe(chatHistoryMediaBudgetBytes());+ expect(ingestMediaBudgetBytes(0)).toBe(chatHistoryMediaBudgetBytes());+ expect(ingestMediaBudgetBytes(Number.NaN)).toBe(chatHistoryMediaBudgetBytes());+ });+});diff --git a/src/engine/adapters/inbound-media-cap.ts b/src/engine/adapters/inbound-media-cap.tsindex 301af5b56..86431da79 100644--- a/src/engine/adapters/inbound-media-cap.ts+++ b/src/engine/adapters/inbound-media-cap.ts@@ -88,6 +88,26 @@ export function chatHistoryMediaBudgetBytes(): number {return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_CHAT_HISTORY_MEDIA_BUDGET_BYTES;}+/**+ * How many per-item caps an ingest pass (a caller that supplies its own `mediaMaxBytes`, i.e. the+ * status seed) may accumulate before later items fall back to the omitted marker.+ *+ * The response budget above is sized for ONE HTTP response and is too tight here: two ~10 MiB videos+ * are ~28 MiB of base64 and would strip every later status. But "exempt" must not mean unbounded —+ * a 50-item seed at a 10 MiB per-item cap would be ~650 MiB of base64 on the heap at connect time.+ * Four full-size items is roomy enough for a realistic story feed while keeping the bound.+ */+const INGEST_MEDIA_BUDGET_ITEMS = 4;++/**+ * Aggregate budget for a pass whose caller supplies its own per-item cap. Derived from that cap so+ * the two always move together; falls back to the response budget when the cap is absent/unusable.+ */+export function ingestMediaBudgetBytes(perItemMaxBytes: number): number {+ if (!Number.isFinite(perItemMaxBytes) || perItemMaxBytes <= 0) return chatHistoryMediaBudgetBytes();+ return Math.max(chatHistoryMediaBudgetBytes(), Math.ceil(perItemMaxBytes * INGEST_MEDIA_BUDGET_ITEMS * 1.37));+}+/*** Coerce a sender-declared media size (a protobuf `fileLength`, which may be a number, a Long-like* `{ toNumber() }`, a numeric string, or absent) to a finite byte count. Unknown/garbage → 0, i.e.diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 967a32f61..4c4af9216 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -459,6 +459,20 @@ describe('WhatsAppWebJsAdapter.getChatHistory enrichment (parity with the live pexpect(m3.downloadMedia).not.toHaveBeenCalled();});+ it('does not spend the aggregate budget when the caller passes its own per-item cap (status seed)', async () => {+ process.env[ENV] = '4'; // would omit everything after the first payload on the response path+ const m1 = mediaMsg('M14', 'QUJD');+ const m2 = mediaMsg('M15', 'QUJD');++ const out = await readyAdapter(clientFor(m1, m2)).getChatHistory('status@broadcast', 50, true, 10 * 1024 * 1024);++ // The seed ingests items into the store instead of serialising one HTTP response — its own+ // per-item cap is the accounting, so the aggregate response budget must not strip later items.+ expect(out[0].media).toEqual({ mimetype: 'image/jpeg', data: 'QUJD' });+ expect(out[1].media).toEqual({ mimetype: 'image/jpeg', data: 'QUJD' });+ expect(m2.downloadMedia).toHaveBeenCalled();+ });+it('stops the read loop when the abort signal fires (client disconnect)', async () => {const controller = new AbortController();const m1 = mediaMsg('M11', 'QUJD');@@ -3825,14 +3839,63 @@ describe('WhatsAppWebJsAdapter honest outcomes (no phantom success)', () => {{ id: '[email protected]', success: true, status: 200, message: 'The participant was added successfully' },{id: '[email protected]',- success: false,+ success: true,status: 403,- message: 'The participant can be added by sending private invitation only',+ message: 'the participant can only be added by private invitation — invite sent',},{ id: '[email protected]', success: false, status: 409, message: 'The participant is already a group member' },]);});+ it('honors isInviteV4Sent: an all-invite batch resolves instead of throwing "failed for all"', async () => {+ // wwebjs delivers an inviteV4 and reports 403 + isInviteV4Sent: true for each participant —+ // every participant was reached, so the batch is a success-with-invite, not a refusal.+ const addParticipants = jest.fn().mockResolvedValue({+ '[email protected]': {+ code: 403,+ message: 'The participant can be added by sending private invitation only',+ isInviteV4Sent: true,+ },+ '[email protected]': {+ code: 403,+ message: 'The participant can be added by sending private invitation only',+ isInviteV4Sent: true,+ },+ });+ const adapter = readyAdapter({ getChatById: jest.fn().mockResolvedValue(groupChat({ addParticipants })) });++ const results = await adapter.addParticipants(GROUP, ['628111', '628222']);++ expect(results).toEqual([+ {+ id: '[email protected]',+ success: true,+ status: 403,+ message: 'the participant can only be added by private invitation — invite sent',+ },+ {+ id: '[email protected]',+ success: true,+ status: 403,+ message: 'the participant can only be added by private invitation — invite sent',+ },+ ]);+ });++ it('still throws when a 403 came with NO invite sent (the invite could not be delivered)', async () => {+ const addParticipants = jest.fn().mockResolvedValue({+ '[email protected]': {+ code: 403,+ message: 'The participant can be added by sending private invitation only',+ isInviteV4Sent: false,+ },+ });+ const adapter = readyAdapter({ getChatById: jest.fn().mockResolvedValue(groupChat({ addParticipants })) });+ const err = await adapter.addParticipants(GROUP, ['628111']).catch((e: unknown) => e);+ expect(err).toBeInstanceOf(EngineRefusedError);+ expect((err as Error).message).toMatch(/failed for all 1 participant/);+ });+it('throws EngineRefusedError (403) when the library resolves a batch-refusal STRING (e.g. not admin)', async () => {const addParticipants = jest.fn()@@ -3858,16 +3921,28 @@ describe('WhatsAppWebJsAdapter honest outcomes (no phantom success)', () => {describe.each([['removeParticipants'], ['promoteParticipants'], ['demoteParticipants']])('%s (batch {status} is honored)',op => {- it('resolves one success entry per requested participant on {status: 200}', async () => {+ it('resolves one batch-confirmed entry per requested participant on {status: 200}', async () => {const chat = groupChat({ [op]: jest.fn().mockResolvedValue({ status: 200 }) });const adapter = readyAdapter({ getChatById: jest.fn().mockResolvedValue(chat) });const results = await (adapter as unknown as Record<string, (g: string, p: string[]) => Promise<unknown>>)[op](GROUP,['628111', '[email protected]'],);+ // wwebjs confirms the batch only — the entries must say so rather than claim an+ // individually-confirmed outcome the engine never reported.expect(results).toEqual([- { id: '[email protected]', success: true, status: 200 },- { id: '[email protected]', success: true, status: 200 },+ {+ id: '[email protected]',+ success: true,+ status: 200,+ message: 'confirmed with the batch — wwebjs reports no per-participant outcome',+ },+ {+ id: '[email protected]',+ success: true,+ status: 200,+ message: 'confirmed with the batch — wwebjs reports no per-participant outcome',+ },]);});diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 6c299a1dc..3cdf62d0e 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -82,6 +82,7 @@ import {coerceDeclaredSize,inboundMediaConcurrency,inboundMediaMaxBytes,+ ingestMediaBudgetBytes,inboundMediaTimeoutMs,isMediaDownloadEnabled,withInboundDownloadTimeout,@@ -1872,12 +1873,20 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin}// Per-participant outcome: code 200 = added; 403 invite-only / 404 not registered / 408// recently left / 409 already a member / 419 group full (GroupChat.js:102-116).- const results: ParticipantOperationResult[] = Object.entries(raw ?? {}).map(([id, r]) => ({- id,- success: r.code === 200,- status: r.code,- message: r.message || undefined,- }));+ const results: ParticipantOperationResult[] = Object.entries(raw ?? {}).map(([id, r]) => {+ // A 403 with isInviteV4Sent is not a failure: wwebjs already delivered the private group+ // invite (GroupChat.js:203-240). Report it as success-with-invite — otherwise an all-invite+ // batch throws "failed for all" (HTTP 403) even though every participant was reached.+ const inviteSent = r.code === 403 && r.isInviteV4Sent === true;+ return {+ id,+ success: r.code === 200 || inviteSent,+ status: r.code,+ message: inviteSent+ ? 'the participant can only be added by private invitation — invite sent'+ : r.message || undefined,+ };+ });return this.assertParticipantResults('addParticipants', groupId, results);}@@ -1896,8 +1905,11 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin/*** whatsapp-web.js remove/promote/demote resolve `{status: 200}` for the whole batch and reject on* a page-side failure (GroupChat.js:267-298,305-340,343-374) — there is no per-participant- * breakdown to map. A non-200 status is a batch refusal; a 200 confirms the batch, so report one- * success entry per requested participant rather than discarding the outcome.+ * breakdown to map: the page-side code even drops requested ids it can't find in the group and+ * still resolves 200, so a 200 confirms the batch, not any individual. A non-200 status is a+ * batch refusal. Within the per-participant shape the truthful report is one entry per requested+ * participant carrying the batch status, annotated so a consumer can tell it apart from an+ * individually-confirmed outcome (addParticipants); nothing per-participant exists to map.*/private async runStatusOnlyParticipantOp(op: 'removeParticipants' | 'promoteParticipants' | 'demoteParticipants',@@ -1914,7 +1926,12 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginif (res?.status !== 200) {throw new EngineRefusedError(`${op} refused for group ${groupId} (status ${res?.status ?? 'unknown'})`);}- return participantIds.map(id => ({ id, success: true, status: 200 }));+ return participantIds.map(id => ({+ id,+ success: true,+ status: 200,+ message: 'confirmed with the batch — wwebjs reports no per-participant outcome',+ }));}/**@@ -2216,7 +2233,16 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin// running total crosses the budget, later media messages get the declared-only `omitted` marker —// no download — while everything already inlined stays inline (a small history is byte-identical// to before). `signal` (client disconnect) stops the loop between messages; partials are returned.- let mediaBudget = includeMedia ? chatHistoryMediaBudgetBytes() : 0;+ // The 25 MiB default is sized for ONE HTTP response and is too tight for a caller that ingests+ // into a store instead (mediaMaxBytes — the status seed): two ~10 MiB videos are ~28 MiB of+ // base64 and would strip every later status. Such a caller gets a budget derived from its own+ // per-item cap rather than an exemption — unbounded here would mean a 50-item seed could stack+ // ~650 MiB of base64 on the heap at connect time.+ let mediaBudget = !includeMedia+ ? Number.POSITIVE_INFINITY+ : mediaMaxBytes === undefined+ ? chatHistoryMediaBudgetBytes()+ : ingestMediaBudgetBytes(mediaMaxBytes);for (const msg of messages) {if (signal?.aborted) {break;diff --git a/src/engine/identity/lid-mapping-store.service.ts b/src/engine/identity/lid-mapping-store.service.tsindex 21cc26e8b..4595ba4e5 100644--- a/src/engine/identity/lid-mapping-store.service.ts+++ b/src/engine/identity/lid-mapping-store.service.ts@@ -3,6 +3,7 @@ import { InjectRepository } from '@nestjs/typeorm';import { Repository } from 'typeorm';import { LidMapping } from './lid-mapping.entity';import { createLogger } from '../../common/services/logger.service';+import { resolveNonNegativeIntEnv } from '../../config/configuration';// Default cap on the in-memory lid->phone mirror. Every other long-lived map in the audited surface is// bounded (the per-session lidPhoneCache is 5000); the LID mirror was the lone exception. A miss falls@@ -16,7 +17,10 @@ export const LID_MAPPING_CACHE_DEFAULT = 5000;* (mirrors {@link BaileysMessageStore}).*/export interface LidMappingStore {- /** Sync read from the in-memory cache: phone digits, `null` = known-unresolved, `undefined` = never seen. */+ /**+ * Sync read from the in-memory cache: phone digits, `null` = known-unresolved, `undefined` = never+ * seen. A miss is warmed from the persisted table in the background, so a later read can hit.+ */getCached(lid: string): string | null | undefined;/** Sync reverse lookup: the lids currently mapped to this phone (used by the message from-filter). */lidsForPhone(phone: string): string[];@@ -32,7 +36,8 @@ export interface LidMappingStore {** The forward map is bounded by an LRU cap (`LID_MAPPING_CACHE_MAX`, default 5000) so a long-running,* contact-heavy account does not accumulate one entry per distinct LID ever seen into a slow memory leak.- * A cache miss falls back to engine re-resolution (the table remains the source of truth), so eviction+ * A cache miss is warmed from the table in the background (rows past the preload cap stay resolvable)+ * and otherwise falls back to engine re-resolution (the table remains the source of truth), so eviction* only costs a re-resolution, never data loss. The reverse map is reconciled on each eviction so it does* not retain entries for LIDs no longer in the forward cache.*/@@ -41,6 +46,8 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {private readonly logger = createLogger('LidMappingStore');private readonly lidToPhone = new Map<string, string | null>();private readonly phoneToLids = new Map<string, Set<string>>();+ /** Repository fallbacks in flight, one per lid, so a hot miss path can't stack duplicate queries. */+ private readonly pendingLookups = new Set<string>();// 0 = unbounded (legacy behaviour). Every other long-lived map in the audited surface is bounded, so// the default is finite; the env override exists for operators who explicitly want the old behaviour.private readonly maxCachedLids: number;@@ -49,8 +56,7 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {@InjectRepository(LidMapping, 'data')private readonly repo: Repository<LidMapping>,) {- const parsed = Number(process.env.LID_MAPPING_CACHE_MAX ?? LID_MAPPING_CACHE_DEFAULT);- this.maxCachedLids = Number.isFinite(parsed) && parsed >= 0 ? Math.floor(parsed) : LID_MAPPING_CACHE_DEFAULT;+ this.maxCachedLids = resolveNonNegativeIntEnv(process.env.LID_MAPPING_CACHE_MAX, LID_MAPPING_CACHE_DEFAULT);}async onModuleInit(): Promise<void> {@@ -66,7 +72,14 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {*/async reload(): Promise<void> {try {- const rows = await this.repo.find();+ // Deterministic preload: an unordered find() followed by LRU eviction keeps an ARBITRARY+ // subset once the table exceeds the cap. Order by last-write and take at most the cap, so+ // the resident subset is the most-recently-written mappings; older rows stay persisted and+ // are warmed back on the first cache miss (see getCached).+ const rows = await this.repo.find({+ order: { updatedAt: 'DESC' },+ take: this.maxCachedLids > 0 ? this.maxCachedLids : undefined,+ });this.lidToPhone.clear();this.phoneToLids.clear();for (const row of rows) {@@ -89,6 +102,7 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {this.lidToPhone.set(lid, phone as string | null);return phone;}+ this.warmFromTable(lid);return undefined;}@@ -111,6 +125,28 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {}}+ /**+ * Repository fallback for a cache miss. Rows past the preload cap (or evicted by the LRU) are+ * still persisted, so a miss is warmed from the table: THIS lookup still returns undefined —+ * the sync read contract can't await, and callers fall back to engine re-resolution — but the+ * next one hits. A table miss is NOT cached (a false negative would shadow a later remember);+ * a read error is swallowed (the table may not exist yet), the same posture as reload().+ */+ private warmFromTable(lid: string): void {+ if (!lid || this.pendingLookups.has(lid)) return;+ this.pendingLookups.add(lid);+ void this.repo+ .findOne({ where: { lid } })+ .then(row => {+ // Last-write-wins: a remember() that landed while the lookup was in flight is newer.+ if (row && !this.lidToPhone.has(row.lid)) {+ this.index(row.lid, row.phone);+ }+ })+ .catch(() => undefined)+ .finally(() => this.pendingLookups.delete(lid));+ }+/** Update both in-memory indexes, dropping any stale reverse entry from a previous phone. */private index(lid: string, phone: string | null): void {const prev = this.lidToPhone.get(lid);diff --git a/src/engine/identity/lid-mapping-store.spec.ts b/src/engine/identity/lid-mapping-store.spec.tsindex f5f2ba369..5435ec28e 100644--- a/src/engine/identity/lid-mapping-store.spec.ts+++ b/src/engine/identity/lid-mapping-store.spec.ts@@ -2,12 +2,17 @@ import { Repository } from 'typeorm';import { LidMappingStoreService } from './lid-mapping-store.service';import { LidMapping } from './lid-mapping.entity';-/** Minimal in-memory stand-in for the TypeORM repo: just the find()/upsert() the store uses. */+/** Minimal in-memory stand-in for the TypeORM repo: just the find()/findOne()/upsert() the store uses. */function makeFakeRepo(seed: Partial<LidMapping>[] = []) {const rows: LidMapping[] = seed.map(r => ({ lid: '', phone: null, sessionId: null, updatedAt: new Date(0), ...r }));return {rows,find: jest.fn().mockImplementation(() => Promise.resolve(rows.map(r => ({ ...r })))),+ findOne: jest+ .fn()+ .mockImplementation((options: { where: { lid: string } }) =>+ Promise.resolve(rows.find(r => r.lid === options.where.lid) ?? null),+ ),upsert: jest.fn().mockImplementation((values: Partial<LidMapping>) => {const i = rows.findIndex(r => r.lid === values.lid);if (i >= 0) rows[i] = { ...rows[i], ...values };@@ -156,4 +161,82 @@ describe('LidMappingStoreService — LRU cap', () => {// The constructor must not throw, and must apply the default (5000) rather than NaN/0.expect((store as unknown as { maxCachedLids: number }).maxCachedLids).toBe(5000);});++ it('treats a blank env value as unset, not as 0 (unbounded)', () => {+ process.env.LID_MAPPING_CACHE_MAX = '';+ const repo = makeFakeRepo();+ const store = new LidMappingStoreService(repo as unknown as Repository<LidMapping>);+ expect((store as unknown as { maxCachedLids: number }).maxCachedLids).toBe(5000);+ });+});++describe('LidMappingStoreService — deterministic preload + repository fallback', () => {+ const prevMax = process.env.LID_MAPPING_CACHE_MAX;+ afterEach(() => {+ if (prevMax === undefined) delete process.env.LID_MAPPING_CACHE_MAX;+ else process.env.LID_MAPPING_CACHE_MAX = prevMax;+ });++ it('preloads deterministically: last-write-first, capped at the LRU limit', async () => {+ process.env.LID_MAPPING_CACHE_MAX = '3';+ const repo = makeFakeRepo();+ const store = new LidMappingStoreService(repo as unknown as Repository<LidMapping>);+ await store.onModuleInit();+ expect(repo.find).toHaveBeenCalledWith({ order: { updatedAt: 'DESC' }, take: 3 });+ });++ it('preloads without a take when the cap is disabled (0)', async () => {+ process.env.LID_MAPPING_CACHE_MAX = '0';+ const repo = makeFakeRepo();+ const store = new LidMappingStoreService(repo as unknown as Repository<LidMapping>);+ await store.onModuleInit();+ expect(repo.find).toHaveBeenCalledWith({ order: { updatedAt: 'DESC' }, take: undefined });+ });++ it('warms an evicted-but-persisted mapping from the repository on a cache miss', async () => {+ process.env.LID_MAPPING_CACHE_MAX = '1';+ const repo = makeFakeRepo();+ const store = new LidMappingStoreService(repo as unknown as Repository<LidMapping>);+ await store.onModuleInit();+ await store.remember('lid-a', '620001');+ await store.remember('lid-b', '620002'); // evicts lid-a (cap 1); its row stays persisted++ expect(store.getCached('lid-a')).toBeUndefined(); // the miss itself stays a miss (sync contract)+ await new Promise(resolve => setImmediate(resolve)); // let the fallback lookup settle++ expect(repo.findOne).toHaveBeenCalledWith({ where: { lid: 'lid-a' } });+ expect(store.getCached('lid-a')).toBe('620001'); // the NEXT lookup hits the warmed cache+ });++ it('runs at most one fallback query per lid while a lookup is in flight', async () => {+ const repo = makeFakeRepo([{ lid: 'lid-a', phone: '620001' }]);+ // No onModuleInit: the cache starts empty even though the row is persisted.+ const store = new LidMappingStoreService(repo as unknown as Repository<LidMapping>);+ let resolveFind: (row: LidMapping | null) => void = () => undefined;+ repo.findOne.mockImplementationOnce(+ () =>+ new Promise<LidMapping | null>(resolve => {+ resolveFind = resolve;+ }),+ );++ expect(store.getCached('lid-a')).toBeUndefined();+ expect(store.getCached('lid-a')).toBeUndefined();+ expect(repo.findOne).toHaveBeenCalledTimes(1);++ resolveFind({ lid: 'lid-a', phone: '620001' } as LidMapping);+ await new Promise(resolve => setImmediate(resolve));+ expect(store.getCached('lid-a')).toBe('620001');+ });++ it('swallows a fallback read error (table unavailable) — the miss stays a miss and never throws', async () => {+ const repo = makeFakeRepo();+ repo.findOne.mockRejectedValueOnce(new Error('no such table: lid_mappings'));+ const store = new LidMappingStoreService(repo as unknown as Repository<LidMapping>);++ expect(store.getCached('lid-a')).toBeUndefined();+ await new Promise(resolve => setImmediate(resolve));+ // A table miss is not cached as a negative either — a later remember() must not be shadowed.+ expect(store.getCached('lid-a')).toBeUndefined();+ });});diff --git a/src/modules/auth/auth.service.spec.ts b/src/modules/auth/auth.service.spec.tsindex 4c69bf911..d39f6a2ee 100644--- a/src/modules/auth/auth.service.spec.ts+++ b/src/modules/auth/auth.service.spec.ts@@ -4,7 +4,7 @@ jest.mock('fs', () => ({ __esModule: true, ...jest.requireActual<typeof import('import { Test, TestingModule } from '@nestjs/testing';import { getRepositoryToken } from '@nestjs/typeorm';-import { Repository } from 'typeorm';+import { FindOperator, Repository } from 'typeorm';import { UnauthorizedException, NotFoundException, ConflictException } from '@nestjs/common';import { createHash, createHmac } from 'crypto';import * as fs from 'fs';@@ -114,6 +114,73 @@ describe('AuthService', () => {service = module.get<AuthService>(AuthService);});+ // ── last-admin guard test double ──────────────────────────────────++ /**+ * In-memory stand-in for the api_keys table: findOne()/count()/save()/remove() backed by a Map.+ * count() HONORS the where-clause — the last-admin guard's query filters on role/isActive/+ * expiresAt AND session scope, so a mock that ignores the predicate (e.g. reporting a fixed+ * set size) would let a session-scoped admin count as a surviving key manager and the+ * allowedSessions filter would never actually be exercised. Interleaving is driven purely by+ * promise resolution order, so concurrency scenarios stay deterministic regardless of which+ * request runs its critical section first.+ */+ function setupKeys(seed: ApiKey[]): void {+ const keys = new Map(seed.map(k => [k.id, k]));+ (repository.findOne as jest.Mock).mockImplementation((options: { where: { id: string } }) =>+ Promise.resolve(keys.get(options.where.id) ?? null),+ );+ (repository.count as jest.Mock).mockImplementation((options?: { where?: Array<Record<string, unknown>> }) =>+ Promise.resolve(+ [...keys.values()].filter(k => (options?.where ?? []).some(branch => matchesWhere(k, branch))).length,+ ),+ );+ (repository.remove as jest.Mock).mockImplementation((key: ApiKey) => {+ keys.delete(key.id);+ return Promise.resolve(key);+ });+ (repository.save as jest.Mock).mockImplementation((key: ApiKey) => {+ keys.set(key.id, key);+ return Promise.resolve(key);+ });+ }++ function setupLiveAdmins(...ids: string[]): void {+ setupKeys(ids.map(id => createMockApiKey({ id, role: ApiKeyRole.ADMIN })));+ }++ /** OR semantics across the where array; AND across the fields of a single branch. */+ function matchesWhere(key: ApiKey, branch: Record<string, unknown>): boolean {+ return Object.entries(branch).every(([field, condition]) => matchesCondition(dbColumnValue(key, field), condition));+ }++ /** Mirror the simple-array columns' stored shape: null stays null, an array is stored as a CSV. */+ function dbColumnValue(key: ApiKey, field: string): unknown {+ const value = (key as unknown as Record<string, unknown>)[field];+ if ((field === 'allowedSessions' || field === 'allowedIps') && Array.isArray(value)) return value.join(',');+ return value;+ }++ function matchesCondition(value: unknown, condition: unknown): boolean {+ if (condition instanceof FindOperator) {+ switch (condition.type) {+ case 'not':+ return !matchesCondition(value, condition.value);+ case 'isNull':+ return value === null || value === undefined;+ case 'moreThan':+ return (+ value instanceof Date && condition.value instanceof Date && value.getTime() > condition.value.getTime()+ );+ case 'equal':+ return value === condition.value;+ default:+ throw new Error(`unsupported FindOperator in count mock: ${String(condition.type)}`);+ }+ }+ return value === condition;+ }+// ── createApiKey ──────────────────────────────────────────────────describe('createApiKey', () => {@@ -359,34 +426,6 @@ describe('AuthService', () => {// ── last-admin guard under concurrency ─────────────────────────────describe('last-admin guard under concurrency', () => {- /**- * In-memory stand-in for the DB: the set of currently usable admin key ids. count() reports- * OTHER usable admins (the guard's query always excludes the target, itself a live usable- * admin at check time); save()/remove() apply the capability change synchronously at call- * time. Interleaving is then driven purely by promise resolution order, so each scenario- * below has a deterministic outcome regardless of which request runs its section first.- */- function setupLiveAdmins(...ids: string[]): void {- const liveAdmins = new Set(ids);- const keys = new Map(ids.map(id => [id, createMockApiKey({ id, role: ApiKeyRole.ADMIN })]));- (repository.findOne as jest.Mock).mockImplementation((options: { where: { id: string } }) =>- Promise.resolve(keys.get(options.where.id) ?? null),- );- (repository.count as jest.Mock).mockImplementation(() => Promise.resolve(liveAdmins.size - 1));- (repository.remove as jest.Mock).mockImplementation((key: ApiKey) => {- liveAdmins.delete(key.id);- return Promise.resolve(key);- });- (repository.save as jest.Mock).mockImplementation((key: ApiKey) => {- if (key.role === ApiKeyRole.ADMIN && key.isActive) {- liveAdmins.add(key.id);- } else {- liveAdmins.delete(key.id);- }- return Promise.resolve(key);- });- }-const outcomes = (results: PromiseSettledResult<unknown>[]) => ({succeeded: results.filter(r => r.status === 'fulfilled'),conflicts: results.filter(r => r.status === 'rejected' && r.reason instanceof ConflictException),@@ -455,6 +494,75 @@ describe('AuthService', () => {});});+ // ── last-admin invariant vs session-scoped admins ─────────────────++ describe('last-admin invariant vs session-scoped admins', () => {+ // Key-lifecycle routes are fenced behind @RequireUnscopedKey, so a session-scoped admin can+ // never manage keys: it must NOT count as a surviving admin, and scoping the last unscoped+ // admin must be rejected like a demotion — otherwise the system locks itself out for good.+ const unscopedAdmin = (id: string) => createMockApiKey({ id, role: ApiKeyRole.ADMIN });+ const scopedAdmin = (id: string) => createMockApiKey({ id, role: ApiKeyRole.ADMIN, allowedSessions: ['sess-1'] });++ it('rejects deleting the last unscoped admin even while a session-scoped admin survives', async () => {+ setupKeys([unscopedAdmin('admin-a'), scopedAdmin('admin-scoped')]);++ await expect(service.delete('admin-a')).rejects.toThrow(/last active admin/i);+ expect(repository.remove).not.toHaveBeenCalled();+ });++ it('rejects revoking the last unscoped admin even while a session-scoped admin survives', async () => {+ setupKeys([unscopedAdmin('admin-a'), scopedAdmin('admin-scoped')]);++ await expect(service.revoke('admin-a')).rejects.toThrow(/last active admin/i);+ expect(repository.save).not.toHaveBeenCalled();+ });++ it('rejects demoting the last unscoped admin even while a session-scoped admin survives', async () => {+ setupKeys([unscopedAdmin('admin-a'), scopedAdmin('admin-scoped')]);++ await expect(service.update('admin-a', { role: ApiKeyRole.OPERATOR })).rejects.toThrow(/last active admin/i);+ });++ it('rejects scoping the last unscoped admin — the same capability-stripping as a demotion', async () => {+ setupKeys([unscopedAdmin('admin-a'), scopedAdmin('admin-scoped')]);++ await expect(service.update('admin-a', { allowedSessions: ['sess-9'] })).rejects.toThrow(/last active admin/i);+ expect(repository.save).not.toHaveBeenCalled();+ });++ it('treats an empty allowedSessions write as unscoped — not capability-stripping', async () => {+ setupKeys([unscopedAdmin('admin-a')]);++ await expect(service.update('admin-a', { allowedSessions: [] })).resolves.toBeDefined();+ });++ it('lets a session-scoped admin be deleted — it never counted toward the invariant', async () => {+ setupKeys([unscopedAdmin('admin-a'), scopedAdmin('admin-scoped')]);++ await expect(service.delete('admin-scoped')).resolves.toBeUndefined();+ expect(repository.remove).toHaveBeenCalledTimes(1);+ });++ it('allows stripping an unscoped admin when another unscoped admin remains', async () => {+ setupKeys([unscopedAdmin('admin-a'), unscopedAdmin('admin-b'), scopedAdmin('admin-scoped')]);++ await expect(service.update('admin-a', { allowedSessions: ['sess-9'] })).resolves.toBeDefined();+ });++ it('re-reads the target inside the critical section instead of trusting the pre-lock snapshot', async () => {+ // The pre-lock read sees a usable admin; a concurrent (already serialized) mutation demoted+ // it before this request's section ran. The fresh read must win — no spurious conflict.+ const stale = createMockApiKey({ id: 'admin-a', role: ApiKeyRole.ADMIN });+ const fresh = createMockApiKey({ id: 'admin-a', role: ApiKeyRole.OPERATOR });+ (repository.findOne as jest.Mock).mockResolvedValueOnce(stale).mockResolvedValue(fresh);+ (repository.count as jest.Mock).mockResolvedValue(0);+ (repository.remove as jest.Mock).mockImplementation((key: ApiKey) => Promise.resolve(key));++ await expect(service.delete('admin-a')).resolves.toBeUndefined();+ expect(repository.remove).toHaveBeenCalledWith(fresh);+ });+ });+// ── validateApiKey ────────────────────────────────────────────────describe('validateApiKey', () => {@@ -727,6 +835,39 @@ describe('AuthService', () => {expect(bannerText()).not.toContain('owa_k1_d'); // no fingerprint of the dead key});+ it('boot keeps the bootstrap file when only the pepper changed (prefix matches, hash does not)', async () => {+ const warnSpy = jest+ .spyOn((service as unknown as { logger: { warn: (...args: unknown[]) => void } }).logger, 'warn')+ .mockImplementation(() => undefined);+ (repository.count as jest.Mock).mockResolvedValue(1);+ existsSpy.mockReturnValue(true);+ readSpy.mockReturnValue('owa_k1_pepperchanged');+ // The hash lookup misses (the current pepper hashes the same key differently), but the+ // unhashed prefix still resolves to the live row → wrong pepper, not a stale file.+ (repository.findOne as jest.Mock)+ .mockResolvedValueOnce(null)+ .mockResolvedValue(createMockApiKey({ keyPrefix: 'owa_k1_peppe', keyHash: 'hash-under-old-pepper' }));++ await service.onModuleInit();++ expect(repository.findOne).toHaveBeenCalledWith({ where: { keyPrefix: 'owa_k1_peppe' } });+ expect(unlinkSpy).not.toHaveBeenCalled();+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('API_KEY_PEPPER'), expect.anything());+ expect(bannerText()).toContain('(check dashboard for keys)'); // still not advertised as live+ });++ it('boot still deletes the file when no row carries the file key prefix (genuine staleness)', async () => {+ (repository.count as jest.Mock).mockResolvedValue(1);+ existsSpy.mockReturnValue(true);+ readSpy.mockReturnValue('owa_k1_deaddeaddead');+ (repository.findOne as jest.Mock).mockResolvedValue(null); // neither the hash nor the prefix resolves++ await service.onModuleInit();++ expect(repository.findOne).toHaveBeenCalledWith({ where: { keyPrefix: 'owa_k1_deadd' } });+ expect(unlinkSpy).toHaveBeenCalledWith(expect.stringContaining('.api-key'));+ });+it('boot treats a revoked bootstrap key as stale too', async () => {(repository.count as jest.Mock).mockResolvedValue(1);existsSpy.mockReturnValue(true);diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.tsindex 98c393b36..3b8968b53 100644--- a/src/modules/auth/auth.service.ts+++ b/src/modules/auth/auth.service.ts@@ -8,7 +8,7 @@ import {} from '@nestjs/common';import { ModuleRef } from '@nestjs/core';import { InjectRepository } from '@nestjs/typeorm';-import { IsNull, MoreThan, Not, Repository } from 'typeorm';+import { Equal, IsNull, MoreThan, Not, Repository } from 'typeorm';import { randomBytes } from 'crypto';import { existsSync, readFileSync, unlinkSync } from 'fs';import { join } from 'path';@@ -191,6 +191,21 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {const stored = await this.apiKeyRepository.findOne({ where: { keyHash: this.hashKey(rawKey) } });const live = Boolean(stored && stored.isActive && (!stored.expiresAt || stored.expiresAt > new Date()));if (live) return rawKey;+ if (!stored) {+ // A hash miss alone does not prove the key is gone: the same raw key hashes differently under+ // a changed API_KEY_PEPPER. The prefix is seeded unhashed alongside the key, so it still finds+ // the row — when it resolves, the file holds the only copy of a still-live key and must+ // survive. Delete only when nothing carries the prefix either (e.g. a backup restore that+ // lost the key row), preserving the documented self-heal.+ const byPrefix = await this.apiKeyRepository.findOne({ where: { keyPrefix: rawKey.substring(0, 12) } });+ if (byPrefix) {+ this.logger.warn(+ 'Bootstrap API key file does not match any stored key hash — API_KEY_PEPPER changed since the key was seeded? The key itself is still live, so the file is kept; restore the original pepper or rotate the key to repair.',+ { keyPrefix: byPrefix.keyPrefix, action: 'bootstrap_key_pepper_mismatch' },+ );+ return null;+ }+ }this.removeBootstrapKeyFile('it no longer resolves to an active key');return null;}@@ -279,13 +294,20 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {async update(id: string, dto: UpdateApiKeyDto): Promise<ApiKey> {const apiKey = await this.findOne(id);+ // Scoping the last unscoped admin (non-empty allowedSessions) strips key-management just as+ // surely as demoting or expiring it: @RequireUnscopedKey would then 403 every lifecycle route.const removesOrSchedulesLastAdmin =(dto.role !== undefined && dto.role !== ApiKeyRole.ADMIN) ||- (dto.expiresAt !== undefined && dto.expiresAt !== null);+ (dto.expiresAt !== undefined && dto.expiresAt !== null) ||+ (dto.allowedSessions !== undefined && dto.allowedSessions.length > 0);const applyAndSave = async (): Promise<ApiKey> => {+ // Re-read the target inside the critical section: the pre-lock snapshot can be stale — a+ // concurrent serialized mutation may already have changed this key's usability — so the+ // last-admin check and the write both run against fresh state.+ const target = await this.findOne(id);if (removesOrSchedulesLastAdmin) {- await this.assertNotLastUsableAdmin(apiKey);+ await this.assertNotLastUsableAdmin(target);}// Capture the authorization-relevant fields BEFORE applying the change. Only a change to role,@@ -294,19 +316,19 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {// NOT disconnect clients. REST enforces the new state immediately; without eviction a live socket// keeps streaming events for sessions/IPs the key just lost until it resubscribes or drops.const before = {- role: apiKey.role,- allowedIps: apiKey.allowedIps,- allowedSessions: apiKey.allowedSessions,- expiresAt: apiKey.expiresAt,+ role: target.role,+ allowedIps: target.allowedIps,+ allowedSessions: target.allowedSessions,+ expiresAt: target.expiresAt,};- if (dto.name) apiKey.name = dto.name;- if (dto.role) apiKey.role = dto.role;- if (dto.allowedIps !== undefined) apiKey.allowedIps = dto.allowedIps;- if (dto.allowedSessions !== undefined) apiKey.allowedSessions = dto.allowedSessions;- if (dto.expiresAt !== undefined) apiKey.expiresAt = dto.expiresAt ? new Date(dto.expiresAt) : null;+ if (dto.name) target.name = dto.name;+ if (dto.role) target.role = dto.role;+ if (dto.allowedIps !== undefined) target.allowedIps = dto.allowedIps;+ if (dto.allowedSessions !== undefined) target.allowedSessions = dto.allowedSessions;+ if (dto.expiresAt !== undefined) target.expiresAt = dto.expiresAt ? new Date(dto.expiresAt) : null;- const saved = await this.apiKeyRepository.save(apiKey);+ const saved = await this.apiKeyRepository.save(target);// Compare membership, not order: a pure reorder of allowedIps/allowedSessions is a no-op for the// .includes()-based enforcement, so sort before stringify to avoid a spurious eviction on a reorder.@@ -324,7 +346,12 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {// Run check+write inside the shared critical section ONLY when this update can strip the last// usable admin; every other update (rename, promotion, non-admin keys) stays lock-free.- return removesOrSchedulesLastAdmin && AuthService.isUsableAdmin(apiKey)+ // The predicate is the target's ROLE, not its usability: usability also depends on isActive,+ // expiry and scope, any of which a concurrent serialized mutation may have just changed. Reading+ // that from the pre-lock snapshot would let a target that only LOOKS unusable skip the lock and+ // run its check unserialized — the very race the lock exists to close. Role is the stable,+ // conservative key: it over-locks a little (an already-revoked admin) and never under-locks.+ return removesOrSchedulesLastAdmin && apiKey.role === ApiKeyRole.ADMIN? this.adminCapabilityLock.run(AuthService.ADMIN_CAPABILITY_LOCK_KEY, applyAndSave): applyAndSave();}@@ -332,15 +359,19 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {async delete(id: string): Promise<void> {const apiKey = await this.findOne(id);const removeKey = async (): Promise<void> => {- await this.assertNotLastUsableAdmin(apiKey);+ // Re-read inside the critical section (same staleness hazard as update()): never run the+ // last-admin check against the pre-lock snapshot.+ const target = await this.findOne(id);+ await this.assertNotLastUsableAdmin(target);// Drop any un-flushed usage accumulator so a deleted key leaves nothing behind in the Map.this.pendingUsage.delete(id);- await this.apiKeyRepository.remove(apiKey);- this.removeBootstrapKeyFileIfMatching(apiKey);+ await this.apiKeyRepository.remove(target);+ this.removeBootstrapKeyFileIfMatching(target);};- // A target that is not a usable admin can skip the lock: it is not counted as one, so removing- // it cannot strand the system — some other usable admin (or none at all) exists independently.- if (AuthService.isUsableAdmin(apiKey)) {+ // Lock on the ROLE, not on the pre-lock usability snapshot: isActive/expiry/scope can change+ // under a concurrent serialized mutation, so a target that merely looks unusable here must not+ // skip the critical section. A non-admin target genuinely cannot strand the system.+ if (apiKey.role === ApiKeyRole.ADMIN) {await this.adminCapabilityLock.run(AuthService.ADMIN_CAPABILITY_LOCK_KEY, removeKey);} else {await removeKey();@@ -355,36 +386,70 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {async revoke(id: string): Promise<ApiKey> {const apiKey = await this.findOne(id);const revokeKey = async (): Promise<ApiKey> => {- await this.assertNotLastUsableAdmin(apiKey);+ // Re-read inside the critical section (same staleness hazard as update()).+ const target = await this.findOne(id);+ await this.assertNotLastUsableAdmin(target);// A revoked key fails validation before its next flush, so its accumulator would orphan —// drop it here.this.pendingUsage.delete(id);- apiKey.isActive = false;- const saved = await this.apiKeyRepository.save(apiKey);- this.removeBootstrapKeyFileIfMatching(apiKey);+ target.isActive = false;+ const saved = await this.apiKeyRepository.save(target);+ this.removeBootstrapKeyFileIfMatching(target);return saved;};- const saved = AuthService.isUsableAdmin(apiKey)- ? await this.adminCapabilityLock.run(AuthService.ADMIN_CAPABILITY_LOCK_KEY, revokeKey)- : await revokeKey();+ // Same reasoning as delete(): the lock predicate is the stable role, not a snapshot of usability.+ const saved =+ apiKey.role === ApiKeyRole.ADMIN+ ? await this.adminCapabilityLock.run(AuthService.ADMIN_CAPABILITY_LOCK_KEY, revokeKey)+ : await revokeKey();// Kick any WebSocket connections already authenticated with this key: without this, a revoked// key keeps receiving events on already-subscribed sockets until they happen to disconnect.this.evictActiveSockets(id, 'revoked');return saved;}+ /**+ * "Usable admin" for the last-admin invariant: an active, unexpired ADMIN key with NO session+ * scope. The key-lifecycle routes are fenced behind @RequireUnscopedKey (AuthController), so a+ * session-scoped admin can authenticate but can never manage keys — counting it as a surviving+ * admin would bless the removal of the last key that actually can, a permanent management+ * lockout with no in-band recovery (the boot seed only fires on an EMPTY table, not on zero+ * unscoped admins).+ */private static isUsableAdmin(key: ApiKey, now = new Date()): boolean {- return key.role === ApiKeyRole.ADMIN && key.isActive && (!key.expiresAt || key.expiresAt > now);+ return (+ key.role === ApiKeyRole.ADMIN &&+ key.isActive &&+ (!key.expiresAt || key.expiresAt > now) &&+ (!key.allowedSessions || key.allowedSessions.length === 0)+ );}private async assertNotLastUsableAdmin(target: ApiKey): Promise<void> {const now = new Date();if (!AuthService.isUsableAdmin(target, now)) return;+ // Match isUsableAdmin at the SQL level: only UNSCOPED admins count. The simple-array column+ // stores an empty array as '' (rows updated with allowedSessions: [] hold exactly that), so+ // "no session scope" is NULL or '' — IsNull() alone would miss the '' rows.const otherUsableAdmins = await this.apiKeyRepository.count({where: [- { id: Not(target.id), role: ApiKeyRole.ADMIN, isActive: true, expiresAt: IsNull() },- { id: Not(target.id), role: ApiKeyRole.ADMIN, isActive: true, expiresAt: MoreThan(now) },+ { id: Not(target.id), role: ApiKeyRole.ADMIN, isActive: true, expiresAt: IsNull(), allowedSessions: IsNull() },+ { id: Not(target.id), role: ApiKeyRole.ADMIN, isActive: true, expiresAt: IsNull(), allowedSessions: Equal('') },+ {+ id: Not(target.id),+ role: ApiKeyRole.ADMIN,+ isActive: true,+ expiresAt: MoreThan(now),+ allowedSessions: IsNull(),+ },+ {+ id: Not(target.id),+ role: ApiKeyRole.ADMIN,+ isActive: true,+ expiresAt: MoreThan(now),+ allowedSessions: Equal(''),+ },],});if (otherUsableAdmins === 0) {diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.tsindex d90241a32..368d2f4a8 100644--- a/src/modules/events/events.gateway.spec.ts+++ b/src/modules/events/events.gateway.spec.ts@@ -587,7 +587,8 @@ describe('EventsGateway rate limiting', () => {it('rejects the handshake above the window BEFORE validateApiKey runs', async () => {process.env.WS_RATE_LIMIT_HANDSHAKE_MAX = '3';process.env.WS_RATE_LIMIT_HANDSHAKE_WINDOW_MS = '60000';- authService.validateApiKey.mockResolvedValue({ id: 'k1', name: 'k', allowedSessions: null });+ // Failed handshakes are what the window is for — an authenticated one is refunded (below).+ authService.validateApiKey.mockRejectedValue(new Error('bad key'));const gw = buildGateway();for (let i = 0; i < 3; i++) {@@ -609,6 +610,47 @@ describe('EventsGateway rate limiting', () => {);});+ it('emits the RATE_LIMITED error frame BEFORE disconnecting, so the client can tell throttling from a dead server', async () => {+ process.env.WS_RATE_LIMIT_HANDSHAKE_MAX = '1';+ authService.validateApiKey.mockRejectedValue(new Error('bad key'));+ const gw = buildGateway();++ await gw.handleConnection(asSocket(makeSock('s1', { apiKey: 'good' })));+ const blocked = makeSock('s-blocked', { apiKey: 'good' });+ await gw.handleConnection(asSocket(blocked));++ // Order is the client-visible contract: socket.io delivers the queued error frame ahead of+ // the disconnect packet, and the dashboard keys its reconnect banner on receiving a+ // distinguishable error plus the server-initiated close.+ expect(blocked.emit).toHaveBeenCalledWith(+ 'message',+ expect.objectContaining({ type: 'error', code: 'RATE_LIMITED' }),+ );+ expect(blocked.disconnect).toHaveBeenCalled();+ const emitOrder = blocked.emit.mock.invocationCallOrder[0];+ const disconnectOrder = blocked.disconnect.mock.invocationCallOrder[0];+ expect(emitOrder).toBeLessThan(disconnectOrder);+ });++ it('does not spend the shared per-IP budget on handshakes that authenticate', async () => {+ // The window is charged pre-auth to keep a flood off the DB, but every client behind one+ // NAT/proxy IP shares the subject — charging successful connects too would let a few+ // dashboards re-mounting lock each other out. Authenticated volume is bounded by the+ // per-key socket cap instead.+ process.env.WS_RATE_LIMIT_HANDSHAKE_MAX = '2';+ process.env.WS_RATE_LIMIT_HANDSHAKE_WINDOW_MS = '60000';+ process.env.WS_MAX_SOCKETS_PER_KEY = '99';+ authService.validateApiKey.mockResolvedValue({ id: 'k1', name: 'k', allowedSessions: null });+ const gw = buildGateway();++ for (let i = 0; i < 6; i++) {+ const sock = makeSock(`ok${i}`, { apiKey: 'good' });+ await gw.handleConnection(asSocket(sock));+ expect(sock.disconnect).not.toHaveBeenCalled();+ }+ expect(authService.validateApiKey).toHaveBeenCalledTimes(6);+ });+it('throttles an unauthenticated handshake flood before any credential/audit work', async () => {process.env.WS_RATE_LIMIT_HANDSHAKE_MAX = '2';const gw = buildGateway();@@ -628,7 +670,7 @@ describe('EventsGateway rate limiting', () => {process.env.WS_RATE_LIMIT_HANDSHAKE_MAX = '1';process.env.WS_RATE_LIMIT_HANDSHAKE_WINDOW_MS = '60000';jest.useFakeTimers();- authService.validateApiKey.mockResolvedValue({ id: 'k1', name: 'k', allowedSessions: null });+ authService.validateApiKey.mockRejectedValue(new Error('bad key'));const gw = buildGateway();await gw.handleConnection(asSocket(makeSock('a', { apiKey: 'good' })));@@ -640,15 +682,18 @@ describe('EventsGateway rate limiting', () => {jest.advanceTimersByTime(60_001);const recovered = makeSock('c', { apiKey: 'good' });await gw.handleConnection(asSocket(recovered));- expect(recovered.disconnect).not.toHaveBeenCalled();+ // No longer shed by the window: it reaches the credential check. (It is still rejected here+ // because this test drives the window with failing credentials, so assert on WHICH rejection.)expect(authService.validateApiKey).toHaveBeenCalledTimes(2);+ expect(recovered.emit).toHaveBeenCalledWith('message', expect.objectContaining({ code: 'UNAUTHORIZED' }));+ expect(recovered.emit).not.toHaveBeenCalledWith('message', expect.objectContaining({ code: 'RATE_LIMITED' }));});it('samples the violation audit: one row per subject per minute, suppressed count folded in', async () => {process.env.WS_RATE_LIMIT_HANDSHAKE_MAX = '1';process.env.WS_RATE_LIMIT_HANDSHAKE_WINDOW_MS = '60000';jest.useFakeTimers();- authService.validateApiKey.mockResolvedValue({ id: 'k1', name: 'k', allowedSessions: null });+ authService.validateApiKey.mockRejectedValue(new Error('bad key'));const gw = buildGateway();await gw.handleConnection(asSocket(makeSock('a', { apiKey: 'good' }))); // alloweddiff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex dc52849ef..3d281a02a 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -284,6 +284,12 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate(client.data as { apiKey: unknown; rawApiKey: string }).apiKey = validKey;(client.data as { rawApiKey: string }).rawApiKey = apiKey;this.trackSocket(validKey.id, client);+ // The handshake window is charged pre-auth to keep an unauthenticated flood off the DB. This+ // one turned out to be authentic, so give the slot back: the window then bounds FAILED+ // handshakes, and authenticated connections stay bounded by maxSocketsPerKey above. Without+ // this, every client behind one NAT/proxy IP shares a 10/min budget and normal dashboard+ // re-mounts lock each other out.+ this.handshakeLimiter.refund(clientIp);this.logger.log(`Client connected: ${client.id} (key: ${validKey.name})`);} catch (error) {this.logger.warn(`Client ${client.id} rejected: Auth error`, {diff --git a/src/modules/events/ws-rate-limit.spec.ts b/src/modules/events/ws-rate-limit.spec.tsindex 8c356ed68..f9f5bf316 100644--- a/src/modules/events/ws-rate-limit.spec.ts+++ b/src/modules/events/ws-rate-limit.spec.ts@@ -136,3 +136,34 @@ describe('SlidingWindowLimiter (pre-auth per-IP handshake budget)', () => {expect((limiter as unknown as { hits: Map<string, unknown> }).hits.size).toBeLessThanOrEqual(100);});});++describe('SlidingWindowLimiter.refund', () => {+ it('returns a consumed slot so an authenticated handshake does not spend the pre-auth budget', () => {+ const now = 0;+ const limiter = new SlidingWindowLimiter(2, 1000, () => now);+ expect(limiter.allow('ip')).toBe(true);+ limiter.refund('ip'); // handshake turned out to be authentic+ expect(limiter.allow('ip')).toBe(true);+ expect(limiter.allow('ip')).toBe(true);+ // Only the two un-refunded attempts count, so the third is shed.+ expect(limiter.allow('ip')).toBe(false);+ });++ it('still sheds a flood of FAILED handshakes (nothing is refunded for those)', () => {+ const now = 0;+ const limiter = new SlidingWindowLimiter(3, 1000, () => now);+ expect(limiter.allow('ip')).toBe(true);+ expect(limiter.allow('ip')).toBe(true);+ expect(limiter.allow('ip')).toBe(true);+ expect(limiter.allow('ip')).toBe(false);+ });++ it('is a no-op for an unknown or already-empty subject', () => {+ const limiter = new SlidingWindowLimiter(1, 1000, () => 0);+ expect(() => limiter.refund('never-seen')).not.toThrow();+ expect(limiter.allow('never-seen')).toBe(true);+ limiter.refund('never-seen');+ limiter.refund('never-seen');+ expect(limiter.allow('never-seen')).toBe(true);+ });+});diff --git a/src/modules/events/ws-rate-limit.ts b/src/modules/events/ws-rate-limit.tsindex 1c3f5890f..8258a7fd5 100644--- a/src/modules/events/ws-rate-limit.ts+++ b/src/modules/events/ws-rate-limit.ts@@ -143,4 +143,20 @@ export class SlidingWindowLimiter {evictOverflow(this.hits, this.maxKeys);return allowed;}++ /**+ * Give back the most recent attempt recorded for `subject`.+ *+ * The handshake window is consumed BEFORE authentication (that is the point — an unauthenticated+ * flood must not reach the DB key validation on every attempt), which also charges every+ * legitimate connect. Behind a NAT or a reverse proxy without TRUSTED_PROXIES every client shares+ * one subject, so a handful of dashboards re-mounting could exhaust the window between them.+ * Refunding a handshake that turned out to be authentic keeps the budget aimed at failures;+ * authenticated abuse is bounded separately by the per-key socket cap.+ */+ refund(subject: string): void {+ const recent = this.hits.get(subject);+ if (!recent?.length) return;+ recent.pop();+ }}diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.tsindex 8eb1c3ac3..3c7f3dd38 100644--- a/src/modules/infra/infra.controller.spec.ts+++ b/src/modules/infra/infra.controller.spec.ts@@ -49,6 +49,7 @@ import { WebhookDeliveryFailure } from '../webhook/entities/webhook-delivery-faiimport { IntegrationDeliveryFailure } from '../integration/entities/integration-delivery-failure.entity';import { StatusUpdate } from '../status-store/entities/status-update.entity';import { AuditAction } from '../audit/entities/audit-log.entity';+import { recordOsEnvKeys } from '../../config/env-precedence';describe('InfraController access control (Vuln 2)', () => {const reflector = new Reflector();@@ -1046,6 +1047,158 @@ describe('InfraController.saveConfig built-in/external mode flips and the save-texpect(env).toContain('S3_ACCESS_KEY_ID=minioadmin');expect(env).toContain('MINIO_BUILTIN=true');});++ it('an absent builtIn field inherits built-in mode without clobbering a stored custom password', () => {+ // Secrets are never echoed back to the form, so an absent password field means "unchanged".+ // Merely inheriting the built-in mode must not re-stamp the bundled 'openwa' over a custom+ // password (e.g. an operator who re-keyed the bundled container via POSTGRES_PASSWORD).+ const env = written(+ { database: { type: 'postgres', poolSize: 25 } },+ 'DATABASE_TYPE=postgres\nPOSTGRES_BUILTIN=true\nDATABASE_HOST=postgres\nDATABASE_PORT=5432\nDATABASE_USERNAME=openwa\nDATABASE_PASSWORD=CustomPw123!\nDATABASE_NAME=openwa\nPOSTGRES_SCHEMA=public\n',+ );+ expect(env).toContain('POSTGRES_BUILTIN=true');+ expect(env).toContain('DATABASE_PASSWORD=CustomPw123!');+ expect(env).toContain('DATABASE_POOL_SIZE=25');+ });++ it('an explicit password wins while the built-in mode is only inherited', () => {+ const env = written(+ { database: { type: 'postgres', password: 'NewPw456!' } },+ 'DATABASE_TYPE=postgres\nPOSTGRES_BUILTIN=true\nDATABASE_HOST=postgres\nDATABASE_PASSWORD=openwa\nDATABASE_NAME=openwa\n',+ );+ expect(env).toContain('DATABASE_PASSWORD=NewPw456!');+ expect(env).not.toContain('DATABASE_PASSWORD=openwa');+ });++ it('an explicit builtIn:true keeps a re-keyed bundled password (the dashboard always sends builtIn)', () => {+ // Infrastructure.tsx sends `database.builtIn` on every save and never echoes the password back,+ // so treating "explicit builtIn:true + no password" as a reset re-wrote a re-keyed container's+ // credential on each save, breaking the next boot's DB auth.+ const env = written(+ { database: { type: 'postgres', builtIn: true } },+ 'DATABASE_TYPE=postgres\nPOSTGRES_BUILTIN=true\nDATABASE_HOST=postgres\nDATABASE_PASSWORD=CustomPw123!\nDATABASE_NAME=openwa\n',+ );+ expect(env).toContain('DATABASE_PASSWORD=CustomPw123!');+ });++ it('does not carry an EXTERNAL password into the bundled container when switching to built-in', () => {+ // The stored secret belongs to the external DB; the bundled container is seeded with 'openwa'+ // unless the operator re-keys it, so switching modes must reset rather than inherit.+ const env = written(+ { database: { type: 'postgres', builtIn: true } },+ 'DATABASE_TYPE=postgres\nPOSTGRES_BUILTIN=false\nDATABASE_HOST=db.example.com\nDATABASE_PASSWORD=ExternalPw!\nDATABASE_NAME=appdb\n',+ );+ expect(env).toContain('DATABASE_PASSWORD=openwa');+ expect(env).not.toContain('ExternalPw!');+ });++ // The guard must evaluate what the next boot would SEE: load-env.ts loads with dotenv+ // override:false, so a value in the container environment (compose `environment:`) wins over the+ // saved file. Snapshot + clear every guard-relevant key so these tests are hermetic.+ describe('process-environment precedence', () => {+ const GUARD_ENV_KEYS = [+ 'DATABASE_TYPE',+ 'DATABASE_PASSWORD',+ 'POSTGRES_BUILTIN',+ 'DATABASE_HOST',+ 'STORAGE_TYPE',+ 'S3_ACCESS_KEY_ID',+ 'S3_SECRET_ACCESS_KEY',+ 'S3_ENDPOINT',+ 'MINIO_BUILTIN',+ 'REDIS_PASSWORD',+ ];+ let savedEnv: Array<[string, string | undefined]>;+ beforeEach(() => {+ savedEnv = GUARD_ENV_KEYS.map(k => [k, process.env[k]]);+ for (const k of GUARD_ENV_KEYS) delete process.env[k];+ });+ afterEach(() => {+ for (const [k, v] of savedEnv) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+ });++ it('accepts an external Postgres whose strong password comes from the process environment', () => {+ // The compose deployment the guard used to refuse on EVERY save: the file still holds the+ // bundled built-in credentials, but boot would see the env password, not the file's.+ process.env.DATABASE_PASSWORD = 'Sup3rSecret!';+ const env = written(+ {+ database: { type: 'postgres', builtIn: false, host: 'db.example.com', username: 'app', database: 'appdb' },+ },+ BUILTIN_POSTGRES_ENV,+ );+ expect(env).toContain('POSTGRES_BUILTIN=false');+ expect(env).toContain('DATABASE_HOST=db.example.com');+ // The stale bundled password is still dropped from the file — the environment supplies it.+ expect(env).not.toContain('DATABASE_PASSWORD');+ });++ it('a blank process-env forward counts as unset, so a weak merged config is still rejected', () => {+ // Compose renders `- DATABASE_PASSWORD=${DATABASE_PASSWORD:-}` as an empty value when the+ // operator sets nothing; boot clears that blank (clearBlankEnv) and falls to the file. The+ // guard does the same — a blank forward can neither mask a weak file value nor supply one.+ process.env.DATABASE_PASSWORD = '';+ expectRejected(+ {+ database: { type: 'postgres', builtIn: false, host: 'db.example.com', username: 'app', database: 'appdb' },+ },+ BUILTIN_POSTGRES_ENV,+ /DATABASE_PASSWORD/,+ );+ });++ it('a weak process-env value wins over a strong saved one and is still rejected', () => {+ // Precedence cuts both ways: boot would see the env value, so a weak env password must not be+ // rescued by a strong one sitting in the file.+ process.env.DATABASE_PASSWORD = 'password';+ expectRejected(+ { queue: { enabled: true } },+ 'DATABASE_TYPE=postgres\nPOSTGRES_BUILTIN=false\nDATABASE_HOST=db.example.com\nDATABASE_PASSWORD=Str0ngSaved!\n',+ /DATABASE_PASSWORD/,+ );+ });++ // The cases above delete every guard key from process.env, which cannot happen in production:+ // load-env merges data/.env.generated INTO process.env at boot, so the file's own values are+ // sitting there while this save runs. Reading them back as if they were an orchestrator+ // override makes the guard validate the config being REPLACED.+ describe('saved-file values echoed in process.env are not mistaken for host overrides', () => {+ afterEach(() => {+ // Restore the permissive snapshot the rest of the file assumes.+ recordOsEnvKeys(process.env);+ });++ it('refuses a built-in -> external flip that keeps the bundled password (boot would crash-loop)', () => {+ recordOsEnvKeys({}); // the host supplied nothing; everything below came from the file+ process.env.DATABASE_TYPE = 'postgres';+ process.env.POSTGRES_BUILTIN = 'true';+ process.env.DATABASE_HOST = 'postgres';+ process.env.DATABASE_PASSWORD = 'openwa';+ expectRejected(+ {+ database: { type: 'postgres', builtIn: false, host: 'db.example.com', username: 'app', database: 'appdb' },+ },+ BUILTIN_POSTGRES_ENV,+ /DATABASE_PASSWORD/,+ );+ });++ it('still honors a genuine host override of the same key', () => {+ recordOsEnvKeys({ DATABASE_PASSWORD: 'Sup3rSecret!' });+ process.env.DATABASE_PASSWORD = 'Sup3rSecret!';+ const env = written(+ {+ database: { type: 'postgres', builtIn: false, host: 'db.example.com', username: 'app', database: 'appdb' },+ },+ BUILTIN_POSTGRES_ENV,+ );+ expect(env).toContain('DATABASE_HOST=db.example.com');+ });+ });+ });});describe('InfraController.saveConfig persists strictly-coerced form booleans', () => {@@ -1262,6 +1415,99 @@ describe('InfraController.importData round-trips export-data (no silent message/expect(dlf.payload).toEqual({ foo: 'bar' });});+ it('round-trips the ingress dispatch-lifecycle columns so a restored pending event still replays', async () => {+ await seedSession('s1');+ const ingressRepo = ds.getRepository(IngressEvent);+ // A pending event (still carrying its payload, awaiting reconciler replay) and a retired one+ // (dispatch outcome recorded, payload slimmed to NULL).+ await ingressRepo.save(+ ingressRepo.create({+ id: 'ie-pending',+ instanceId: 'acct1',+ pluginId: 'chatwoot',+ providerDeliveryId: 'dlv-1',+ route: 'chatwoot/acct1',+ payload: { headers: {}, query: {}, body: '{}', rawBody: '{}' },+ payloadHash: 'abc123',+ sessionId: 's1',+ dispatchState: 'pending',+ dispatchAttempts: 2,+ lastDispatchAt: new Date('2026-01-02T03:04:05.000Z'),+ }),+ );+ await ingressRepo.save(+ ingressRepo.create({+ id: 'ie-retired',+ instanceId: 'acct1',+ pluginId: 'chatwoot',+ providerDeliveryId: 'dlv-2',+ route: 'chatwoot/acct1',+ payload: null,+ payloadHash: 'def456',+ sessionId: 's1',+ dispatchState: 'dispatched',+ dispatchAttempts: 1,+ lastDispatchAt: new Date('2026-01-02T03:04:05.000Z'),+ }),+ );++ const dump = await controller.exportData();+ expect(dump.counts.ingressEvents).toBe(2);++ await ingressRepo.clear();+ const res = await controller.importData({ tables: dump.tables });++ expect(res.warnings).toEqual([]);+ expect(res.imported).toBe(true);+ expect(res.counts.ingressEvents).toBe(2);++ // A restored 'pending' row that lost its dispatchState would read as NULL ("not watched"): the+ // reconciler would never replay it while the dedup key still blocked the provider's retry.+ const pending = await ingressRepo.findOneByOrFail({ id: 'ie-pending' });+ expect(pending.dispatchState).toBe('pending');+ expect(pending.dispatchAttempts).toBe(2);+ expect(pending.lastDispatchAt).toEqual(new Date('2026-01-02T03:04:05.000Z'));+ expect(pending.payloadHash).toBe('abc123');+ expect(pending.payload).toEqual({ headers: {}, query: {}, body: '{}', rawBody: '{}' });++ const retired = await ingressRepo.findOneByOrFail({ id: 'ie-retired' });+ expect(retired.dispatchState).toBe('dispatched');+ expect(retired.payloadHash).toBe('def456');+ // A retired payload must stay NULL — re-materializing it as '{}' would make the slimmed dedup+ // row read as a pending event with an empty body.+ expect(retired.payload).toBeNull();+ });++ it('imports a pre-lifecycle backup (no dispatch columns) as not-watched legacy rows', async () => {+ await seedSession('s1');+ const res = await controller.importData({+ tables: {+ ingressEvents: [+ {+ id: 'ie-legacy',+ instanceId: 'acct1',+ pluginId: 'chatwoot',+ providerDeliveryId: 'dlv-9',+ route: 'chatwoot/acct1',+ payload: { headers: {}, query: {}, body: '{}', rawBody: '{}' },+ sessionId: 's1',+ createdAt: '2026-01-01T00:00:00.000Z',+ },+ ] as never,+ },+ });++ expect(res.warnings).toEqual([]);+ expect(res.imported).toBe(true);+ // Columns absent from an older backup import as NULL/0 — the same "not watched" reading legacy+ // rows have by design (the reconciler never sweeps them, so an upgrade can't mass-replay history).+ const legacy = await ds.getRepository(IngressEvent).findOneByOrFail({ id: 'ie-legacy' });+ expect(legacy.dispatchState).toBeNull();+ expect(legacy.dispatchAttempts).toBe(0);+ expect(legacy.lastDispatchAt).toBeNull();+ expect(legacy.payloadHash).toBeNull();+ });+it('rolls back and reports imported:false when a row fails — existing data is preserved', async () => {// Pre-existing data that must survive a failed import.await seedSession('s1');diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.tsindex d4e1bf689..61da4ffeb 100644--- a/src/modules/infra/infra.controller.ts+++ b/src/modules/infra/infra.controller.ts@@ -39,6 +39,7 @@ import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.import { ImportStorageDto } from './dto/import-storage.dto';import { SaveConfigDto } from './dto/save-config.dto';import { assertNoDefaultSecretsInProduction } from '../../config/bootstrap-security';+import { BLANK_SHADOWED_ENV_KEYS, isOsProvidedEnv } from '../../config/env-precedence';import * as fs from 'fs';import * as path from 'path';import { randomUUID } from 'crypto';@@ -228,6 +229,12 @@ interface IngressEventRow {// Retired to NULL once the dispatch outcome is recorded; only 'pending' rows still carry one.payload: string | Record<string, unknown> | null;payloadHash?: string | null;+ // Dispatch lifecycle (the AddIngressEventDispatchState migration). A restored 'pending' row must+ // keep these or the reconciler never replays it while the dedup row still blocks the provider's+ // retry. Optional because backups exported before the columns existed don't carry them.+ dispatchState?: 'pending' | 'dispatched' | 'failed' | null;+ dispatchAttempts?: number;+ lastDispatchAt?: string | null;sessionId: string | null;createdAt: string;}@@ -693,7 +700,15 @@ export class InfraController implements OnApplicationBootstrap {updates.DATABASE_HOST = 'postgres';updates.DATABASE_PORT = '5432';updates.DATABASE_USERNAME = 'openwa';- updates.DATABASE_PASSWORD = 'openwa';+ // The bundled credential is only the DEFAULT. Secrets are never echoed back to the form,+ // so an absent password field means "unchanged", not "reset to 'openwa'" — and the+ // dashboard ALWAYS sends builtIn, so keying the reset on "explicit builtIn:true" reset a+ // re-keyed container on every save from the Infrastructure page.+ // What decides it is whether the stored password belongs to this same bundled container:+ // it does when the previous mode was already built-in. Coming from external, the stored+ // value is the external DB's credential and must not be carried into the container.+ const storedPassword = existing.POSTGRES_BUILTIN === 'true' ? existing.DATABASE_PASSWORD : undefined;+ updates.DATABASE_PASSWORD = config.database.password || storedPassword || 'openwa';updates.DATABASE_NAME = 'openwa';// Built-in Postgres is initialized with the default 'public' schema (see// scripts/postgres-init-schema.sh). Pin it so a later switch from a custom-schema@@ -886,19 +901,39 @@ export class InfraController implements OnApplicationBootstrap {// result with the very same boot guard (as production) and refuse the save when that boot// would refuse to start. This is what stops a built-in->external flip with no fresh// credentials from persisting a config that crash-loops the next production boot.+ // Evaluate what that boot would actually SEE, not just what the file holds: load-env.ts+ // loads with dotenv override:false, so a value supplied via the container environment+ // (compose `environment:`) wins over this file — the precedence the file header documents.+ // Without that, a deployment providing DATABASE_PASSWORD & co. through the environment is+ // refused on EVERY save even though its boot passes the guard. A blank compose-forwarded+ // value counts as unset exactly like clearBlankEnv treats it at boot.+ //+ // Only a HOST-supplied key may win. load-env also merges .env and data/.env.generated into+ // process.env, so reading process.env alone would hand back the very file this save is+ // replacing — the guard would then bless a flip by validating the OLD config (a built-in ->+ // external switch keeping the bundled 'openwa' password would save cleanly and crash-loop the+ // next production boot, the exact case this guard exists for). isOsProvidedEnv separates the+ // two using the snapshot load-env takes before either file is loaded.+ const bootValue = (key: string): string | undefined => {+ const envValue = isOsProvidedEnv(key) ? process.env[key] : undefined;+ if (envValue !== undefined && (envValue.trim() !== '' || !BLANK_SHADOWED_ENV_KEYS.includes(key))) {+ return envValue;+ }+ return merged[key];+ };try {assertNoDefaultSecretsInProduction({nodeEnv: 'production',- databaseType: merged.DATABASE_TYPE,- databasePassword: merged.DATABASE_PASSWORD,- postgresBuiltIn: merged.POSTGRES_BUILTIN,- databaseHost: merged.DATABASE_HOST,- storageType: merged.STORAGE_TYPE,- s3AccessKey: merged.S3_ACCESS_KEY_ID,- s3SecretKey: merged.S3_SECRET_ACCESS_KEY,- s3Endpoint: merged.S3_ENDPOINT,- minioBuiltIn: merged.MINIO_BUILTIN,- redisPassword: merged.REDIS_PASSWORD,+ databaseType: bootValue('DATABASE_TYPE'),+ databasePassword: bootValue('DATABASE_PASSWORD'),+ postgresBuiltIn: bootValue('POSTGRES_BUILTIN'),+ databaseHost: bootValue('DATABASE_HOST'),+ storageType: bootValue('STORAGE_TYPE'),+ s3AccessKey: bootValue('S3_ACCESS_KEY_ID'),+ s3SecretKey: bootValue('S3_SECRET_ACCESS_KEY'),+ s3Endpoint: bootValue('S3_ENDPOINT'),+ minioBuiltIn: bootValue('MINIO_BUILTIN'),+ redisPassword: bootValue('REDIS_PASSWORD'),});} catch (error) {const detail = error instanceof Error ? error.message : String(error);@@ -1674,22 +1709,32 @@ export class InfraController implements OnApplicationBootstrap {}}- // Import ingress events (durable inbound dedup oracle; payload is JSON)+ // Import ingress events (durable inbound dedup oracle; payload is JSON). The dispatch-lifecycle+ // columns ride along: dropping them would strand a restored 'pending' row (NULL dispatchState is+ // never swept by the reconciler) while its dedup key still blocks the provider's retry. Columns+ // absent from a pre-lifecycle backup import as NULL/0 — the same "not watched" reading legacy+ // rows have by design. dispatchAttempts is NOT NULL, so it coalesces to 0 rather than NULL.let ingressEventsCount = 0;if (data.tables.ingressEvents?.length) {for (const ie of data.tables.ingressEvents) {try {await insert(- `INSERT INTO ingress_events (id, "instanceId", "pluginId", "providerDeliveryId", route, payload, "sessionId", "createdAt")- VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,+ `INSERT INTO ingress_events (id, "instanceId", "pluginId", "providerDeliveryId", route, payload, "payloadHash", "sessionId", "dispatchState", "dispatchAttempts", "lastDispatchAt", "createdAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,[ie.id,ie.instanceId,ie.pluginId,ie.providerDeliveryId,ie.route,- typeof ie.payload === 'string' ? ie.payload : JSON.stringify(ie.payload ?? {}),+ // A retired (NULL) payload must stay NULL — re-materializing it as '{}' would make a+ // slimmed dedup row read as a pending event with an empty body.+ ie.payload == null ? null : typeof ie.payload === 'string' ? ie.payload : JSON.stringify(ie.payload),+ ie.payloadHash ?? null,ie.sessionId,+ ie.dispatchState ?? null,+ ie.dispatchAttempts ?? 0,+ ie.lastDispatchAt ?? null,ie.createdAt,],);diff --git a/src/modules/integration/conversation-mapping.service.spec.ts b/src/modules/integration/conversation-mapping.service.spec.tsindex 869527c8d..83164a608 100644--- a/src/modules/integration/conversation-mapping.service.spec.ts+++ b/src/modules/integration/conversation-mapping.service.spec.ts@@ -86,4 +86,51 @@ describe('ConversationMappingService', () => {});expect(await service.findHandoverForChat('sess-1', 'other-chat')).toBeNull();});++ it('delete removes the row so a later reverse-key insert no longer conflicts', async () => {+ await service.upsert(key, 'conv-1');+ const row = await service.get(key);+ if (!row) throw new Error('expected a mapping row');++ await service.delete(row.id);++ expect(await service.get(key)).toBeNull();+ // The reverse key is free again: binding conv-1 to a different chat now succeeds.+ await expect(+ service.upsert({ sessionId: 'sess-2', chatId: 'chat-2', pluginId: 'chatwoot', instanceId: 'acct1' }, 'conv-1'),+ ).resolves.toBeUndefined();+ });++ it('rebindSession moves a stale row onto the current session (forward key moves with it)', async () => {+ await service.upsert(key, 'conv-1');+ const row = await service.get(key);+ if (!row) throw new Error('expected a mapping row');++ await service.rebindSession(row.id, 'sess-2');++ expect(await service.get(key)).toBeNull();+ const rebound = await service.getByProvider(key.pluginId, key.instanceId, 'conv-1');+ expect(rebound?.sessionId).toBe('sess-2');+ expect(+ await service.get({ sessionId: 'sess-2', chatId: 'chat-1', pluginId: 'chatwoot', instanceId: 'acct1' }),+ ).not.toBeNull();+ });++ it('rebindSession supersedes (deletes) the stale row when the current session already owns the chat', async () => {+ // sess-1's row and sess-2's row bind the SAME chat for the same plugin+instance under different+ // provider conversations (e.g. the provider opened a fresh conversation after the re-pair).+ await service.upsert(key, 'conv-1');+ await service.upsert(+ { sessionId: 'sess-2', chatId: 'chat-1', pluginId: 'chatwoot', instanceId: 'acct1' },+ 'conv-2',+ );+ const stale = await service.get(key);+ if (!stale) throw new Error('expected a stale mapping row');++ await service.rebindSession(stale.id, 'sess-2');++ // The forward-key collision is resolved in favor of sess-2's own (fresher) row; the stale one is gone.+ expect(await service.getByProvider('chatwoot', 'acct1', 'conv-1')).toBeNull();+ expect((await service.getByProvider('chatwoot', 'acct1', 'conv-2'))?.sessionId).toBe('sess-2');+ });});diff --git a/src/modules/integration/conversation-mapping.service.ts b/src/modules/integration/conversation-mapping.service.tsindex 1d4442940..1c375d531 100644--- a/src/modules/integration/conversation-mapping.service.ts+++ b/src/modules/integration/conversation-mapping.service.ts@@ -106,4 +106,26 @@ export class ConversationMappingService {async setHandover(id: string, state: HandoverState): Promise<void> {await this.repo.update({ id }, { handoverState: state });}++ /**+ * Rebind a mapping whose session was deleted (and re-paired under a new id) onto the caller's+ * current session, so the stale row stops failing every reverse-key resolution. If the current+ * session ALREADY holds a forward-key row for the same chat+plugin+instance, the update hits+ * UQ_conversation_mappings_forward — the only index a sessionId-only update can collide with (the+ * row already owns its reverse key). That existing row is the fresher binding for the same chat,+ * so the stale row is superseded by deleting it instead.+ */+ /** Remove a mapping row by id — the supersede half of the stale-session repair path. */+ async delete(id: string): Promise<void> {+ await this.repo.delete({ id });+ }++ async rebindSession(id: string, sessionId: string): Promise<void> {+ try {+ await this.repo.update({ id }, { sessionId });+ } catch (err) {+ if (!isUniqueViolation(err)) throw err;+ await this.repo.delete({ id });+ }+ }}diff --git a/src/modules/integration/ingress-enqueue.service.spec.ts b/src/modules/integration/ingress-enqueue.service.spec.tsindex 36cf1a50c..1d1146d91 100644--- a/src/modules/integration/ingress-enqueue.service.spec.ts+++ b/src/modules/integration/ingress-enqueue.service.spec.ts@@ -134,6 +134,17 @@ describe('IngressEnqueueService', () => {else process.env.INGRESS_RETRY_DELAY_MS = prevD;}});++ it('treats a blank INGRESS_RETRY_DELAY_MS as unset, not as 0', () => {+ const prevD = process.env.INGRESS_RETRY_DELAY_MS;+ try {+ process.env.INGRESS_RETRY_DELAY_MS = '';+ expect(resolveIngressJobOptions()).toEqual({ attempts: 3, backoff: { type: 'exponential', delay: 5000 } });+ } finally {+ if (prevD === undefined) delete process.env.INGRESS_RETRY_DELAY_MS;+ else process.env.INGRESS_RETRY_DELAY_MS = prevD;+ }+ });});describe('buildIngressDeadLetterRow', () => {diff --git a/src/modules/integration/ingress-enqueue.service.ts b/src/modules/integration/ingress-enqueue.service.tsindex a275c1954..387fee479 100644--- a/src/modules/integration/ingress-enqueue.service.ts+++ b/src/modules/integration/ingress-enqueue.service.ts@@ -7,6 +7,7 @@ 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';+import { resolveNonNegativeIntEnv } from '../../config/configuration';/*** Outcome of an enqueue attempt. 'queued' = handed to BullMQ; 'dispatched' = delivered inline; 'failed'@@ -28,10 +29,9 @@ export type EnqueueOutcome = { outcome: 'queued' | 'dispatched' | 'failed'; erro*/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 },+ backoff: { type: 'exponential', delay: resolveNonNegativeIntEnv(process.env.INGRESS_RETRY_DELAY_MS, 5000) },};}diff --git a/src/modules/integration/ingress-reconciler.service.spec.ts b/src/modules/integration/ingress-reconciler.service.spec.tsindex eabe2ee94..da03903a3 100644--- a/src/modules/integration/ingress-reconciler.service.spec.ts+++ b/src/modules/integration/ingress-reconciler.service.spec.ts@@ -3,7 +3,9 @@ import { IngressEvent } from './entities/ingress-event.entity';import { IntegrationDeliveryFailure } from './entities/integration-delivery-failure.entity';import { IngressReconcilerService, IngressReconcilerOptions } from './ingress-reconciler.service';import { IngressEnqueueService } from './ingress-enqueue.service';+import { PluginInstanceService } from './plugin-instance.service';import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';+import { RedriveService } from './redrive.service';import { IngressJobData } from '../queue/processors/ingress.processor';const OPTS: IngressReconcilerOptions = { intervalMs: 60_000, graceMs: 60_000, batchSize: 50, maxAttempts: 5 };@@ -17,6 +19,7 @@ describe('IngressReconcilerService.sweep', () => {let failures: Repository<IntegrationDeliveryFailure>;let enqueue: jest.Mock;let getPlugin: jest.Mock;+ let resolveInstance: jest.Mock;let service: IngressReconcilerService;let seq: number;@@ -33,11 +36,13 @@ describe('IngressReconcilerService.sweep', () => {failures = ds.getRepository(IntegrationDeliveryFailure);enqueue = jest.fn().mockResolvedValue({ outcome: 'queued' });getPlugin = jest.fn().mockReturnValue(undefined);+ resolveInstance = jest.fn().mockResolvedValue({ enabled: true });service = new IngressReconcilerService(events,failures,{ enqueue } as unknown as IngressEnqueueService,{ getPlugin } as unknown as PluginLoaderService,+ { resolve: resolveInstance } as unknown as PluginInstanceService,);});@@ -270,6 +275,66 @@ describe('IngressReconcilerService.sweep', () => {expect((await failures.findOneByOrFail({ id: dlq.id })).redriven).toBe(true);});+ it('does not replay an event a manual redrive already delivered', async () => {+ // Live-path shape after a swallowed inline failure: the event row is still 'pending' and a DLQ+ // row carries the payload. A successful manual redrive must close the event row too, or this+ // sweep replays the same delivery a second time.+ const id = await insertEvent();+ await failures.save(+ failures.create({+ direction: 'inbound',+ pluginId: 'plug',+ instanceId: 'inst',+ sessionId: 'sess-1',+ deliveryId: 'd-1',+ attempts: 1,+ lastError: 'inline dispatch failed',+ payload: { route: 'chatwoot', ingress: { headers: {}, query: {}, body: '{}', rawBody: '{}' } },+ redriven: false,+ }),+ );+ const redrive = new RedriveService(failures, events, { enqueue } as unknown as IngressEnqueueService);++ const res = await redrive.redriveInstance('plug', 'inst');++ expect(res.redriven).toBe(1);+ expect((await stored(id)).dispatchState).toBe('dispatched');+ enqueue.mockClear();+ const stats = await service.sweep(OPTS);+ expect(stats.scanned).toBe(0);+ expect(enqueue).not.toHaveBeenCalled();+ });++ it('skips a row whose instance was disabled after persist, and replays it once re-enabled', async () => {+ const id = await insertEvent();+ resolveInstance.mockResolvedValue({ enabled: false });++ const stats = await service.sweep(OPTS);++ expect(stats).toMatchObject({ scanned: 0, skipped: 1 });+ expect(enqueue).not.toHaveBeenCalled();+ const event = await stored(id);+ expect(event.dispatchState).toBe('pending');+ expect(event.dispatchAttempts).toBe(0); // an ineligible row does not burn its replay budget++ // The row is not terminal: a re-enabled instance receives the event on a later sweep.+ resolveInstance.mockResolvedValue({ enabled: true });+ const stats2 = await service.sweep(OPTS);+ expect(stats2.replayed).toBe(1);+ expect((await stored(id)).dispatchState).toBe('dispatched');+ });++ it('skips a row whose instance was deleted after persist', async () => {+ await insertEvent();+ resolveInstance.mockResolvedValue(null);++ const stats = await service.sweep(OPTS);++ expect(stats).toMatchObject({ scanned: 0, skipped: 1 });+ expect(enqueue).not.toHaveBeenCalled();+ expect(await failures.count()).toBe(0);+ });+it('keeps the batch alive when one row throws during bookkeeping', async () => {await insertEvent();await insertEvent();@@ -303,7 +368,13 @@ describe('IngressReconcilerService.onModuleInit (scheduling)', () => {it('does not schedule a timer when INGRESS_RECONCILE_INTERVAL_MS <= 0', () => {process.env.INGRESS_RECONCILE_INTERVAL_MS = '0';const [events, failures] = repos();- const svc = new IngressReconcilerService(events, failures, {} as IngressEnqueueService, {} as PluginLoaderService);+ const svc = new IngressReconcilerService(+ events,+ failures,+ {} as IngressEnqueueService,+ {} as PluginLoaderService,+ {} as PluginInstanceService,+ );jest.useFakeTimers();try {@@ -317,10 +388,39 @@ describe('IngressReconcilerService.onModuleInit (scheduling)', () => {}});+ it('treats a blank INGRESS_RECONCILE_INTERVAL_MS as unset and sweeps on the default interval', () => {+ process.env.INGRESS_RECONCILE_INTERVAL_MS = '';+ const [events, failures] = repos();+ const svc = new IngressReconcilerService(+ events,+ failures,+ {} as IngressEnqueueService,+ {} as PluginLoaderService,+ {} as PluginInstanceService,+ );++ jest.useFakeTimers();+ try {+ const sweepSpy = jest.spyOn(svc, 'sweep').mockResolvedValue({ scanned: 0, replayed: 0, failed: 0, skipped: 0 });+ svc.onModuleInit();+ jest.advanceTimersByTime(60_000);+ expect(sweepSpy).toHaveBeenCalledTimes(1);+ svc.onModuleDestroy();+ } finally {+ jest.useRealTimers();+ }+ });+it('sweeps on the configured interval and stops after onModuleDestroy', () => {delete process.env.INGRESS_RECONCILE_INTERVAL_MS;const [events, failures] = repos();- const svc = new IngressReconcilerService(events, failures, {} as IngressEnqueueService, {} as PluginLoaderService);+ const svc = new IngressReconcilerService(+ events,+ failures,+ {} as IngressEnqueueService,+ {} as PluginLoaderService,+ {} as PluginInstanceService,+ );jest.useFakeTimers();try {diff --git a/src/modules/integration/ingress-reconciler.service.ts b/src/modules/integration/ingress-reconciler.service.tsindex ffe3e7746..baac1b986 100644--- a/src/modules/integration/ingress-reconciler.service.ts+++ b/src/modules/integration/ingress-reconciler.service.ts@@ -5,12 +5,15 @@ import { IngressEvent } from './entities/ingress-event.entity';import { IntegrationDeliveryFailure } from './entities/integration-delivery-failure.entity';import { IngressEnqueueService, buildIngressDeadLetterRow } from './ingress-enqueue.service';import { extractConversationId } from './ingress.service';+import { PluginInstanceService } from './plugin-instance.service';import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';import { IngressJobData } from '../queue/processors/ingress.processor';import { createLogger } from '../../common/services/logger.service';+import { resolveNonNegativeIntEnv } from '../../config/configuration';export interface IngressReconcilerOptions {- // Sweep cadence. <= 0 disables the reconciler (mirrors INGRESS_RETENTION_DAYS <= 0).+ // Sweep cadence. 0 disables the reconciler. A blank or otherwise unparseable value falls back to+ // the default rather than disabling the sweep, so a mis-set variable can never silently turn it off.intervalMs: number;// A 'pending' row only becomes sweep-eligible once its last activity (creation or latest attempt)// is older than this — the live path gets the whole window to record its own outcome first.@@ -22,13 +25,11 @@ export interface IngressReconcilerOptions {}export function resolveIngressReconcilerOptions(env: NodeJS.ProcessEnv = process.env): IngressReconcilerOptions {- const interval = Number(env.INGRESS_RECONCILE_INTERVAL_MS);- const grace = Number(env.INGRESS_RECONCILE_GRACE_MS);const batch = Number(env.INGRESS_RECONCILE_BATCH_SIZE);const maxAttempts = Number(env.INGRESS_RECONCILE_MAX_ATTEMPTS);return {- intervalMs: Number.isInteger(interval) ? interval : 60_000,- graceMs: Number.isInteger(grace) && grace >= 0 ? grace : 60_000,+ intervalMs: resolveNonNegativeIntEnv(env.INGRESS_RECONCILE_INTERVAL_MS, 60_000),+ graceMs: resolveNonNegativeIntEnv(env.INGRESS_RECONCILE_GRACE_MS, 60_000),batchSize: Number.isInteger(batch) && batch >= 1 ? batch : 50,maxAttempts: Number.isInteger(maxAttempts) && maxAttempts >= 1 ? maxAttempts : 5,};@@ -72,6 +73,7 @@ export class IngressReconcilerService implements OnModuleInit, OnModuleDestroy {private readonly failures: Repository<IntegrationDeliveryFailure>,private readonly ingressEnqueue: IngressEnqueueService,private readonly loader: PluginLoaderService,+ private readonly instances: PluginInstanceService,) {}onModuleInit(): void {@@ -127,8 +129,23 @@ export class IngressReconcilerService implements OnModuleInit, OnModuleDestroy {stats.skipped++;continue;}- stats.scanned++;try {+ // Re-apply the eligibility oracle the live path checks at the door (IngressService.handle+ // 404s an unknown/disabled instance): an instance disabled or deleted AFTER persist must+ // not receive the replay. The row stays 'pending' — a re-enabled instance is replayed by a+ // later sweep; a deleted one ages out via INGRESS_DEDUP_RETENTION_DAYS pruning.+ const instance = await this.instances.resolve(row.pluginId, row.instanceId);+ if (!instance || !instance.enabled) {+ this.logger.log('Skipping ingress event for a disabled or deleted instance', {+ pluginId: row.pluginId,+ instanceId: row.instanceId,+ deliveryId: row.providerDeliveryId,+ action: 'ingress_reconcile_instance_ineligible',+ });+ stats.skipped++;+ continue;+ }+ stats.scanned++;const outcome = await this.reconcileRow(row, opts.maxAttempts, now);if (outcome === 'replayed') stats.replayed++;else stats.failed++;diff --git a/src/modules/integration/instance-throttler.guard.spec.ts b/src/modules/integration/instance-throttler.guard.spec.tsindex 5f29cc76f..b897233e5 100644--- a/src/modules/integration/instance-throttler.guard.spec.ts+++ b/src/modules/integration/instance-throttler.guard.spec.ts@@ -23,4 +23,44 @@ describe('InstanceThrottlerGuard', () => {const req = { params: { pluginId: 'chatwoot' }, ip: '203.0.113.9' };await expect(guard.getTracker(req)).resolves.toContain('203.0.113.9');});++ // A blank compose `${KEY:-}` forward must never become a limit of 0: the throttler would then+ // reject the first hit on every instance, silently 429ing all inbound webhooks.+ describe('tier resolution from the environment', () => {+ const KEYS = ['INGRESS_INSTANCE_LIMIT', 'INGRESS_INSTANCE_TTL'] as const;+ const saved: Array<[string, string | undefined]> = [];+ beforeEach(() => {+ saved.length = 0;+ for (const k of KEYS) saved.push([k, process.env[k]]);+ });+ afterEach(() => {+ for (const [k, v] of saved) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+ });++ const resolveTiers = async (): Promise<Array<{ limit: number; ttl: number }>> => {+ const guard = Object.create(InstanceThrottlerGuard.prototype) as InstanceThrottlerGuard & {+ throttlers: Array<{ limit: number; ttl: number }>;+ onModuleInit(): Promise<void>;+ };+ // Skip ThrottlerGuard's own onModuleInit (needs the injected storage/options).+ jest.spyOn(Object.getPrototypeOf(InstanceThrottlerGuard.prototype), 'onModuleInit').mockResolvedValue(undefined);+ await guard.onModuleInit();+ return guard.throttlers;+ };++ it.each(['', ' '])('treats a blank value (%p) as unset instead of a limit of 0', async blank => {+ process.env.INGRESS_INSTANCE_LIMIT = blank;+ process.env.INGRESS_INSTANCE_TTL = blank;+ expect(await resolveTiers()).toEqual([{ name: 'instance', limit: 120, ttl: 60000 }]);+ });++ it('honors real values', async () => {+ process.env.INGRESS_INSTANCE_LIMIT = '5';+ process.env.INGRESS_INSTANCE_TTL = '1000';+ expect(await resolveTiers()).toEqual([{ name: 'instance', limit: 5, ttl: 1000 }]);+ });+ });});diff --git a/src/modules/integration/instance-throttler.guard.ts b/src/modules/integration/instance-throttler.guard.tsindex bc273feb1..1d245ede2 100644--- a/src/modules/integration/instance-throttler.guard.ts+++ b/src/modules/integration/instance-throttler.guard.ts@@ -1,5 +1,6 @@import { Injectable } from '@nestjs/common';import { ProxyAwareThrottlerGuard } from '../../common/security/proxy-aware-throttler.guard';+import { resolveNonNegativeIntEnv } from '../../config/configuration';/*** Rate-limit bucket keyed on the ingress route's (pluginId, instanceId) instead of the client IP.@@ -24,11 +25,16 @@ import { ProxyAwareThrottlerGuard } from '../../common/security/proxy-aware-throexport class InstanceThrottlerGuard extends ProxyAwareThrottlerGuard {async onModuleInit(): Promise<void> {await super.onModuleInit();+ // `??` only defaults on undefined, so a blank compose `${KEY:-}` forward used to reach+ // `Number('')` === 0 — a limit of 0 rejects the very first hit, silently 429ing EVERY inbound+ // webhook. Boot validation cannot catch it either (env.validation treats a blank value as+ // unset). resolveNonNegativeIntEnv treats blank as unset and only accepts plain decimals; an+ // explicit 0 is still rejected at boot by the positive-int check on INGRESS_INSTANCE_LIMIT.this.throttlers = [{name: 'instance',- limit: Number(process.env.INGRESS_INSTANCE_LIMIT ?? 120),- ttl: Number(process.env.INGRESS_INSTANCE_TTL ?? 60000),+ limit: resolveNonNegativeIntEnv(process.env.INGRESS_INSTANCE_LIMIT, 120),+ ttl: resolveNonNegativeIntEnv(process.env.INGRESS_INSTANCE_TTL, 60000),},];}diff --git a/src/modules/integration/redrive.service.spec.ts b/src/modules/integration/redrive.service.spec.tsindex 64ffe7745..af6e23e8f 100644--- a/src/modules/integration/redrive.service.spec.ts+++ b/src/modules/integration/redrive.service.spec.ts@@ -1,19 +1,26 @@import { RedriveService } from './redrive.service';import { IngressEnqueueService } from './ingress-enqueue.service';import { IntegrationDeliveryFailure } from './entities/integration-delivery-failure.entity';+import { IngressEvent } from './entities/ingress-event.entity';import { Repository } from 'typeorm';describe('RedriveService', () => {let repo: jest.Mocked<Partial<Repository<IntegrationDeliveryFailure>>>;+ let events: jest.Mocked<Partial<Repository<IngressEvent>>>;let ingressEnqueue: jest.Mocked<Partial<IngressEnqueueService>>;beforeEach(() => {repo = { find: jest.fn(), update: jest.fn().mockResolvedValue(undefined), count: jest.fn().mockResolvedValue(0) };+ events = { update: jest.fn().mockResolvedValue(undefined) };ingressEnqueue = { enqueue: jest.fn().mockResolvedValue({ outcome: 'queued' }) };});function makeSvc(): RedriveService {- return new RedriveService(repo as Repository<IntegrationDeliveryFailure>, ingressEnqueue as IngressEnqueueService);+ return new RedriveService(+ repo as Repository<IntegrationDeliveryFailure>,+ events as Repository<IngressEvent>,+ ingressEnqueue as IngressEnqueueService,+ );}it('re-enqueues non-redriven inbound failures for an instance and marks them redriven', async () => {@@ -69,6 +76,37 @@ describe('RedriveService', () => {expect(repo.update).toHaveBeenCalledWith({ id: 'f2' }, { redriven: true });});+ it('retires the matching pending ingress_events row on a successful redrive (the reconciler must not replay it)', async () => {+ // A live-path inline failure leaves the event row 'pending' next to the DLQ row; marking only+ // the DLQ row redriven would let the reconciler sweep the event row and deliver it a second time.+ const rows = [+ {+ id: 'f1',+ direction: 'inbound',+ pluginId: 'p',+ instanceId: 'i',+ deliveryId: 'd1',+ payload: { route: 'chatwoot', ingress: { headers: {}, query: {}, body: '{}', rawBody: '{}' } },+ sessionId: 's',+ redriven: false,+ },+ ];+ (repo.find as jest.Mock).mockResolvedValue(rows);+ const svc = makeSvc();++ const res = await svc.redriveInstance('p', 'i');++ expect(res.redriven).toBe(1);+ expect(events.update).toHaveBeenCalledTimes(1);+ const [criteria, patch] = (events.update as jest.Mock).mock.calls[0] as [+ Record<string, unknown>,+ Record<string, unknown>,+ ];+ expect(criteria).toEqual({ pluginId: 'p', instanceId: 'i', providerDeliveryId: 'd1', dispatchState: 'pending' });+ expect(patch).toMatchObject({ dispatchState: 'dispatched', payload: null });+ expect(patch.lastDispatchAt).toBeInstanceOf(Date);+ });+it('leaves the row redrivable (does not mark redriven) when the inline re-dispatch is swallowed as failed', async () => {// A queue-disabled fallback that silently fails must NOT retire the DLQ row, or the event is lost// permanently with no way to redrive it again.@@ -93,6 +131,7 @@ describe('RedriveService', () => {expect(res.redriven).toBe(0);expect(ingressEnqueue.enqueue).toHaveBeenCalledTimes(1);expect(repo.update).toHaveBeenCalledWith({ id: 'f9' }, { attempts: 1, lastError: 'redrive dispatch failed' });+ expect(events.update).not.toHaveBeenCalled(); // nothing was delivered, so the event row stays as-is});it('queries only non-redriven inbound rows for the instance and returns 0 when none are found', async () => {@@ -133,5 +172,7 @@ describe('RedriveService', () => {expect.objectContaining({ deliveryId: 'f3', sessionId: undefined }),'redrive:f3',);+ // A legacy row without a deliveryId predates persist-before-ack — there is no event row to retire.+ expect(events.update).not.toHaveBeenCalled();});});diff --git a/src/modules/integration/redrive.service.ts b/src/modules/integration/redrive.service.tsindex ab0f0decd..743c32ea6 100644--- a/src/modules/integration/redrive.service.ts+++ b/src/modules/integration/redrive.service.ts@@ -2,6 +2,7 @@ import { Injectable } from '@nestjs/common';import { InjectRepository } from '@nestjs/typeorm';import { Repository } from 'typeorm';import { IntegrationDeliveryFailure } from './entities/integration-delivery-failure.entity';+import { IngressEvent } from './entities/ingress-event.entity';import { IngressEnqueueService } from './ingress-enqueue.service';import { IngressJobData } from '../queue/processors/ingress.processor';import { KeyedAsyncLock } from './ordering-lock';@@ -24,6 +25,7 @@ export class RedriveService {constructor(@InjectRepository(IntegrationDeliveryFailure, 'data') private readonly repo: Repository<IntegrationDeliveryFailure>,+ @InjectRepository(IngressEvent, 'data') private readonly events: Repository<IngressEvent>,private readonly ingressEnqueue: IngressEnqueueService,) {}@@ -69,6 +71,17 @@ export class RedriveService {// inline-dispatch failure ('failed') leaves the row redriven=false so it stays redrivable, instead// of silently marking it handled and permanently losing the event.if (outcome !== 'failed') {+ // Retire the matching ingress_events row FIRST (mirrors the reconciler's own ordering): a+ // live-path inline failure leaves that row 'pending' next to this DLQ row, so without the mark+ // the reconciler would sweep and replay the same delivery — a double delivery to the plugin.+ // Conditional on 'pending' so a row the reconciler already closed is left alone; a legacy DLQ+ // row (deliveryId null) predates persist-before-ack and has no event row to retire.+ if (row.deliveryId) {+ await this.events.update(+ { pluginId, instanceId, providerDeliveryId: row.deliveryId, dispatchState: 'pending' },+ { dispatchState: 'dispatched', lastDispatchAt: new Date(), payload: null },+ );+ }await this.repo.update({ id: row.id }, { redriven: true });redriven++;} else {diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.tsindex 936ae8eaf..b8c2ae850 100644--- a/src/modules/message/bulk-message.service.spec.ts+++ b/src/modules/message/bulk-message.service.spec.ts@@ -2,7 +2,12 @@ import { Test, TestingModule } from '@nestjs/testing';import { PayloadTooLargeException } from '@nestjs/common';import { getRepositoryToken } from '@nestjs/typeorm';import { In, Not } from 'typeorm';-import { BulkMessageService, resolveFinalBatchStatus, sanitizeBatchError } from './bulk-message.service';+import {+ BulkMessageService,+ resolveFinalBatchStatus,+ sanitizeBatchError,+ resolveMaxConcurrentBatches,+} from './bulk-message.service';import { MessageBatch, BatchStatus, BatchMessageStatus, BatchMessageResult } from './entities/message-batch.entity';import { MessageStatus } from './entities/message.entity';import { SendBulkMessageDto } from './dto/bulk-message.dto';@@ -35,6 +40,19 @@ describe('resolveFinalBatchStatus', () => {});});+describe('resolveMaxConcurrentBatches', () => {+ const prev = process.env.BULK_MAX_CONCURRENT_BATCHES;+ afterEach(() => {+ if (prev === undefined) delete process.env.BULK_MAX_CONCURRENT_BATCHES;+ else process.env.BULK_MAX_CONCURRENT_BATCHES = prev;+ });++ it('treats a blank BULK_MAX_CONCURRENT_BATCHES as unset, not as 0 (unlimited)', () => {+ process.env.BULK_MAX_CONCURRENT_BATCHES = '';+ expect(resolveMaxConcurrentBatches()).toBe(50);+ });+});+/** Regression lock: orphaned (restart-interrupted) PROCESSING batches are transitioned. */describe('BulkMessageService.onApplicationBootstrap', () => {let service: BulkMessageService;@@ -734,31 +752,47 @@ describe('BulkMessageService.createBatch base64 media cap', () => {expect(repo.findOne).toHaveBeenCalledWith({ where: { batchId: 'dup', sessionId: 's2' } });});- it('collapses duplicate chatIds before persisting (first occurrence wins, order preserved)', async () => {+ it('collapses exact duplicate entries before persisting (first occurrence wins, order preserved)', async () => {const dto = {messages: [{ chatId: '[email protected]', type: 'text' as const, content: { text: 'first' } },{ chatId: '[email protected]', type: 'text' as const, content: { text: 'second' } },- { chatId: '[email protected]', type: 'text' as const, content: { text: 'duplicate — dropped' } },+ { chatId: '[email protected]', type: 'text' as const, content: { text: 'first' } }, // exact duplicate — dropped],} as unknown as SendBulkMessageDto;const batch = await service.createBatch('s1', dto);expect(batch.messages.map(m => m.chatId)).toEqual(['[email protected]', '[email protected]']);- expect(batch.messages[0].content).toEqual({ text: 'first' }); // the first entry for an id wins+ expect(batch.messages[0].content).toEqual({ text: 'first' }); // the first entry winsexpect(batch.progress.total).toBe(2);expect(batch.progress.pending).toBe(2);});- it('runs the engine once per unique chatId across the full create→process path', async () => {+ it('keeps distinct messages to the same chatId (different type/content/variables are not duplicates)', async () => {+ const dto = {+ messages: [+ { chatId: '[email protected]', type: 'text' as const, content: { text: 'part 1' } },+ { chatId: '[email protected]', type: 'image' as const, content: { image: { url: 'https://example.com/pic.jpg' } } },+ { chatId: '[email protected]', type: 'text' as const, content: { text: 'part 1' }, variables: { name: 'x' } },+ ],+ } as unknown as SendBulkMessageDto;++ const batch = await service.createBatch('s1', dto);++ expect(batch.messages.map(m => m.type)).toEqual(['text', 'image', 'text']);+ expect(batch.progress.total).toBe(3);+ expect(batch.progress.pending).toBe(3);+ });++ it('runs the engine once per exact duplicate entry across the full create→process path', async () => {const engine = { sendTextMessage: jest.fn().mockResolvedValue({ id: 'wa', timestamp: 1 }) };sessionService.getEngine.mockReturnValue(engine);const dto = {messages: [{ chatId: '[email protected]', type: 'text' as const, content: { text: 'first' } },{ chatId: '[email protected]', type: 'text' as const, content: { text: 'second' } },- { chatId: '[email protected]', type: 'text' as const, content: { text: 'duplicate — dropped' } },+ { chatId: '[email protected]', type: 'text' as const, content: { text: 'first' } }, // exact duplicate — dropped],options: { delayBetweenMessages: 0, randomizeDelay: false, stopOnError: false },} as unknown as SendBulkMessageDto;@@ -773,4 +807,30 @@ describe('BulkMessageService.createBatch base64 media cap', () => {expect(engine.sendTextMessage).toHaveBeenNthCalledWith(1, '[email protected]', 'first');expect(engine.sendTextMessage).toHaveBeenNthCalledWith(2, '[email protected]', 'second');});++ it('sends every distinct message to the same chatId across the full create→process path', async () => {+ const engine = {+ sendTextMessage: jest.fn().mockResolvedValue({ id: 'wa-t', timestamp: 1 }),+ sendImageMessage: jest.fn().mockResolvedValue({ id: 'wa-i', timestamp: 2 }),+ };+ sessionService.getEngine.mockReturnValue(engine);+ const dto = {+ messages: [+ { chatId: '[email protected]', type: 'text' as const, content: { text: 'part 1' } },+ { chatId: '[email protected]', type: 'image' as const, content: { image: { url: 'https://example.com/pic.jpg' } } },+ ],+ options: { delayBetweenMessages: 0, randomizeDelay: false, stopOnError: false },+ } as unknown as SendBulkMessageDto;++ const batch = await service.createBatch('s1', dto);+ // Same fire-and-forget caveat as above — drive processing explicitly with the batch "in the DB".+ repo.findOne.mockResolvedValue(batch);+ await (service as unknown as { processBatch: (id: string) => Promise<void> }).processBatch(batch.id);++ expect(engine.sendTextMessage).toHaveBeenCalledTimes(1);+ expect(engine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'part 1');+ expect(engine.sendImageMessage).toHaveBeenCalledTimes(1);+ expect(batch.progress.sent).toBe(2);+ expect(batch.results).toHaveLength(2);+ });});diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.tsindex 5401a5db0..fa207b689 100644--- a/src/modules/message/bulk-message.service.ts+++ b/src/modules/message/bulk-message.service.ts@@ -1,7 +1,7 @@import { Injectable, Logger, BadRequestException, NotFoundException, OnApplicationBootstrap } from '@nestjs/common';import { InjectRepository } from '@nestjs/typeorm';import { In, Not, QueryDeepPartialEntity, Repository } from 'typeorm';-import { randomUUID } from 'crypto';+import { createHash, randomUUID } from 'crypto';import {MessageBatch,BatchStatus,@@ -18,6 +18,7 @@ import { assertBase64WithinMediaCap, stripBase64DataUri } from './media-cap.utilimport { SsrfBlockedError, SSRF_BLOCKED_CLIENT_MESSAGE } from '../../common/security/ssrf-guard';import { renderTemplate } from '../../common/utils/template-render';import { IWhatsAppEngine, MessageResult } from '../../engine/interfaces/whatsapp-engine.interface';+import { resolveNonNegativeIntEnv } from '../../config/configuration';// Type definitions for bulk message contentinterface BulkMessageContent {@@ -66,9 +67,7 @@ export function sanitizeBatchError(error: unknown): { code: string; message: str*/const DEFAULT_MAX_CONCURRENT_BATCHES = 50;export function resolveMaxConcurrentBatches(): number {- const raw = Number(process.env.BULK_MAX_CONCURRENT_BATCHES);- if (!Number.isFinite(raw) || raw < 0) return DEFAULT_MAX_CONCURRENT_BATCHES;- return Math.floor(raw); // 0 = unlimited+ return resolveNonNegativeIntEnv(process.env.BULK_MAX_CONCURRENT_BATCHES, DEFAULT_MAX_CONCURRENT_BATCHES); // 0 = unlimited}@Injectable()@@ -112,14 +111,20 @@ export class BulkMessageService implements OnApplicationBootstrap {throw new BadRequestException(`Session '${sessionId}' is not active`);}- // Collapse duplicate chatIds — first occurrence wins, order preserved — so a recipient gets at- // most one message per batch. Repeats would only re-run the engine (and the moderation gate)- // for an id already covered by the first entry.- const seenChatIds = new Set<string>();+ // Collapse exact duplicate entries — same chatId, type, content, and variables; first+ // occurrence wins, order preserved. A true repeat would only re-run the engine (and the+ // moderation gate) for an entry already covered, but distinct messages to the same chatId+ // (a text followed by an image, say) must all be sent.+ const seenEntries = new Set<string>();const messages: SendBulkMessageDto['messages'] = [];for (const message of dto.messages) {- if (seenChatIds.has(message.chatId)) continue;- seenChatIds.add(message.chatId);+ // Hashed, not retained verbatim: the raw JSON of a 100-item media batch is a second copy of+ // the whole payload (up to the body limit) held for the length of the loop.+ const fingerprint = createHash('sha256')+ .update(JSON.stringify([message.chatId, message.type, message.content, message.variables]))+ .digest('base64');+ if (seenEntries.has(fingerprint)) continue;+ seenEntries.add(fingerprint);messages.push(message);}@@ -185,7 +190,7 @@ export class BulkMessageService implements OnApplicationBootstrap {`Created batch ${batchId} with ${messages.length} messages` +(messages.length === dto.messages.length? ''- : ` (${dto.messages.length - messages.length} duplicate chatId entr${dto.messages.length - messages.length === 1 ? 'y' : 'ies'} dropped)`),+ : ` (${dto.messages.length - messages.length} exact duplicate entr${dto.messages.length - messages.length === 1 ? 'y' : 'ies'} dropped)`),);// Start processing asynchronouslydiff --git a/src/modules/message/dto/bulk-message.dto.ts b/src/modules/message/dto/bulk-message.dto.tsindex 32a98b0c0..ebf9eb9ac 100644--- a/src/modules/message/dto/bulk-message.dto.ts+++ b/src/modules/message/dto/bulk-message.dto.ts@@ -133,7 +133,8 @@ export class SendBulkMessageDto {batchId?: string;@ApiProperty({- description: 'Array of messages (max 100 per request; duplicate chatIds are collapsed — first occurrence wins)',+ description:+ 'Array of messages (max 100 per request; exact duplicate entries are collapsed — first occurrence wins)',type: [BulkMessageItemDto],})@IsArray()diff --git a/src/modules/message/pending-message-reaper.service.spec.ts b/src/modules/message/pending-message-reaper.service.spec.tsindex b5d8924a1..2d1958742 100644--- a/src/modules/message/pending-message-reaper.service.spec.ts+++ b/src/modules/message/pending-message-reaper.service.spec.ts@@ -159,10 +159,10 @@ describe('PendingMessageReaperService.sweep', () => {expect((payload.message.metadata as { media: { data?: string } }).media.data).toBeUndefined();});- it('keeps the batch alive when one row fails to save', async () => {+ it('keeps the batch alive when one row fails to persist', async () => {const first = await insertMessage();const second = await insertMessage();- const saveSpy = jest.spyOn(messages, 'save').mockRejectedValueOnce(new Error('db hiccup'));+ const updateSpy = jest.spyOn(messages, 'update').mockRejectedValueOnce(new Error('db hiccup'));const stats = await service.sweep(OPTS);@@ -170,7 +170,26 @@ describe('PendingMessageReaperService.sweep', () => {expect((await stored(first)).status).toBe(MessageStatus.PENDING);expect((await stored(second)).status).toBe(MessageStatus.FAILED);expect(persistedCalls()).toHaveLength(1);- saveSpy.mockRestore();+ updateSpy.mockRestore();+ });++ it('does not overwrite a row whose send resolved between the sweep read and the reap write', async () => {+ const id = await insertMessage();+ const realUpdate = messages.update.bind(messages);+ // The live send path persists its own SENT + waMessageId outcome just before the reap write+ // lands; the guarded UPDATE must then match nothing instead of clobbering it back to FAILED.+ jest.spyOn(messages, 'update').mockImplementationOnce(async (criteria, partial) => {+ await realUpdate({ id }, { status: MessageStatus.SENT, waMessageId: 'wamid.race' });+ return realUpdate(criteria, partial);+ });++ const stats = await service.sweep(OPTS);++ expect(stats).toEqual({ scanned: 1, reaped: 0, failed: 0 });+ const row = await stored(id);+ expect(row.status).toBe(MessageStatus.SENT);+ expect(row.waMessageId).toBe('wamid.race');+ expect(persistedCalls()).toHaveLength(0);});});@@ -202,6 +221,15 @@ describe('resolvePendingMessageReaperOptions', () => {}),).toEqual({ intervalMs: 600_000, graceMs: 3_600_000, batchSize: 50 });});++ it('treats blank values as unset, not as 0 (which would disable the reaper)', () => {+ expect(+ resolvePendingMessageReaperOptions({+ MESSAGE_REAPER_INTERVAL_MS: '',+ MESSAGE_REAPER_GRACE_MS: ' ',+ }),+ ).toEqual({ intervalMs: 600_000, graceMs: 3_600_000, batchSize: 50 });+ });});describe('PendingMessageReaperService.onModuleInit (scheduling)', () => {diff --git a/src/modules/message/pending-message-reaper.service.ts b/src/modules/message/pending-message-reaper.service.tsindex 7a01b4cb2..b9e466591 100644--- a/src/modules/message/pending-message-reaper.service.ts+++ b/src/modules/message/pending-message-reaper.service.ts@@ -1,12 +1,15 @@import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';import { InjectRepository } from '@nestjs/typeorm';-import { LessThan, Repository } from 'typeorm';+import { LessThan, QueryDeepPartialEntity, Repository } from 'typeorm';import { Message, MessageDirection, MessageStatus } from './entities/message.entity';import { HookManager } from '../../core/hooks';import { createLogger } from '../../common/services/logger.service';+import { resolveNonNegativeIntEnv } from '../../config/configuration';export interface PendingMessageReaperOptions {- // Sweep cadence. <= 0 disables the reaper (mirrors INGRESS_RECONCILE_INTERVAL_MS <= 0).+ // Sweep cadence. 0 disables the reaper (mirrors INGRESS_RECONCILE_INTERVAL_MS). A blank or+ // otherwise unparseable value falls back to the default rather than disabling the sweep, so a+ // mis-set variable can never silently turn the reaper off.intervalMs: number;// An outgoing PENDING row only becomes reap-eligible once it is older than this — the live send// path gets the whole window to persist its own SENT/FAILED outcome first.@@ -15,12 +18,10 @@ export interface PendingMessageReaperOptions {}export function resolvePendingMessageReaperOptions(env: NodeJS.ProcessEnv = process.env): PendingMessageReaperOptions {- const interval = Number(env.MESSAGE_REAPER_INTERVAL_MS);- const grace = Number(env.MESSAGE_REAPER_GRACE_MS);const batch = Number(env.MESSAGE_REAPER_BATCH_SIZE);return {- intervalMs: Number.isInteger(interval) ? interval : 10 * 60_000,- graceMs: Number.isInteger(grace) && grace >= 0 ? grace : 60 * 60_000,+ intervalMs: resolveNonNegativeIntEnv(env.MESSAGE_REAPER_INTERVAL_MS, 10 * 60_000),+ graceMs: resolveNonNegativeIntEnv(env.MESSAGE_REAPER_GRACE_MS, 60 * 60_000),batchSize: Number.isInteger(batch) && batch >= 1 ? batch : 50,};}@@ -79,7 +80,8 @@ export class PendingMessageReaperService implements OnModuleInit, OnModuleDestro/*** One bounded pass over the stale outgoing-PENDING backlog. Overlap-guarded: a slow sweep never- * stacks a second pass on top of itself.+ * stacks a second pass on top of itself. Each reap write is guarded on the row still being+ * PENDING, so a send that resolves between the find and the write keeps its own outcome.*/async sweep(opts: PendingMessageReaperOptions, now: Date = new Date()): Promise<PendingMessageReaperStats> {const stats: PendingMessageReaperStats = { scanned: 0, reaped: 0, failed: 0 };@@ -99,10 +101,11 @@ export class PendingMessageReaperService implements OnModuleInit, OnModuleDestrofor (const row of rows) {stats.scanned++;try {- await this.reapRow(row, now);- stats.reaped++;+ if (await this.reapRow(row, now)) {+ stats.reaped++;+ }} catch (err) {- // A bookkeeping failure (repo save) must not abort the batch; the row stays PENDING and+ // A bookkeeping failure (repo update) must not abort the batch; the row stays PENDING and// is retried next sweep.this.logger.error('Reaping a stuck pending message failed',@@ -123,7 +126,7 @@ export class PendingMessageReaperService implements OnModuleInit, OnModuleDestro}}- private async reapRow(row: Message, now: Date): Promise<void> {+ private async reapRow(row: Message, now: Date): Promise<boolean> {// A reaped row is terminal: it is never retried and its media is never rendered, so drop the// base64 payload exactly as MessageService.saveFailedMessage does for a genuine send failure —// keeping a multi-MB payload in a terminal row only bloats the messages table. The reapedAt@@ -134,7 +137,17 @@ export class PendingMessageReaperService implements OnModuleInit, OnModuleDestro}row.metadata = { ...(row.metadata ?? {}), reapedAt: now.toISOString() };row.status = MessageStatus.FAILED;- await this.messages.save(row);+ // The guard lives IN the UPDATE: a send that resolved between this sweep's find() and this+ // write has already persisted its own SENT + waMessageId, and a blind save would clobber that+ // terminal outcome back to FAILED/null. Zero affected rows = the live path won the race —+ // leave the row alone and skip the emission below.+ const reaped = await this.messages.update({ id: row.id, status: MessageStatus.PENDING }, {+ status: row.status,+ metadata: row.metadata,+ } as QueryDeepPartialEntity<Message>);+ if (!reaped.affected) {+ return false;+ }// Reconcile provider copies of the earlier PENDING emission: fire-and-forget with a shallow// snapshot, the exact shape of MessageService.emitPersisted — a plugin handler must never// break the sweep.@@ -145,5 +158,6 @@ export class PendingMessageReaperService implements OnModuleInit, OnModuleDestro{ sessionId: row.sessionId, source: 'PendingMessageReaperService' },).catch(() => undefined);+ return true;}}diff --git a/src/modules/plugins/dto/plugin.dto.ts b/src/modules/plugins/dto/plugin.dto.tsindex 107f67e74..6c7e11f81 100644--- a/src/modules/plugins/dto/plugin.dto.ts+++ b/src/modules/plugins/dto/plugin.dto.ts@@ -88,8 +88,8 @@ export class InstallFromUrlDto {'HTTPS URL of the plugin .zip to download and install. Plain http:// is rejected: the package is ' +'executable code, so it must be integrity-protected in transit (hosts on private networks remain ' +'subject to the SSRF guard). Optional content pinning: append `#sha256=<64 hex>` (fragment — never ' +- 'sent to the server) or `?sha256=<64 hex>` to require the downloaded archive to match that digest; ' +- 'a mismatch fails the install.',+ 'sent to the server; query params are ignored) to require the downloaded archive to match that ' ++ 'digest; a mismatch fails the install.',})@IsString()@IsUrl(diff --git a/src/modules/plugins/plugin-download.spec.ts b/src/modules/plugins/plugin-download.spec.tsindex 3a78ef40e..da585a874 100644--- a/src/modules/plugins/plugin-download.spec.ts+++ b/src/modules/plugins/plugin-download.spec.ts@@ -2,9 +2,10 @@ import { expectedSha256FromUrl, assertDownloadSha256 } from './plugin-download';import { createHash } from 'crypto';/**- * Optional content integrity for plugin downloads: the expected sha256 travels IN the URL- * (`#sha256=` fragment — never sent to the server — or a `?sha256=`/`?checksum=` query param), and- * verification is fail-closed whenever a marker is present.+ * Optional content integrity for plugin downloads: the expected sha256 travels IN the URL as a+ * `#sha256=` fragment (never sent to the server), and verification is fail-closed whenever the+ * marker is present. Query params — even ones named `sha256`/`checksum` — are NOT markers: they+ * are sent to the server and may belong to the download host's own contract.*/describe('expectedSha256FromUrl', () => {const digest = 'a'.repeat(64);@@ -14,9 +15,11 @@ describe('expectedSha256FromUrl', () => {expect(expectedSha256FromUrl(`https://h/pkg.zip#sha256=${digest.toUpperCase()}`)).toBe(digest);});- it('extracts the digest from ?sha256= / ?checksum= query params', () => {- expect(expectedSha256FromUrl(`https://h/pkg.zip?sha256=${digest}`)).toBe(digest);- expect(expectedSha256FromUrl(`https://h/pkg.zip?checksum=${digest}`)).toBe(digest);+ it('does not seize ?sha256= / ?checksum= query params — they belong to the host, not to OpenWA', () => {+ expect(expectedSha256FromUrl(`https://h/pkg.zip?sha256=${digest}`)).toBeNull();+ expect(expectedSha256FromUrl(`https://h/pkg.zip?checksum=${digest}`)).toBeNull();+ // A host-side checksum param in its own (non-sha256-hex) format must not fail the download.+ expect(expectedSha256FromUrl('https://h/pkg.zip?checksum=1a2b3c4d&dl=1')).toBeNull();});it('returns null when the URL carries no integrity marker', () => {@@ -27,13 +30,12 @@ describe('expectedSha256FromUrl', () => {it('fails closed on a malformed marker', () => {expect(() => expectedSha256FromUrl('https://h/pkg.zip#sha256=xyz')).toThrow(/64-character hex/i);- expect(() => expectedSha256FromUrl(`https://h/pkg.zip?sha256=${'a'.repeat(63)}`)).toThrow(/64-character hex/i);+ expect(() => expectedSha256FromUrl(`https://h/pkg.zip#sha256=${'a'.repeat(63)}`)).toThrow(/64-character hex/i);});- it('fails closed when fragment and query disagree', () => {- expect(() => expectedSha256FromUrl(`https://h/pkg.zip?sha256=${digest}#sha256=${'b'.repeat(64)}`)).toThrow(- /conflicting/i,- );+ it('honors the fragment alongside unrelated query params (the params are simply ignored)', () => {+ expect(expectedSha256FromUrl(`https://h/pkg.zip?checksum=1a2b3c#sha256=${digest}`)).toBe(digest);+ expect(expectedSha256FromUrl(`https://h/pkg.zip?sha256=${'b'.repeat(64)}#sha256=${digest}`)).toBe(digest);});});diff --git a/src/modules/plugins/plugin-download.ts b/src/modules/plugins/plugin-download.tsindex 0c46e6481..a06329351 100644--- a/src/modules/plugins/plugin-download.ts+++ b/src/modules/plugins/plugin-download.ts@@ -12,12 +12,15 @@ const SHA256_HEX = /^[0-9a-f]{64}$/i;* Optional content integrity for a plugin download, carried IN the URL so it works over any* transport (a catalog `download` link, a dashboard paste, a raw API call):* - URL fragment: https://host/pkg.zip#sha256=<64 hex> — never sent to the server- * - query param: https://host/pkg.zip?sha256=<64 hex> — `checksum=` is accepted too+ * The fragment is the only honored marker: unlike a query param it is not part of the request, so+ * it cannot collide with a param the download host itself uses — a `?sha256=`/`?checksum=` on a+ * CDN or artifact URL means something to THAT host, and seizing it as an integrity pin would+ * fail or mis-verify an unrelated download.* Returns the lowercase expected digest, or null when the URL carries no integrity marker.*- * Throws when a marker is present but malformed (not 64 hex chars) or when fragment and query- * disagree: the caller explicitly asked for integrity, so an unusable marker fails closed rather- * than silently degrading to no verification.+ * Throws when the marker is present but malformed (not 64 hex chars): the caller explicitly asked+ * for integrity, so an unusable marker fails closed rather than silently degrading to no+ * verification.*/export function expectedSha256FromUrl(url: string): string | null {let parsed: URL;@@ -26,23 +29,12 @@ export function expectedSha256FromUrl(url: string): string | null {} catch {return null; // not a parseable URL — the SSRF guard / fetch rejects it downstream}- const markers: string[] = [];- if (parsed.hash.startsWith('#sha256=')) {- markers.push(parsed.hash.slice('#sha256='.length));- }- for (const key of ['sha256', 'checksum']) {- const value = parsed.searchParams.get(key);- if (value !== null) markers.push(value);- }- if (markers.length === 0) return null;- const digests = markers.map(marker => marker.trim().toLowerCase());- if (digests.some(digest => !SHA256_HEX.test(digest))) {+ if (!parsed.hash.startsWith('#sha256=')) return null;+ const digest = parsed.hash.slice('#sha256='.length).trim().toLowerCase();+ if (!SHA256_HEX.test(digest)) {throw new Error('the URL carries a sha256 integrity marker that is not a 64-character hex digest');}- if (new Set(digests).size > 1) {- throw new Error('the URL carries conflicting sha256 integrity markers');- }- return digests[0];+ return digest;}/**diff --git a/src/modules/plugins/plugins.service.spec.ts b/src/modules/plugins/plugins.service.spec.tsindex a94042566..f97fd9314 100644--- a/src/modules/plugins/plugins.service.spec.ts+++ b/src/modules/plugins/plugins.service.spec.ts@@ -282,13 +282,19 @@ describe('PluginsService — download integrity (optional #sha256 pinning)', ()expect(loader.getPlugin('svc-plg')).toBeDefined();});- it('also accepts the digest as a ?sha256= query parameter', async () => {+ it('ignores a ?sha256= query parameter — only the #sha256= fragment pins the digest', async () => {const buf = pkg();serveOnce(buf);+ const wrong = '0'.repeat(64);- const dto = await service.installFromUrl(`https://plugins.example/svc-plg.zip?sha256=${sha256(buf)}`);+ // The query digest does not match the bytes, yet the install still succeeds on the fragment's+ // verdict: a query param is never an integrity marker (it belongs to the download host).+ const dto = await service.installFromUrl(+ `https://plugins.example/svc-plg.zip?sha256=${wrong}#sha256=${sha256(buf)}`,+ );expect(dto.id).toBe('svc-plg');+ expect(loader.getPlugin('svc-plg')).toBeDefined();});it('fails closed when the pinned digest does not match (package substituted in transit)', async () => {diff --git a/src/modules/plugins/plugins.service.ts b/src/modules/plugins/plugins.service.tsindex 3006aac44..abe0128dc 100644--- a/src/modules/plugins/plugins.service.ts+++ b/src/modules/plugins/plugins.service.ts@@ -344,9 +344,9 @@ export class PluginsService {* Install a plugin from an HTTPS URL: download the .zip through the SSRF guard (host validated,* connection pinned, redirects refused, size-capped), then run the exact same validate-write-load* pipeline as an uploaded package. The downloaded buffer is treated as untrusted, identical to an- * upload. When the URL pins a digest (`#sha256=<hex>` fragment or `?sha256=` query — see- * plugin-download.ts), the bytes MUST match it: a mismatch means the package was substituted in- * transit and the install fails closed.+ * upload. When the URL pins a digest (`#sha256=<hex>` fragment — the only honored marker; query+ * params are deliberately ignored, see plugin-download.ts), the bytes MUST match it: a mismatch+ * means the package was substituted in transit and the install fails closed.*/async installFromUrl(url: string): Promise<PluginDto> {const maxBytes = this.configService.get<number>('plugins.downloadMaxBytes') ?? 5 * 1024 * 1024;diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 716d01f87..56e996366 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -367,10 +367,12 @@ describe('SessionService', () => {expect(stoppingOf().has('g-init')).toBe(true); // still marked so start() aborts});- it('isolates a failing destroy(): teardown is best-effort so both engines are reconciled from the map', async () => {+ it('surfaces a failing destroy() in the failed bucket while still reconciling both engines from the map', async () => {// destroyEngineSafely delegates to teardownEngineSafely, which isolates + time-bounds failures and// never throws — a stuck destroy() therefore cannot stall the batch or poison other orphans. The- // engine is removed from the Map regardless of teardown outcome (it stops holding a slot).+ // engine is removed from the Map regardless of teardown outcome (it stops holding a slot), but a+ // teardown that threw/timed out must land in `failed` (its Chromium/socket may still be alive),+ // not be misreported as cleanly stopped — the infra import turns `failed` into restartRequired.const good = { destroy: jest.fn().mockResolvedValue(undefined) };const bad = { destroy: jest.fn().mockRejectedValue(new Error('stuck chromium')) };enginesOf().set('good', good);@@ -383,8 +385,9 @@ describe('SessionService', () => {// Map reconciled for both regardless of teardown outcome — neither holds a concurrency slot.expect(enginesOf().has('good')).toBe(false);expect(enginesOf().has('bad')).toBe(false);- expect(result.failed).toEqual([]); // teardown failures are isolated, not surfaced as failed- expect(result.stopped.sort()).toEqual(['bad', 'good']);+ expect(result.stopped).toEqual(['good']);+ expect(result.failed).toEqual(['bad']);+ expect(result.notRunning).toEqual([]);});it('is a bounded no-op for an empty id list', async () => {@@ -531,6 +534,34 @@ describe('SessionService', () => {expect(engineFactory.create).toHaveBeenCalledTimes(1);});+ it('registers an in-flight start before the findOne await so the import pre-flight sees it', async () => {+ // The infra import pre-flight (getActiveSessionIds) must not miss a start that is still inside+ // its initial findOne round-trip: an import with stopOrphans could otherwise DELETE the session+ // row while an engine for it is being created, orphaning that engine until process restart.+ let releaseFindOne: (session: unknown) => void = () => undefined;+ (repository.findOne as jest.Mock)+ .mockImplementationOnce(+ () =>+ new Promise(resolve => {+ releaseFindOne = resolve;+ }),+ )+ .mockResolvedValue(createMockSession());+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ (engineFactory.create as jest.Mock).mockClear().mockReturnValue(mockEngine);++ const started = service.start('sess-uuid-1');+ // findOne has not resolved, so no engine exists yet — but the reservation must already be visible.+ expect(service.getActiveSessionIds()).toContain('sess-uuid-1');++ releaseFindOne(createMockSession());+ await started;+ // The reservation is cleared once start() settles; the registered engine keeps the id active.+ const initializing = (service as unknown as { initializingSessions: Set<string> }).initializingSessions;+ expect(initializing.has('sess-uuid-1')).toBe(false);+ expect(service.getActiveSessionIds()).toContain('sess-uuid-1');+ });+it('evicts and tears down the engine when engine.initialize() fails (no orphan wedging the session)', async () => {(repository.findOne as jest.Mock).mockResolvedValue(createMockSession());(repository.update as jest.Mock).mockResolvedValue({ affected: 1 });diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex cbdd18d77..12a8bcfd2 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -348,23 +348,27 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatthis.engines.clear();}- /** Destroy one engine, isolating + time-bounding failures so shutdown can't be stalled or aborted. */- private async destroyEngineSafely(sessionId: string, engine: IWhatsAppEngine): Promise<void> {+ /** Destroy one engine, isolating + time-bounding failures so shutdown can't be stalled or aborted.+ * Resolves to whether the destroy actually completed (see teardownEngineSafely). */+ private async destroyEngineSafely(sessionId: string, engine: IWhatsAppEngine): Promise<boolean> {this.logger.log(`Destroying engine for session ${sessionId}`, { sessionId, action: 'shutdown' });- await this.teardownEngineSafely(sessionId, engine, e => e.destroy(), 'destroy');+ return this.teardownEngineSafely(sessionId, engine, e => e.destroy(), 'destroy');}/*** Run an engine teardown (destroy/disconnect), isolating + time-bounding failures so a stuck* Chromium/socket can neither hang nor abort the caller. Always resolves — the caller is then free* to reconcile the engines Map and proceed with DB cleanup regardless of teardown outcome.+ * Resolves to whether the teardown actually completed: `false` means it threw or hit the 10s+ * deadline, so the underlying Chromium/socket may still be alive (a caller with an operator-facing+ * outcome, like stopOrphanEngines, must surface that instead of reporting a clean stop).*/private async teardownEngineSafely(sessionId: string,engine: IWhatsAppEngine,teardown: (e: IWhatsAppEngine) => Promise<void>,label: 'destroy' | 'disconnect' | 'force-destroy',- ): Promise<void> {+ ): Promise<boolean> {let timer: ReturnType<typeof setTimeout> | undefined;try {await Promise.race([@@ -373,11 +377,13 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicattimer = setTimeout(() => reject(new Error(`engine.${label}() timed out`)), 10_000);}),]);+ return true;} catch (err) {this.logger.error(`Failed to ${label} engine for session ${sessionId}`, String(err), {sessionId,action: `engine_${label}_failed`,});+ return false;} finally {if (timer) clearTimeout(timer);}@@ -553,31 +559,38 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat}async start(id: string): Promise<Session> {- const session = await this.findOne(id);-- // Reserve the slot SYNCHRONOUSLY (same tick as the has() check) so two near-simultaneous- // start() calls can't both pass the check and orphan an engine — the has() -> engines.set()- // window spans the awaited hook below. The second caller is rejected; the finally clears the- // reservation on success AND failure so a failed start never wedges at "already starting".- if (this.engines.has(id)) {- throw new BadRequestException('Session is already started');- }+ // Reserve the slot SYNCHRONOUSLY at entry — before even the findOne await. Two near-simultaneous+ // start() calls must not both pass the check and orphan an engine (the has() -> engines.set()+ // window spans the awaited hook below), and the infra import pre-flight (getActiveSessionIds)+ // must see an in-flight start during the findOne round-trip too: registered only after findOne,+ // a start would be invisible in that window and a stopOrphans import could DELETE the session+ // row while an engine for it is being created. The finally clears the reservation on success+ // AND failure so a failed start never wedges at "already starting".if (this.initializingSessions.has(id)) {throw new BadRequestException('Session is already starting');}- const maxConcurrentSessions = resolveMaxConcurrentSessions(this.configService);- if (maxConcurrentSessions !== null) {- // Count each session once. A session mid-initialization is transiently in BOTH `engines` (set at- // the start of initializeEngine) and `initializingSessions` (until start()'s finally), so summing- // the two sizes would double-count it and falsely reject new starts at ~half the configured cap.- const activeCount = new Set<string>([...this.engines.keys(), ...this.initializingSessions]).size;- if (activeCount >= maxConcurrentSessions) {- throw new BadRequestException(`Maximum concurrent sessions reached (${maxConcurrentSessions})`);- }- }this.initializingSessions.add(id);try {+ const session = await this.findOne(id);++ if (this.engines.has(id)) {+ throw new BadRequestException('Session is already started');+ }+ const maxConcurrentSessions = resolveMaxConcurrentSessions(this.configService);+ if (maxConcurrentSessions !== null) {+ // Count each OTHER session once. A session mid-initialization is transiently in BOTH+ // `engines` (set at the start of initializeEngine) and `initializingSessions` (until+ // start()'s finally), so summing the two sizes would double-count it; and `id` itself is+ // already reserved in `initializingSessions` (added at entry), so it must not count+ // against the cap it is being checked against.+ const activeIds = new Set<string>([...this.engines.keys(), ...this.initializingSessions]);+ activeIds.delete(id);+ if (activeIds.size >= maxConcurrentSessions) {+ throw new BadRequestException(`Maximum concurrent sessions reached (${maxConcurrentSessions})`);+ }+ }+// A fresh start intentionally (re-)creates the engine — clear any stale stop/delete mark.this.stoppingSessions.delete(id);@@ -2438,9 +2451,18 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatreturn;}try {- await this.destroyEngineSafely(id, engine);+ const tornDown = await this.destroyEngineSafely(id, engine);+ // The engine leaves the Map regardless of teardown outcome so it stops holding a+ // concurrency slot — but only a completed teardown counts as `stopped`. A throw/timeout+ // means the Chromium/socket may still be alive and writing, so the id lands in `failed`+ // and the caller (the infra import) can flag restartRequired instead of reporting a+ // clean stop for a wedged engine.if (this.isLiveEngine(id, engine)) this.engines.delete(id);- stopped.push(id);+ if (tornDown) {+ stopped.push(id);+ } else {+ failed.push(id);+ }} catch (err) {// destroyEngineSafely never throws today (it isolates via teardownEngineSafely), but defend// against a future change so a single orphan cannot abort the batch.diff --git a/src/modules/stats/stats.service.spec.ts b/src/modules/stats/stats.service.spec.tsindex faa3bf222..132a67c50 100644--- a/src/modules/stats/stats.service.spec.ts+++ b/src/modules/stats/stats.service.spec.ts@@ -1,3 +1,4 @@+import { NotFoundException } from '@nestjs/common';import { DataSource } from 'typeorm';import { StatsService, timeSeriesTimestampSql, hourBucketSql, maxCreatedAtSql } from './stats.service';import { Session, SessionStatus } from '../session/entities/session.entity';@@ -339,6 +340,28 @@ describe('StatsService aggregate memo (in-process TTL)', () => {expect(spy.mock.calls.length).toBeGreaterThan(n);});+ it('does not serve a deleted session from the memo — the stale entry is evicted, not served', async () => {+ const service = makeService(30000);++ const first = await service.getSessionStats('s1'); // populates the 'session:s1' memo entry+ expect(first.session.name).toBe('n1');++ await ds.getRepository(Session).delete('s1');+ // Within the TTL the memo still holds the deleted session's snapshot; serving it would+ // resurrect a deleted session with a 200 instead of the honest 404.+ await expect(service.getSessionStats('s1')).rejects.toThrow(NotFoundException);++ // The stale entry is evicted, not just bypassed: a re-created session recomputes immediately+ // instead of waiting out the TTL with the pre-delete snapshot.+ await ds+ .getRepository(Session)+ .save(+ ds.getRepository(Session).create({ id: 's1', name: 'n1-recreated', status: SessionStatus.READY, config: {} }),+ );+ const recomputed = await service.getSessionStats('s1');+ expect(recomputed.session.name).toBe('n1-recreated');+ });+it('bounds every cross-session aggregate with a createdAt range predicate the standalone index serves', async () => {const service = makeService(30000);// Capture the generated SQL the same way the reserved-word regression tests above do.diff --git a/src/modules/stats/stats.service.ts b/src/modules/stats/stats.service.tsindex b5a85e878..d42df09b5 100644--- a/src/modules/stats/stats.service.ts+++ b/src/modules/stats/stats.service.ts@@ -83,7 +83,9 @@ export class StatsService {* 'messages:<period>', 'session:<id>'). The aggregates run GROUP BY scans over the whole* messages table — on the default SQLite backend synchronously on the event loop — so* dashboard polling would otherwise re-run them on every request. TTL-only invalidation:- * entries expire after stats.cacheTtlMs; there is no write-path hook. Key cardinality is+ * entries expire after stats.cacheTtlMs; there is no write-path hook. Session-scoped entries+ * are additionally re-validated on serve (getSessionStats), so a deleted session is not+ * resurrected from the memo. Key cardinality is* bounded (4 global shapes + one per session), so no size eviction is needed.*/private readonly memo = new Map<string, { expiresAt: number; value: unknown }>();@@ -270,7 +272,16 @@ export class StatsService {}async getSessionStats(sessionId: string): Promise<SessionStats> {- return this.memoized(`session:${sessionId}`, () => this.loadSessionStats(sessionId));+ // The memo has no write-path hook, so a `session:<id>` entry can outlive its session row and+ // would keep serving a deleted session's stats until the TTL expires. Re-check existence on+ // every call — a cheap primary-key lookup next to the aggregate scans the memo exists to+ // avoid — and drop the stale entry instead of serving it.+ const key = `session:${sessionId}`;+ if ((await this.sessionRepo.count({ where: { id: sessionId } })) === 0) {+ this.memo.delete(key);+ throw new NotFoundException('Session not found');+ }+ return this.memoized(key, () => this.loadSessionStats(sessionId));}private async loadSessionStats(sessionId: string): Promise<SessionStats> {diff --git a/src/modules/status-store/status-store.service.spec.ts b/src/modules/status-store/status-store.service.spec.tsindex d4c22cbd7..544bdee7c 100644--- a/src/modules/status-store/status-store.service.spec.ts+++ b/src/modules/status-store/status-store.service.spec.ts@@ -227,6 +227,33 @@ describe('StatusStoreService (ingest / list / getMedia)', () => {expect(row.mediaPath).toBeFalsy();});+ it('names the reason when the file lands but the row update fails (webhook must not see a bare omission)', async () => {+ // The in-memory row returned here is exactly what dispatchStatusReceived sends. Every other+ // omission path sets omitReason, so leaving it unset made a real media loss indistinguishable+ // from an unexplained omission — and nothing retries it.+ const saveSpy = jest.spyOn(repository, 'save');+ let calls = 0;+ saveSpy.mockImplementation((row: never) => {+ calls += 1;+ if (calls === 2) return Promise.reject(new Error('db blip')); // the post-write update+ return Promise.resolve(row);+ });+ try {+ const { row } = await service.ingest('sess', {+ waStatusId: 'w-row-fail',+ contactJid: '[email protected]',+ type: 'image',+ media: { mimetype: 'image/jpeg', data: Buffer.from('q').toString('base64') },+ postedAt: 9100,+ });+ expect(row.mediaOmitted).toBe(true);+ expect(row.omitReason).toBe('write_failed');+ expect(row.mediaPath).toBeFalsy();+ } finally {+ saveSpy.mockRestore();+ }+ });+it('respects a configured status.mediaMaxBytes cap', async () => {const strictService = new StatusStoreService(repository,@@ -537,6 +564,27 @@ describe('StatusStoreService.purgeExpired', () => {expect(await repository.count()).toBe(0);expect(fs.existsSync(mediaFile)).toBe(false);});++ it('returns 0 without throwing when every expired row keeps its row (all media deletes fail)', async () => {+ const a = await ingestWithMedia('expired-a', 1000);+ const b = await ingestWithMedia('expired-b', 2000);++ // Every expired row has a media file and every delete fails, so nothing is deletable — an+ // unguarded delete([]) would throw TypeORM's empty-criteria error instead of returning 0.+ const failingStorage = {+ deleteFile: jest.fn().mockRejectedValue(new Error('backend down')),+ } as unknown as StorageService;+ const failingService = new StatusStoreService(repository, failingStorage, fakeConfigService());++ const now = 2000 + 24 * 60 * 60 * 1000 + 1;+ await expect(failingService.purgeExpired(now)).resolves.toBe(0);++ // Rows and files all survive for the next sweep's retry.+ const remaining = await repository.find();+ expect(remaining.map(r => r.waStatusId).sort()).toEqual(['expired-a', 'expired-b']);+ expect(fs.existsSync(path.join(baseDir, 'media', a.mediaPath!))).toBe(true);+ expect(fs.existsSync(path.join(baseDir, 'media', b.mediaPath!))).toBe(true);+ });});describe('StatusStoreService.sweepOrphanedMedia', () => {@@ -635,13 +683,31 @@ describe('StatusStoreService.sweepOrphanedMedia', () => {expect(await shortGrace.sweepOrphanedMedia(t0 + 1001)).toBe(1);expect(fs.existsSync(path.join(baseDir, 'media', 'statuses', 'sess', 'orphan.jpg'))).toBe(false);});++ it('enumerates past the listFiles() cap so orphans beyond it are still reaped', async () => {+ // listFiles() truncates at STORAGE_LIST_MAX_FILES (a per-call DoS guard, not a completeness+ // contract); the sweep reconciles against the FULL store, so it streams iterateFiles() instead.+ process.env.STORAGE_LIST_MAX_FILES = '5';+ try {+ for (let i = 0; i < 8; i++) writeFile(`statuses/sess/orphan-${i}.jpg`, 'orphan');+ // The capped call the sweep used to make would see only 5 of the 8 orphans.+ expect((await storageService.listFiles()).filter(f => f.startsWith('statuses/'))).toHaveLength(5);++ const t0 = Date.now();+ expect(await service.sweepOrphanedMedia(t0)).toBe(0); // first sighting starts the grace clock+ expect(await service.sweepOrphanedMedia(t0 + 61 * 60 * 1000)).toBe(8); // all 8, not the capped 5+ expect(fs.readdirSync(path.join(baseDir, 'media', 'statuses', 'sess'))).toHaveLength(0);+ } finally {+ delete process.env.STORAGE_LIST_MAX_FILES;+ }+ });});describe('StatusStoreService onModuleInit/onModuleDestroy (sweep scheduling)', () => {const mockDeps = (): { repo: Repository<StatusUpdate>; storage: StorageService; find: jest.Mock } => {const find = jest.fn().mockResolvedValue([]);const repo = { find } as unknown as Repository<StatusUpdate>;- const storage = { listFiles: jest.fn().mockResolvedValue([]) } as unknown as StorageService;+ const storage = { iterateFiles: jest.fn().mockReturnValue([]) } as unknown as StorageService;return { repo, storage, find };};diff --git a/src/modules/status-store/status-store.service.ts b/src/modules/status-store/status-store.service.tsindex 97963687d..0bf8e6485 100644--- a/src/modules/status-store/status-store.service.ts+++ b/src/modules/status-store/status-store.service.ts@@ -21,12 +21,15 @@ const PURGE_INTERVAL_MS = 15 * 60 * 1000;* pre-gates history downloads at the same cap so over-cap blobs are never fetched. */export const DEFAULT_MEDIA_MAX_BYTES = 10 * 1024 * 1024;/** Default cadence of the orphaned-media reconciliation sweep (overridable via- * STATUS_ORPHAN_SWEEP_INTERVAL_MS). Lighter-than-it-sounds: one listFiles + one indexed query. */+ * STATUS_ORPHAN_SWEEP_INTERVAL_MS). Lighter-than-it-sounds: one streamed enumeration + one indexed query. */const DEFAULT_ORPHAN_SWEEP_INTERVAL_MS = 60 * 60 * 1000;/** Default grace window before an unreferenced status media file is deleted (overridable via* STATUS_ORPHAN_GRACE_MS), so a file mid-ingest is never reaped. */const DEFAULT_ORPHAN_GRACE_MS = 60 * 60 * 1000;+/** Storage key prefix owned by the status store; the media bucket is shared with chat media. */+const STATUS_MEDIA_PREFIX = 'statuses/';+/** Subtypes whose registered mimetype name differs from the conventional file extension. */const MIME_SUBTYPE_EXT_OVERRIDES: Record<string, string> = { jpeg: 'jpg', quicktime: 'mov' };@@ -183,7 +186,7 @@ export class StatusStoreService implements OnModuleInit, OnModuleDestroy {const media = s.media;if (!media?.data) return;- const key = `statuses/${sessionId}/${randomUUID()}.${extFromMimetype(media.mimetype)}`;+ const key = `${STATUS_MEDIA_PREFIX}${sessionId}/${randomUUID()}.${extFromMimetype(media.mimetype)}`;try {await this.storageService.putFile(key, Buffer.from(media.data, 'base64'));} catch (error) {@@ -215,6 +218,11 @@ export class StatusStoreService implements OnModuleInit, OnModuleDestroy {row.mediaPath = undefined;row.mediaMimetype = undefined;row.mediaOmitted = true;+ // This same object is what the status.received webhook carries, and every other omission path+ // names its reason ('engine_omitted' / 'over_cap' / 'write_failed'). Leaving it unset here+ // would hand a consumer a media-less status it cannot tell apart from an unexplained+ // omission — the media really is gone (nothing retries), so say so.+ row.omitReason = 'write_failed';}}@@ -319,6 +327,8 @@ export class StatusStoreService implements OnModuleInit, OnModuleDestroy {}),);+ // Every media delete may have failed — delete([]) throws TypeORM's empty-criteria error.+ if (deletableIds.length === 0) return 0;const result = await this.repository.delete(deletableIds);return result.affected ?? deletableIds.length;}@@ -335,7 +345,14 @@ export class StatusStoreService implements OnModuleInit, OnModuleDestroy {*/async sweepOrphanedMedia(now: number = Date.now()): Promise<number> {const graceMs = this.configService.get<number>('status.orphanGraceMs', DEFAULT_ORPHAN_GRACE_MS);- const files = (await this.storageService.listFiles()).filter(file => file.startsWith('statuses/'));+ // Stream via iterateFiles: listFiles() truncates at STORAGE_LIST_MAX_FILES (a per-call DoS+ // guard, not a completeness contract), which would strand every orphan past the cap. Scope the+ // walk to the statuses/ prefix so dropping that cap does not pull the whole media store — chat+ // media shares this bucket — through the iterator and its dedupe set.+ const files: string[] = [];+ for await (const file of this.storageService.iterateFiles(STATUS_MEDIA_PREFIX)) {+ if (file.startsWith(STATUS_MEDIA_PREFIX)) files.push(file);+ }const rows = await this.repository.find({where: { mediaPath: Not(IsNull()) },select: { mediaPath: true },diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.tsindex e581b4b58..0f3602512 100644--- a/src/modules/webhook/webhook.service.spec.ts+++ b/src/modules/webhook/webhook.service.spec.ts@@ -1023,6 +1023,55 @@ describe('WebhookService', () => {loggerSpy.mockRestore();});+ it('queued mode: parked enqueues drain to the queue on shutdown instead of dead-lettering', async () => {+ (service as unknown as { queueEnabled: boolean }).queueEnabled = true;+ const hooks = [+ createMockWebhook({ id: 'wh-a', url: 'https://a.example/hook', events: ['message.received'] }),+ createMockWebhook({ id: 'wh-b', url: 'https://b.example/hook', events: ['message.received'] }),+ createMockWebhook({ id: 'wh-c', url: 'https://c.example/hook', events: ['message.received'] }),+ ];+ (repository.find as jest.Mock).mockResolvedValue(hooks);+ (hookManager.execute as jest.Mock).mockImplementation((_event: string, data: unknown) =>+ Promise.resolve({ continue: true, data }),+ );+ (configService.get as jest.Mock).mockImplementation(<T>(key: string, def?: T): T | boolean | number => {+ if (key === 'queue.enabled') return true;+ if (key === 'webhook.shutdownDrainMs') return 1000;+ return def as T;+ });+ // One active slot, generous parked bound: B and C park behind A, whose enqueue hangs.+ (service as unknown as { dispatchLimiter: ConcurrencyLimiter }).dispatchLimiter = new ConcurrencyLimiter(1, 1000);++ let releaseActive: (value: unknown) => void = () => undefined;+ let firstAdd = true;+ (webhookQueue.add as jest.Mock).mockImplementation(+ () =>+ new Promise(resolve => {+ if (firstAdd) {+ firstAdd = false;+ releaseActive = resolve;+ } else {+ resolve(undefined);+ }+ }),+ );++ const dispatchP = service.dispatch('sess-1', 'message.received', { from: '[email protected]' });+ for (let i = 0; i < 20 && webhookQueue.add.mock.calls.length === 0; i++) await new Promise(r => setImmediate(r));++ // Shutdown starts while A holds the slot and B/C are parked. Queued mode must not close the+ // limiter: a parked task is just webhookQueue.add() — durable in Redis once it runs — and it+ // holds an activeCount slot via handoff, so the drain loop waits for the whole chain.+ const destroyP = service.onModuleDestroy();+ releaseActive(undefined);+ await destroyP;+ await dispatchP;++ // All three reached the queue; none was dead-lettered as webhook_dispatch_shutdown.+ expect(webhookQueue.add).toHaveBeenCalledTimes(3);+ expect(failureRepository.insert).not.toHaveBeenCalled();+ });+it('records a dispatch that arrives after the limiter closed (no fetch, dead-letter row)', async () => {const webhook = createMockWebhook({ events: ['message.received'] });(repository.find as jest.Mock).mockResolvedValue([webhook]);diff --git a/src/modules/webhook/webhook.service.ts b/src/modules/webhook/webhook.service.tsindex 8b362dd10..92ca17bca 100644--- a/src/modules/webhook/webhook.service.ts+++ b/src/modules/webhook/webhook.service.ts@@ -171,19 +171,24 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {/*** Bounded drain of the direct-delivery path (queued BullMQ jobs are durable in Redis and need no- * drain). Closing the limiter rejects every PARKED delivery; the dispatch catch records each one in- * webhook_delivery_failures like any other undispatched delivery. In-flight deliveries (a direct- * delivery can outlive WEBHOOK_TIMEOUT via its backoff sleeps) get up to WEBHOOK_SHUTDOWN_DRAIN_MS- * to finish; anything still running after that is about to be dropped by process exit, so it is- * logged per delivery — a dead-letter row would be wrong there, since the receiver may already- * have gotten the event. Nest awaits this hook during app.close(), so the bound also keeps- * app.close() itself bounded.+ * drain). In direct mode, closing the limiter rejects every PARKED delivery; the dispatch catch+ * records each one in webhook_delivery_failures like any other undispatched delivery. Queued mode+ * skips the close: a parked dispatch's whole job is webhookQueue.add() — durable in Redis the+ * moment it resolves — so rejecting it would dead-letter work Redis could have kept. A parked+ * waiter holds an activeCount slot via handoff, so the drain loop below covers it either way.+ * In-flight deliveries (a direct delivery can outlive WEBHOOK_TIMEOUT via its backoff sleeps) get+ * up to WEBHOOK_SHUTDOWN_DRAIN_MS to finish; anything still running after that is about to be+ * dropped by process exit, so it is logged per delivery — a dead-letter row would be wrong there,+ * since the receiver may already have gotten the event. Nest awaits this hook during app.close(),+ * so the bound also keeps app.close() itself bounded.*/async onModuleDestroy(): Promise<void> {if (this.cleanupTimer) {clearInterval(this.cleanupTimer);}- this.dispatchLimiter.close();+ if (!this.queueEnabled) {+ this.dispatchLimiter.close();+ }const drainMs = Math.max(0,this.configService.get<number>('webhook.shutdownDrainMs', DEFAULT_WEBHOOK_SHUTDOWN_DRAIN_MS),diff --git a/test/session-scope.e2e-spec.ts b/test/session-scope.e2e-spec.tsindex d23ea34ff..d86ee6bed 100644--- a/test/session-scope.e2e-spec.ts+++ b/test/session-scope.e2e-spec.ts@@ -10,7 +10,7 @@ import { App } from 'supertest/types';import { AppModule } from './../src/app.module';import { applyGlobalValidation } from './../src/config/app-validation';import { AuthService } from './../src/modules/auth/auth.service';-import { ApiKeyRole } from './../src/modules/auth/entities/api-key.entity';+import { ApiKey, ApiKeyRole } from './../src/modules/auth/entities/api-key.entity';import { Session } from './../src/modules/session/entities/session.entity';import { AuditLog, AuditAction, AuditSeverity } from './../src/modules/audit/entities/audit-log.entity';import { WebhookDeliveryFailure } from './../src/modules/webhook/entities/webhook-delivery-failure.entity';@@ -218,4 +218,82 @@ describe('Session-scoped query endpoints (e2e)', () => {expect(row).not.toBeNull();});});++ /**+ * The last-admin invariant must match the @RequireUnscopedKey fence: a session-scoped admin can+ * never manage keys, so it must not count as a surviving admin. Stripping the last UNSCOPED+ * admin — delete, revoke, demote, or scoping it — must 409; before the fix these returned+ * 204/200 while a scoped admin existed, permanently locking the deployment out of key+ * management (the boot seed only fires on an EMPTY api_keys table, not on zero unscoped admins).+ */+ describe('last-admin invariant vs session-scoped admins', () => {+ let soleAdminKey: string; // raw key of the only remaining UNSCOPED admin+ let soleAdminId: string;++ beforeEach(async () => {+ const authService = app.get(AuthService);+ const created = await authService.createApiKey({ name: 'e2e-sole-admin', role: ApiKeyRole.ADMIN });+ soleAdminKey = created.rawKey;+ soleAdminId = created.apiKey.id;++ // Revoke every OTHER unscoped admin directly in the DB (bypassing the service leaves the+ // bootstrap key file alone), so soleAdmin is the last key that can manage keys — the+ // session-scoped admin from the outer fixture must not count.+ const apiKeyRepo: Repository<ApiKey> = app.get(getRepositoryToken(ApiKey, 'main'));+ const others = (await apiKeyRepo.find()).filter(+ k => k.id !== soleAdminId && k.role === ApiKeyRole.ADMIN && k.isActive && !k.allowedSessions?.length,+ );+ for (const k of others) {+ k.isActive = false;+ await apiKeyRepo.save(k);+ }+ });++ it('rejects DELETE of the last unscoped admin (a scoped admin does not count)', async () => {+ await request(app.getHttpServer())+ .delete(`/api/auth/api-keys/${soleAdminId}`)+ .set('X-API-Key', soleAdminKey)+ .expect(409);+ });++ it('rejects revoking the last unscoped admin', async () => {+ await request(app.getHttpServer())+ .post(`/api/auth/api-keys/${soleAdminId}/revoke`)+ .set('X-API-Key', soleAdminKey)+ .expect(409);+ });++ it('rejects demoting the last unscoped admin', async () => {+ await request(app.getHttpServer())+ .put(`/api/auth/api-keys/${soleAdminId}`)+ .set('X-API-Key', soleAdminKey)+ .send({ role: 'operator' })+ .expect(409);+ });++ it('rejects scoping the last unscoped admin (would strip key-management capability)', async () => {+ await request(app.getHttpServer())+ .put(`/api/auth/api-keys/${soleAdminId}`)+ .set('X-API-Key', soleAdminKey)+ .send({ allowedSessions: [sessA] })+ .expect(409);+ });++ it('still allows the mutation once another unscoped admin exists', async () => {+ const authService = app.get(AuthService);+ const second = await authService.createApiKey({ name: 'e2e-second-admin', role: ApiKeyRole.ADMIN });++ await request(app.getHttpServer())+ .put(`/api/auth/api-keys/${soleAdminId}`)+ .set('X-API-Key', soleAdminKey)+ .send({ allowedSessions: [sessA] })+ .expect(200);+ // soleAdminKey is now session-scoped itself (the fence would 403 it) — the surviving+ // unscoped admin carries the delete.+ await request(app.getHttpServer())+ .delete(`/api/auth/api-keys/${soleAdminId}`)+ .set('X-API-Key', second.rawKey)+ .expect(204);+ });+ });});diff --git a/test/setup-e2e-env.e2e-spec.ts b/test/setup-e2e-env.e2e-spec.tsnew file mode 100644index 000000000..8110ee252--- /dev/null+++ b/test/setup-e2e-env.e2e-spec.ts@@ -0,0 +1,14 @@+/**+ * Boot-env contract for the e2e family: setup-e2e.ts (a jest setupFile) re-runs before every+ * suite in the worker, so each suite must boot with queue and Redis off regardless of what an+ * earlier suite in the same worker left in process.env — queue-on.e2e-spec.ts mutates+ * REDIS_ENABLED at module load and can't restore it when it self-skips. Run alone this passes+ * trivially; its regression value is in a shared-worker run after queue-on (or with a dirty+ * ambient env), where a missing reset shows up as REDIS_ENABLED !== 'false' here.+ */+describe('e2e boot environment', () => {+ it('boots with queue and Redis disabled', () => {+ expect(process.env.QUEUE_ENABLED).toBe('false');+ expect(process.env.REDIS_ENABLED).toBe('false');+ });+});diff --git a/test/setup-e2e.ts b/test/setup-e2e.tsindex aad54b026..11ab102eb 100644--- a/test/setup-e2e.ts+++ b/test/setup-e2e.ts@@ -17,6 +17,10 @@ const e2eMainDb = join(tmpdir(), `openwa-e2e-main-${process.pid}.sqlite`);rmSync(e2eMainDb, { force: true });process.env.MAIN_DATABASE_NAME = e2eMainDb;process.env.QUEUE_ENABLED = 'false';+// Likewise force Redis off per suite: queue-on.e2e-spec.ts flips REDIS_ENABLED=true at module+// load and can't restore it when it self-skips, so without this reset later suites in the same+// jest worker would boot with Redis-backed throttling/cache.+process.env.REDIS_ENABLED = 'false';process.env.AUTO_START_SESSIONS = 'false';// Keep the auth/audit + data schema zero-config for the test boot.process.env.MAIN_DATABASE_SYNCHRONIZE = 'true';