Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix: reliability + config hardening batch (Docker quickstart #677 + bounded search/SSRF/auth + CI gate) (#680)
Yudhi Armyndharis8f1343bb2c8c
diff --git a/.env.example b/.env.exampleindex 164727fbe..18cd8d0dd 100644--- a/.env.example+++ b/.env.example@@ -153,7 +153,10 @@ POSTGRES_BUILTIN=false # Use built-in PostgreSQL container?# PostgreSQL settings (ignored for sqlite, auto-configured if POSTGRES_BUILTIN=true)DATABASE_HOST=localhostDATABASE_PORT=5432-DATABASE_NAME=openwa+# PostgreSQL database name ONLY. Leave unset for SQLite (DATABASE_TYPE=sqlite) to use the+# default file path ./data/openwa.sqlite — a bare value here would become the SQLite file PATH+# and, under a read-only container rootfs, trigger a SQLITE_CANTOPEN boot-loop (#677).+# DATABASE_NAME=openwa# PostgreSQL schema (ignored for sqlite). Default 'public' keeps the historical behavior.# Set to a dedicated schema to isolate OpenWA's tables + migration ledger (e.g. on managed# Postgres where you get a project schema, or to share one DB across apps). The schema mustdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 3ab1a29dd..1cc3ed6d8 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -32,6 +32,13 @@ jobs:- name: Run ESLintrun: npm run lint+ # `nest build` uses tsconfig.build.json which excludes **/*spec.ts, and ts-jest/eslint don't+ # full-program type-check specs — so without this gate, type errors in spec files are invisible+ # to CI. tsconfig.json already includes both `src` and `test`, so this is the cheapest full-program+ # check covering specs (no separate tsconfig.spec.json needed).+ - name: Type-check full program (including specs)+ run: npx tsc --noEmit -p tsconfig.json+- name: Check formattingrun: npm run format -- --checkdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex c274dfd0f..b713669e0 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -13,9 +13,13 @@ permissions:packages: writejobs:- # ──── Build & Test Gate ───────────────────────────────────────────- test:- name: Test Gate+ # ──── Release Gate (CI-strength) ──────────────────────────────────+ # Mirror the CI workflow's gate jobs so a tag can never publish an image or GitHub Release that+ # lint, the spec type-check, unit + e2e tests, the Postgres migration smoke, or the dashboard+ # build/lint would have rejected. Each job below matches its CI counterpart; only the tag-match+ # guard and the publish jobs (docker, release) are release-specific.+ lint:+ name: Lintruns-on: ubuntu-lateststeps:- uses: actions/checkout@v7@@ -24,7 +28,7 @@ jobs:uses: actions/setup-node@v6with:node-version: ${{ env.NODE_VERSION }}- cache: npm+ cache: 'npm'- name: Install dependenciesrun: npm ci@@ -44,23 +48,158 @@ jobs:fiecho "Tag $TAG matches package.json $PKG_VERSION"- - name: Check doc version consistency+ - name: Security audit+ run: npm audit --audit-level=critical++ - name: Run ESLint+ run: npm run lint++ # Same gap as CI: `nest build` excludes specs, so a spec-only type regression slips past every+ # existing release gate. tsconfig.json includes both src and test, so this is the full-program+ # check that also covers spec files.+ - name: Type-check full program (including specs)+ run: npx tsc --noEmit -p tsconfig.json++ - name: Check formatting+ run: npm run format -- --check++ - name: Check version consistency (docs track package.json)run: npm run check:versions- - name: Run tests+ test:+ name: Test+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v7++ - name: Setup Node.js+ uses: actions/setup-node@v6+ with:+ node-version: ${{ env.NODE_VERSION }}+ cache: 'npm'++ - name: Install dependencies+ run: npm ci++ - name: Run unit testsrun: npm test -- --coverage- - name: Build+ - name: Run e2e smoke tests+ run: npm run test:e2e++ test-postgres:+ name: Test (PostgreSQL migrations)+ runs-on: ubuntu-latest+ services:+ postgres:+ image: postgres:16-alpine+ env:+ POSTGRES_USER: openwa+ POSTGRES_PASSWORD: openwa+ POSTGRES_DB: openwa+ ports:+ - 5432:5432+ options: >-+ --health-cmd "pg_isready -U openwa"+ --health-interval 10s+ --health-timeout 5s+ --health-retries 5+ steps:+ - uses: actions/checkout@v7++ - name: Setup Node.js+ uses: actions/setup-node@v6+ with:+ node-version: ${{ env.NODE_VERSION }}+ cache: 'npm'++ - name: Install dependencies+ run: npm ci++ - name: Build (compiles the data migrations to dist/)+ run: npm run build++ # Applies the full data-migration chain to a real Postgres and asserts every generated-uuid PK+ # has a DB DEFAULT — the dialect gap SQLite-only tests can't see.+ - name: Migrate + uuid-default smoke against PostgreSQL+ run: npm run test:pg-smoke+ env:+ DATABASE_TYPE: postgres+ DATABASE_HOST: localhost+ DATABASE_PORT: '5432'+ DATABASE_USERNAME: openwa+ DATABASE_PASSWORD: openwa+ DATABASE_NAME: openwa++ # Runtime-proves BuiltInFtsProvider on Postgres (websearch_to_tsquery + ts_headline against the+ # STORED body_ts tsvector). The spec self-skips unless DATABASE_TYPE=postgres, so it is a no-op+ # in the default test job and only executes here against the postgres:16 service.+ - name: Postgres FTS provider spec+ run: npx jest src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts+ env:+ DATABASE_TYPE: postgres+ DATABASE_HOST: localhost+ DATABASE_PORT: '5432'+ DATABASE_USERNAME: openwa+ DATABASE_PASSWORD: openwa+ DATABASE_NAME: openwa++ dashboard:+ name: Dashboard+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v7++ - name: Setup Node.js+ uses: actions/setup-node@v6+ with:+ node-version: ${{ env.NODE_VERSION }}+ cache: 'npm'+ cache-dependency-path: dashboard/package-lock.json++ - name: Install dependencies+ run: cd dashboard && npm ci++ - name: Run ESLint+ run: cd dashboard && npm run lint++ - name: Check i18n parity+ run: cd dashboard && npm run i18n:check++ - name: Build dashboard+ run: cd dashboard && npm run build++ - name: Run dashboard unit tests+ run: cd dashboard && npm run test:unit++ build:+ name: Build+ runs-on: ubuntu-latest+ needs: [lint, test, dashboard]+ steps:+ - uses: actions/checkout@v7++ - name: Setup Node.js+ uses: actions/setup-node@v6+ with:+ node-version: ${{ env.NODE_VERSION }}+ cache: 'npm'++ - name: Install dependencies+ run: npm ci++ - name: Build projectrun: npm run build# ──── Create GitHub Release ───────────────────────────────────────release:name: GitHub Releaseruns-on: ubuntu-latest- # Gate the public Release on a successfully built+pushed image, so a tag never produces a GitHub- # Release without a matching container image (the docker job also builds the dashboard, which the- # test gate above does not). Trades a few minutes of buildx latency for release/image consistency.- needs: [test, docker]+ # Gate the public Release on every CI-strength job AND a successfully built+pushed image, so a tag+ # never produces a GitHub Release without passing the same gate CI enforces plus a matching+ # container image (the docker job also builds the dashboard, which the gates above verify+ # separately). Trades a few minutes of buildx latency for release/image consistency.+ needs: [lint, test, test-postgres, dashboard, build, docker]steps:- uses: actions/checkout@v7with:@@ -102,7 +241,7 @@ jobs:docker:name: Docker Releaseruns-on: ubuntu-latest- needs: [test]+ needs: [lint, test, test-postgres, dashboard, build]steps:- uses: actions/checkout@v7diff --git a/dashboard/src/hooks/useWebSocket.ts b/dashboard/src/hooks/useWebSocket.tsindex 40da2b4cb..0d085fd9f 100644--- a/dashboard/src/hooks/useWebSocket.ts+++ b/dashboard/src/hooks/useWebSocket.ts@@ -1,5 +1,6 @@import { useEffect, useRef, useCallback, useState } from 'react';import { io, Socket } from 'socket.io-client';+import { warnIfInsecureHttpUrl } from '../utils/urlSecurity';interface SessionStatusEvent {sessionId: string;@@ -74,6 +75,8 @@ interface ServerEventEnvelope {// Use current origin for WebSocket (goes through nginx proxy in Docker)// Falls back to env var or localhost for developmentconst SOCKET_URL = import.meta.env.VITE_WS_URL || window.location.origin;+// Warn when the WebSocket origin is an insecure http:// URL on a non-localhost host.+warnIfInsecureHttpUrl(SOCKET_URL, 'VITE_WS_URL');export function useWebSocket(events: WebSocketEvents = {}) {const socketRef = useRef<Socket | null>(null);diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex a106413c3..d57a29c47 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -1,6 +1,8 @@// API Service Layer for OpenWA Dashboard// Centralized API client with TypeScript types+import { warnIfInsecureHttpUrl } from '../utils/urlSecurity';+// Resolve the API base URL. By default this is the same-origin relative path '/api',// correct when the dashboard and API are served from the same origin (the default// single-container setup). For a split-origin deployment (dashboard hosted separately@@ -10,7 +12,11 @@// same-origin '/api' and a split deployment failed with "Invalid API Key" (#91).// Exported so direct fetches (e.g. auth/validate in Login.tsx / App.tsx) honor VITE_API_URL// too — otherwise split-origin deployments break. Empty VITE_API_URL → '/api'.-export const API_BASE_URL = `${(import.meta.env.VITE_API_URL ?? '').replace(/\/+$/, '')}/api`;+const API_ORIGIN = (import.meta.env.VITE_API_URL ?? '').replace(/\/+$/, '');+export const API_BASE_URL = `${API_ORIGIN}/api`;+// Warn (not refuse — would break dev + TLS-terminating-proxy) when the API origin is an+// insecure http:// URL pointing at a non-localhost host (API keys sent in cleartext).+if (API_ORIGIN) warnIfInsecureHttpUrl(API_ORIGIN, 'VITE_API_URL');// =============================================================================// Typesdiff --git a/dashboard/src/utils/urlSecurity.test.ts b/dashboard/src/utils/urlSecurity.test.tsnew file mode 100644index 000000000..a35e7bcb1--- /dev/null+++ b/dashboard/src/utils/urlSecurity.test.ts@@ -0,0 +1,58 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { isLocalhostHost, warnIfInsecureHttpUrl } from './urlSecurity.ts';++test('isLocalhostHost recognizes loopback hosts', () => {+ assert.ok(isLocalhostHost('localhost'));+ assert.ok(isLocalhostHost('127.0.0.1'));+ assert.ok(isLocalhostHost('[::1]'));+ assert.ok(isLocalhostHost('::1'));+});++test('isLocalhostHost rejects non-loopback hosts', () => {+ assert.ok(!isLocalhostHost('gateway.example.com'));+ assert.ok(!isLocalhostHost('10.0.0.1'));+});++test('warnIfInsecureHttpUrl warns on non-localhost http', () => {+ const warns: string[] = [];+ const original = console.warn;+ console.warn = (msg: string) => warns.push(msg);+ try {+ warnIfInsecureHttpUrl('http://gateway.example.com', 'VITE_API_URL');+ } finally {+ console.warn = original;+ }+ assert.equal(warns.length, 1);+ assert.match(warns[0]!, /insecure http/);+ assert.match(warns[0]!, /gateway\.example\.com/);+});++test('warnIfInsecureHttpUrl is silent on localhost http (dev)', () => {+ const warns: string[] = [];+ const original = console.warn;+ console.warn = (msg: string) => warns.push(msg);+ try {+ warnIfInsecureHttpUrl('http://localhost:2785', 'VITE_API_URL');+ warnIfInsecureHttpUrl('http://127.0.0.1:2785', 'SOCKET_URL');+ } finally {+ console.warn = original;+ }+ assert.equal(warns.length, 0);+});++test('warnIfInsecureHttpUrl is silent on https', () => {+ const warns: string[] = [];+ const original = console.warn;+ console.warn = (msg: string) => warns.push(msg);+ try {+ warnIfInsecureHttpUrl('https://gateway.example.com', 'VITE_API_URL');+ } finally {+ console.warn = original;+ }+ assert.equal(warns.length, 0);+});++test('warnIfInsecureHttpUrl returns the URL unchanged (does not throw)', () => {+ assert.equal(warnIfInsecureHttpUrl('http://gateway.example.com', 'x'), 'http://gateway.example.com');+});diff --git a/dashboard/src/utils/urlSecurity.ts b/dashboard/src/utils/urlSecurity.tsnew file mode 100644index 000000000..154153ad7--- /dev/null+++ b/dashboard/src/utils/urlSecurity.ts@@ -0,0 +1,27 @@+const LOCALHOST_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);++/** Whether a hostname is a loopback/local address where plaintext http is acceptable. */+export function isLocalhostHost(hostname: string): boolean {+ return LOCALHOST_HOSTS.has(hostname.toLowerCase().replace(/^\[|\]$/g, ''));+}++/**+ * Warn (NOT throw) when a URL is `http://` and the host is not localhost. Sending API keys over+ * plaintext http to a non-local host exposes credentials on the wire; warning instead of refusing+ * keeps local dev and TLS-terminating-proxy setups working. Returns the original URL unchanged so+ * the caller can chain.+ */+export function warnIfInsecureHttpUrl(url: string, label: string): string {+ try {+ const parsed = new URL(url);+ if (parsed.protocol === 'http:' && !isLocalhostHost(parsed.hostname)) {+ console.warn(+ `[OpenWA] ${label} uses an insecure http:// URL (host: ${parsed.hostname}). ` ++ 'API keys are sent in cleartext over http. Use https:// in production.',+ );+ }+ } catch {+ // Unparseable — the downstream fetch will produce a clear error; not our job to validate here.+ }+ return url;+}diff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex 9ce920f57..99c68d6f3 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -52,7 +52,7 @@ services:- XDG_CACHE_HOME=/tmp/.cache- LOG_LEVEL=${LOG_LEVEL:-info}- DATABASE_TYPE=${DATABASE_TYPE:-sqlite}- - DATABASE_NAME=${DATABASE_NAME:-/app/data/openwa.sqlite}+ - DATABASE_NAME=${DATABASE_NAME:-}- DATABASE_SYNCHRONIZE=${DATABASE_SYNCHRONIZE:-true}# Engine. Forwarded empty by default so the dashboard (Infrastructure > Engine) selects the# active engine via data/.env.generated (default whatsapp-web.js); main.ts treats a blankdiff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/ClientConfig.java b/sdk/java/src/main/java/com/rmyndharis/openwa/ClientConfig.javaindex 4b0a2ae28..4bec59875 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/ClientConfig.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/ClientConfig.java@@ -35,6 +35,7 @@ public final class ClientConfig {if (b.timeout != null && (b.timeout.isZero() || b.timeout.isNegative())) {throw new IllegalArgumentException("OpenWAClient: timeout must be positive");}+ warnIfInsecureHttp(url);// baseUrl/apiKey are stripped so a trailing newline from a file/env var can't break the request.this.baseUrl = url;this.apiKey = key;@@ -53,6 +54,30 @@ public final class ClientConfig {return false;}+ /**+ * Warn (not throw) when baseUrl is {@code http://} and the host is not localhost. The API key+ * is sent as an {@code X-API-Key} header on every request — over plaintext http to a non-local+ * host that's cleartext on the wire. Warning (not refusing) keeps local dev and+ * TLS-terminating-proxy topologies working.+ */+ private static void warnIfInsecureHttp(String url) {+ try {+ URI uri = new URI(url);+ String scheme = uri.getScheme();+ String host = uri.getHost();+ if ("http".equalsIgnoreCase(scheme) && host != null) {+ String h = host.replaceAll("^\\[|\\]$", "").toLowerCase();+ if (!h.equals("localhost") && !h.equals("127.0.0.1") && !h.equals("::1")) {+ System.err.println(+ "[OpenWA SDK] WARNING: baseUrl uses an insecure http:// URL (host: " + host + "). "+ + "The API key will be sent in cleartext. Use https:// in production.");+ }+ }+ } catch (URISyntaxException e) {+ // Already validated above — a repeat failure here is a no-op.+ }+ }+public static Builder builder() {return new Builder();}diff --git a/sdk/javascript/src/client.ts b/sdk/javascript/src/client.tsindex fdb65e8f3..884b306aa 100644--- a/sdk/javascript/src/client.ts+++ b/sdk/javascript/src/client.ts@@ -23,7 +23,7 @@* @packageDocumentation*/-import { request, encodeSegment, type ClientConfig, type FetchLike, type RequestOptions } from './http.js';+import { request, encodeSegment, warnIfInsecureHttpUrl, type ClientConfig, type FetchLike, type RequestOptions } from './http.js';import { CatalogResource } from './resources/catalog.js';import { ChannelsResource } from './resources/channels.js';import { ChatsResource } from './resources/chats.js';@@ -66,6 +66,8 @@ export class OpenWAClient {defaultHeaders: options.defaultHeaders ?? {},fetch: options.fetch ?? globalThis.fetch,};++ warnIfInsecureHttpUrl(options.baseUrl);}// ── Resources ────────────────────────────────────────────────────diff --git a/sdk/javascript/src/http.ts b/sdk/javascript/src/http.tsindex b899d2aa4..f67f8a2b5 100644--- a/sdk/javascript/src/http.ts+++ b/sdk/javascript/src/http.ts@@ -130,3 +130,24 @@ export async function request<T>(return text as unknown as T;}}++const LOCALHOST_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);++/**+ * Warn (NOT throw) when a URL is `http://` and the host is not localhost. The API key is sent as+ * an `X-API-Key` header on every request — over plaintext http to a non-local host that's cleartext+ * on the wire. Warning (not refusing) keeps local dev and TLS-terminating-proxy topologies working.+ */+export function warnIfInsecureHttpUrl(url: string, label = 'baseUrl'): void {+ try {+ const parsed = new URL(url);+ if (parsed.protocol === 'http:' && !LOCALHOST_HOSTS.has(parsed.hostname.toLowerCase())) {+ console.warn(+ `[OpenWA SDK] ${label} uses an insecure http:// URL (host: ${parsed.hostname}). ` ++ 'The API key will be sent in cleartext. Use https:// in production.',+ );+ }+ } catch {+ // Unparseable — the request will fail downstream with a clear error.+ }+}diff --git a/sdk/javascript/src/index.ts b/sdk/javascript/src/index.tsindex 2612b2f69..7fb9f92ed 100644--- a/sdk/javascript/src/index.ts+++ b/sdk/javascript/src/index.ts@@ -29,4 +29,4 @@ export type { OpenWAClientOptions } from './client.js';export * from './errors.js';export type * from './types.js';export type { ClientConfig, FetchLike, HttpMethod, RequestOptions } from './http.js';-export { buildUrl } from './http.js';+export { buildUrl, warnIfInsecureHttpUrl } from './http.js';diff --git a/sdk/php/src/Client.php b/sdk/php/src/Client.phpindex 3ba37d91a..cfca3c441 100644--- a/sdk/php/src/Client.php+++ b/sdk/php/src/Client.php@@ -84,6 +84,8 @@ class Clientthrow new OpenWAException('OpenWA Client: apiKey is required');}+ self::warnIfInsecureHttp($config['baseUrl']);+$this->http = new HttpExecutor($config['baseUrl'],$config['apiKey'],@@ -107,6 +109,28 @@ class Client$this->templates = new TemplatesResource($this->http);}+ /**+ * Warn (not throw) when baseUrl is http:// and the host is not localhost. The API key is sent+ * as an X-API-Key header on every request — over plaintext http to a non-local host that's+ * cleartext on the wire. Warning (not refusing) keeps local dev and TLS-terminating-proxy+ * topologies working.+ */+ private static function warnIfInsecureHttp(string $url): void+ {+ $scheme = \parse_url($url, \PHP_URL_SCHEME);+ $host = \parse_url($url, \PHP_URL_HOST);+ if ($scheme === 'http' && $host !== null && $host !== false) {+ $host = \trim($host, '[]');+ if (!\in_array($host, ['localhost', '127.0.0.1', '::1'], true)) {+ \trigger_error(+ "OpenWA Client: baseUrl uses an insecure http:// URL (host: {$host}). "+ . 'The API key will be sent in cleartext. Use https:// in production.',+ \E_USER_WARNING+ );+ }+ }+ }+/** Validate the configured API key and resolve its role. */public function auth(): array{diff --git a/sdk/php/tests/ClientTest.php b/sdk/php/tests/ClientTest.phpindex ef95178f6..0bc65984e 100644--- a/sdk/php/tests/ClientTest.php+++ b/sdk/php/tests/ClientTest.php@@ -21,7 +21,7 @@ class ClientTest extends TestCasepublic function testRequiresApiKey(): void{$this->expectException(\OpenWA\Exceptions\OpenWAException::class);- new \OpenWA\Client(['baseUrl' => 'http://x', 'apiKey' => '']);+ new \OpenWA\Client(['baseUrl' => 'https://x', 'apiKey' => '']);}public function testSendsApiKeyHeader(): void@@ -38,7 +38,7 @@ class ClientTest extends TestCase{$backend = (new MockBackend())->on(200, []);$client = new \OpenWA\Client([- 'baseUrl' => 'http://x',+ 'baseUrl' => 'https://x','apiKey' => 'REAL_KEY','httpClient' => $backend->httpClient(),'defaultHeaders' => ['X-Trace' => 'keep', 'X-API-Key' => 'EVIL'],diff --git a/sdk/python/openwa/client.py b/sdk/python/openwa/client.pyindex 15256ea05..39b57fb50 100644--- a/sdk/python/openwa/client.py+++ b/sdk/python/openwa/client.py@@ -23,8 +23,10 @@ monkey-patching required.from __future__ import annotations+import warningsfrom types import TracebackTypefrom typing import Any, Mapping+from urllib.parse import urlparseimport httpx@@ -47,6 +49,29 @@ from .resources import (from .types import AuthValidateResponse+_LOCALHOST_HOSTS = {"localhost", "127.0.0.1", "::1"}+++def _warn_if_insecure_http(url: str) -> None:+ """Warn (not raise) when base_url is http:// and the host is not localhost.++ The API key is sent as an X-API-Key header on every request — over plaintext http+ to a non-local host that's cleartext on the wire. Warning (not refusing) keeps local+ dev and TLS-terminating-proxy topologies working.+ """+ try:+ parsed = urlparse(url)+ host = (parsed.hostname or "").strip("[]")+ if parsed.scheme == "http" and host not in _LOCALHOST_HOSTS:+ warnings.warn(+ f"OpenWAClient: base_url uses an insecure http:// URL (host: {host}). "+ "The API key will be sent in cleartext. Use https:// in production.",+ stacklevel=3,+ )+ except Exception:+ pass++class OpenWAClient:def __init__(self,@@ -61,6 +86,7 @@ class OpenWAClient:raise ValueError("OpenWAClient: base_url is required")if not api_key:raise ValueError("OpenWAClient: api_key is required")+ _warn_if_insecure_http(base_url)self._http = HttpExecutor(base_url=base_url,api_key=api_key,diff --git a/src/common/security/bull-board-auth.middleware.spec.ts b/src/common/security/bull-board-auth.middleware.spec.tsindex 892cd0212..55145156e 100644--- a/src/common/security/bull-board-auth.middleware.spec.ts+++ b/src/common/security/bull-board-auth.middleware.spec.ts@@ -1,15 +1,20 @@-import { UnauthorizedException, ForbiddenException } from '@nestjs/common';+import { HttpException, UnauthorizedException, ForbiddenException } from '@nestjs/common';import { ConfigService } from '@nestjs/config';import { Request, Response } from 'express';import { BullBoardAuthMiddleware } from './bull-board-auth.middleware';import { AuthService } from '../../modules/auth/auth.service';import { ApiKeyRole } from '../../modules/auth/entities/api-key.entity';+import { KeyRateLimiter } from '../../modules/mcp/mcp-rate-limit';++const res = {} as Response;++const reqFromIp = (ip: string, headers: Record<string, unknown> = {}): Request =>+ ({ headers, query: {}, ip, socket: { remoteAddress: ip } }) as unknown as Request;describe('BullBoardAuthMiddleware', () => {let mw: BullBoardAuthMiddleware;let authService: { validateApiKey: jest.Mock; hasPermission: jest.Mock };let configService: { get: jest.Mock };- const res = {} as Response;const reqWith = (headers: Record<string, unknown> = {}, query: Record<string, unknown> = {}): Request =>({ headers, query, ip: '127.0.0.1', socket: { remoteAddress: '127.0.0.1' } }) as unknown as Request;@@ -86,3 +91,99 @@ describe('BullBoardAuthMiddleware', () => {expect(authService.validateApiKey).not.toHaveBeenCalled();});});++// Bull Board is raw Express middleware (outside the Nest guard pipeline) and previously had no pre-auth+// throttle, so a flood of login attempts reached the validateApiKey DB lookup unbounded. The throttle+// mirrors MCP's createIpThrottle: a per-IP sliding window checked BEFORE the credential check.+describe('BullBoardAuthMiddleware pre-auth IP throttle (mirrors MCP createIpThrottle)', () => {+ let authService: { validateApiKey: jest.Mock; hasPermission: jest.Mock };+ let configService: { get: jest.Mock };+ const res = {} as Response;++ beforeEach(() => {+ authService = { validateApiKey: jest.fn(), hasPermission: jest.fn() };+ configService = { get: jest.fn().mockReturnValue(undefined) };+ });++ const adminMw = (ipLimit: number): BullBoardAuthMiddleware => {+ authService.validateApiKey.mockResolvedValue({ role: ApiKeyRole.ADMIN });+ authService.hasPermission.mockReturnValue(true);+ return new BullBoardAuthMiddleware(+ authService as unknown as AuthService,+ configService as unknown as ConfigService,+ new KeyRateLimiter(ipLimit, 60_000),+ );+ };++ // Typed extractor for the first argument passed to a next() mock (avoids unsafe any member access).+ const firstNextArg = (mock: jest.Mock): unknown => (mock.mock.calls as Array<Array<unknown>>)[0]?.[0];++ it('N allowed, the (N+1)th from the same IP rejected with 429 (validateApiKey not reached)', async () => {+ const mw = adminMw(3);+ const headers = { 'x-api-key': 'admin' };++ // 3 allowed+ for (let i = 0; i < 3; i++) {+ const next = jest.fn();+ await mw.use(reqFromIp('198.51.100.4', headers), res, next);+ expect(next).toHaveBeenCalledWith(); // no error+ }+ expect(authService.validateApiKey).toHaveBeenCalledTimes(3);++ // 4th from the same IP → throttled before the credential check+ const next = jest.fn();+ await mw.use(reqFromIp('198.51.100.4', headers), res, next);+ expect(next).toHaveBeenCalledWith(expect.any(HttpException));+ expect((firstNextArg(next) as HttpException).getStatus()).toBe(429);+ // The throttled request never reached the DB lookup+ expect(authService.validateApiKey).toHaveBeenCalledTimes(3);+ });++ it('a second IP has an independent bucket', async () => {+ const mw = adminMw(2);+ const headers = { 'x-api-key': 'admin' };++ // Exhaust the bucket for 198.51.100.4+ for (let i = 0; i < 2; i++) {+ await mw.use(reqFromIp('198.51.100.4', headers), res, jest.fn());+ }+ const throttledNext = jest.fn();+ await mw.use(reqFromIp('198.51.100.4', headers), res, throttledNext);+ expect(firstNextArg(throttledNext)).toBeInstanceOf(HttpException);++ // A different IP is unaffected+ const otherNext = jest.fn();+ await mw.use(reqFromIp('203.0.113.9', headers), res, otherNext);+ expect(otherNext).toHaveBeenCalledWith(); // allowed+ expect(authService.validateApiKey).toHaveBeenCalledWith('admin', '203.0.113.9');+ });++ it('a missing key still consumes a throttle slot (pre-auth gate fires first)', async () => {+ const mw = adminMw(1);+ // First request: no key → Unauthorized, but the throttle slot is consumed (check runs before extractKey).+ const next1 = jest.fn();+ await mw.use(reqFromIp('198.51.100.4', {}), res, next1);+ expect(firstNextArg(next1)).toBeInstanceOf(UnauthorizedException);++ // Second request WITH a valid key from the same IP → throttled (bucket already exhausted by #1)+ const next2 = jest.fn();+ await mw.use(reqFromIp('198.51.100.4', { 'x-api-key': 'admin' }), res, next2);+ expect(firstNextArg(next2)).toBeInstanceOf(HttpException);+ expect((firstNextArg(next2) as HttpException).getStatus()).toBe(429);+ });++ it('the default limiter (no injection) is generous — legit operator usage is never throttled', async () => {+ // Mirrors production wiring (main.ts constructs with 2 args → MCP IP-rate-limit policy, 120/60s).+ // A single legit admin request passes; the bucket is shared across all existing happy-path tests+ // (each uses a fresh middleware instance), proving the default is wired and non-blocking.+ const defaultMw = new BullBoardAuthMiddleware(+ authService as unknown as AuthService,+ configService as unknown as ConfigService,+ );+ authService.validateApiKey.mockResolvedValue({ role: ApiKeyRole.ADMIN });+ authService.hasPermission.mockReturnValue(true);+ const next = jest.fn();+ await defaultMw.use(reqFromIp('203.0.113.9', { 'x-api-key': 'admin' }), res, next);+ expect(next).toHaveBeenCalledWith(); // allowed+ });+});diff --git a/src/common/security/bull-board-auth.middleware.ts b/src/common/security/bull-board-auth.middleware.tsindex 0c8f4b379..ba466636a 100644--- a/src/common/security/bull-board-auth.middleware.ts+++ b/src/common/security/bull-board-auth.middleware.ts@@ -3,6 +3,7 @@ import { ConfigService } from '@nestjs/config';import { Request, Response, NextFunction } from 'express';import { AuthService } from '../../modules/auth/auth.service';import { ApiKeyRole } from '../../modules/auth/entities/api-key.entity';+import { KeyRateLimiter, readIpRateLimitConfig } from '../../modules/mcp/mcp-rate-limit';import { resolveClientIp } from '../utils/ip';/**@@ -15,29 +16,52 @@ import { resolveClientIp } from '../utils/ip';** The ?apiKey query-string fallback was removed: an ADMIN key in the* URL leaks into proxy/access logs, browser history, bookmarks, and the Referer header.+ *+ * A pre-auth per-IP throttle (mirroring the MCP mount's createIpThrottle) bounds a credential-probing+ * flood BEFORE it reaches the validateApiKey DB lookup. It uses the same KeyRateLimiter + IP-rate-limit+ * settings as MCP, so the two raw-Express mounts share one generous pre-auth IP-flood policy.*/@Injectable()export class BullBoardAuthMiddleware implements NestMiddleware {+ private readonly ipRateLimiter: KeyRateLimiter;+constructor(private readonly authService: AuthService,private readonly configService: ConfigService,- ) {}+ ipRateLimiter?: KeyRateLimiter,+ ) {+ // Default to MCP's pre-auth per-IP policy (max 120 / 60s) when not supplied. Tests inject a tight+ // limiter; production (instantiated manually in main.ts) takes the default.+ this.ipRateLimiter = ipRateLimiter ?? BullBoardAuthMiddleware.createDefaultIpLimiter();+ }++ private static createDefaultIpLimiter(): KeyRateLimiter {+ const { max, windowMs } = readIpRateLimitConfig();+ return new KeyRateLimiter(max, windowMs);+ }async use(req: Request, _res: Response, next: NextFunction): Promise<void> {try {+ const clientIp = this.getClientIp(req);+ // Pre-auth, per-IP throttle — runs BEFORE the credential check so a login-attempt flood is rejected+ // before the DB lookup. Mirrors MCP's createIpThrottle. Throws HttpException(429) when exceeded;+ // forwarded to Nest's exception layer below as a standard 429.+ this.ipRateLimiter.check(clientIp);+const rawKey = this.extractKey(req);if (!rawKey) {throw new UnauthorizedException('API key is required to access the queue dashboard');}- const apiKey = await this.authService.validateApiKey(rawKey, this.getClientIp(req));+ const apiKey = await this.authService.validateApiKey(rawKey, clientIp);if (!this.authService.hasPermission(apiKey, ApiKeyRole.ADMIN)) {throw new ForbiddenException('Admin role required to access the queue dashboard');}next();} catch (err) {- // Forward to Nest's exception layer so the response uses the standard format.+ // Forward to Nest's exception layer so the response uses the standard format. A throttle overrun+ // surfaces here as an HttpException(429) → rendered as a standard 429 by the global exception filter.next(err);}}diff --git a/src/common/security/ssrf-guard.spec.ts b/src/common/security/ssrf-guard.spec.tsindex d1c8eee57..61fad01a7 100644--- a/src/common/security/ssrf-guard.spec.ts+++ b/src/common/security/ssrf-guard.spec.ts@@ -58,6 +58,9 @@ describe('isBlockedAddress', () => {['::ffff:0:7f00:1', 'IPv4-translatable loopback 127.0.0.1 (RFC6052, hex)'],['::ffff:0:127.0.0.1', 'IPv4-translatable loopback (RFC6052, dotted tail)'],['::ffff:0:a9fe:a9fe', 'IPv4-translatable cloud metadata 169.254.169.254 (RFC6052)'],+ ['0:0:0:0:0:ffff:7f00:1', 'fully-expanded IPv4-mapped loopback 127.0.0.1 (hex)'],+ ['0:0:0:0:0:ffff:127.0.0.1', 'fully-expanded IPv4-mapped loopback (dotted tail)'],+ ['0:0:0:0:0:ffff:a9fe:a9fe', 'fully-expanded IPv4-mapped cloud metadata 169.254.169.254'],])('blocks %s (%s)', ip => {expect(isBlockedAddress(ip)).toBe(true);});@@ -71,6 +74,8 @@ describe('isBlockedAddress', () => {['2002:0808:0808::', '6to4 of public 8.8.8.8 stays allowed'],['64:ff9b::0808:0808', 'NAT64 of public 8.8.8.8 stays allowed'],['::ffff:0:0808:0808', 'IPv4-translatable public 8.8.8.8 stays allowed'],+ ['0:0:0:0:0:ffff:0808:0808', 'fully-expanded IPv4-mapped public 8.8.8.8 stays allowed (hex)'],+ ['0:0:0:0:0:ffff:8.8.8.8', 'fully-expanded IPv4-mapped public 8.8.8.8 stays allowed (dotted)'],])('allows %s (%s)', ip => {expect(isBlockedAddress(ip)).toBe(false);});diff --git a/src/common/security/ssrf-guard.ts b/src/common/security/ssrf-guard.tsindex bd346a0b2..411f8a48a 100644--- a/src/common/security/ssrf-guard.ts+++ b/src/common/security/ssrf-guard.ts@@ -19,6 +19,22 @@ export class SsrfBlockedError extends Error {*/export const SSRF_BLOCKED_CLIENT_MESSAGE = 'Destination address is not allowed';+/**+ * Map an error to a client/surfaced message, redacting SSRF detail. An `SsrfBlockedError`'s message+ * names the resolved internal IP ("… resolves to a blocked internal address: 10.0.0.5") — a recon /+ * metadata-service probe oracle when surfaced verbatim to an HTTP response, a persisted DLQ row, or a+ * hook payload. Log the full detail server-side (when a `logger` is supplied) and return the generic+ * {@link SSRF_BLOCKED_CLIENT_MESSAGE} instead; any other error passes through verbatim so genuine+ * receiver failures (5xx, timeout, bad-zip) keep their actionable text.+ */+export function redactSsrfError(error: unknown, logger?: { warn: (message: string) => void }, site?: string): string {+ if (error instanceof SsrfBlockedError) {+ logger?.warn(`SSRF guard blocked ${site ?? 'an outbound fetch'}: ${error.message}`);+ return SSRF_BLOCKED_CLIENT_MESSAGE;+ }+ return error instanceof Error ? error.message : String(error);+}+/*** Outbound webhook SSRF protection. Default ON; disable only with an explicit* WEBHOOK_SSRF_PROTECT=false (e.g. a closed network that delivers to internal sidecars — prefer@@ -172,6 +188,20 @@ export function isBlockedAddress(ip: string): boolean {) {return isBlockedAddress(hextetsToV4(hextets[6], hextets[7]));}+ // Fully-expanded IPv4-mapped (::ffff:0:0/96 → 0:0:0:0:0:ffff:X:X): the compressed "::ffff:"+ // form is caught by the prefix check above, but the fully-expanded literal bypasses it.+ // Distinct from IPv4-compat (idx5 has no 0xffff) and RFC6052 (0xffff at idx4, not idx5).+ // Classify by the embedded IPv4 (public stays allowed).+ if (+ hextets[0] === 0 &&+ hextets[1] === 0 &&+ hextets[2] === 0 &&+ hextets[3] === 0 &&+ hextets[4] === 0 &&+ hextets[5] === 0xffff+ ) {+ return isBlockedAddress(hextetsToV4(hextets[6], hextets[7]));+ }}return false;}diff --git a/src/common/storage/storage.service.spec.ts b/src/common/storage/storage.service.spec.tsindex 3d72d6b11..72bdc7b90 100644--- a/src/common/storage/storage.service.spec.ts+++ b/src/common/storage/storage.service.spec.ts@@ -209,3 +209,36 @@ describe('StorageService import resource caps (decompression-bomb defense)', ()expect(count).toBe(1);});});++describe('StorageService local traversal (async + bounded)', () => {+ let baseDir: string;+ let service: StorageService;++ beforeEach(() => {+ ({ service, baseDir } = makeLocalService());+ });++ afterEach(() => {+ fs.rmSync(baseDir, { recursive: true, force: true });+ delete process.env.STORAGE_LIST_MAX_FILES;+ });++ it('lists files across nested subdirectories (async traversal)', async () => {+ await service.putFile('a.txt', Buffer.from('a'));+ await service.putFile('sub/b.txt', Buffer.from('b'));+ await service.putFile('sub/deep/c.txt', Buffer.from('c'));++ const files = await service.listFiles();+ expect(files.sort()).toEqual(['a.txt', 'sub/b.txt', 'sub/deep/c.txt']);+ });++ it('stops at the STORAGE_LIST_MAX_FILES cap instead of enumerating a huge tree', 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 files = await service.listFiles();+ expect(files.length).toBe(5); // capped, not 20+ });+});diff --git a/src/common/storage/storage.service.ts b/src/common/storage/storage.service.tsindex 45a916816..acaf9fe2e 100644--- a/src/common/storage/storage.service.ts+++ b/src/common/storage/storage.service.ts@@ -29,6 +29,10 @@ interface S3Config {const DEFAULT_IMPORT_MAX_BYTES = 200 * 1024 * 1024;/** Max number of entries an import archive may contain. Bounds an entry-count DoS. */const DEFAULT_IMPORT_MAX_ENTRIES = 100_000;+/** Max number of local files a single traversal enumerates. Bounds a count DoS on a huge media dir. */+const DEFAULT_LIST_MAX_FILES = 100_000;+/** Max directory depth a local traversal descends. Prevents a pathological tree from running unbounded. */+const LOCAL_TRAVERSAL_MAX_DEPTH = 20;function positiveIntFromEnv(name: string, fallback: number): number {const parsed = Number.parseInt(process.env[name] ?? '', 10);@@ -357,23 +361,38 @@ export class StorageService {// Local Storage Operations// ============================================================================- private listLocalFiles(dir = ''): string[] {- const fullPath = path.join(this.localPath, dir);+ /**+ * 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).+ */+ 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 }];- if (!fs.existsSync(fullPath)) {- return files;- }-- const entries = fs.readdirSync(fullPath, { withFileTypes: true });+ while (queue.length > 0) {+ const { dir, depth } = queue.shift()!;+ if (depth >= LOCAL_TRAVERSAL_MAX_DEPTH) continue;- for (const entry of entries) {- const relativePath = dir ? path.join(dir, entry.name) : entry.name;+ const fullPath = path.join(this.localPath, dir);+ let entries: fs.Dirent[];+ try {+ entries = await fs.promises.readdir(fullPath, { withFileTypes: true });+ } catch {+ continue; // dir vanished or unreadable — skip rather than abort the whole traversal+ }- if (entry.isDirectory()) {- files.push(...this.listLocalFiles(relativePath));- } else if (entry.isFile()) {- files.push(relativePath);+ for (const entry of entries) {+ const relativePath = dir ? path.join(dir, entry.name) : entry.name;+ 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+ }}}diff --git a/src/common/utils/secret-file.spec.ts b/src/common/utils/secret-file.spec.tsindex 2daab685a..aa38440f5 100644--- a/src/common/utils/secret-file.spec.ts+++ b/src/common/utils/secret-file.spec.ts@@ -38,4 +38,18 @@ describe('writeSecretFile', () => {expectOwnerOnly(p);expect(readFileSync(p, 'utf8')).toBe('new');});++ it('warns to the console when a chmod fails (does not stay silently world-readable)', () => {+ const p = join(dir, 'ghost');+ const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => undefined);++ // chmod a path that does not exist → ENOENT on the pre-write call. The write still succeeds+ // (create-mode), and the failure is surfaced via console.warn instead of being swallowed.+ writeSecretFile(p, 'secret');++ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('pre-write chmod 0o600 failed'));+ expect(readFileSync(p, 'utf8')).toBe('secret');++ warnSpy.mockRestore();+ });});diff --git a/src/common/utils/secret-file.ts b/src/common/utils/secret-file.tsindex 388719952..baaba53ef 100644--- a/src/common/utils/secret-file.ts+++ b/src/common/utils/secret-file.ts@@ -12,13 +12,16 @@ import { writeFileSync, chmodSync } from 'fs';export function writeSecretFile(filePath: string, content: string): void {try {chmodSync(filePath, 0o600);- } catch {- /* file not present yet, or unsupported — create-mode below covers a new file */+ } catch (error) {+ // file not present yet, or chmod unsupported — create-mode below covers a new file. Log the+ // failure so a world-readable secret on a chmod-unsupported FS (or an unexpected error) is+ // not silently left world-readable after a rewrite.+ console.warn(`[OpenWA] pre-write chmod 0o600 failed for ${filePath}: ${(error as Error).message}`);}writeFileSync(filePath, content, { mode: 0o600 });try {chmodSync(filePath, 0o600);- } catch {- /* best-effort */+ } catch (error) {+ console.warn(`[OpenWA] post-write chmod 0o600 failed for ${filePath}: ${(error as Error).message}`);}}diff --git a/src/config/env.validation.spec.ts b/src/config/env.validation.spec.tsindex 233402a01..bc199dac6 100644--- a/src/config/env.validation.spec.ts+++ b/src/config/env.validation.spec.ts@@ -146,4 +146,57 @@ describe('validateEnv', () => {}),).not.toThrow();});++ it('rejects DATABASE_SYNCHRONIZE=true with DATABASE_TYPE=postgres (drops body_ts → /search 501)', () => {+ // The Postgres data connection hardcodes migrationsRun=true; an opted-in synchronize=true makes+ // TypeORM re-sync from entities on every boot, dropping the migration-created `body_ts` generated+ // tsvector column (not declared on the Message entity) → /search 501 every restart. The breaking+ // combo must fail fast at boot.+ expect(() =>+ validateEnv({+ DATABASE_TYPE: 'postgres',+ DATABASE_HOST: 'db',+ DATABASE_USERNAME: 'u',+ DATABASE_PASSWORD: 'p',+ DATABASE_SYNCHRONIZE: 'true',+ }),+ ).toThrow(/DATABASE_SYNCHRONIZE.*postgres|migrations/);+ // The production default (synchronize=false / unset) is fine on Postgres.+ expect(() =>+ validateEnv({+ DATABASE_TYPE: 'postgres',+ DATABASE_HOST: 'db',+ DATABASE_USERNAME: 'u',+ DATABASE_PASSWORD: 'p',+ DATABASE_SYNCHRONIZE: 'false',+ }),+ ).not.toThrow();+ expect(() =>+ validateEnv({+ DATABASE_TYPE: 'postgres',+ DATABASE_HOST: 'db',+ DATABASE_USERNAME: 'u',+ DATABASE_PASSWORD: 'p',+ }),+ ).not.toThrow();+ // SQLite is migration-managed only when synchronize is unset/false, but the combo is NOT breaking+ // there (SQLite has no generated-column migration to drop), so it stays allowed.+ expect(() => validateEnv({ DATABASE_TYPE: 'sqlite', DATABASE_SYNCHRONIZE: 'true' })).not.toThrow();+ });++ it('rejects a bare SQLite DATABASE_NAME (PG-name leak) that has no path separator or file extension', () => {+ // Regression for #677: .env.example shipped `DATABASE_NAME=openwa` (a PostgreSQL db name).+ // In a SQLite run that bare name becomes the file PATH → SQLite opens a file named 'openwa'+ // under the read-only app rootfs → SQLITE_CANTOPEN boot-loop. The guard catches the leak at boot.+ expect(() => validateEnv({ DATABASE_TYPE: 'sqlite', DATABASE_NAME: 'openwa' })).toThrow(/file path/);+ expect(() => validateEnv({ DATABASE_TYPE: 'sqlite', DATABASE_NAME: 'prod_db' })).toThrow(/file path/);+ // A bare name WITH a .sqlite/.db suffix is a legitimate file in the cwd — let it pass.+ expect(() => validateEnv({ DATABASE_TYPE: 'sqlite', DATABASE_NAME: 'openwa.sqlite' })).not.toThrow();+ expect(() => validateEnv({ DATABASE_TYPE: 'sqlite', DATABASE_NAME: 'cache.db' })).not.toThrow();+ // A path (with a separator) is always honored, explicit host paths included.+ expect(() => validateEnv({ DATABASE_TYPE: 'sqlite', DATABASE_NAME: '/app/data/openwa.sqlite' })).not.toThrow();+ expect(() => validateEnv({ DATABASE_TYPE: 'sqlite', DATABASE_NAME: './data/openwa.sqlite' })).not.toThrow();+ // Unset falls through to the default path (configuration.ts) — the boot-loop fix.+ expect(() => validateEnv({ DATABASE_TYPE: 'sqlite' })).not.toThrow();+ });});diff --git a/src/config/env.validation.ts b/src/config/env.validation.tsindex e37f0dc65..ad039ce3c 100644--- a/src/config/env.validation.ts+++ b/src/config/env.validation.ts@@ -45,6 +45,18 @@ export function validateEnv(config: EnvConfig): EnvConfig {errors.push(`${key} is required when DATABASE_TYPE=postgres`);}}+ // The Postgres data connection always runs migrations (app.module.ts hardcodes migrationsRun=true).+ // An opted-in DATABASE_SYNCHRONIZE=true makes TypeORM re-sync the schema from entities on every+ // boot, which immediately DROPS the migration-created `body_ts` generated tsvector column (the+ // Message entity doesn't declare it) → /search returns 501 on every restart. Prod default is+ // synchronize=false; reject only the breaking combo. Read raw (no trim) to match the exact+ // `=== 'true'` comparison at configuration.ts so the guard fires precisely when synchronize would+ // actually be enabled downstream.+ if (config['DATABASE_SYNCHRONIZE'] === 'true') {+ errors.push(+ 'DATABASE_SYNCHRONIZE=true is not allowed with DATABASE_TYPE=postgres: the Postgres data connection always runs migrations, and synchronize would drop the migration-created body_ts tsvector column that /search depends on (returns 501 on every restart). Set DATABASE_SYNCHRONIZE=false (the production default) and manage the schema via migrations.',+ );+ }// POSTGRES_SCHEMA is optional (defaults to 'public' in configuration.ts). When set, validate it// is a legal, non-reserved Postgres identifier so a typo / injection-ish value fails fast at boot// rather than reaching CREATE TABLE "<schema>"."..." (or a search_path SET) at migration time.@@ -67,6 +79,17 @@ export function validateEnv(config: EnvConfig): EnvConfig {if (dataDbName && resolve(dataDbName) === resolve(MAIN_DB_PATH)) {errors.push(`DATABASE_NAME must not point at the main database file (${MAIN_DB_PATH}); use a separate file`);}+ // Reject a bare name with no path separator and no .sqlite/.db suffix — the exact signature of a+ // PostgreSQL DATABASE_NAME (e.g. 'openwa') leaking into a SQLite run (#677). That bare name becomes+ // the SQLite file PATH, opening a file named 'openwa' under the read-only app rootfs →+ // SQLITE_CANTOPEN boot-loop. A genuine SQLite path always has a separator or a file suffix.+ if (dataDbName && !dataDbName.includes('/') && !dataDbName.includes('\\') && !/\.(sqlite|db)$/i.test(dataDbName)) {+ errors.push(+ `DATABASE_NAME must be a file path under the data volume for SQLite (e.g. ./data/openwa.sqlite); got ${JSON.stringify(+ dataDbName,+ )}. A bare name is the PostgreSQL DB name — leave DATABASE_NAME unset for SQLite to use the default ./data/openwa.sqlite.`,+ );+ }}const checkPort = (key: string): void => {diff --git a/src/config/load-env.spec.ts b/src/config/load-env.spec.tsindex 6be9227ed..763752b74 100644--- a/src/config/load-env.spec.ts+++ b/src/config/load-env.spec.ts@@ -25,9 +25,12 @@ describe('loadEnvironment', () => {// The loader runs as a side effect on import; resetModules forces a fresh evaluation each call so a// test's mocked cwd/env is in effect when it runs (the spec never imports it statically, so it never// runs against the real project tree).- const runLoader = async (): Promise<void> => {+ // require() (not dynamic import()) so the relative specifier doesn't trip TS2835 under+ // moduleResolution:nodenext; jest.resetModules() above still forces a fresh module evaluation.+ const runLoader = (): void => {jest.resetModules();- await import('./load-env');+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ require('./load-env');};beforeEach(() => {@@ -45,24 +48,24 @@ describe('loadEnvironment', () => {}});- it('loads REDIS_HOST from a .env file so it reaches the webhook worker connection', async () => {+ it('loads REDIS_HOST from a .env file so it reaches the webhook worker connection', () => {delete process.env.REDIS_HOST;makeTempCwd({ '.env': 'REDIS_HOST=redis.internal\n', 'data/.env.generated': '' });- await runLoader();+ runLoader();expect(process.env.REDIS_HOST).toBe('redis.internal');expect(workerConnectionOptions().host).toBe('redis.internal');});- it('lets a real process env value win over the .env file (precedence preserved)', async () => {+ it('lets a real process env value win over the .env file (precedence preserved)', () => {process.env.REDIS_HOST = 'host-from-process-env';makeTempCwd({'.env': 'REDIS_HOST=host-from-dotenv\n','data/.env.generated': 'REDIS_HOST=host-from-generated\n',});- await runLoader();+ runLoader();expect(process.env.REDIS_HOST).toBe('host-from-process-env');expect(workerConnectionOptions().host).toBe('host-from-process-env');diff --git a/src/core/agent-tools/tool-invoker.spec.ts b/src/core/agent-tools/tool-invoker.spec.tsindex c0a58abf0..7cfe3a24e 100644--- a/src/core/agent-tools/tool-invoker.spec.ts+++ b/src/core/agent-tools/tool-invoker.spec.ts@@ -117,4 +117,72 @@ describe('invokeTool', () => {// No 5th argument — must not throwawait expect(invokeTool(readTool, { n: 1 }, 'rawkey', a as unknown as AuthService)).resolves.toBeDefined();});++ // onAuthFailure: MCP auth-failure audit hook (mirrors the REST ApiKeyGuard). Fires at the auth boundary+ // only — never on success, never on input-validation/handler errors (parity with the guard).+ describe('onAuthFailure callback (MCP auth-failure audit boundary)', () => {+ it('is invoked with the error on a missing key (Unauthorized)', async () => {+ const onAuthFailure = jest.fn();+ await expect(+ invokeTool(readTool, { n: 1 }, undefined, auth() as unknown as AuthService, undefined, onAuthFailure),+ ).rejects.toBeInstanceOf(UnauthorizedException);+ expect(onAuthFailure).toHaveBeenCalledTimes(1);+ expect((onAuthFailure.mock.calls[0] as unknown[])[0]).toBeInstanceOf(UnauthorizedException);+ });++ it('is invoked on a wrong-role rejection (Forbidden)', async () => {+ const a = auth();+ (a.hasPermission as jest.Mock).mockReturnValue(false);+ const onAuthFailure = jest.fn();+ const writeTool: ToolDescriptor = { ...readTool, tier: 'write', requiredRole: ApiKeyRole.OPERATOR };+ await expect(+ invokeTool(writeTool, { n: 1 }, 'rawkey', a as unknown as AuthService, undefined, onAuthFailure),+ ).rejects.toBeInstanceOf(ForbiddenException);+ expect(onAuthFailure).toHaveBeenCalledTimes(1);+ });++ it('is invoked when validateApiKey rejects (IP/revoked/expired/session-not-allowed)', async () => {+ const a = auth();+ (a.validateApiKey as jest.Mock).mockRejectedValueOnce(new UnauthorizedException('IP address not allowed'));+ const onAuthFailure = jest.fn();+ await expect(+ invokeTool(readTool, { n: 1 }, 'rawkey', a as unknown as AuthService, undefined, onAuthFailure),+ ).rejects.toBeInstanceOf(UnauthorizedException);+ expect(onAuthFailure).toHaveBeenCalledTimes(1);+ });++ it('is NOT invoked on a successful auth (happy path)', async () => {+ const onAuthFailure = jest.fn();+ await invokeTool(readTool, { n: 1 }, 'rawkey', auth() as unknown as AuthService, undefined, onAuthFailure);+ expect(onAuthFailure).not.toHaveBeenCalled();+ });++ it('is NOT invoked on a post-auth zod validation error (BadRequest)', async () => {+ const onAuthFailure = jest.fn();+ await expect(+ invokeTool(readTool, { n: 'bad' }, 'rawkey', auth() as unknown as AuthService, undefined, onAuthFailure),+ ).rejects.toBeInstanceOf(BadRequestException);+ expect(onAuthFailure).not.toHaveBeenCalled();+ });++ it('is NOT invoked when a tool handler throws after successful auth', async () => {+ const onAuthFailure = jest.fn();+ const throwingHandler: ToolDescriptor = {+ ...readTool,+ handler: () => Promise.reject(new ForbiddenException('handler-level forbid')),+ };+ await expect(+ invokeTool(throwingHandler, { n: 1 }, 'rawkey', auth() as unknown as AuthService, undefined, onAuthFailure),+ ).rejects.toBeInstanceOf(ForbiddenException);+ // A handler-thrown 403 is NOT an auth failure — must not be audited as api_key_auth_failed.+ expect(onAuthFailure).not.toHaveBeenCalled();+ });++ it('works without onAuthFailure (backward compatible)', async () => {+ // No 6th argument — a missing key still rejects without calling an undefined hook.+ await expect(invokeTool(readTool, { n: 1 }, undefined, auth() as unknown as AuthService)).rejects.toBeInstanceOf(+ UnauthorizedException,+ );+ });+ });});diff --git a/src/core/agent-tools/tool-invoker.ts b/src/core/agent-tools/tool-invoker.tsindex ed95f8216..a9aac59b1 100644--- a/src/core/agent-tools/tool-invoker.ts+++ b/src/core/agent-tools/tool-invoker.ts@@ -14,6 +14,11 @@ import type { ToolDescriptor } from './tool-descriptor';* after `validateApiKey` succeeds and BEFORE role/input checks. Use this to* key rate-limiters off the authenticated identity rather than the raw header* string, preventing pre-auth bucket allocation by anonymous callers.+ * @param onAuthFailure Optional callback invoked with the error when the AUTH+ * phase rejects (missing/invalid/revoked/expired key, wrong role, IP/session not+ * allowed). Mirrors the REST ApiKeyGuard's auth-failure hook (which records the+ * audit trail). Fires BEFORE input validation and the tool handler, so a 401/403+ * thrown from a handler body is NOT surfaced here. Re-thrown after the callback.*/export async function invokeTool(tool: ToolDescriptor,@@ -21,30 +26,42 @@ export async function invokeTool(rawKey: string | undefined,authService: AuthService,onAuthenticated?: (apiKeyId: string) => void,+ onAuthFailure?: (error: unknown) => void,): Promise<unknown> {- if (!rawKey) {- throw new UnauthorizedException('Missing API key');- }- // Pre-extract sessionId for the scope check BEFORE full validation (REST reads- // req.params.sessionId in the guard, before the pipe).- const probe = (rawInput ?? {}) as Record<string, unknown>;- const sessionId = tool.sessionScoped && typeof probe.sessionId === 'string' ? probe.sessionId : undefined;+ // AUTH PHASE — every rejection here is an authentication/authorization failure (the MCP analog of the+ // REST ApiKeyGuard's authorize()). Wrapped so onAuthFailure can record the audit trail at the boundary.+ let apiKey: Awaited<ReturnType<typeof authService.validateApiKey>>;+ try {+ if (!rawKey) {+ throw new UnauthorizedException('Missing API key');+ }+ // Pre-extract sessionId for the scope check BEFORE full validation (REST reads+ // req.params.sessionId in the guard, before the pipe).+ const probe = (rawInput ?? {}) as Record<string, unknown>;+ const sessionId = tool.sessionScoped && typeof probe.sessionId === 'string' ? probe.sessionId : undefined;- // Fail closed: a sessionScoped tool MUST carry a non-empty sessionId before auth. Otherwise an- // undefined scope would skip the per-key allowedSessions check inside validateApiKey, letting a- // session-restricted key drive the tool against any session. This enforces the fence at the runtime- // boundary regardless of an individual tool's input schema.- if (tool.sessionScoped && !sessionId) {- throw new BadRequestException('sessionId is required for this tool');- }+ // Fail closed: a sessionScoped tool MUST carry a non-empty sessionId before auth. Otherwise an+ // undefined scope would skip the per-key allowedSessions check inside validateApiKey, letting a+ // session-restricted key drive the tool against any session. This enforces the fence at the runtime+ // boundary regardless of an individual tool's input schema.+ if (tool.sessionScoped && !sessionId) {+ throw new BadRequestException('sessionId is required for this tool');+ }- const apiKey = await authService.validateApiKey(rawKey, undefined, sessionId);- onAuthenticated?.(apiKey.id);+ apiKey = await authService.validateApiKey(rawKey, undefined, sessionId);+ onAuthenticated?.(apiKey.id);- if (tool.requiredRole && !authService.hasPermission(apiKey, tool.requiredRole)) {- throw new ForbiddenException('API key lacks the required role');+ if (tool.requiredRole && !authService.hasPermission(apiKey, tool.requiredRole)) {+ throw new ForbiddenException('API key lacks the required role');+ }+ } catch (error) {+ // auditMcpAuthFailure (the only current caller hook) filters to 401/403, so the BadRequestException+ // for a missing sessionId above is NOT audited (parity with the REST guard, which skips 400s).+ onAuthFailure?.(error);+ throw error;}+ // VALIDATION + HANDLER PHASE — not part of auth; their errors are not auth failures.let input: unknown;try {input = tool.inputSchema.parse(rawInput);diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.tsindex 8a90db1c7..06c5605a4 100644--- a/src/core/plugins/plugin-loader.service.ts+++ b/src/core/plugins/plugin-loader.service.ts@@ -25,6 +25,7 @@ import {PluginType,PluginLogger,validateIngressManifest,+ warnUnauthenticatedIngressRoutes,} from './plugin.interfaces';import { effectiveNetAllow, isNetHostAllowed, performPluginFetch } from './plugin-net';import { PluginStorageService } from './plugin-storage.service';@@ -249,6 +250,11 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {// load and become provisionable. No-op for plugins that declare no ingress.validateIngressManifest(manifest);+ // Surface a loud warning for any ingress route that skips signature verification — a scheme:'none'+ // route is a fully-unauthenticated public endpoint that can trigger WhatsApp sends. Additive (a+ // warning, not a refusal) so a legit scheme:'none' deployment still boots.+ warnUnauthenticatedIngressRoutes(manifest, this.logger);+// Check if plugin already loadedif (this.plugins.has(manifest.id)) {throw new Error(`Plugin ${manifest.id} is already loaded`);diff --git a/src/core/plugins/plugin-manifest-ingress.spec.ts b/src/core/plugins/plugin-manifest-ingress.spec.tsindex 3a7d9e0ac..d78f12d79 100644--- a/src/core/plugins/plugin-manifest-ingress.spec.ts+++ b/src/core/plugins/plugin-manifest-ingress.spec.ts@@ -1,4 +1,4 @@-import { validateIngressManifest, SUPPORTED_SDK_MAJOR } from './plugin.interfaces';+import { validateIngressManifest, SUPPORTED_SDK_MAJOR, warnUnauthenticatedIngressRoutes } from './plugin.interfaces';const baseManifest = () => ({id: 'chatwoot',@@ -55,3 +55,29 @@ describe('validateIngressManifest', () => {expect(() => validateIngressManifest(m as never)).toThrow(/duplicate/i);});});++describe('warnUnauthenticatedIngressRoutes', () => {+ it('warns once per scheme:none route, naming the plugin and route', () => {+ const logger = { warn: jest.fn() };+ const m = baseManifest();+ (m.ingress[0].signature as { scheme: string }).scheme = 'none';+ warnUnauthenticatedIngressRoutes(m as never, logger);+ expect(logger.warn).toHaveBeenCalledTimes(1);+ expect(logger.warn).toHaveBeenCalledWith(+ expect.stringMatching(/UNAUTHENTICATED/i),+ expect.objectContaining({ pluginId: 'chatwoot', route: 'chatwoot', action: 'ingress_unauthenticated_route' }),+ );+ });++ it('does not warn for an authenticated scheme', () => {+ const logger = { warn: jest.fn() };+ warnUnauthenticatedIngressRoutes(baseManifest() as never, logger);+ expect(logger.warn).not.toHaveBeenCalled();+ });++ it('is a no-op for a manifest with no ingress routes', () => {+ const logger = { warn: jest.fn() };+ warnUnauthenticatedIngressRoutes({ id: 'x', name: 'X', version: '1.0.0', main: 'i.js' } as never, logger);+ expect(logger.warn).not.toHaveBeenCalled();+ });+});diff --git a/src/core/plugins/plugin-net.spec.ts b/src/core/plugins/plugin-net.spec.tsindex 5d7a4f1e1..3f3ff8f32 100644--- a/src/core/plugins/plugin-net.spec.ts+++ b/src/core/plugins/plugin-net.spec.ts@@ -6,7 +6,7 @@ function fakeSafeFetch(response: Response, sink: { init?: RequestInit }): typeofreturn (<T>(_url: string, init: RequestInit, use: (r: Response) => Promise<T> | T): Promise<T> => {sink.init = init;return Promise.resolve(use(response));- }) as typeof withSafeFetch;+ }) as unknown as typeof withSafeFetch;}function cannedResponse(body: string, headers: Record<string, string>, status = 200): Response {@@ -102,7 +102,7 @@ describe('performPluginFetch', () => {let release!: () => void;const gate = new Promise<void>(r => (release = r));const blocking = (<T>(_url: string, _init: RequestInit, use: (r: Response) => Promise<T> | T): Promise<T> =>- gate.then(() => use(cannedResponse('{}', {})))) as typeof withSafeFetch;+ gate.then(() => use(cannedResponse('{}', {})))) as unknown as typeof withSafeFetch;const inflight: Promise<unknown>[] = [];for (let i = 0; i < 16; i++) {diff --git a/src/core/plugins/plugin.interfaces.ts b/src/core/plugins/plugin.interfaces.tsindex 1bfc3dcfb..aec44c42d 100644--- a/src/core/plugins/plugin.interfaces.ts+++ b/src/core/plugins/plugin.interfaces.ts@@ -258,6 +258,29 @@ export function validateIngressManifest(manifest: PluginManifest): void {}}+/**+ * Warns about each ingress route declared with `scheme: 'none'` — a fully-unauthenticated public endpoint+ * that anyone who can reach the host can use to trigger WhatsApp sends. Purely additive (a warning): a+ * deployment that legitimately relies on scheme:'none' (a provider that offers no HMAC) still boots; the+ * loud log surfaces the exposure so an operator can front the URL with a network/reverse-proxy guard.+ * Called from PluginLoaderService.loadPlugin at boot and on dynamic install.+ */+export function warnUnauthenticatedIngressRoutes(+ manifest: PluginManifest,+ logger: { warn: (message: string, context?: Record<string, unknown>) => void },+): void {+ for (const r of manifest.ingress ?? []) {+ if (r.signature.scheme === 'none') {+ logger.warn(+ `Ingress route '${r.route}' of plugin '${manifest.id}' uses signature scheme 'none' — it is an ` ++ `UNAUTHENTICATED public endpoint that can trigger WhatsApp sends. Only keep this if the provider ` ++ `offers no HMAC and the URL is guarded by a network/reverse-proxy ACL.`,+ { pluginId: manifest.id, route: r.route, action: 'ingress_unauthenticated_route' },+ );+ }+ }+}+/*** Thrown by a plugin capability when a call is rejected (missing permission, out-of-scope session,* unstarted session, etc.). Gives plugins a predictable failure instead of a raw TypeError.diff --git a/src/database/data-source-main.spec.ts b/src/database/data-source-main.spec.tsindex 9e4ca0bfb..aa34b22ca 100644--- a/src/database/data-source-main.spec.ts+++ b/src/database/data-source-main.spec.ts@@ -1,6 +1,6 @@import mainDataSource from './data-source-main';-// The app runs the MAIN connection (auth + audit) as a separate always-SQLite connection. The+// The app runs the MAIN connection (auth/audit) as a separate always-SQLite connection. The// default data-source.ts CLI only manages the DATA connection's migrations, so this standalone// DataSource exists so the CLI can run/generate the main-owned migrations too.describe('main CLI DataSource', () => {@@ -18,4 +18,38 @@ describe('main CLI DataSource', () => {expect(entities).toContain('auth');expect(entities).toContain('audit');});++ // jest.resetModules() + a typed require forces a fresh evaluation of the module with the env var+ // we set, proving MAIN_DATABASE_NAME flows into the DataSource options (not just the cached+ // top-level import, which was evaluated with whatever env existed at spec load).+ it("defaults to './data/main.sqlite' when MAIN_DATABASE_NAME is unset", () => {+ const previous = process.env.MAIN_DATABASE_NAME;+ delete process.env.MAIN_DATABASE_NAME;+ jest.resetModules();+ try {+ // require() (not dynamic import()) — the relative specifier trips TS2835 under+ // moduleResolution:nodenext; jest.resetModules() above still forces a fresh evaluation.+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const mod = require('./data-source-main') as typeof import('./data-source-main');+ expect(String(mod.default.options.database)).toBe('./data/main.sqlite');+ } finally {+ if (previous !== undefined) process.env.MAIN_DATABASE_NAME = previous;+ }+ });++ it('honors MAIN_DATABASE_NAME when set (mirrors configuration.ts)', () => {+ const previous = process.env.MAIN_DATABASE_NAME;+ process.env.MAIN_DATABASE_NAME = '/tmp/test-main.sqlite';+ jest.resetModules();+ try {+ // require() (not dynamic import()) — the relative specifier trips TS2835 under+ // moduleResolution:nodenext; jest.resetModules() above still forces a fresh evaluation.+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const mod = require('./data-source-main') as typeof import('./data-source-main');+ expect(String(mod.default.options.database)).toBe('/tmp/test-main.sqlite');+ } finally {+ if (previous !== undefined) process.env.MAIN_DATABASE_NAME = previous;+ else delete process.env.MAIN_DATABASE_NAME;+ }+ });});diff --git a/src/database/data-source-main.ts b/src/database/data-source-main.tsindex 630f13e58..40e0629a0 100644--- a/src/database/data-source-main.ts+++ b/src/database/data-source-main.ts@@ -20,9 +20,10 @@ loadCliEnv();*/const mainDataSource = new DataSource({type: 'sqlite',- // Hardcoded to match the runtime main path (configuration.ts), so the CLI and the app never target+ // Mirrors the runtime main path (configuration.ts) — MAIN_DATABASE_NAME overrides the default+ // ./data/main.sqlite (e.g. e2e points it at a temp file), so the CLI and the app never target// different main databases.- database: './data/main.sqlite',+ database: process.env.MAIN_DATABASE_NAME || './data/main.sqlite',entities: [__dirname + '/../modules/auth/**/*.entity{.ts,.js}', __dirname + '/../modules/audit/**/*.entity{.ts,.js}'],migrations: [__dirname + '/migrations-main/*{.ts,.js}'],synchronize: false,diff --git a/src/engine/adapters/baileys-session-store.ts b/src/engine/adapters/baileys-session-store.tsindex 21e74d819..57c5d769c 100644--- a/src/engine/adapters/baileys-session-store.ts+++ b/src/engine/adapters/baileys-session-store.ts@@ -147,9 +147,11 @@ export class BaileysSessionStore {* Best-effort read of a message's disappearing timer (seconds). `WebMessageInfo.ephemeralDuration` is* populated on history-synced messages but is typically ABSENT on a live 1:1 `messages.upsert`, so fall* back to the per-message `contextInfo.expiration` WhatsApp stamps on every message in a disappearing- * chat — read after unwrapping the ephemeral / view-once / document-with-caption envelope.+ * chat — read after unwrapping the ephemeral / view-once / document-with-caption envelope. Exposed so+ * the history-backfill mapper can populate the same signal the live path uses, without duplicating the+ * extraction.*/- private extractEphemeralDuration(msg: WAMessage): number | undefined {+ extractEphemeralDuration(msg: WAMessage): number | undefined {const fromInfo = msg.ephemeralDuration;if (typeof fromInfo === 'number' && fromInfo > 0) {return fromInfo;diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex f47950e0f..f7eb8b76f 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -1360,6 +1360,10 @@ export class BaileysAdapter implements IWhatsAppEngine {timestamp: this.toUnixSeconds(msg.messageTimestamp),pushName: msg.pushName ?? undefined,selfJid: this.normalizedSelfJid(),+ // Populate the disappearing-messages timer using the same extraction the live path and the+ // session-store cache share (`msg.ephemeralDuration` primary, `contextInfo.expiration` fallback),+ // so the history sink can apply the STORE_EPHEMERAL_MESSAGES opt-out symmetrically with onMessage.+ ephemeralDuration: this.sessionStore.extractEphemeralDuration(msg),},jid => this.sessionStore.toNeutralJid(jid),);diff --git a/src/modules/audit/audit.controller.spec.ts b/src/modules/audit/audit.controller.spec.tsindex a0937efb7..1e457bd47 100644--- a/src/modules/audit/audit.controller.spec.ts+++ b/src/modules/audit/audit.controller.spec.ts@@ -10,7 +10,7 @@ describe('AuditController access control', () => {it('GET /audit requires the ADMIN role', () => {// Read the handler off the prototype as an opaque object so the lint unbound-method rule// (which guards against detached method `this`) doesn't fire on a metadata-only lookup.- const proto = AuditController.prototype as unknown as Record<string, object>;+ const proto = AuditController.prototype as unknown as Record<string, (...args: unknown[]) => unknown>;const role = new Reflector().get<ApiKeyRole | undefined>(REQUIRED_ROLE_KEY, proto.findAll);expect(role).toBe(ApiKeyRole.ADMIN);});diff --git a/src/modules/auth/auth.service.spec.ts b/src/modules/auth/auth.service.spec.tsindex aeb3864a7..cd2f9c3f9 100644--- a/src/modules/auth/auth.service.spec.ts+++ b/src/modules/auth/auth.service.spec.ts@@ -213,6 +213,22 @@ describe('AuthService', () => {await expect(service.delete('nonexistent')).rejects.toThrow(NotFoundException);});++ it('evicts active WebSocket sockets authenticated with the deleted key', async () => {+ const evictApiKey = jest.fn();+ jest+ .spyOn((service as unknown as { moduleRef: { get: (...a: unknown[]) => unknown } }).moduleRef, 'get')+ .mockReturnValue({ evictApiKey });++ const key = createMockApiKey();+ (repository.findOne as jest.Mock).mockResolvedValue(key);+ (repository.remove as jest.Mock).mockResolvedValue(key);++ await service.delete('uuid-1');++ expect(repository.remove).toHaveBeenCalledWith(key);+ expect(evictApiKey).toHaveBeenCalledWith('uuid-1');+ });});describe('revoke', () => {@@ -225,6 +241,38 @@ describe('AuthService', () => {expect(result.isActive).toBe(false);});++ it('evicts active WebSocket sockets authenticated with the revoked key', async () => {+ const evictApiKey = jest.fn();+ jest+ .spyOn((service as unknown as { moduleRef: { get: (...a: unknown[]) => unknown } }).moduleRef, 'get')+ .mockReturnValue({ evictApiKey });++ const key = createMockApiKey({ isActive: true });+ (repository.findOne as jest.Mock).mockResolvedValue(key);+ (repository.save as jest.Mock).mockImplementation(k => Promise.resolve(k));++ await service.revoke('uuid-1');++ expect(key.isActive).toBe(false);+ expect(evictApiKey).toHaveBeenCalledWith('uuid-1');+ });++ it('does not roll back the revoke if WebSocket eviction throws (best-effort)', async () => {+ jest+ .spyOn((service as unknown as { moduleRef: { get: (...a: unknown[]) => unknown } }).moduleRef, 'get')+ .mockImplementation(() => {+ throw new Error('gateway unavailable');+ });++ const key = createMockApiKey({ isActive: true });+ (repository.findOne as jest.Mock).mockResolvedValue(key);+ (repository.save as jest.Mock).mockImplementation(k => Promise.resolve(k));++ const result = await service.revoke('uuid-1');++ expect(result.isActive).toBe(false); // revoke still succeeded+ });});// ── validateApiKey ────────────────────────────────────────────────diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.tsindex e2bbcfd50..42d75aa27 100644--- a/src/modules/auth/auth.service.ts+++ b/src/modules/auth/auth.service.ts@@ -1,4 +1,5 @@import { Injectable, NotFoundException, UnauthorizedException, OnModuleInit } from '@nestjs/common';+import { ModuleRef } from '@nestjs/core';import { InjectRepository } from '@nestjs/typeorm';import { Repository } from 'typeorm';import { randomBytes } from 'crypto';@@ -10,6 +11,7 @@ import { hashApiKey } from './api-key-hash';import { ApiKey, ApiKeyRole } from './entities/api-key.entity';import { CreateApiKeyDto, UpdateApiKeyDto } from './dto';import { createLogger } from '../../common/services/logger.service';+import { EventsGateway } from '../events/events.gateway';const API_KEY_FILE = join(process.cwd(), 'data', '.api-key');@@ -55,6 +57,7 @@ export class AuthService implements OnModuleInit {constructor(@InjectRepository(ApiKey, 'main')private readonly apiKeyRepository: Repository<ApiKey>,+ private readonly moduleRef: ModuleRef,) {}async onModuleInit(): Promise<void> {@@ -184,6 +187,7 @@ export class AuthService implements OnModuleInit {// 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.evictActiveSockets(id);this.logger.log(`API key deleted: ${apiKey.name}`, {keyId: id,action: 'api_key_deleted',@@ -196,7 +200,32 @@ export class AuthService implements OnModuleInit {// drop it here.this.pendingUsage.delete(id);apiKey.isActive = false;- return this.apiKeyRepository.save(apiKey);+ const saved = await this.apiKeyRepository.save(apiKey);+ // 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);+ return saved;+ }++ /**+ * Disconnect every WebSocket socket authenticated with the given key id. Resolved lazily via+ * ModuleRef (not constructor injection) to avoid a static DI cycle between AuthModule and+ * EventsModule. Best-effort: if the WS gateway isn't loaded (or has no sockets for the key),+ * this is a silent no-op.+ */+ private evictActiveSockets(keyId: string): void {+ try {+ const gateway = this.moduleRef.get(EventsGateway, { strict: false });+ if (gateway) {+ gateway.evictApiKey(keyId);+ }+ } catch (error) {+ // Eviction is best-effort: the key's DB state is already authoritative (validateApiKey+ // rejects it), so a failure here must never roll back the revoke/delete.+ this.logger.warn(`Failed to evict WebSocket sockets for key ${keyId}`, {+ error: error instanceof Error ? error.message : String(error),+ });+ }}async validateApiKey(rawKey: string, clientIp?: string, sessionId?: string): Promise<ApiKey> {diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.tsindex 431d45fab..926c8409d 100644--- a/src/modules/events/events.gateway.spec.ts+++ b/src/modules/events/events.gateway.spec.ts@@ -225,6 +225,85 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {expect(res.code).toBe('FORBIDDEN_SESSION');expect(sock.join).not.toHaveBeenCalled();});++ // Client-IP resolution: an IP-restricted key (allowedIps set) must be ENFORCED at the WS surface,+ // not blanket-rejected. validateApiKey throws "Client IP could not be determined" when allowedIps is+ // set but no clientIp is supplied — so the gateway must pass the trusted-proxy-aware IP at connect+ // and at subscribe re-validation. Without the fix every IP-restricted key was locked out of WS.+ it('passes the trusted-proxy-aware client IP to validateApiKey at connect (RED-without-fix: undefined)', async () => {+ authService.validateApiKey.mockResolvedValue({ id: 'k1', name: 'k', allowedSessions: null });+ const sock = makeSocket({ apiKey: 'good' }); // address defaults to 203.0.113.5+ await gateway.handleConnection(asSocket(sock));+ expect(authService.validateApiKey).toHaveBeenCalledWith('good', '203.0.113.5');+ expect(sock.disconnect).not.toHaveBeenCalled();+ });++ it('passes the resolved client IP to validateApiKey on subscribe re-validation', async () => {+ authService.validateApiKey.mockResolvedValue({ id: 'k1', name: 'k', allowedSessions: null });+ const sock = makeSocket({ apiKey: 'good' });+ await gateway.handleConnection(asSocket(sock));+ authService.validateApiKey.mockClear();+ await gateway.handleMessage(asSocket(sock), subscribeMsg('sess-1', ['message.received']));+ expect(authService.validateApiKey).toHaveBeenCalledWith('good', '203.0.113.5');+ });++ it('honors TRUSTED_PROXIES + X-Forwarded-For when resolving the WS client IP', async () => {+ const prev = process.env.TRUSTED_PROXIES;+ process.env.TRUSTED_PROXIES = '10.0.0.1';+ try {+ authService.validateApiKey.mockResolvedValue({ id: 'k1', name: 'k', allowedSessions: null });+ const sock = makeSocket({ apiKey: 'good' });+ sock.handshake.address = '10.0.0.1'; // immediate peer is the trusted proxy+ sock.handshake.headers['x-forwarded-for'] = '198.51.100.7';+ await gateway.handleConnection(asSocket(sock));+ expect(authService.validateApiKey).toHaveBeenCalledWith('good', '198.51.100.7');+ } finally {+ process.env.TRUSTED_PROXIES = prev;+ }+ });++ // Revocation teardown: a revoked key's already-subscribed sockets are evicted immediately,+ // with a clean close (an UNAUTHORIZED reason) rather than lingering until natural disconnect.+ describe('evictApiKey (revoke/disable socket teardown)', () => {+ it('disconnects every active socket authenticated with the revoked key', async () => {+ authService.validateApiKey.mockResolvedValue({ id: 'k1', name: 'k', allowedSessions: null });+ const sock = makeSocket({ apiKey: 'good' });+ await gateway.handleConnection(asSocket(sock));+ expect(sock.disconnect).not.toHaveBeenCalled();++ gateway.evictApiKey('k1');++ expect(sock.disconnect).toHaveBeenCalledWith(true);+ expect(sock.emit).toHaveBeenCalledWith('message', expect.objectContaining({ code: 'UNAUTHORIZED' }));+ });++ it('does NOT evict sockets authenticated with a different (still-active) key', async () => {+ authService.validateApiKey.mockResolvedValue({ id: 'k1', name: 'k', allowedSessions: null });+ const sock = makeSocket({ apiKey: 'good' });+ await gateway.handleConnection(asSocket(sock));++ gateway.evictApiKey('some-other-key');++ expect(sock.disconnect).not.toHaveBeenCalled();+ });++ it('is a no-op when no sockets are tracked for the key', () => {+ expect(() => gateway.evictApiKey('nobody')).not.toThrow();+ });++ it('cleans up tracking on disconnect so an evicted key holds no stale socket refs', async () => {+ authService.validateApiKey.mockResolvedValue({ id: 'k1', name: 'k', allowedSessions: null });+ const sock = makeSocket({ apiKey: 'good' });+ await gateway.handleConnection(asSocket(sock));++ gateway.evictApiKey('k1');+ // Socket.IO fires the disconnect handler on disconnect(true); simulate it here to confirm+ // untracking is idempotent and leaves no dangling references.+ gateway.handleDisconnect(asSocket(sock));++ expect(() => gateway.evictApiKey('k1')).not.toThrow();+ });+ });});// A capturing, chainable Socket.IO server stub: server.to(r1).to(r2)...emit(...) all@@ -243,7 +322,11 @@ const makeCapturingServer = () => {};describe('EventsGateway.emitToRooms fan-out', () => {- const gw = () => new EventsGateway({ validateApiKey: jest.fn() } as unknown as AuthService);+ const gw = () =>+ new EventsGateway(+ { validateApiKey: jest.fn() } as unknown as AuthService,+ { logWarn: jest.fn().mockResolvedValue(null) } as unknown as AuditService,+ );it('delivers one event with a single broadcast across all four rooms (no per-room duplicate emit)', () => {const gateway = gw();@@ -276,7 +359,10 @@ describe('event catalog ⇔ emitter invariants (drift guard)', () => {// method against a capturing server. Reflection-based so it cannot rot: a new emit*// method is auto-discovered; an advertised-but-unemitted event fails the equality.const deriveEmittedEvents = (): Set<string> => {- const gateway = new EventsGateway({ validateApiKey: jest.fn() } as unknown as AuthService);+ const gateway = new EventsGateway(+ { validateApiKey: jest.fn() } as unknown as AuthService,+ { logWarn: jest.fn().mockResolvedValue(null) } as unknown as AuditService,+ );const captured: string[] = [];const op: { to: () => unknown; emit: (ch: string, msg: WSEventMessage) => boolean } = {to: () => op,diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex 99ac7f42c..6ce1895b0 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -14,6 +14,8 @@ import { AuthService } from '../auth/auth.service';import { AuditService } from '../audit/audit.service';import { AuditAction } from '../audit/entities/audit-log.entity';import { resolveCorsPolicy } from '../../config/bootstrap-security';+import { resolveClientIp as resolveRequestClientIp, type RequestLike } from '../../common/utils/ip';+import type { ApiKey } from '../auth/entities/api-key.entity';/*** WebSocket CORS origin: reuse the HTTP CORS policy instead of a hardcoded '*'.@@ -24,6 +26,17 @@ function resolveWsCorsOrigin(): boolean | string[] {const policy = resolveCorsPolicy(process.env.CORS_ORIGINS, process.env.NODE_ENV);return policy.allowAnyOrigin ? true : policy.origins;}++/**+ * Read TRUSTED_PROXIES once as a list — mirrors mcp.server.ts so the WS surface resolves the+ * client IP with the same trusted-proxy-aware logic as the REST guard and the MCP mount.+ */+function readTrustedProxies(): string[] {+ return (process.env.TRUSTED_PROXIES ?? '')+ .split(',')+ .map(s => s.trim())+ .filter(Boolean);+}import type {WSClientMessage,WSSubscribeRequest,@@ -66,6 +79,13 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGateprivate logger = new Logger('EventsGateway');+ /**+ * Active sockets keyed by their validating API-key id, so a key revoked/disabled+ * mid-connection can have its live subscriptions torn down immediately (otherwise+ * an already-subscribed socket keeps receiving events until it happens to disconnect).+ */+ private readonly socketsByKeyId = new Map<string, Set<Socket>>();+constructor(private readonly authService: AuthService,private readonly auditService: AuditService,@@ -75,16 +95,72 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatethis.logger.log('WebSocket Gateway initialized');}+ /**+ * Resolve the trusted-proxy-aware client IP for a socket, reusing the same shared+ * `resolveClientIp` helper as the REST guard and MCP mount. X-Forwarded-For is only+ * honored when the immediate peer is a configured trusted proxy, preventing IP-spoofing+ * of the allowedIps allowlist over the WS surface.+ */+ private resolveClientIp(client: Socket): string {+ const handshake = client.handshake;+ const req: RequestLike = {+ ip: handshake.address,+ socket: { remoteAddress: handshake.address },+ headers: handshake.headers ?? {},+ };+ return resolveRequestClientIp(req, readTrustedProxies());+ }++ private trackSocket(keyId: string, client: Socket): void {+ let sockets = this.socketsByKeyId.get(keyId);+ if (!sockets) {+ sockets = new Set();+ this.socketsByKeyId.set(keyId, sockets);+ }+ sockets.add(client);+ }++ private untrackSocket(client: Socket): void {+ const keyId = (client.data as { apiKey?: Pick<ApiKey, 'id'> } | undefined)?.apiKey?.id;+ if (!keyId) return;+ const sockets = this.socketsByKeyId.get(keyId);+ if (!sockets) return;+ sockets.delete(client);+ if (sockets.size === 0) {+ this.socketsByKeyId.delete(keyId);+ }+ }++ /**+ * Tear down every active socket authenticated with `keyId`. Called by AuthService when a+ * key is revoked or deleted so the key's already-subscribed sockets stop receiving events+ * immediately instead of lingering until they disconnect on their own. Each socket gets a+ * clean close (an `UNAUTHORIZED` reason) rather than a silent drop.+ */+ evictApiKey(keyId: string): void {+ const sockets = this.socketsByKeyId.get(keyId);+ if (!sockets || sockets.size === 0) return;+ this.logger.log(`Evicting ${sockets.size} WebSocket connection(s) for revoked key ${keyId}`);+ this.socketsByKeyId.delete(keyId);+ for (const client of sockets) {+ client.emit('message', this.createError('UNAUTHORIZED', 'API key has been revoked'));+ client.disconnect(true);+ }+ }+async handleConnection(client: Socket) {// Accept the key only via Socket.IO's `auth` field or the header — never the query string, which// leaks the credential into proxy/access logs. (The deprecated `?apiKey=` fallback was removed.)const handshakeAuth = client.handshake.auth as { apiKey?: string } | undefined;const apiKey = handshakeAuth?.apiKey || (client.handshake.headers['x-api-key'] as string);+ // Resolve the client IP once here so both the validation and the audit trail use the same+ // trusted-proxy-aware value (parity with the REST guard / MCP mount).+ const clientIp = this.resolveClientIp(client);if (!apiKey) {this.logger.warn(`Client ${client.id} rejected: No API key provided`);void this.auditService.logWarn(AuditAction.API_KEY_AUTH_FAILED, {- ipAddress: client.handshake.address,+ ipAddress: clientIp,metadata: { surface: 'websocket' },errorMessage: 'missing API key',});@@ -95,13 +171,16 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatetry {// validateApiKey THROWS on any failure (it never resolves to a falsy value), so the rejection- // path is the catch below — a separate `if (!validKey)` branch here was dead code.- const validKey = await this.authService.validateApiKey(apiKey);+ // path is the catch below — a separate `if (!validKey)` branch here was dead code. The clientIp+ // is passed so an IP-restricted key (allowedIps set) is ENFORCED rather than blanket-rejected+ // for "Client IP could not be determined".+ const validKey = await this.authService.validateApiKey(apiKey, clientIp);// Store the validated key AND the raw key — the raw key lets handleSubscribe// RE-validate on each subscription so a key revoked mid-connection is caught.(client.data as { apiKey: unknown; rawApiKey: string }).apiKey = validKey;(client.data as { rawApiKey: string }).rawApiKey = apiKey;+ this.trackSocket(validKey.id, client);this.logger.log(`Client connected: ${client.id} (key: ${validKey.name})`);} catch (error) {this.logger.warn(`Client ${client.id} rejected: Auth error`, {@@ -110,7 +189,7 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate// Audit the rejected credential like the REST guard does, so probing over the WS surface leaves// a forensic trail too. Fire-and-forget: audit logging must never affect the rejection path.void this.auditService.logWarn(AuditAction.API_KEY_AUTH_FAILED, {- ipAddress: client.handshake.address,+ ipAddress: clientIp,metadata: { surface: 'websocket' },errorMessage: error instanceof Error ? error.message : String(error),});@@ -120,6 +199,7 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate}handleDisconnect(client: Socket) {+ this.untrackSocket(client);this.logger.log(`Client disconnected: ${client.id}`);}@@ -154,10 +234,13 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate// Re-validate the API key on every subscribe: a long-lived socket whose key was// revoked/expired after connect must not be able to keep opening new subscriptions.+ // The clientIp is re-resolved (trusted-proxy-aware) so an IP-restricted key is enforced+ // here too, not just at connect.const rawApiKey = (client.data as { rawApiKey?: string }).rawApiKey;+ const clientIp = this.resolveClientIp(client);let subscriberKey: { allowedSessions?: string[] | null } | null;try {- subscriberKey = rawApiKey ? await this.authService.validateApiKey(rawApiKey) : null;+ subscriberKey = rawApiKey ? await this.authService.validateApiKey(rawApiKey, clientIp) : null;} catch {subscriberKey = null;}diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.tsindex 6585e4734..245e3fbe3 100644--- a/src/modules/infra/infra.controller.spec.ts+++ b/src/modules/infra/infra.controller.spec.ts@@ -60,7 +60,9 @@ describe('InfraController access control (Vuln 2)', () => {] as const;it.each(adminOnly)('%s requires the ADMIN role', method => {- const handler = InfraController.prototype[method as keyof InfraController] as object;+ const handler = InfraController.prototype[method as keyof InfraController] as unknown as (+ ...args: unknown[]+ ) => unknown;const role = reflector.get<ApiKeyRole | undefined>(REQUIRED_ROLE_KEY, handler);expect(role).toBe(ApiKeyRole.ADMIN);});diff --git a/src/modules/integration/ingress-signature.spec.ts b/src/modules/integration/ingress-signature.spec.tsindex 597cd1239..389f27450 100644--- a/src/modules/integration/ingress-signature.spec.ts+++ b/src/modules/integration/ingress-signature.spec.ts@@ -2,6 +2,7 @@ import { createHmac } from 'node:crypto';import { verifyIngressSignature } from './ingress-signature';const secret = 'topsecret';+const instanceId = 'inst-123';const rawBody = '{"event":"message_created"}';const sig = (body: string) => 'sha256=' + createHmac('sha256', secret).update(body).digest('hex');@@ -15,7 +16,7 @@ describe('verifyIngressSignature', () => {};it('accepts a correct hmac-sha256 signature over the raw body', () => {- const r = verifyIngressSignature(spec, { rawBody, headers: { 'x-sig': sig(rawBody) }, secret, now: 0 });+ const r = verifyIngressSignature(spec, { rawBody, headers: { 'x-sig': sig(rawBody) }, secret, now: 0, instanceId });expect(r.ok).toBe(true);});@@ -25,6 +26,7 @@ describe('verifyIngressSignature', () => {headers: { 'x-sig': sig(rawBody) },secret,now: 0,+ instanceId,});expect(r.ok).toBe(false);});@@ -38,6 +40,7 @@ describe('verifyIngressSignature', () => {headers: { 'x-sig': signed, 'x-ts': String(t) },secret,now: (t + 400) * 1000,+ instanceId,});expect(r.ok).toBe(false);expect(r.reason).toMatch(/replay|stale|tolerance/i);@@ -52,23 +55,24 @@ describe('verifyIngressSignature', () => {headers: { 'x-sig': signed, 'x-ts': String(t) },secret,now: (t + 10) * 1000,+ instanceId,});expect(r.ok).toBe(true);});it('rejects a missing signature header', () => {- const r = verifyIngressSignature(spec, { rawBody, headers: {}, secret, now: 0 });+ const r = verifyIngressSignature(spec, { rawBody, headers: {}, secret, now: 0, instanceId });expect(r.ok).toBe(false);});it('accepts a shared-secret match and rejects a mismatch (constant time)', () => {const sharedSpec = { scheme: 'shared-secret' as const, header: 'X-Token' };- expect(verifyIngressSignature(sharedSpec, { rawBody, headers: { 'x-token': secret }, secret, now: 0 }).ok).toBe(- true,- );- expect(verifyIngressSignature(sharedSpec, { rawBody, headers: { 'x-token': 'nope' }, secret, now: 0 }).ok).toBe(- false,- );+ expect(+ verifyIngressSignature(sharedSpec, { rawBody, headers: { 'x-token': secret }, secret, now: 0, instanceId }).ok,+ ).toBe(true);+ expect(+ verifyIngressSignature(sharedSpec, { rawBody, headers: { 'x-token': 'nope' }, secret, now: 0, instanceId }).ok,+ ).toBe(false);});it('accepts a legitimately-signed body containing $-substitution sequences (no String.replace mangling)', () => {@@ -80,6 +84,7 @@ describe('verifyIngressSignature', () => {headers: { 'x-sig': sig(trickyBody) },secret,now: 0,+ instanceId,});expect(r.ok).toBe(true);});@@ -94,12 +99,15 @@ describe('verifyIngressSignature', () => {headers: { 'x-sig': signed, 'x-ts': String(t) },secret,now: (t + 10) * 1000,+ instanceId,});expect(r.ok).toBe(true);});it('accepts scheme "none" without a signature', () => {- expect(verifyIngressSignature({ scheme: 'none' }, { rawBody, headers: {}, secret, now: 0 }).ok).toBe(true);+ expect(verifyIngressSignature({ scheme: 'none' }, { rawBody, headers: {}, secret, now: 0, instanceId }).ok).toBe(+ true,+ );});it('fails closed on an empty secret even for a structurally valid HMAC', () => {@@ -110,7 +118,36 @@ describe('verifyIngressSignature', () => {headers: { 'x-sig': digest },secret: '',now: 0,+ instanceId,});expect(out.ok).toBe(false);});++ it('accepts a contentTemplate that uses the {id} placeholder (instance id mixed into the signature base)', () => {+ // RED without the {id} substitution: a provider that signs `{id}.{rawBody}` would be silently 401'd+ // because the placeholder is left literal in the signed bytes.+ const withId = {+ ...spec,+ contentTemplate: '{id}.{rawBody}',+ };+ const signed = 'sha256=' + createHmac('sha256', secret).update(`${instanceId}.${rawBody}`).digest('hex');+ const r = verifyIngressSignature(withId, {+ rawBody,+ headers: { 'x-sig': signed },+ secret,+ now: 0,+ instanceId,+ });+ expect(r.ok).toBe(true);++ // A different instance id must NOT verify (the {id} is actually part of the signed material).+ const r2 = verifyIngressSignature(withId, {+ rawBody,+ headers: { 'x-sig': signed },+ secret,+ now: 0,+ instanceId: 'other-inst',+ });+ expect(r2.ok).toBe(false);+ });});diff --git a/src/modules/integration/ingress-signature.ts b/src/modules/integration/ingress-signature.tsindex e93310740..4460651b6 100644--- a/src/modules/integration/ingress-signature.ts+++ b/src/modules/integration/ingress-signature.ts@@ -6,6 +6,10 @@ export interface VerifyInput {headers: Record<string, string>; // lower-cased keyssecret: string;now: number; // ms epoch (injected so replay tests are deterministic — never Date.now() in here)+ // The integration instance id (from the request path). Substituted into `{id}` in the contentTemplate+ // — a provider that mixes the webhook/instance id into its signature base string (e.g. `{id}.{timestamp}.{rawBody}`)+ // would otherwise be silently 401'd. Always available at the runtime call site.+ instanceId: string;}function header(headers: Record<string, string>, name?: string): string | undefined {@@ -46,12 +50,13 @@ export function verifyIngressSignature(// replacement would (a) only replace the first occurrence and (b) interpret $&, $`, $', $$, $n in the// replacement (the attacker-controlled rawBody), so a body containing a `$`-sequence would diverge the// signed bytes from the provider's and reject a legitimately-signed delivery. The function form inserts- // each value literally and, because rawBody is substituted (not re-scanned), a `{timestamp}` embedded- // in the body is never re-interpreted.+ // each value literally and, because rawBody is substituted (not re-scanned), a `{timestamp}` or `{id}`+ // embedded in the body is never re-interpreted. `{id}` resolves to the integration instance id — the only+ // identifier the host has at verify time for a provider that mixes the webhook/instance id into its sig.const template = spec.contentTemplate ?? '{rawBody}';const timestamp = header(input.headers, spec.timestampHeader) ?? '';- const signedContent = template.replace(/\{rawBody\}|\{timestamp\}/g, token =>- token === '{rawBody}' ? input.rawBody : timestamp,+ const signedContent = template.replace(/\{rawBody\}|\{timestamp\}|\{id\}/g, token =>+ token === '{rawBody}' ? input.rawBody : token === '{timestamp}' ? timestamp : input.instanceId,);const digest = createHmac('sha256', input.secret).update(signedContent)diff --git a/src/modules/integration/ingress.service.ts b/src/modules/integration/ingress.service.tsindex a07ca1526..ad9ddc2f1 100644--- a/src/modules/integration/ingress.service.ts+++ b/src/modules/integration/ingress.service.ts@@ -80,6 +80,7 @@ export class IngressService {headers: req.headers,secret: instance.secret,now: this.deps.now(),+ instanceId: req.instanceId,});if (!verdict.ok) return { status: 401, body: verdict.reason ?? 'signature verification failed' };diff --git a/src/modules/integration/integration-retention.service.spec.ts b/src/modules/integration/integration-retention.service.spec.tsnew file mode 100644index 000000000..9de980083--- /dev/null+++ b/src/modules/integration/integration-retention.service.spec.ts@@ -0,0 +1,207 @@+import { DataSource, Repository } from 'typeorm';+import { IngressEvent } from './entities/ingress-event.entity';+import { IntegrationDeliveryFailure } from './entities/integration-delivery-failure.entity';+import { IntegrationRetentionService } from './integration-retention.service';++const daysAgo = (d: number): Date => {+ const dt = new Date();+ dt.setDate(dt.getDate() - d);+ return dt;+};++describe('IntegrationRetentionService.pruneOlderThan', () => {+ let ds: DataSource;+ let service: IntegrationRetentionService;++ beforeEach(async () => {+ ds = new DataSource({+ type: 'sqlite',+ database: ':memory:',+ entities: [IngressEvent, IntegrationDeliveryFailure],+ synchronize: true,+ });+ await ds.initialize();+ service = new IntegrationRetentionService(+ ds.getRepository(IngressEvent),+ ds.getRepository(IntegrationDeliveryFailure),+ );++ const events = ds.getRepository(IngressEvent);+ const failures = ds.getRepository(IntegrationDeliveryFailure);+ // Two old + two recent rows in each table. createdAt is set explicitly so the test controls the+ // window boundary rather than the @CreateDateColumn "now" default.+ await events+ .createQueryBuilder()+ .insert()+ .values([+ {+ id: 'ev-old-1',+ instanceId: 'i',+ pluginId: 'p',+ providerDeliveryId: 'd1',+ route: 'r',+ payload: { headers: {}, query: {}, body: '{}', rawBody: '{}' },+ createdAt: daysAgo(30),+ },+ {+ id: 'ev-old-2',+ instanceId: 'i',+ pluginId: 'p',+ providerDeliveryId: 'd2',+ route: 'r',+ payload: { headers: {}, query: {}, body: '{}', rawBody: '{}' },+ createdAt: daysAgo(15),+ },+ {+ id: 'ev-new-1',+ instanceId: 'i',+ pluginId: 'p',+ providerDeliveryId: 'd3',+ route: 'r',+ payload: { headers: {}, query: {}, body: '{}', rawBody: '{}' },+ createdAt: daysAgo(3),+ },+ {+ id: 'ev-new-2',+ instanceId: 'i',+ pluginId: 'p',+ providerDeliveryId: 'd4',+ route: 'r',+ payload: { headers: {}, query: {}, body: '{}', rawBody: '{}' },+ createdAt: daysAgo(1),+ },+ ])+ .execute();+ await failures+ .createQueryBuilder()+ .insert()+ .values([+ {+ direction: 'inbound',+ pluginId: 'p',+ instanceId: 'i',+ attempts: 1,+ lastError: 'x',+ redriven: false,+ createdAt: daysAgo(40),+ },+ {+ direction: 'outbound',+ pluginId: 'p',+ instanceId: 'i',+ attempts: 2,+ lastError: 'y',+ redriven: false,+ createdAt: daysAgo(20),+ },+ {+ direction: 'inbound',+ pluginId: 'p',+ instanceId: 'i',+ attempts: 1,+ lastError: 'z',+ redriven: false,+ createdAt: daysAgo(5),+ },+ {+ direction: 'inbound',+ pluginId: 'p',+ instanceId: 'i',+ attempts: 1,+ lastError: 'w',+ redriven: false,+ createdAt: daysAgo(2),+ },+ ])+ .execute();+ });++ afterEach(async () => {+ if (ds.isInitialized) await ds.destroy();+ });++ it('deletes only rows older than the window and keeps recent ones', async () => {+ const result = await service.pruneOlderThan(10);++ expect(result).toEqual({ events: 2, failures: 2 });++ const remainingEvents = await ds.getRepository(IngressEvent).find({ order: { id: 'ASC' } });+ const remainingFailures = await ds.getRepository(IntegrationDeliveryFailure).find({ order: { createdAt: 'ASC' } });+ expect(remainingEvents.map(e => e.id)).toEqual(['ev-new-1', 'ev-new-2']);+ expect(remainingFailures).toHaveLength(2);+ expect(remainingFailures.every(f => f.createdAt > daysAgo(10))).toBe(true);+ });++ it('deletes nothing when the window exceeds every row age', async () => {+ const result = await service.pruneOlderThan(365);+ expect(result).toEqual({ events: 0, failures: 0 });+ expect(await ds.getRepository(IngressEvent).count()).toBe(4);+ expect(await ds.getRepository(IntegrationDeliveryFailure).count()).toBe(4);+ });++ it('deletes everything when the window is 0 days', async () => {+ // A 0-day cutoff = everything strictly older than "now" is pruned. (onModuleInit treats <=0 as a+ // disabled opt-out and never calls this; here we confirm the method itself is bounded by age.)+ const result = await service.pruneOlderThan(0);+ expect(result.events + result.failures).toBe(8);+ });++ // Note: the "deletes only rows older than the window" case above is itself the bounded-delete proof —+ // an unbounded DELETE would have removed all rows (counts of 4/4), not just the aged subset.+});++describe('IntegrationRetentionService.onModuleInit (retention scheduling)', () => {+ const original = process.env.INGRESS_RETENTION_DAYS;++ const mockRepos = () => {+ const eventsDelete = jest.fn().mockResolvedValue({ affected: 0 });+ const failuresDelete = jest.fn().mockResolvedValue({ affected: 0 });+ return {+ eventsDelete,+ failuresDelete,+ events: { delete: eventsDelete } as unknown as Repository<IngressEvent>,+ failures: { delete: failuresDelete } as unknown as Repository<IntegrationDeliveryFailure>,+ };+ };++ afterEach(() => {+ if (original === undefined) delete process.env.INGRESS_RETENTION_DAYS;+ else process.env.INGRESS_RETENTION_DAYS = original;+ });++ it('disables pruning (no startup prune, no timer) when INGRESS_RETENTION_DAYS <= 0', () => {+ process.env.INGRESS_RETENTION_DAYS = '0';+ const repos = mockRepos();+ const svc = new IntegrationRetentionService(repos.events, repos.failures);++ expect(() => svc.onModuleInit()).not.toThrow();+ expect(repos.eventsDelete).not.toHaveBeenCalled();+ expect(repos.failuresDelete).not.toHaveBeenCalled();+ svc.onModuleDestroy();+ });++ it('defaults to 90 days when unset, prunes once at startup, and schedules a daily timer', () => {+ delete process.env.INGRESS_RETENTION_DAYS;+ const repos = mockRepos();+ const svc = new IntegrationRetentionService(repos.events, repos.failures);++ jest.useFakeTimers();+ try {+ const pruneSpy = jest.spyOn(svc, 'pruneOlderThan');+ svc.onModuleInit();+ // Startup prune fires immediately (90-day default).+ expect(pruneSpy).toHaveBeenCalledWith(90);+ pruneSpy.mockClear();+ // The recurring timer fires daily thereafter.+ jest.advanceTimersByTime(24 * 60 * 60 * 1000);+ expect(pruneSpy).toHaveBeenCalledWith(90);+ svc.onModuleDestroy();+ // After destroy, advancing the timer must NOT trigger further prunes.+ pruneSpy.mockClear();+ jest.advanceTimersByTime(24 * 60 * 60 * 1000);+ expect(pruneSpy).not.toHaveBeenCalled();+ } finally {+ jest.useRealTimers();+ }+ });+});diff --git a/src/modules/integration/integration-retention.service.ts b/src/modules/integration/integration-retention.service.tsnew file mode 100644index 000000000..00ca69b0b--- /dev/null+++ b/src/modules/integration/integration-retention.service.ts@@ -0,0 +1,71 @@+import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';+import { InjectRepository } from '@nestjs/typeorm';+import { LessThan, Repository } from 'typeorm';+import { IngressEvent } from './entities/ingress-event.entity';+import { IntegrationDeliveryFailure } from './entities/integration-delivery-failure.entity';+import { createLogger } from '../../common/services/logger.service';++/**+ * Bounds the growth of two append-only integration-fabric tables that otherwise grow without bound:+ * `ingress_events` (the inbound dedup/event log) and `integration_delivery_failures` (the DLQ).+ *+ * Mirrors the AuditService / WebhookService retention: runs once at startup then daily via a raw+ * `setInterval` (unref'd), gated by INGRESS_RETENTION_DAYS (default 90; set <= 0 to disable). Both+ * tables carry a `createdAt` column (ingress_events is indexed on it), so the prune is an indexed+ * `createdAt < cutoff` delete — the same shape as the sibling prunes.+ */+@Injectable()+export class IntegrationRetentionService implements OnModuleInit, OnModuleDestroy {+ private readonly logger = createLogger('IntegrationRetentionService');+ private cleanupTimer?: ReturnType<typeof setInterval>;++ constructor(+ @InjectRepository(IngressEvent, 'data') private readonly eventRepository: Repository<IngressEvent>,+ @InjectRepository(IntegrationDeliveryFailure, 'data')+ private readonly failureRepository: Repository<IntegrationDeliveryFailure>,+ ) {}++ onModuleInit(): void {+ const parsed = Number.parseInt(process.env.INGRESS_RETENTION_DAYS ?? '', 10);+ const retentionDays = Number.isInteger(parsed) ? Math.max(0, parsed) : 90;+ if (retentionDays <= 0) {+ this.logger.log('Integration ingress retention disabled (INGRESS_RETENTION_DAYS <= 0)');+ return;+ }+ const runPrune = (): void => {+ this.pruneOlderThan(retentionDays)+ .then(({ events, failures }) => {+ if (events > 0) this.logger.log(`Pruned ${events} ingress event(s) older than ${retentionDays} day(s)`);+ if (failures > 0) {+ this.logger.log(`Pruned ${failures} integration delivery-failure(s) older than ${retentionDays} day(s)`);+ }+ })+ .catch(err =>+ this.logger.error('Integration ingress retention failed', err instanceof Error ? err.stack : String(err)),+ );+ };+ runPrune(); // prune once at startup+ this.cleanupTimer = setInterval(runPrune, 24 * 60 * 60 * 1000);+ this.cleanupTimer.unref?.();+ }++ onModuleDestroy(): void {+ if (this.cleanupTimer) {+ clearInterval(this.cleanupTimer);+ }+ }++ /**+ * Delete ingress_events + integration_delivery_failures rows older than the retention window.+ * Returns the number removed from each table.+ */+ async pruneOlderThan(olderThanDays: number): Promise<{ events: number; failures: number }> {+ const cutoff = new Date();+ cutoff.setDate(cutoff.getDate() - olderThanDays);+ const [eventsResult, failuresResult] = await Promise.all([+ this.eventRepository.delete({ createdAt: LessThan(cutoff) }),+ this.failureRepository.delete({ createdAt: LessThan(cutoff) }),+ ]);+ return { events: eventsResult.affected || 0, failures: failuresResult.affected || 0 };+ }+}diff --git a/src/modules/integration/integration.module.ts b/src/modules/integration/integration.module.tsindex 7f1d9b4b9..347a26618 100644--- a/src/modules/integration/integration.module.ts+++ b/src/modules/integration/integration.module.ts@@ -11,6 +11,7 @@ import { IngressController } from './ingress.controller';import { IngressEnqueueService, buildIngressDeadLetterRow } from './ingress-enqueue.service';import { RedriveService } from './redrive.service';import { RedriveController } from './redrive.controller';+import { IntegrationRetentionService } from './integration-retention.service';import { IntegrationInstanceController } from './integration-instance.controller';import { ScopeBindingService } from './scope-binding.service';import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';@@ -32,6 +33,7 @@ import { createLogger } from '../../common/services/logger.service';IngressEnqueueService,RedriveService,ScopeBindingService,+ IntegrationRetentionService,{provide: IngressService,inject: [diff --git a/src/modules/mcp/mcp.module.ts b/src/modules/mcp/mcp.module.tsindex f542d9b05..973df62d4 100644--- a/src/modules/mcp/mcp.module.ts+++ b/src/modules/mcp/mcp.module.ts@@ -2,6 +2,7 @@ import { type DynamicModule, Module, type MiddlewareConsumer, type NestModule }import { HttpAdapterHost } from '@nestjs/core';import { ToolRegistryService } from '../../core/agent-tools/tool-registry.service';import { AuthService } from '../auth/auth.service';+import { AuditService } from '../audit/audit.service';import { KeyRateLimiter, readRateLimitConfig, readIpRateLimitConfig } from './mcp-rate-limit';import { mountMcpServer } from './mcp.server';@@ -20,6 +21,8 @@ export class McpModule implements NestModule {private readonly registry: ToolRegistryService,private readonly authService: AuthService,private readonly httpAdapterHost: HttpAdapterHost,+ // AuditModule is @Global(), so AuditService is injectable here without an explicit import.+ private readonly auditService: AuditService,) {}static forRoot(options: McpModuleOptions = {}): DynamicModule {@@ -43,6 +46,14 @@ export class McpModule implements NestModule {const rateLimiter = new KeyRateLimiter(max, windowMs);const ipCfg = readIpRateLimitConfig();const ipRateLimiter = new KeyRateLimiter(ipCfg.max, ipCfg.windowMs);- mountMcpServer(httpAdapter, this.registry, this.authService, rateLimiter, ipRateLimiter, { basePath, serverInfo });+ mountMcpServer(+ httpAdapter,+ this.registry,+ this.authService,+ rateLimiter,+ ipRateLimiter,+ { basePath, serverInfo },+ this.auditService,+ );}}diff --git a/src/modules/mcp/mcp.server.spec.ts b/src/modules/mcp/mcp.server.spec.tsindex 7b2267e27..7889a877a 100644--- a/src/modules/mcp/mcp.server.spec.ts+++ b/src/modules/mcp/mcp.server.spec.ts@@ -1,6 +1,8 @@+import { BadRequestException, ForbiddenException, UnauthorizedException } from '@nestjs/common';import type { Request, Response } from 'express';-import { createIpThrottle, resolveMcpReadOnly } from './mcp.server';+import { auditMcpAuthFailure, createIpThrottle, resolveMcpReadOnly } from './mcp.server';import { KeyRateLimiter } from './mcp-rate-limit';+import { AuditAction } from '../audit/entities/audit-log.entity';describe('resolveMcpReadOnly (secure-by-default MCP read-only flag)', () => {const prev = process.env.MCP_READONLY;@@ -78,3 +80,58 @@ describe('createIpThrottle (pre-auth per-IP MCP throttle)', () => {expect(next).toHaveBeenCalledWith();});});++// MCP auth is raw Express (outside the Nest guard pipeline) so it bypasses the global ApiKeyGuard's+// auth-failure audit. auditMcpAuthFailure mirrors the REST guard: a WARN API_KEY_AUTH_FAILED record on+// a 401/403 only. Success and non-auth errors (bad input) must NOT be audited — parity with REST.+describe('auditMcpAuthFailure (MCP auth-failure audit trail, mirrors REST ApiKeyGuard)', () => {+ const reqContext = { ipAddress: '203.0.113.7', method: 'POST', path: '/mcp' };+ let auditService: { logWarn: jest.Mock };++ beforeEach(() => {+ auditService = { logWarn: jest.fn() };+ });++ it('writes a WARN API_KEY_AUTH_FAILED record on a missing/invalid key (UnauthorizedException)', () => {+ auditMcpAuthFailure(auditService, new UnauthorizedException('Missing API key'), reqContext);+ expect(auditService.logWarn).toHaveBeenCalledWith(AuditAction.API_KEY_AUTH_FAILED, {+ ipAddress: '203.0.113.7',+ method: 'POST',+ path: '/mcp',+ errorMessage: 'Missing API key',+ });+ });++ it('writes a record on a wrong-role rejection (ForbiddenException)', () => {+ auditMcpAuthFailure(auditService, new ForbiddenException('API key lacks the required role'), reqContext);+ expect(auditService.logWarn).toHaveBeenCalledTimes(1);+ const call = (auditService.logWarn.mock.calls as Array<[unknown, { errorMessage?: string }]>)[0];+ expect(call[1].errorMessage).toBe('API key lacks the required role');+ });++ it('mirrors the REST guard exactly: IP-not-allowed (Unauthorized) is audited', () => {+ // validateApiKey throws Unauthorized for IP-not-allowed / revoked / expired / session-not-allowed.+ auditMcpAuthFailure(auditService, new UnauthorizedException('IP address not allowed'), reqContext);+ expect(auditService.logWarn).toHaveBeenCalledWith(+ AuditAction.API_KEY_AUTH_FAILED,+ expect.objectContaining({ errorMessage: 'IP address not allowed' }),+ );+ });++ it('does NOT audit a non-auth error (e.g. bad tool input — BadRequestException)', () => {+ auditMcpAuthFailure(auditService, new BadRequestException('sessionId is required for this tool'), reqContext);+ expect(auditService.logWarn).not.toHaveBeenCalled();+ });++ it('does nothing when auditService is unavailable (mount without DI)', () => {+ expect(() => auditMcpAuthFailure(undefined, new UnauthorizedException('x'), reqContext)).not.toThrow();+ });++ it('success path never reaches the catch (helper only invoked on thrown auth errors)', () => {+ // Structural: auditMcpAuthFailure is only called from the tool handler's catch block, so a+ // successful invokeTool returns a result without auditing. Assert the helper is a no-op on+ // a non-401/403 throw to confirm the success-equivalent (no auth failure) is not audited.+ auditMcpAuthFailure(auditService, new BadRequestException('not an auth failure'), reqContext);+ expect(auditService.logWarn).not.toHaveBeenCalled();+ });+});diff --git a/src/modules/mcp/mcp.server.ts b/src/modules/mcp/mcp.server.tsindex 8a9f3c791..1169e0b98 100644--- a/src/modules/mcp/mcp.server.ts+++ b/src/modules/mcp/mcp.server.ts@@ -1,4 +1,4 @@-import { HttpException, Logger } from '@nestjs/common';+import { ForbiddenException, HttpException, Logger, UnauthorizedException } from '@nestjs/common';import type { HttpAdapterHost } from '@nestjs/core';import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';@@ -8,6 +8,8 @@ import express, { type Request, type RequestHandler, type Response } from 'expreimport { invokeTool } from '../../core/agent-tools/tool-invoker';import type { ToolRegistryService } from '../../core/agent-tools/tool-registry.service';import type { AuthService } from '../auth/auth.service';+import type { AuditService } from '../audit/audit.service';+import { AuditAction } from '../audit/entities/audit-log.entity';import { handleToolError, jsonToolResult, smartToolResult } from './tool-result';import type { KeyRateLimiter } from './mcp-rate-limit';import { resolveClientIp } from '../../common/utils/ip';@@ -17,6 +19,13 @@ const logger = new Logger('McpServer');type HttpAdapter = NonNullable<HttpAdapterHost['httpAdapter']>;type ToolExtra = RequestHandlerExtra<ServerRequest, ServerNotification>;+/** Request-scoped context forwarded to the audit trail on an MCP auth failure (mirrors the REST guard). */+export interface McpRequestContext {+ ipAddress?: string;+ method?: string;+ path?: string;+}+/** Extract the raw API key from MCP request headers. Accepts X-Api-Key or Bearer token. */function extractApiKey(extra: ToolExtra): string | undefined {const headers = extra.requestInfo?.headers ?? {};@@ -32,6 +41,46 @@ function extractApiKey(extra: ToolExtra): string | undefined {return undefined;}+/**+ * Mirror the REST ApiKeyGuard's auth-failure audit trail for MCP. The MCP mount is raw Express (outside+ * the Nest guard pipeline), so without this a credential-probing flood against /mcp leaves no forensic+ * record. Records a WARN `API_KEY_AUTH_FAILED` for rejected/denied authentication attempts (401/403 only);+ * non-auth errors (e.g. a 400 from bad tool input) are NOT audited — parity with the REST guard, which+ * only records Unauthorized/Forbidden. Fire-and-forget; best-effort (AuditService swallows insert errors).+ */+export function auditMcpAuthFailure(+ auditService: Pick<AuditService, 'logWarn'> | undefined,+ error: unknown,+ reqContext: McpRequestContext,+): void {+ if (!auditService) return;+ if (error instanceof UnauthorizedException || error instanceof ForbiddenException) {+ void auditService.logWarn(AuditAction.API_KEY_AUTH_FAILED, {+ ipAddress: reqContext.ipAddress,+ method: reqContext.method,+ path: reqContext.path,+ errorMessage: error instanceof Error ? error.message : String(error),+ });+ }+}++/** Read TRUSTED_PROXIES once as a list (shared by the pre-auth throttle and the audit IP resolver). */+function readTrustedProxies(): string[] {+ return (process.env.TRUSTED_PROXIES ?? '')+ .split(',')+ .map(s => s.trim())+ .filter(Boolean);+}++/** Resolve the trusted-proxy-aware client IP + HTTP method/path for an audit record. */+function resolveReqContext(req: Request): McpRequestContext {+ return {+ ipAddress: resolveClientIp(req, readTrustedProxies()),+ method: req.method,+ path: req.path,+ };+}+/*** Build the MCP server ONCE and register all tools from the registry.* The SDK's `registerTool` accepts `AnySchema` (z4.$ZodType) directly, so we@@ -43,6 +92,8 @@ function buildServer(rateLimiter: KeyRateLimiter,readOnly: boolean,serverInfo: { name: string; version: string },+ auditService: AuditService | undefined,+ reqContext: McpRequestContext,): McpServer {const server = new McpServer({ name: serverInfo.name, version: serverInfo.version },@@ -66,7 +117,18 @@ function buildServer(async (input: Record<string, unknown>, extra: ToolExtra) => {const rawKey = extractApiKey(extra);try {- const result = await invokeTool(tool, input, rawKey, authService, id => rateLimiter.check(id));+ const result = await invokeTool(+ tool,+ input,+ rawKey,+ authService,+ id => rateLimiter.check(id),+ // onAuthFailure: mirror the REST ApiKeyGuard — record rejected/denied auth attempts (401/403+ // only) at the auth boundary so the audit trail covers MCP credential probing. Fires inside+ // invokeTool's auth phase (before the tool handler), so handler-thrown 403s are NOT mislabeled+ // as auth failures. Best-effort; success and non-auth errors skip this.+ error => auditMcpAuthFailure(auditService, error, reqContext),+ );return tool.resultDisposition === 'json'? jsonToolResult(result as object): smartToolResult(result as object);@@ -105,11 +167,7 @@ export interface MountMcpServerOptions {*/export function createIpThrottle(ipRateLimiter: KeyRateLimiter): RequestHandler {return (req, res, next) => {- const trustedProxies = (process.env.TRUSTED_PROXIES ?? '')- .split(',')- .map(s => s.trim())- .filter(Boolean);- const ip = resolveClientIp(req, trustedProxies);+ const ip = resolveClientIp(req, readTrustedProxies());try {ipRateLimiter.check(ip);next();@@ -141,6 +199,7 @@ export function mountMcpServer(rateLimiter: KeyRateLimiter,ipRateLimiter: KeyRateLimiter,options: MountMcpServerOptions = {},+ auditService?: AuditService,): void {const basePath = (options.basePath ?? '/mcp').replace(/\/$/, '') || '/mcp';const serverInfo = options.serverInfo ?? { name: 'openwa', version: '0.0.0' };@@ -153,7 +212,15 @@ export function mountMcpServer(logger.log(`MCP server mounted at POST ${basePath} (${tools.length} tools)`);const handler: RequestHandler = async (req: Request, res: Response) => {- const server = buildServer(registry, authService, rateLimiter, readOnly, serverInfo);+ const server = buildServer(+ registry,+ authService,+ rateLimiter,+ readOnly,+ serverInfo,+ auditService,+ resolveReqContext(req),+ );const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });try {res.on('close', () => {diff --git a/src/modules/plugins/plugin-installer.spec.ts b/src/modules/plugins/plugin-installer.spec.tsindex f63bbb02e..72569f0ed 100644--- a/src/modules/plugins/plugin-installer.spec.ts+++ b/src/modules/plugins/plugin-installer.spec.ts@@ -1,4 +1,5 @@import AdmZip from 'adm-zip';+import { BadRequestException } from '@nestjs/common';import { parsePluginPackage } from './plugin-installer';const validManifest = { id: 'my-plg', name: 'My Plugin', version: '1.0.0', type: 'extension', main: 'index.js' };@@ -9,6 +10,63 @@ function zipOf(files: Record<string, string>): Buffer {return z.toBuffer();}+/**+ * Build a valid plugin zip, then corrupt one entry's compressed bytes so `getData()` throws a+ * decompression/CRC error (BAD_CRC / zlib invalid-code) — simulating a truncated or damaged archive.+ */+function zipWithCorruptEntry(target: string): Buffer {+ const z = new AdmZip();+ z.addFile('manifest.json', Buffer.from(JSON.stringify(validManifest)));+ z.addFile('index.js', Buffer.from('module.exports=class{}'));+ z.addFile(target, Buffer.from('A'.repeat(100)));+ const buf = Buffer.from(z.toBuffer()); // writable copy+ const locsig = Buffer.from([0x50, 0x4b, 0x03, 0x04]); // PK\x03\x04 local file header signature+ let off = buf.indexOf(locsig);+ while (off !== -1) {+ const nameLen = buf.readUInt16LE(off + 26);+ const extraLen = buf.readUInt16LE(off + 28);+ const name = buf.slice(off + 30, off + 30 + nameLen).toString();+ const dataStart = off + 30 + nameLen + extraLen;+ if (name === target) {+ buf[dataStart] ^= 0xff; // flip the first compressed byte → bad CRC / invalid deflate stream+ break;+ }+ off = buf.indexOf(locsig, off + 1);+ }+ return buf;+}++/**+ * Build a plugin zip whose `target` entry declares uncompressed size = 0 in BOTH the central+ * directory and the local header, while the entry still carries real (deflated) content. adm-zip+ * only sets zlib `maxOutputLength` when the declared size is > 0, so without a bound this entry+ * inflates with no cap — the zip-bomb residual gap (a lying-header entry).+ */+function zipWithLyingZeroSizeEntries(targets: Record<string, string>): Buffer {+ const z = new AdmZip();+ z.addFile('manifest.json', Buffer.from(JSON.stringify(validManifest)));+ z.addFile('index.js', Buffer.from('module.exports=class{}'));+ for (const [name, content] of Object.entries(targets)) z.addFile(name, Buffer.from(content));+ const buf = Buffer.from(z.toBuffer()); // writable copy+ const censig = Buffer.from([0x50, 0x4b, 0x01, 0x02]); // PK\x01\x02 central directory header signature+ let off = buf.indexOf(censig);+ while (off !== -1) {+ const nameLen = buf.readUInt16LE(off + 28);+ const name = buf.slice(off + 46, off + 46 + nameLen).toString();+ if (name in targets) {+ const locoff = buf.readUInt32LE(off + 42); // CENOFF — local header offset+ buf.writeUInt32LE(0, off + 24); // CENLEN = 0 (declared uncompressed size, central)+ buf.writeUInt32LE(0, locoff + 22); // LOCLEN = 0 (declared uncompressed size, local)+ }+ off = buf.indexOf(censig, off + 1);+ }+ return buf;+}++function zipWithLyingZeroSizeEntry(target: string, content: string): Buffer {+ return zipWithLyingZeroSizeEntries({ [target]: content });+}+describe('parsePluginPackage', () => {it('parses a flat package (manifest + files at the root)', () => {const out = parsePluginPackage(@@ -123,4 +181,49 @@ describe('parsePluginPackage', () => {const buf = zipOf({ 'manifest.json': JSON.stringify(validManifest), 'index.js': 'a'.repeat(100) });expect(() => parsePluginPackage(buf, { maxEntries: 100, maxTotalBytes: 10 })).toThrow(/size limit/i);});++ it('rejects a corrupt entry with a clean 400, not an uncaught decompression error / 500', () => {+ // A truncated/damaged entry throws BAD_CRC / a zlib error from getData(); without the try/catch+ // that escapes as an HTTP 500. It must surface as a BadRequestException (clean 400).+ const buf = zipWithCorruptEntry('data.bin');+ expect(() => parsePluginPackage(buf)).toThrow(BadRequestException);+ expect(() => parsePluginPackage(buf)).toThrow(/corrupt or too large/i);+ });++ it('rejects a lying size=0 entry whose actual content exceeds the cap (no unbounded inflation)', () => {+ // adm-zip skips zlib `maxOutputLength` when declared size is 0, so this entry would inflate with+ // NO cap. The declared aggregate (0 + tiny manifest + index) passes the pre-check; only the+ // actual-bytes bound stops the lying entry. Actual content (500B) exceeds the per-entry cap (200B)+ // → ERR_BUFFER_TOO_LARGE → BadRequestException.+ const buf = zipWithLyingZeroSizeEntry('big.bin', 'A'.repeat(500));+ expect(() => parsePluginPackage(buf, { maxEntries: 100, maxTotalBytes: 200 })).toThrow(BadRequestException);+ expect(() => parsePluginPackage(buf, { maxEntries: 100, maxTotalBytes: 200 })).toThrow(/corrupt or too large/i);+ });++ it('rejects many lying size=0 entries whose aggregate exceeds the cap (multi-entry zip bomb)', () => {+ // Each lying entry is individually under the per-entry cap (150B < 300B), and the declared sum+ // is tiny (lying sizes are 0 + manifest + index), so both the declared pre-check and the per-entry+ // bound pass. Without the running actual-bytes counter, these accumulate unbounded in `entries`+ // before the function returns → OOM. The aggregate bound aborts as soon as the running total+ // crosses the cap.+ const buf = zipWithLyingZeroSizeEntries({+ 'big1.bin': 'A'.repeat(150),+ 'big2.bin': 'A'.repeat(150),+ 'big3.bin': 'A'.repeat(150),+ });+ expect(() => parsePluginPackage(buf, { maxEntries: 100, maxTotalBytes: 300 })).toThrow(BadRequestException);+ expect(() => parsePluginPackage(buf, { maxEntries: 100, maxTotalBytes: 300 })).toThrow(/too large/i);+ });++ it('happy path unchanged: a normal small plugin installs identically (no regression)', () => {+ const buf = zipOf({+ 'manifest.json': JSON.stringify(validManifest),+ 'index.js': 'module.exports=class{}',+ 'extra.txt': 'some extra bytes',+ });+ const out = parsePluginPackage(buf);+ expect(out.manifest.id).toBe('my-plg');+ expect(out.entries.map(e => e.relPath).sort()).toEqual(['extra.txt', 'index.js', 'manifest.json']);+ expect(out.entries.find(e => e.relPath === 'extra.txt')?.data.toString()).toBe('some extra bytes');+ });});diff --git a/src/modules/plugins/plugin-installer.ts b/src/modules/plugins/plugin-installer.tsindex 5c3f1bf19..7716a8a85 100644--- a/src/modules/plugins/plugin-installer.ts+++ b/src/modules/plugins/plugin-installer.ts@@ -1,5 +1,6 @@import AdmZip from 'adm-zip';import * as path from 'path';+import * as zlib from 'zlib';import { BadRequestException } from '@nestjs/common';import { PluginManifest, PluginType } from '../../core/plugins';@@ -25,6 +26,25 @@ export const INSTALLABLE_TYPES = new Set<string>([PluginType.EXTENSION]);const SAFE_ID = /^[a-z0-9][a-z0-9._-]*$/i;const REQUIRED_FIELDS = ['id', 'name', 'version', 'type', 'main'] as const;+/**+ * Decompress one zip entry with a hard cap on actual output bytes. adm-zip only forwards zlib+ * `maxOutputLength` when the entry's declared uncompressed size is positive, so an entry that lies+ * about being empty (header.size = 0) would otherwise inflate with NO cap — a memory-exhaustion+ * vector. For that case we inflate bounded ourselves; every other path is left to `getData()` (a+ * corrupt/CRC mismatch or a lying-small header throws `BAD_CRC` / `ERR_BUFFER_TOO_LARGE`, which the+ * caller catches and maps to a clean 400).+ */+function readEntryData(entry: AdmZip.IZipEntry, maxBytes: number): Buffer {+ if (entry.header.size === 0 && entry.header.compressedSize > 0) {+ const compressed = entry.getCompressedData();+ if (compressed.length === 0) return Buffer.alloc(0);+ // maxOutputLength aborts inflation (ERR_BUFFER_TOO_LARGE) once output exceeds the cap, so a+ // lying size=0 entry cannot grow unbounded in memory before we reject the archive.+ return zlib.inflateRawSync(compressed, { maxOutputLength: maxBytes });+ }+ return entry.getData();+}+export interface ParsedPackage {manifest: PluginManifest;/** Files to write under the plugin directory, relative to the package root, zip-slip-safe. */@@ -57,9 +77,17 @@ export function parsePluginPackage(buffer: Buffer, limits: PackageLimits = DEFAUconst dir = path.posix.dirname(manifestEntry.entryName);const prefix = dir === '.' ? '' : dir + '/';+ let manifestRaw: Buffer;+ try {+ manifestRaw = readEntryData(manifestEntry, limits.maxTotalBytes);+ } catch {+ // A corrupt / oversized manifest entry must surface as a clean 400, not an uncaught+ // decompression error (BAD_CRC / ERR_BUFFER_TOO_LARGE) that would escape as an HTTP 500.+ throw new BadRequestException('Plugin package is corrupt or too large to extract');+ }let parsed: unknown;try {- parsed = JSON.parse(manifestEntry.getData().toString('utf-8'));+ parsed = JSON.parse(manifestRaw.toString('utf-8'));} catch {throw new BadRequestException('manifest.json is not valid JSON');}@@ -95,6 +123,7 @@ export function parsePluginPackage(buffer: Buffer, limits: PackageLimits = DEFAUif (declared > limits.maxTotalBytes) throw new BadRequestException('The archive contents exceed the size limit');const entries: { relPath: string; data: Buffer }[] = [];+ let actualBytes = 0;for (const e of packaged) {const relPath = e.entryName.slice(prefix.length);if (!relPath) continue;@@ -102,7 +131,25 @@ export function parsePluginPackage(buffer: Buffer, limits: PackageLimits = DEFAUif (relPath.includes('\\') || norm.startsWith('..') || norm === '..' || path.posix.isAbsolute(norm)) {throw new BadRequestException(`Unsafe path in archive: ${e.entryName}`);}- entries.push({ relPath: norm, data: e.getData() });+ let data: Buffer;+ try {+ data = readEntryData(e, limits.maxTotalBytes);+ } catch {+ // Corrupt entry (bad CRC / truncated), a lying-small header (zlib ERR_BUFFER_TOO_LARGE), or a+ // lying size=0 entry that exceeds the cap — all must yield a clean 400, never an uncaught+ // decompression error (HTTP 500).+ throw new BadRequestException('Plugin package is corrupt or too large to extract');+ }+ // Aggregate actual-bytes bound: the declared-sum pre-check above uses header.size (which lying+ // size=0 entries contribute as 0), and the per-entry cap only bounds each entry individually. A+ // crafted archive with many lying-size=0 entries (each just under the per-entry cap) would pass+ // both and accumulate unbounded in `entries` before the function returns. Abort as soon as the+ // running total of decompressed bytes exceeds the cap.+ actualBytes += data.length;+ if (actualBytes > limits.maxTotalBytes) {+ throw new BadRequestException('Plugin package is too large to extract');+ }+ entries.push({ relPath: norm, data });}const mainRel = path.posix.normalize(manifest.main);diff --git a/src/modules/plugins/plugins.service.spec.ts b/src/modules/plugins/plugins.service.spec.tsindex 5a79ff37a..ecde6e7fc 100644--- a/src/modules/plugins/plugins.service.spec.ts+++ b/src/modules/plugins/plugins.service.spec.ts@@ -145,6 +145,19 @@ describe('PluginsService — install / uninstall (real loader + disk)', () => {await Promise.all([p1, p2]);expect(calls).toBe(2);});++ // A literal link-local IP is rejected synchronously by the SSRF guard before any fetch/DNS, so this+ // is fully offline. The download path follows redirects, so the guard always runs (no opt-out flag);+ // the rejected-IP detail must be redacted from the surfaced BadRequestException (recon oracle).+ it('installFromUrl redacts the resolved internal IP when the SSRF guard blocks the URL', async () => {+ const err = await service.installFromUrl('https://169.254.169.254/pkg.zip').catch((e: unknown) => e);++ expect(err).toBeInstanceOf(BadRequestException);+ const message = (err as BadRequestException).message;+ expect(message).toMatch(/^Failed to download plugin from URL: /);+ expect(message).not.toMatch(/169\.254\.169\.254/);+ expect(message).toBe('Failed to download plugin from URL: Destination address is not allowed');+ });});describe('PluginsService — getConfigUiHtml (sandboxed config editor)', () => {diff --git a/src/modules/plugins/plugins.service.ts b/src/modules/plugins/plugins.service.tsindex 0ce8e157f..8e45b90d0 100644--- a/src/modules/plugins/plugins.service.ts+++ b/src/modules/plugins/plugins.service.ts@@ -16,10 +16,19 @@ import { redactSecretConfig, restoreSecretConfig } from './redact-config';import { parsePluginPackage } from './plugin-installer';import { fetchSafeBuffer } from './plugin-download';import { annotateCatalog, CatalogEntry, CatalogPlugin } from './catalog';+import { redactSsrfError } from '../../common/security/ssrf-guard';+import { createLogger } from '../../common/services/logger.service';/** Cap on the catalog JSON download (the catalog is small; this bounds a hostile response). */const CATALOG_MAX_BYTES = 1 * 1024 * 1024;+/**+ * Module-level logger so the SSRF redactor can log the full blocked-address detail server-side before+ * returning the generic message (the service has no `this.logger` and its methods are sync/void-returning+ * around the download calls).+ */+const logger = createLogger('PluginsService');+/** A plugin can host provisioned instances iff it declares an ingress route AND the webhook:ingress* permission — mirrors IntegrationInstanceController.assertIngressCapable. */export function isIngressCapable(manifest: { ingress?: unknown[]; permissions?: string[] }): boolean {@@ -332,7 +341,7 @@ export class PluginsService {buffer = await fetchSafeBuffer(url, { maxBytes });} catch (error) {throw new BadRequestException(- `Failed to download plugin from URL: ${error instanceof Error ? error.message : String(error)}`,+ `Failed to download plugin from URL: ${redactSsrfError(error, logger, 'plugin download')}`,);}// Peek the id (the SSRF download stays outside the lock) so the install — which writes the plugin@@ -354,7 +363,7 @@ export class PluginsService {raw = await fetchSafeBuffer(url, { maxBytes: CATALOG_MAX_BYTES });} catch (error) {throw new BadRequestException(- `Failed to fetch plugin catalog: ${error instanceof Error ? error.message : String(error)}`,+ `Failed to fetch plugin catalog: ${redactSsrfError(error, logger, 'plugin catalog download')}`,);}@@ -455,7 +464,7 @@ export class PluginsService {buffer = await fetchSafeBuffer(url, { maxBytes });} catch (error) {throw new BadRequestException(- `Failed to download plugin from URL: ${error instanceof Error ? error.message : String(error)}`,+ `Failed to download plugin from URL: ${redactSsrfError(error, logger, 'plugin download')}`,);}return this.updatePackage(id, buffer);diff --git a/src/modules/queue/processors/webhook.processor.spec.ts b/src/modules/queue/processors/webhook.processor.spec.tsindex acd931632..484740cff 100644--- a/src/modules/queue/processors/webhook.processor.spec.ts+++ b/src/modules/queue/processors/webhook.processor.spec.ts@@ -156,4 +156,26 @@ describe('WebhookProcessor', () => {expect(mockFetch).toHaveBeenCalledWith('https://8.8.8.8/hook', expect.objectContaining({ redirect: 'manual' }));expect(repo.update).not.toHaveBeenCalled(); // never treated as delivered});++ // A literal link-local IP triggers the SSRF guard synchronously before any fetch/DNS, so this is+ // fully offline. The webhook:error hook payload and the durable DLQ row must both carry the generic+ // message — the resolved internal IP is a recon oracle. The server-side logger.error keeps full detail.+ it('redacts the resolved internal IP from the webhook:error payload and DLQ row on an SSRF block', async () => {+ process.env.WEBHOOK_SSRF_PROTECT = 'true';+ // final attempt (attemptsMade=0, maxRetries=1 → 1 >= 1) so the hook + DLQ fire+ await expect(processor.process(makeJob({ url: 'https://169.254.169.254/h', maxRetries: 1 }, 0))).rejects.toThrow();++ expect(mockFetch).not.toHaveBeenCalled(); // blocked before any network++ const hookCalls = hookManager.execute.mock.calls as unknown as Array<[string, { error: string }, unknown]>;+ const errorHookCall = hookCalls.find(c => c[0] === 'webhook:error');+ expect(errorHookCall).toBeDefined();+ expect(errorHookCall![1].error).toBe('Destination address is not allowed');+ expect(errorHookCall![1].error).not.toMatch(/169\.254\.169\.254/);++ expect(failureRepo.insert).toHaveBeenCalledTimes(1);+ const inserted = (failureRepo.insert.mock.calls[0] as unknown[])[0] as { lastError: string };+ expect(inserted.lastError).toBe('Destination address is not allowed');+ expect(inserted.lastError).not.toMatch(/169\.254\.169\.254/);+ });});diff --git a/src/modules/queue/processors/webhook.processor.ts b/src/modules/queue/processors/webhook.processor.tsindex a36a326d0..ec6990834 100644--- a/src/modules/queue/processors/webhook.processor.ts+++ b/src/modules/queue/processors/webhook.processor.ts@@ -11,7 +11,7 @@ import { Webhook } from '../../webhook/entities/webhook.entity';import { WebhookDeliveryFailure } from '../../webhook/entities/webhook-delivery-failure.entity';import { recordWebhookDeliveryFailure, statusCodeFromError } from '../../webhook/utils/record-delivery-failure';import { HookManager } from '../../../core/hooks';-import { withSafeFetch, isSsrfProtectionEnabled } from '../../../common/security/ssrf-guard';+import { withSafeFetch, isSsrfProtectionEnabled, redactSsrfError } from '../../../common/security/ssrf-guard';import { incrementWebhookDeliveryFailures } from '../../../common/metrics/webhook-delivery-metrics';export interface WebhookJobResult {@@ -136,6 +136,10 @@ export class WebhookProcessor extends WorkerHost {// On final failure (all retries exhausted): fire the error hook AND persist a durable record so// the lost event is visible after the BullMQ failed-set / logs roll off.if (isFinalAttempt) {+ // The hook payload and the durable row are surfaced to operators/plugins — redact SSRF detail+ // (resolved internal IP) from the client-facing message. The full `errorMessage` is already+ // logged server-side above; statusCodeFromError never matches an SSRF block (matches ^HTTP \d{3}).+ const clientError = redactSsrfError(error);await this.hookManager.execute('webhook:error',{@@ -143,7 +147,7 @@ export class WebhookProcessor extends WorkerHost {event,webhookId,deliveryId: payload.deliveryId,- error: errorMessage,+ error: clientError,attempt: job.attemptsMade + 1,},{ sessionId, source: 'WebhookProcessor' },@@ -157,7 +161,7 @@ export class WebhookProcessor extends WorkerHost {deliveryId: payload.deliveryId,attempts: job.attemptsMade + 1,lastStatusCode: statusCodeFromError(errorMessage),- lastError: errorMessage,+ lastError: clientError,});incrementWebhookDeliveryFailures();}diff --git a/src/modules/queue/redis-connection.spec.ts b/src/modules/queue/redis-connection.spec.tsindex cd61dcfb8..26f11a817 100644--- a/src/modules/queue/redis-connection.spec.ts+++ b/src/modules/queue/redis-connection.spec.ts@@ -11,7 +11,7 @@ describe('workerConnectionOptions (webhook Worker connection)', () => {// The producer sets enableOfflineQueue:false for fast-fail; the Worker must keep ioredis's default// (true). Asserting it is absent guards against the regression where the Worker inherited the// producer-only fast-fail from the shared connection and threw "Stream isn't writeable" on a blip.- const opts = workerConnectionOptions() as Record<string, unknown>;+ const opts = workerConnectionOptions() as unknown as Record<string, unknown>;expect(opts.enableOfflineQueue).toBeUndefined();});diff --git a/src/modules/search/providers/builtin-fts.provider.ts b/src/modules/search/providers/builtin-fts.provider.tsindex b72522314..b8dd6669e 100644--- a/src/modules/search/providers/builtin-fts.provider.ts+++ b/src/modules/search/providers/builtin-fts.provider.ts@@ -4,8 +4,8 @@ import { DataSource } from 'typeorm';import type { MessageType } from '../../../engine/interfaces/whatsapp-engine.interface';import { MessageDirection } from '../../message/entities/message.entity';import type { SearchProvider, SearchQuery, SearchResults, SearchHit } from '../search.types';+import { SEARCH_LIMIT_MAX } from '../search.constants';-const LIMIT_CAP = Number(process.env.SEARCH_LIMIT_MAX) || 100;const MAX_SNIPPET_WORDS = 24;/** Shape returned by the dialect-specific SELECT in buildSqlite / buildPostgres. */@@ -88,7 +88,7 @@ export class BuiltInFtsProvider implements SearchProvider {await this.ensureFts();const start = Date.now();const isPostgres = this.dataSource.options.type === 'postgres';- const limit = Math.max(1, Math.min(query.limit ?? 50, LIMIT_CAP));+ const limit = Math.max(1, Math.min(query.limit ?? 50, SEARCH_LIMIT_MAX));const offset = Math.max(0, query.offset ?? 0);const { sql, params } = isPostgresdiff --git a/src/modules/search/providers/plugin-search-provider.spec.ts b/src/modules/search/providers/plugin-search-provider.spec.tsindex 2860b31f0..72268fb0e 100644--- a/src/modules/search/providers/plugin-search-provider.spec.ts+++ b/src/modules/search/providers/plugin-search-provider.spec.ts@@ -1,7 +1,8 @@import { ServiceUnavailableException } from '@nestjs/common';+import { MessageDirection } from '../../message/entities/message.entity';import { PluginSearchProvider } from './plugin-search-provider';import type { PluginSearchTransport } from './plugin-search-provider';-import type { SearchResults } from '../search.types';+import type { SearchHit, SearchResults } from '../search.types';const fakeTransport = (overrides: Partial<PluginSearchTransport> = {}): PluginSearchTransport => ({dispatchSearch: jest@@ -53,4 +54,76 @@ describe('PluginSearchProvider', () => {await expect(p.health()).resolves.toEqual({ ok: true });});++ const mkHit = (overrides: Partial<SearchHit>): SearchHit => ({+ messageId: 'm',+ waMessageId: 'w',+ sessionId: 's1',+ chatId: 'c',+ body: 'hi',+ snippet: 'hi',+ timestamp: 1,+ type: 'text',+ direction: MessageDirection.OUTGOING,+ from: '[email protected]',+ ...overrides,+ });++ it('strips hits whose sessionId is outside query.sessionIds (host-side re-filter)', async () => {+ // The plugin is trusted to honor sessionIds, but a bug/leak must not surface an out-of-scope hit.+ // Without the host-side filter the leaked hit would pass straight through to the caller.+ const inScope = mkHit({ messageId: 'm1', sessionId: 's1' });+ const leaked = mkHit({ messageId: 'm2', sessionId: 'sX' });+ const results: SearchResults = { hits: [inScope, leaked], total: 2, tookMs: 3, provider: 'plugin:p' };+ const dispatchSearch = jest.fn().mockResolvedValue({ ok: true, results });+ const p = new PluginSearchProvider('p', 'P', fakeTransport({ dispatchSearch }), 1000);++ const res = await p.search({ q: 'hi', sessionIds: ['s1'] });+ expect(res.hits.map(h => h.sessionId)).toEqual(['s1']);+ expect(res.total).toBe(1);+ expect(res.tookMs).toBe(3);+ expect(res.provider).toBe('plugin:p');+ });++ it('preserves the plugin total when all hits are in-scope (pagination must still work)', async () => {+ // A well-behaved plugin returns a full page of in-scope hits with the true total spanning more pages.+ // Overwriting total with the page hit count would make "Load More" (hits.length < total) never fire,+ // stranding every result past page 1 for a scoped key.+ const hits = [mkHit({ messageId: 'm1', sessionId: 's1' }), mkHit({ messageId: 'm2', sessionId: 's1' })];+ const results: SearchResults = { hits, total: 500, tookMs: 3, provider: 'plugin:p' };+ const dispatchSearch = jest.fn().mockResolvedValue({ ok: true, results });+ const p = new PluginSearchProvider('p', 'P', fakeTransport({ dispatchSearch }), 1000);++ const res = await p.search({ q: 'hi', sessionIds: ['s1'] });+ expect(res.hits.map(h => h.sessionId)).toEqual(['s1', 's1']);+ expect(res.total).toBe(500); // preserved — not overwritten to the page count (2)+ });++ it('does not re-filter when sessionIds is unset (admin / unrestricted key)', async () => {+ const h1 = mkHit({ messageId: 'm1', sessionId: 's1' });+ const h2 = mkHit({ messageId: 'm2', sessionId: 'sX' });+ const results: SearchResults = { hits: [h1, h2], total: 2, tookMs: 3, provider: 'plugin:p' };+ const dispatchSearch = jest.fn().mockResolvedValue({ ok: true, results });+ const p = new PluginSearchProvider('p', 'P', fakeTransport({ dispatchSearch }), 1000);++ const res = await p.search({ q: 'hi' });+ expect(res.hits.map(h => h.sessionId)).toEqual(['s1', 'sX']);+ expect(res.total).toBe(2);+ });++ it('treats an empty sessionIds array as unrestricted (parity with the built-in SQL scoping)', async () => {+ // The built-in provider only emits its `IN (...)` clause when sessionIds is set AND non-empty+ // (applyFilters: `q.sessionIds && q.sessionIds.length`); an empty array is a no-op there. The+ // host-side re-filter must match that exactly so swapping providers never changes results for the+ // same query — diverging here would itself be a bug.+ const h1 = mkHit({ messageId: 'm1', sessionId: 's1' });+ const h2 = mkHit({ messageId: 'm2', sessionId: 'sX' });+ const results: SearchResults = { hits: [h1, h2], total: 2, tookMs: 1, provider: 'plugin:p' };+ const dispatchSearch = jest.fn().mockResolvedValue({ ok: true, results });+ const p = new PluginSearchProvider('p', 'P', fakeTransport({ dispatchSearch }), 1000);++ const res = await p.search({ q: 'hi', sessionIds: [] });+ expect(res.hits.map(h => h.sessionId)).toEqual(['s1', 'sX']);+ expect(res.total).toBe(2);+ });});diff --git a/src/modules/search/providers/plugin-search-provider.ts b/src/modules/search/providers/plugin-search-provider.tsindex e0234f9e0..f241b2782 100644--- a/src/modules/search/providers/plugin-search-provider.ts+++ b/src/modules/search/providers/plugin-search-provider.ts@@ -35,7 +35,25 @@ export class PluginSearchProvider implements SearchProvider {async search(query: SearchQuery): Promise<SearchResults> {const reply = await this.transport.dispatchSearch({ query, timeoutMs: this.timeoutMs });if (!reply.ok) throw new ServiceUnavailableException(reply.error);- return reply.results;+ // Defense-in-depth: the plugin is expected to honor sessionIds, but re-filter host-side so a plugin+ // bug or leak can never surface a hit outside the caller's allowed session scope — mirroring the+ // SQL-enforced scoping the built-in provider gets for free. The guard mirrors the built-in+ // provider's applyFilters condition (`sessionIds && sessionIds.length`) so the two providers never+ // diverge for the same query (an empty array is a no-op on both paths). When no filtering is+ // needed, return the results untouched. Preserve the plugin's total when no hits were out of scope+ // (the normal, well-behaved case) so pagination ("Load More" = hits.length < total) still works;+ // fall back to the filtered page count only when a leak was actually stripped (the plugin's claimed+ // total is then also suspect). tookMs/provider are passthrough metadata unrelated to scope.+ if (!query.sessionIds || !query.sessionIds.length) return reply.results;+ const allowed = new Set(query.sessionIds);+ const scoped = reply.results.hits.filter(h => allowed.has(h.sessionId));+ const leaked = reply.results.hits.length - scoped.length;+ return {+ hits: scoped,+ total: leaked > 0 ? scoped.length : reply.results.total,+ tookMs: reply.results.tookMs,+ provider: reply.results.provider,+ };}async health(): Promise<SearchHealth> {diff --git a/src/modules/search/search.constants.ts b/src/modules/search/search.constants.tsnew file mode 100644index 000000000..168802776--- /dev/null+++ b/src/modules/search/search.constants.ts@@ -0,0 +1,18 @@+/**+ * Host-side /search pagination bounds. Applied in SearchService BEFORE delegating to any provider,+ * so every backend (built-in DB full-text + plugin-backed) receives bounded pagination — a plugin+ * cannot be coaxed into returning an unbounded result set that pressures host heap. The built-in+ * provider re-asserts SEARCH_LIMIT_MAX inside its own SQL (defense-in-depth) by importing the same+ * constant, keeping a single source for the cap.+ *+ * SEARCH_LIMIT_MAX is env-driven (default 100, matching the historical built-in default).+ * SEARCH_OFFSET_MAX is a fixed deep-pagination guard (an offset this large is almost always a scan+ * or abuse pattern), intentionally not env-driven to avoid expanding the config surface.+ */+export const SEARCH_LIMIT_MAX = Number(process.env.SEARCH_LIMIT_MAX) || 100;++/** Generous upper bound on offset across every provider. */+export const SEARCH_OFFSET_MAX = 100_000;++/** Default page size when a caller omits `limit` (matches the built-in provider's historical default). */+export const SEARCH_DEFAULT_LIMIT = 50;diff --git a/src/modules/search/search.service.spec.ts b/src/modules/search/search.service.spec.tsindex 61c72ad5f..fb41c315e 100644--- a/src/modules/search/search.service.spec.ts+++ b/src/modules/search/search.service.spec.ts@@ -1,6 +1,7 @@import { NotImplementedException } from '@nestjs/common';import { SearchService } from './search.service';import { SearchProviderRegistry } from './search-provider.registry';+import { SEARCH_DEFAULT_LIMIT, SEARCH_LIMIT_MAX, SEARCH_OFFSET_MAX } from './search.constants';import type { SearchProvider, SearchResults } from './search.types';function mkProvider(id: string, search: SearchProvider['search']): SearchProvider {@@ -38,4 +39,47 @@ describe('SearchService', () => {await svc.search({ q: 'x', sessionIds: ['sneaky'] }, ['s1']);expect(search).toHaveBeenCalledWith(expect.objectContaining({ sessionIds: ['s1'] }));});++ it('clamps an excessive limit to SEARCH_LIMIT_MAX before it reaches any provider', async () => {+ // Without the host-side clamp a plugin provider would receive the raw caller value (9999) and+ // could pressure host heap by returning an oversized page. The built-in already rejected this in+ // its own SQL; the clamp extends the same bound to every provider.+ const reg = new SearchProviderRegistry();+ const search = jest.fn().mockResolvedValue(emptyResults);+ reg.register(mkProvider('builtin-fts', search));+ const svc = new SearchService(reg);+ await svc.search({ q: 'x', limit: 9999 });+ const received = (search.mock.calls[0] as [{ limit: number }])[0].limit;+ expect(received).toBe(SEARCH_LIMIT_MAX);+ expect(received).toBeLessThan(9999);+ });++ it('clamps an excessive offset to SEARCH_OFFSET_MAX before it reaches any provider', async () => {+ const reg = new SearchProviderRegistry();+ const search = jest.fn().mockResolvedValue(emptyResults);+ reg.register(mkProvider('builtin-fts', search));+ const svc = new SearchService(reg);+ await svc.search({ q: 'x', offset: 99_999_999 });+ const received = (search.mock.calls[0] as [{ offset: number }])[0].offset;+ expect(received).toBe(SEARCH_OFFSET_MAX);+ expect(received).toBeLessThan(99_999_999);+ });++ it('applies the default limit when the caller omits it', async () => {+ const reg = new SearchProviderRegistry();+ const search = jest.fn().mockResolvedValue(emptyResults);+ reg.register(mkProvider('builtin-fts', search));+ const svc = new SearchService(reg);+ await svc.search({ q: 'x' });+ expect(search).toHaveBeenCalledWith(expect.objectContaining({ limit: SEARCH_DEFAULT_LIMIT }));+ });++ it('passes in-bounds limit/offset through unchanged', async () => {+ const reg = new SearchProviderRegistry();+ const search = jest.fn().mockResolvedValue(emptyResults);+ reg.register(mkProvider('builtin-fts', search));+ const svc = new SearchService(reg);+ await svc.search({ q: 'x', limit: 10, offset: 20 });+ expect(search).toHaveBeenCalledWith(expect.objectContaining({ limit: 10, offset: 20 }));+ });});diff --git a/src/modules/search/search.service.ts b/src/modules/search/search.service.tsindex 46cd806cf..7cd6487f4 100644--- a/src/modules/search/search.service.ts+++ b/src/modules/search/search.service.ts@@ -1,5 +1,6 @@import { Injectable, NotImplementedException } from '@nestjs/common';import { SearchProviderRegistry } from './search-provider.registry';+import { SEARCH_DEFAULT_LIMIT, SEARCH_LIMIT_MAX, SEARCH_OFFSET_MAX } from './search.constants';import type { SearchQuery, SearchResults } from './search.types';@Injectable()@@ -10,7 +11,15 @@ export class SearchService {const provider = this.registry.active();if (!provider) throw new NotImplementedException('Search is not configured (no active search provider).');// Auth scoping is authoritative — a caller cannot override it via the query.- const scoped: SearchQuery = { ...query, sessionIds: callerSessionIds };+ // Bound pagination host-side so EVERY provider (built-in + plugin) receives capped values: the+ // built-in re-clamps in its own SQL, but a plugin would otherwise receive the raw caller value+ // and could pressure host heap by returning an oversized page.+ const scoped: SearchQuery = {+ ...query,+ sessionIds: callerSessionIds,+ limit: Math.min(query.limit ?? SEARCH_DEFAULT_LIMIT, SEARCH_LIMIT_MAX),+ offset: Math.min(query.offset ?? 0, SEARCH_OFFSET_MAX),+ };return provider.search(scoped);}diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 81d489c13..2fc460d15 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -1833,7 +1833,7 @@ describe('SessionService', () => {driverError: { code: 'SQLITE_CONSTRAINT_UNIQUE', message: 'UNIQUE constraint failed' },}); // re-fire- const msg = {+ const msg: IncomingMessage = {id: 'wa-1',from: '[email protected]',to: '[email protected]',@@ -1915,6 +1915,107 @@ describe('SessionService', () => {expect(messageRepository.save).not.toHaveBeenCalled(); // no longer the throwing path});});++ // ── persistHistoryMessages STORE_EPHEMERAL_MESSAGES guard ────────+ describe('persistHistoryMessages ephemeral guard', () => {+ const setupBulkQb = () => {+ const execute = jest.fn().mockResolvedValue({ identifiers: [] });+ const qb = {+ insert: jest.fn().mockReturnThis(),+ values: jest.fn().mockReturnThis(),+ orIgnore: jest.fn().mockReturnThis(),+ execute,+ };+ (messageRepository.createQueryBuilder as jest.Mock) = jest.fn().mockReturnValue(qb);+ (messageRepository.find as jest.Mock).mockResolvedValue([]);+ (messageRepository.create as jest.Mock).mockImplementation((data: Record<string, unknown>) => ({ ...data }));+ return { qb, execute };+ };++ it('skips a disappearing history message when STORE_EPHEMERAL_MESSAGES=false', async () => {+ process.env.STORE_EPHEMERAL_MESSAGES = 'false';+ const callbacks = await startAndCaptureCallbacks();+ const { qb, execute } = setupBulkQb();++ callbacks.onHistoryMessages?.([+ {+ id: 'h-eph',+ from: '[email protected]',+ to: '[email protected]',+ chatId: '[email protected]',+ body: 'vanishing',+ type: 'text',+ timestamp: 1,+ fromMe: false,+ isGroup: false,+ ephemeralDuration: 86400,+ },+ ]);+ await flush();++ // The guard dropped the only message before de-dup, so the bulk insert was never reached.+ expect(qb.values).not.toHaveBeenCalled();+ expect(execute).not.toHaveBeenCalled();+ delete process.env.STORE_EPHEMERAL_MESSAGES;+ });++ it('still persists a disappearing history message when STORE_EPHEMERAL_MESSAGES is unset (default)', async () => {+ delete process.env.STORE_EPHEMERAL_MESSAGES;+ const callbacks = await startAndCaptureCallbacks();+ const { qb } = setupBulkQb();++ callbacks.onHistoryMessages?.([+ {+ id: 'h-eph-default',+ from: '[email protected]',+ to: '[email protected]',+ chatId: '[email protected]',+ body: 'vanishing',+ type: 'text',+ timestamp: 1,+ fromMe: false,+ isGroup: false,+ ephemeralDuration: 86400,+ },+ ]);+ await flush();++ expect(qb.values).toHaveBeenCalledTimes(1);+ const calls = qb.values.mock.calls as unknown[][];+ const insertedRows = calls[0][0] as { waMessageId: string }[];+ expect(insertedRows).toHaveLength(1);+ expect(insertedRows[0].waMessageId).toBe('h-eph-default');+ });++ it('persists a non-disappearing history message even with STORE_EPHEMERAL_MESSAGES=false', async () => {+ process.env.STORE_EPHEMERAL_MESSAGES = 'false';+ const callbacks = await startAndCaptureCallbacks();+ const { qb } = setupBulkQb();++ callbacks.onHistoryMessages?.([+ {+ id: 'h-normal',+ from: '[email protected]',+ to: '[email protected]',+ chatId: '[email protected]',+ body: 'stays',+ type: 'text',+ timestamp: 1,+ fromMe: false,+ isGroup: false,+ // no ephemeralDuration — a regular chat message must never be dropped.+ },+ ]);+ await flush();++ expect(qb.values).toHaveBeenCalledTimes(1);+ const calls = qb.values.mock.calls as unknown[][];+ const insertedRows = calls[0][0] as { waMessageId: string }[];+ expect(insertedRows).toHaveLength(1);+ expect(insertedRows[0].waMessageId).toBe('h-normal');+ delete process.env.STORE_EPHEMERAL_MESSAGES;+ });+ });});// ── stop ──────────────────────────────────────────────────────────diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex be04d8aab..4ab1aec90 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -547,12 +547,20 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat* dispatch (it predates the live session). De-duplicated by `waMessageId` so re-syncs never duplicate.*/private async persistHistoryMessages(id: string, messages: IncomingMessage[]): Promise<void> {+ const storeEphemeralMessages = resolveFeatureFlags(this.configService).storeEphemeralMessages;const byId = new Map<string, IncomingMessage>();for (const m of messages) {// Need an id to de-dup; chatId/from/to are NOT NULL; status/story posts aren't chats.- if (m.id && !m.isStatusBroadcast && m.chatId && m.from && m.to) {- byId.set(m.id, m);+ if (!m.id || m.isStatusBroadcast || !m.chatId || !m.from || !m.to) {+ continue;}+ // Mirror the live onMessage guard: skip disappearing messages when the operator opted out, so a+ // history backfill can't bypass STORE_EPHEMERAL_MESSAGES=false. No-op when the flag is at its+ // default (true); only a message with a positive timer is dropped, never a regular one.+ if (!storeEphemeralMessages && (m.ephemeralDuration ?? 0) > 0) {+ continue;+ }+ byId.set(m.id, m);}if (byId.size === 0) {return;diff --git a/src/modules/settings/settings.controller.spec.ts b/src/modules/settings/settings.controller.spec.tsindex fdc2c89bb..427aa0eb9 100644--- a/src/modules/settings/settings.controller.spec.ts+++ b/src/modules/settings/settings.controller.spec.ts@@ -47,17 +47,17 @@ describe('SettingsController', () => {// read-only at runtime, so the write path must say so (501) rather than fake success.it('PUT /settings is read-only and throws 501 instead of a false-success 200', () => {const controller = new SettingsController(configStub);- expect(() => controller.update({})).toThrow(NotImplementedException);+ expect(() => controller.update()).toThrow(NotImplementedException);});it('PUT /settings still requires the ADMIN role', () => {- const proto = SettingsController.prototype as unknown as Record<string, object>;+ const proto = SettingsController.prototype as unknown as Record<string, (...args: unknown[]) => unknown>;const role = new Reflector().get<ApiKeyRole | undefined>(REQUIRED_ROLE_KEY, proto.update);expect(role).toBe(ApiKeyRole.ADMIN);});it('GET /settings requires the ADMIN role (env-derived config is not for low-privilege keys)', () => {- const proto = SettingsController.prototype as unknown as Record<string, object>;+ const proto = SettingsController.prototype as unknown as Record<string, (...args: unknown[]) => unknown>;const role = new Reflector().get<ApiKeyRole | undefined>(REQUIRED_ROLE_KEY, proto.get);expect(role).toBe(ApiKeyRole.ADMIN);});diff --git a/src/modules/stats/stats.controller.spec.ts b/src/modules/stats/stats.controller.spec.tsindex cc58a48ca..3bacc9a1e 100644--- a/src/modules/stats/stats.controller.spec.ts+++ b/src/modules/stats/stats.controller.spec.ts@@ -11,7 +11,7 @@ describe('StatsController access control', () => {const reflector = new Reflector();// Opaque-object view of the prototype so the lint unbound-method rule doesn't fire on a// metadata-only handler lookup.- const proto = StatsController.prototype as unknown as Record<string, object>;+ const proto = StatsController.prototype as unknown as Record<string, (...args: unknown[]) => unknown>;it.each(['getOverview', 'getMessageStats'] as const)('global stats route %s requires ADMIN', method => {const role = reflector.get<ApiKeyRole | undefined>(REQUIRED_ROLE_KEY, proto[method]);diff --git a/src/modules/webhook/webhook.controller.spec.ts b/src/modules/webhook/webhook.controller.spec.tsindex e1cb5f3d6..39ac6a0fc 100644--- a/src/modules/webhook/webhook.controller.spec.ts+++ b/src/modules/webhook/webhook.controller.spec.ts@@ -63,7 +63,7 @@ describe('Webhook controllers (secret leak + read authz)', () => {it('findOne does not return secret or headers, but keeps safe fields', async () => {(service.findOne as jest.Mock).mockResolvedValue(createSecretWebhook());- const result = await controller.findOne('wh-uuid-1');+ const result = await controller.findOne('sess-1', 'wh-uuid-1');expect(result).not.toHaveProperty('secret');expect(result).not.toHaveProperty('headers');@@ -113,7 +113,7 @@ describe('Webhook controllers (secret leak + read authz)', () => {it('update response returns no secret/headers', async () => {(service.update as jest.Mock).mockResolvedValue(createSecretWebhook({ url: 'https://new.example.com/hook' }));- const result = await controller.update('wh-uuid-1', { url: 'https://new.example.com/hook' });+ const result = await controller.update('sess-1', 'wh-uuid-1', { url: 'https://new.example.com/hook' });expect(result).not.toHaveProperty('secret');expect(result).not.toHaveProperty('headers');diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.tsindex 60f46fccb..51ee1a1f2 100644--- a/src/modules/webhook/webhook.service.spec.ts+++ b/src/modules/webhook/webhook.service.spec.ts@@ -497,6 +497,28 @@ describe('WebhookService', () => {timeoutSpy.mockRestore();});+ // A literal link-local IP is rejected synchronously by the SSRF guard before any fetch/DNS, so this+ // is fully offline. The raw SsrfBlockedError message names the resolved internal IP — an SSRF+ // disclosure oracle — so the test() response must surface the generic constant instead.+ it('test() does not leak the resolved internal IP when the SSRF guard blocks the URL', async () => {+ const origProtect = process.env.WEBHOOK_SSRF_PROTECT;+ delete process.env.WEBHOOK_SSRF_PROTECT; // default → on+ try {+ const webhook = createMockWebhook({ url: 'https://169.254.169.254/' });+ (repository.findOne as jest.Mock).mockResolvedValue(webhook);++ const result = await service.test('sess-1', webhook.id);++ expect(result.success).toBe(false);+ expect(result.error).toBe('Destination address is not allowed');+ expect(result.error).not.toMatch(/169\.254\.169\.254/);+ expect(mockFetch).not.toHaveBeenCalled(); // blocked before any network+ } finally {+ if (origProtect === undefined) delete process.env.WEBHOOK_SSRF_PROTECT;+ else process.env.WEBHOOK_SSRF_PROTECT = origProtect;+ }+ });+it('should NOT dispatch to webhooks that do not match the event', 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 85ffd24a3..4b6dfd15a 100644--- a/src/modules/webhook/webhook.service.ts+++ b/src/modules/webhook/webhook.service.ts@@ -30,6 +30,7 @@ import {isSsrfProtectionEnabled,SsrfBlockedError,SSRF_BLOCKED_CLIENT_MESSAGE,+ redactSsrfError,} from '../../common/security/ssrf-guard';import { HookManager } from '../../core/hooks';@@ -266,7 +267,7 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {} catch (error) {return {success: false,- error: error instanceof Error ? error.message : 'Unknown error',+ error: redactSsrfError(error, this.logger, 'webhook test'),};}}@@ -444,7 +445,7 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {sessionId,event,webhookId: webhook.id,- error: `Queue fallback delivery failed: ${String(fallbackError)}`,+ error: `Queue fallback delivery failed: ${redactSsrfError(fallbackError, this.logger, 'webhook fallback delivery')}`,},{ sessionId, source: 'WebhookService' },);@@ -477,7 +478,7 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {// Execute hook on errorawait this.hookManager.execute('webhook:error',- { sessionId, event, webhookId: webhook.id, error: String(error) },+ { sessionId, event, webhookId: webhook.id, error: redactSsrfError(error, this.logger, 'webhook delivery') },{ sessionId, source: 'WebhookService' },);@@ -552,7 +553,7 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {}// All direct-path retries exhausted — persist a durable failure record before giving up, mirroring// the queued processor's final-attempt path so the queue-disabled path isn't a blind spot.- const errMessage = error instanceof Error ? error.message : String(error);+ const errMessage = redactSsrfError(error);await recordWebhookDeliveryFailure(this.failureRepository, this.logger, {webhookId: webhook.id,sessionId: payload.sessionId,diff --git a/test/search.e2e-spec.ts b/test/search.e2e-spec.tsindex 5cd2beabd..2fdc801df 100644--- a/test/search.e2e-spec.ts+++ b/test/search.e2e-spec.ts@@ -135,42 +135,55 @@ describe('GET /api/search (e2e)', () => {});/**- * The SEARCH_ENABLED=false gate (app.module.ts): when the opt-out env is set, the conditional that- * builds the `searchModules` array omits SearchModule entirely, so the route, controller, service,- * registry, and provider are never wired (zero footprint — no 501 surface, no DI registration). A true- * route-404 e2e needs a separate process/env (jest.resetModules re-imports NestJS core, breaking DI- * identity), so per the task brief this is asserted at the module-registration level: the same gate- * expression AppModule uses, evaluated under both states, proving the opt-out excludes SearchModule.+ * The SEARCH_ENABLED=false gate (src/app.module.ts): the top-level conditional only pushes+ * SearchModule into `searchModules` (spread into AppModule's @Module imports) when the env is not+ * 'false', so an opt-out deployment never imports SearchModule at all — no route, controller,+ * service, registry, or provider (zero footprint, no 501 surface).+ *+ * Rather than re-implementing the gate branch locally (which would only assert a copy of the logic+ * and miss a regression in the real one), this re-evaluates the REAL app.module.ts under each env+ * (jest.isolateModules gives a fresh registry so the top-level conditional re-runs with the env we+ * set) and reads the ACTUAL @Module({ imports }) metadata, asserting whether SearchModule is present.+ * A full route-404 e2e would need a separately-booted app in a different process/env, which is why the+ * main describe above boots only the default (ON) instance; this pins the real opt-out decision.*/-describe('SEARCH_ENABLED gate (module-registration level)', () => {- // Mirrors src/app.module.ts's conditional exactly: `searchModules` is pushed only when the env is- // not 'false'. Asserting both branches pins the gate that determines whether AppModule imports- // SearchModule — the route exists iff this array is non-empty.- const buildSearchImports = (): unknown[] => {- const imports: unknown[] = [];- if (process.env.SEARCH_ENABLED !== 'false') imports.push('SearchModule');- return imports;+describe('SEARCH_ENABLED gate (real AppModule imports)', () => {+ // Re-requires the REAL app.module.ts under a fresh module registry with SEARCH_ENABLED=`value`,+ // then reports whether its actual @Module({ imports }) contains SearchModule. require() (not a+ // dynamic import()) avoids the TS2835 extension requirement under moduleResolution:nodenext.+ const searchModuleImportedWhen = (value: string | undefined): boolean => {+ const previous = process.env.SEARCH_ENABLED;+ if (value === undefined) delete process.env.SEARCH_ENABLED;+ else process.env.SEARCH_ENABLED = value;+ try {+ let imported = false;+ jest.isolateModules(() => {+ /* eslint-disable @typescript-eslint/no-require-imports -- require() (not a dynamic import())+ is the jest pattern for a fresh-evaluation read; the nodenext TS2835 extension rule only+ applies to ES imports, and a dynamic import() would need a separate tsconfig for specs. */+ const { AppModule } = require('../src/app.module') as typeof import('../src/app.module');+ const { SearchModule } =+ require('../src/modules/search/search.module') as typeof import('../src/modules/search/search.module');+ /* eslint-enable @typescript-eslint/no-require-imports */+ const imports: unknown[] = (Reflect.getMetadata('imports', AppModule) as unknown[]) ?? [];+ imported = imports.includes(SearchModule);+ });+ return imported;+ } finally {+ if (previous === undefined) delete process.env.SEARCH_ENABLED;+ else process.env.SEARCH_ENABLED = previous;+ }};- const saved: string | undefined = process.env.SEARCH_ENABLED;-- afterEach(() => {- if (saved === undefined) delete process.env.SEARCH_ENABLED;- else process.env.SEARCH_ENABLED = saved;- });-- it('includes SearchModule by default (SEARCH_ENABLED unset)', () => {- delete process.env.SEARCH_ENABLED;- expect(buildSearchImports()).toHaveLength(1);+ it('imports SearchModule by default (SEARCH_ENABLED unset)', () => {+ expect(searchModuleImportedWhen(undefined)).toBe(true);});- it('includes SearchModule when explicitly enabled', () => {- process.env.SEARCH_ENABLED = 'true';- expect(buildSearchImports()).toHaveLength(1);+ it('imports SearchModule when explicitly enabled', () => {+ expect(searchModuleImportedWhen('true')).toBe(true);});- it('omits SearchModule entirely when SEARCH_ENABLED=false (zero footprint)', () => {- process.env.SEARCH_ENABLED = 'false';- expect(buildSearchImports()).toHaveLength(0);+ it('omits SearchModule entirely when SEARCH_ENABLED=false (route cannot register)', () => {+ expect(searchModuleImportedWhen('false')).toBe(false);});});