Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(search): global message search via open-core SearchProvider + built-in DB full-text (#664)
Yudhi Armyndharisc31a1027eedb
diff --git a/.env.example b/.env.exampleindex ad32435bb..164727fbe 100644--- a/.env.example+++ b/.env.example@@ -294,6 +294,15 @@ RATE_LIMIT_MEDIUM_LIMIT=100 # max requests per window# MCP_IP_RATE_LIMIT_MAX=120 # max requests per IP per window (default 120)# MCP_IP_RATE_LIMIT_WINDOW_MS=60000 # window size in ms (default 60000 = 1 min)+# =============================================================================+# GLOBAL MESSAGE SEARCH+# =============================================================================+# Global message search (optional). Default ON, using the built-in DB full-text+# provider (Postgres tsvector/GIN, SQLite FTS5) — zero external services.+SEARCH_ENABLED=true # set to false to disable the /search route + module entirely+SEARCH_PROVIDER=auto # auto | builtin-fts | none (plugin ids selectable once Spec 2 lands)+SEARCH_LIMIT_MAX=100 # hard cap on the `limit` query param+# =============================================================================# PLUGINS# =============================================================================diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex b2b1bc387..3ab1a29dd 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -110,6 +110,19 @@ jobs:DATABASE_PASSWORD: openwaDATABASE_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: Dashboardruns-on: ubuntu-latestdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 71b5be7bd..f82e8e3ba 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **Global message search across sessions.** `GET /api/search` finds messages across all sessions through an open `SearchProvider` contract, with a built-in database full-text provider (PostgreSQL `tsvector`/`GIN`, SQLite `FTS5`) as the zero-dependency default — no external service required. Search works out of the box on both SQLite and PostgreSQL and survives repeated dialect switching and export/import round-trips; a non-FTS5 SQLite build skips the index gracefully and the route returns `501` instead of crashing boot. Set `SEARCH_ENABLED=false` to disable the route and module entirely (the index is DB-maintained per-write regardless, at negligible in-process cost). Advanced backends (typo-tolerance, CJK word-segmentation, large-scale relevance) will be available as provider plugins.+- **`message:persisted` plugin hook.** A new general extension point fired when a message is durably persisted — on outbound send (from `MessageService`) and on inbound receive (from `SessionService`, where both engine adapters converge on the single persist) — so plugins can react to persisted messages (e.g. an external search indexer) without coupling to the message/session services. The built-in FTS search provider is DB-synced and does not consume this hook; it exists for plugin providers and general use. Fire-and-forget: a handler error is swallowed and never breaks the send/receive path.- **Redis authentication via username.** Added support for `REDIS_USERNAME` to configure the Redis cache connection and BullMQ queue connections that require a username. Thanks @muhfalihr.## [0.8.11] - 2026-07-08diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 1909b403d..56675b108 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -4398,6 +4398,81 @@ For `tools/call` the result is an MCP `CallToolResult` (`content` array of `text> The full catalog of MCP tools (names, tiers, schemas) is documented separately — see **doc 24, MCP Integration**. This section documents only the transport endpoint.+### 6.4.12 Search++Base path `/api/search`. Cross-session full-text message search over an open `SearchProvider` contract;+the built-in database full-text provider (PostgreSQL `tsvector`/`GIN`, SQLite `FTS5`) answers by+default with zero external dependencies. Search is on by default; set `SEARCH_ENABLED=false` to remove+the route and module entirely (the index is DB-maintained regardless — see+[26 - Global Search](./26-global-search.md)). Requires at least `OPERATOR` role.++**Auth:** API key (≥ `OPERATOR`) · **Scope:** session-scoped — a scoped key's `allowedSessions` is+injected server-side from the key (never from the query), so a scoped key cannot broaden its reach; an+ADMIN / null-allowlist key searches all sessions.++#### GET /api/search++Search messages across sessions (active search provider).++**Query parameters**++| Name | Type | Required | Default | Description |+| --- | --- | --- | --- | --- |+| `q` | string | **Yes** | — | Search term. Must be non-empty after trim; whitespace-only is rejected with `400`. Passed to the active provider's native full-text matcher. |+| `sessionId` | string | No | — | Restrict to a single session id (intersected with the key's `allowedSessions` scope). |+| `chatId` | string | No | — | Restrict to a single chat id. |+| `direction` | enum (`incoming` \| `outgoing`) | No | — | Filter by message direction. |+| `type` | string | No | — | Filter by stored message `type` (e.g. `text`, `image`, `video`). Compared against `messages.type`; not an enum validation, any string is accepted and unmatched values simply return no hits. |+| `from` | string | No | — | Filter by sender. |+| `dateFrom` | integer (epoch ms) | No | — | Inclusive lower bound on `timestamp`. A non-numeric value is rejected with `400`. |+| `dateTo` | integer (epoch ms) | No | — | Inclusive upper bound on `timestamp`. A non-numeric value is rejected with `400`. |+| `limit` | integer (≥ 1) | No | `50` | Max hits to return. Clamped to `SEARCH_LIMIT_MAX` (default `100`). A non-numeric value is rejected with `400`. |+| `offset` | integer (≥ 0) | No | `0` | Pagination offset. A non-numeric value is rejected with `400`. |++**Response** `200` — `SearchResults`++```json+{+ "hits": [+ {+ "messageId": "8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a",+ "waMessageId": "[email protected]_3A...",+ "sessionId": "a1b2c3d4-...",+ "chatId": "[email protected]",+ "body": "full original message body...",+ "snippet": "...order <mark>confirmed</mark> for tomorrow…",+ "timestamp": 1751904000000,+ "type": "text",+ "direction": "incoming",+ "from": "[email protected]",+ "score": 0.075+ }+ ],+ "total": 23,+ "tookMs": 6,+ "provider": "builtin-fts"+}+```++- `snippet` is an XSS-safe text excerpt with `<mark>`/`</mark>` highlight markers around the matched+ term (both dialects emit the same markers). Render it as text, never as HTML.+- `total` is an exact count for pagination, computed lazily only when the returned page could be full.+- `provider` names which backend answered (e.g. `builtin-fts`); it is the registered `SearchProvider`+ id, so it changes when a plugin backend is selected via `SEARCH_PROVIDER`.+- `score` is optional and provider-specific (rank ordering is stable within a provider; cross-provider+ scores are not comparable).++**Errors:** `400` empty/whitespace `q`, a non-numeric `dateFrom`/`dateTo`/`limit`/`offset`, or a malformed+SQLite FTS5 query (unbalanced quote/paren, bare operator) — Postgres's `websearch_to_tsquery` is+tolerant and has no equivalent · `401` missing/invalid `X-API-Key` · `403` key role below `OPERATOR` ·+`501` no search provider configured (including a non-FTS5 SQLite build, where the provider is absent) ·+`503` active provider unhealthy (**reserved**: the built-in provider does not return it; it is the+contract surface for a future plugin provider whose `search()` throws `ServiceUnavailableException`).++> Scoping is authoritative: a scoped API key's `allowedSessions` is applied server-side and cannot be+> overridden via the query — there is no `sessionIds` query parameter, and `SearchService` overwrites+> any session scope at the provider boundary.+## 6.5 Real-time API (WebSocket)Live events are delivered over a **Socket.IO** connection (not a raw WebSocket). The server mounts a single Socket.IO namespace, **`/events`**, on the same port as the REST API. There are no REST routes in this module.diff --git a/docs/26-global-search.md b/docs/26-global-search.mdnew file mode 100644index 000000000..e4090b748--- /dev/null+++ b/docs/26-global-search.md@@ -0,0 +1,199 @@+# 26 - Global Search++> **Status:** Backend shipped — `GET /api/search` works out of the box on SQLite and PostgreSQL with+> the built-in database full-text provider, behind an open `SearchProvider` contract. This document is+> the user-facing feature guide: what it is, how to configure and query it, and when to reach for a+> plugin backend. A dashboard panel and the SDK helpers arrive in a later phase; until then the feature+> is driven through the REST endpoint documented here and in+> [06 - API Specification](./06-api-specification.md).++## 26.1 What it is++**Global message search** finds messages across **all sessions** through a single endpoint,+`GET /api/search`. Instead of looping over `GET /api/sessions/:id/messages/...` per session and+filtering client-side, a caller sends one query — a free-text term plus optional structural filters+(session, chat, direction, type, sender, date range) — and gets a ranked, paginated hit list with+highlighted snippets. It is the search substrate the dashboard search panel and external integrations+build on.++Search is **on by default** and works with zero external dependencies: the built-in provider is+DB-native (PostgreSQL `tsvector`/`GIN`, SQLite `FTS5`), so there is no separate search service to+provision, run, or keep in sync. Set `SEARCH_ENABLED=false` to remove the route and module entirely.++## 26.2 The provider model++Search is backed by an open `SearchProvider` contract, not a hardcoded query path:++```ts+interface SearchProvider {+ readonly id: string; // e.g. 'builtin-fts'+ readonly label: string; // human label for dashboard/config+ search(query: SearchQuery): Promise<SearchResults>;+ health(): Promise<SearchHealth>; // ok=false surfaces as 503+}+```++A registry holds the set of registered providers and the currently active one. Core registers+`builtin-fts` at bootstrap; a marketplace plugin registers itself the same way and can be promoted+with `SEARCH_PROVIDER`. When no provider is registered, the route returns `501` (never crashes boot).+The active provider answers every `/search` call, so swapping backends is a config change, not a code+change. Importantly, **indexing is not part of the contract** — each provider owns how its index stays+current (the built-in is DB-level; a plugin is hook-driven, see §26.7).++## 26.3 The built-in DB full-text default++The zero-dependency default (`id: builtin-fts`) uses the database's own full-text engine, so the index+is maintained by the DB on every INSERT/UPDATE/DELETE with no application code in the write path:++- **PostgreSQL (12+)** — a STORED generated `tsvector` column (`body_ts`, config `'simple'`) on+ `messages` with a `GIN` index over it. The column is auto-maintained by Postgres, so sends,+ receives, edits, and deletes stay in sync with zero app logic. Ranking uses `ts_rank`; snippets use+ `ts_headline`.+- **SQLite (FTS5)** — an `FTS5` external-content virtual table (`messages_fts`) keyed on the implicit+ `rowid`, kept in sync by AFTER INSERT/UPDATE/DELETE triggers and backfilled once at migration time.+ Ranking uses FTS5 `rank`; snippets use `snippet()`.++Both dialects wrap the search term in their native "web search"-style helper (`websearch_to_tsquery`+on Postgres, FTS5 `MATCH` on SQLite), so quoted phrases, `OR`, and `-`exclusion behave as the+underlying engine defines them. Snippets are emitted with `<mark>`/`</mark>` highlight markers on both+dialects so the `SearchHit.snippet` contract is dialect-agnostic — and the snippet is already+XSS-safe text; render it as text, never as HTML.++## 26.4 Dual-database switching safety++Search is designed to work identically on SQLite and PostgreSQL and to survive repeated switching+between them (e.g. developing on SQLite, deploying on Postgres, exporting a SQLite DB and importing+it into Postgres). Concretely:++- **Idempotent, dialect-branched migration.** The FTS migration (`1782400000000-AddMessagesFts`)+ branches on the active dialect and uses `IF NOT EXISTS` / `IF NOT` guards, so `migration:run` is+ safe to re-run on either backend. It does the one-time backfill for existing rows on first apply.+- **The provider picks its dialect per `DataSource`.** The built-in provider inspects+ `dataSource.options.type` on every query and builds the correct SQL (`?` vs `$n` placeholders,+ `messages_fts MATCH` vs `body_ts @@`, the right snippet function), so the same code path serves both+ backends without per-dialect configuration.+- **Graceful SQLite fallback.** A SQLite build **without** FTS5 compiled in does **not** crash boot:+ the migration probes `sqlite_compileoption_used('ENABLE_FTS5')` and skips, leaving no FTS schema; the+ provider detects the absent `messages_fts` table and the route returns `501` cleanly. (The bundled+ Docker image and the official Node builds include FTS5, so this only affects a custom-compiled+ SQLite.)+- **Export/import round-trip.** Because the index is a derived, DB-maintained structure (not a+ separate data store), an OpenWA export/import — which clears the `messages` table and re-inserts —+ leaves FTS correct on both dialects: Postgres regenerates the `body_ts` column from the re-inserted+ rows, and SQLite's triggers repopulate `messages_fts` on the re-inserts. No separate search reindex+ step is needed after a restore or a dialect migration. This is covered by the dual-DB test suite.++## 26.5 Configuration++All search configuration lives in the environment (`.env` / Compose / dashboard Infrastructure form):++| Variable | Default | Meaning |+| --- | --- | --- |+| `SEARCH_ENABLED` | `true` (unset) | Set to `false` to remove the `/search` route and the entire search module — zero footprint, no DI wiring. The migration still runs (so the index is ready if you re-enable). |+| `SEARCH_PROVIDER` | `auto` | `auto` selects the built-in provider at runtime; `builtin-fts` pins it explicitly; `none` disables the route at runtime while keeping the config namespace loaded. A plugin provider id selects that plugin once registered. Validated at boot — a typo fails fast. |+| `SEARCH_LIMIT_MAX` | `100` | Hard cap applied to the `limit` query parameter, so a caller cannot request an unbounded result set. |++### The opt-out footprint note++Setting `SEARCH_ENABLED=false` removes the **route and module**, but the **full-text index itself is+maintained per-write regardless**, because the index is DB-level (generated column / triggers), not+application-level. This is deliberate and by design: the index is a cheap derived structure maintained+in-process by the database on the same write that persists the message, so there is no extra network+hop, no separate service, and no double-write. The cost is negligible (a `tsvector` generate on+Postgres, a trigger-fire on SQLite — both in-process, both on columns already being written). If you+want to drop the index entirely, run the migration `down` against the data connection.++> **Dev note — `DATABASE_SYNCHRONIZE=true`.** With synchronize on (a common zero-config dev setting),+> TypeORM creates the `messages` table from the entity, but the FTS migration does **not** run, so+> `/search` returns `501` (no FTS schema) until you run `npm run migration:run` once to install the FTS+> virtual table / generated column. Prod defaults to `synchronize=false` + `migrationsRun=true`, so this+> is dev-only.+>+> **Postgres caveat — do not combine `DATABASE_TYPE=postgres` with `DATABASE_SYNCHRONIZE=true`.** The+> Postgres data connection hardcodes `migrationsRun=true` (unlike SQLite, where it is `!synchronize`),+> so on Postgres both run every boot: the migration adds the generated `body_ts` column, then+> `synchronize` immediately drops it (the `Message` entity does not declare `body_ts`). The result is+> `/search` returning `501` silently on every restart. Use migrations (`DATABASE_SYNCHRONIZE=false`, the+> prod default) for Postgres. SQLite is unaffected (its `migrationsRun` is `!synchronize`).++## 26.6 The HTTP endpoint++See [06 - API Specification §6.4.12](./06-api-specification.md) for the full param/response reference.+In brief:++```+GET /api/search?q=<term>&sessionId=<id>&chatId=<id>&direction=<in|out>&type=<type>+ &from=<sender>&dateFrom=<ms>&dateTo=<ms>&limit=<n>&offset=<n>+```++- **`q`** is required and must be non-empty (whitespace-only is rejected with `400`). Numeric params+ are coerced and validated; a non-numeric `limit`/`offset`/`dateFrom`/`dateTo` surfaces as `400`,+ never as a `NaN` SQL parameter.+- **Auth scoping is authoritative.** The caller's API-key `allowedSessions` is injected by+ `SearchService` — **never** accepted from the query — so a scoped key cannot broaden its reach. An+ ADMIN / null-allowlist key searches all sessions; a scoped key sees only its allowlist even if it+ passes `sessionId`. The DTO carries no `sessionIds` field (it would be rejected as non-whitelisted).+- **Response** is a `SearchResults` object: `{ hits: SearchHit[], total, tookMs, provider }`. Each hit+ carries `messageId`, `waMessageId`, `sessionId`, `chatId`, `body`, `snippet`, `timestamp`, `type`,+ `direction`, `from`, and optional `score`. `total` is an exact count (bounded; computed lazily only+ when the page could be full). `tookMs` is the provider-side query time. `provider` names which+ backend answered (e.g. `builtin-fts`).+- **Errors:** `400` empty/whitespace `q`, a non-numeric numeric param, or a malformed SQLite FTS5 query+ (unbalanced quote/paren, bare operator) — Postgres is tolerant · `401`/`403` auth · `501` no+ provider configured / FTS schema absent (e.g. a non-FTS5 SQLite build) · `503` provider unhealthy+ (**reserved**: the built-in provider does not return it; it is the contract surface for a future+ plugin provider whose `search()` throws `ServiceUnavailableException`).++The endpoint requires at least `OPERATOR` role.++## 26.7 When to use a plugin backend++The built-in DB full-text provider is the right default for the common case: moderate volume, Latin and+mixed-Script text, exact-word and phrase matching, and no extra infrastructure. Reach for a plugin+provider when you need capabilities the SQL engines do not give you:++- **CJK word-segmentation and morphological analysis** — Postgres `'simple'` and SQLite FTS5 tokenize+ on whitespace/punctuation, which does not segment Chinese/Japanese/Korean. A dedicated engine+ (Meilisearch, and others) segments CJK correctly.+- **Typo-tolerance / fuzzy matching** — the built-in matches terms as the engine's tokenizer produces+ them; it does not do Levenshtein-style "did you mean" correction. A search engine backend does.+- **Large-scale relevance and ranking tuning** — at high row counts or with complex relevance needs+ (field weights, synonyms, stop-word lists, custom ranking), a purpose-built search server+ outperforms a relational FTS query and is tunable without touching the message schema.++The upgrade path is the **Meilisearch provider plugin** (the reference plugin backend, Spec 2). It+registers as a `SearchProvider`, indexes via the `message:persisted` plugin hook (so it stays current+without coupling to the message/session services), and is selected by setting `SEARCH_PROVIDER` to its+id. Because the route and the response shape are identical across providers, dashboard panels and SDKs+keep working unchanged when you switch backends.++> **Backfill is the plugin's responsibility.** The `message:persisted` hook fires only for **live**+> traffic — outbound on send, inbound on receive — never for history-backfill persistence. So a plugin+> provider installed on a deployment that already has message history must perform its own one-time+> backfill (read `messages` and index) at enablement; its index will otherwise miss pre-installation+> rows. The built-in DB-FTS provider is unaffected — its index is DB-synced via triggers on every+> insert, including backfill.++## 26.8 Migration and backfill++Adding search to an existing deployment runs the one-time `1782400000000-AddMessagesFts` migration:++- **PostgreSQL** adds the generated `body_ts` column and the `GIN` index. The column is populated for+ all existing rows by Postgres as the `ALTER TABLE ... ADD COLUMN` applies, and the GIN index builds+ **non-`CONCURRENTLY`** (a one-time blocking build). On a very large `messages` table this can hold+ writes for a while — run the upgrade during a **maintenance window**. (You can set `SEARCH_ENABLED=false`+ to skip wiring the route while the migration runs; the migration applies regardless.)+- **SQLite** creates the `messages_fts` virtual table, backfills from the existing `messages` rows in+ one `INSERT ... SELECT`, and installs the sync triggers. This is fast for typical SQLite row counts+ but scales with table size.++The migration is safe to re-run (idempotent guards) and has a `down` path that drops the FTS schema on+both dialects. After it applies, search works immediately — no separate reindex command.++---++> See also: [06 - API Specification](./06-api-specification.md) (§6.4.12 Search),+> [05 - Database Design](./05-database-design.md),+> [03 - System Architecture](./03-system-architecture.md),+> [19 - Plugin Architecture](./19-plugin-architecture.md),+> [15 - Project Roadmap](./15-project-roadmap.md).diff --git a/docs/README.md b/docs/README.mdindex db83cf090..2d12035f2 100644--- a/docs/README.md+++ b/docs/README.md@@ -59,6 +59,7 @@| 23-S| [Plugin Sandboxing](./23-plugin-sandboxing.md) | Worker isolation, capabilities, and plugin limits || 24 | [MCP Integration](./24-mcp-integration.md) | Model Context Protocol tools and auth model || 25 | [Integration Fabric](./25-integration-fabric.md) | Inbound webhook substrate for plugin integrations |+| 26 | [Global Search](./26-global-search.md) | Cross-session message search and the provider model |**Examples**diff --git a/package.json b/package.jsonindex e94a9ee0a..712052a1c 100644--- a/package.json+++ b/package.json@@ -200,6 +200,12 @@"functions": 83,"lines": 84,"statements": 80+ },+ "./src/modules/search/": {+ "branches": 58,+ "functions": 72,+ "lines": 58,+ "statements": 58}},"testEnvironment": "node"diff --git a/src/app.module.ts b/src/app.module.tsindex eb5204228..43e794beb 100644--- a/src/app.module.ts+++ b/src/app.module.ts@@ -34,6 +34,7 @@ import { PluginsModule } from './core/plugins';import { PluginsApiModule } from './modules/plugins/plugins.module';import { AgentToolsModule } from './core/agent-tools/agent-tools.module';import { IntegrationModule } from './modules/integration/integration.module';+import { SearchModule } from './modules/search/search.module';// Only import QueueModule if explicitly enabled to avoid Redis connection errorsconst queueModules: Array<Type | DynamicModule> = [];@@ -45,6 +46,14 @@ if (process.env.QUEUE_ENABLED === 'true') {queueModules.push(queueModule.QueueModule);}+// Global message search. Opt-out via SEARCH_ENABLED=false: the module (route + provider + registry)+// is absent entirely — zero footprint, no DI wiring. Mirrors the queueModules/MCP conditional shape so+// an opt-out deployment never even loads the search providers. Default is ON for zero-config first boot.+const searchModules: Array<Type | DynamicModule> = [];+if (process.env.SEARCH_ENABLED !== 'false') {+ searchModules.push(SearchModule);+}+// Only mount the MCP server if explicitly enabled to avoid startup cost and// the SDK import (which pulls in @modelcontextprotocol/sdk) in non-MCP deployments.const mcpModules: Array<Type | DynamicModule> = [];@@ -256,6 +265,7 @@ if (dashboardServingEnabled && dashboardBuildPresent) {PluginsApiModule, // Phase 5: Plugins APIAgentToolsModule, // Agent-invocable tool registry (protocol-neutral)IntegrationModule, // Integration Fabric: @Public provider-webhook ingress + fast-ack pipeline+ ...searchModules, // Global message search (opt-out via SEARCH_ENABLED=false; default ON)...mcpModules, // MCP Streamable-HTTP server (opt-in via MCP_ENABLED=true)...serveStaticModules, // Bundled dashboard SPA (production single-port setup)],diff --git a/src/config/configuration.spec.ts b/src/config/configuration.spec.tsindex c9c12f30b..195ae66a2 100644--- a/src/config/configuration.spec.ts+++ b/src/config/configuration.spec.ts@@ -111,3 +111,23 @@ describe('configuration — plugin download cap is fail-safe', () => {}});});++describe('configuration search namespace', () => {+ // Save/restore the SEARCH_* env vars so a CI .env that sets them cannot flake the default-value+ // assertions below (mirrors the mutate-and-restore pattern used for PLUGIN_DOWNLOAD_MAX_BYTES etc.).+ const keys = ['SEARCH_ENABLED', 'SEARCH_PROVIDER', 'SEARCH_LIMIT_MAX'];+ const orig: Record<string, string | undefined> = {};+ beforeEach(() => keys.forEach(k => (orig[k] = process.env[k])));+ afterEach(() =>+ keys.forEach(k => {+ if (orig[k] === undefined) delete process.env[k];+ else process.env[k] = orig[k];+ }),+ );++ it('exposes search defaults', () => {+ keys.forEach(k => delete process.env[k]);+ const cfg = configuration();+ expect(cfg.search).toEqual({ enabled: true, provider: 'auto', limitMax: 100 });+ });+});diff --git a/src/config/configuration.ts b/src/config/configuration.tsindex f76bdd546..ceb5b3f1d 100644--- a/src/config/configuration.ts+++ b/src/config/configuration.ts@@ -3,6 +3,15 @@ import { computeFeatureFlags } from './feature-flags';export default () => ({port: parseInt(process.env.PORT || '2785', 10),+ // Global message search. Opt-out via SEARCH_ENABLED=false. Provider defaults to 'auto' (the+ // built-in DB full-text provider — Postgres tsvector/GIN, SQLite FTS5); 'none' disables the+ // /search route + module at runtime while keeping the config namespace loaded.+ search: {+ enabled: process.env.SEARCH_ENABLED !== 'false',+ provider: process.env.SEARCH_PROVIDER || 'auto',+ limitMax: Number(process.env.SEARCH_LIMIT_MAX) || 100,+ },+// Runtime feature flags. Single source of truth: src/config/feature-flags.ts. Exposed here so the// full set is discoverable via ConfigService (`features.*`) instead of scattered process.env reads.features: computeFeatureFlags(),diff --git a/src/config/env.validation.spec.ts b/src/config/env.validation.spec.tsindex 60ded4bc3..233402a01 100644--- a/src/config/env.validation.spec.ts+++ b/src/config/env.validation.spec.ts@@ -112,6 +112,17 @@ describe('validateEnv', () => {expect(() => validateEnv({})).not.toThrow();});+ it('rejects a SEARCH_PROVIDER typo instead of silently falling back to auto', () => {+ // A bogus / typo value must fail fast at boot rather than silently selecting the default provider.+ expect(() => validateEnv({ SEARCH_PROVIDER: 'bogus' })).toThrow(/SEARCH_PROVIDER/);+ // The three documented values are accepted.+ expect(() => validateEnv({ SEARCH_PROVIDER: 'auto' })).not.toThrow();+ expect(() => validateEnv({ SEARCH_PROVIDER: 'builtin-fts' })).not.toThrow();+ expect(() => validateEnv({ SEARCH_PROVIDER: 'none' })).not.toThrow();+ // Unset is accepted (the configuration default of 'auto' applies downstream).+ expect(() => validateEnv({})).not.toThrow();+ });+it('rejects a sqlite data DB path that collides with the internal main database file', () => {// The 'main' (auth/audit) and 'data' connections must be separate SQLite files; sharing one// file means two migration ledgers + synchronize policies on the same tables.diff --git a/src/config/env.validation.ts b/src/config/env.validation.tsindex 5d508bf21..e37f0dc65 100644--- a/src/config/env.validation.ts+++ b/src/config/env.validation.ts@@ -155,10 +155,24 @@ export function validateEnv(config: EnvConfig): EnvConfig {'STORE_EPHEMERAL_MESSAGES','RESOLVE_LID_TO_PHONE','SIMULATE_TYPING',+ 'SEARCH_ENABLED',]) {checkBool(key);}+ // SEARCH_PROVIDER enum: 'auto' selects the built-in DB full-text provider at runtime, 'builtin-fts'+ // pins it explicitly, 'none' keeps the module and route mounted but registers no provider, so+ // /search returns 501; use SEARCH_ENABLED=false to omit the module entirely (route 404). Plugin ids+ // become selectable once the provider registry lands. Reject a typo at boot rather than silently+ // falling back to auto.+ // Raw read (not `str(...)`) so an untrimmed bogus value like `'auto '` is rejected, matching the+ // raw-value philosophy of `checkBool` above; also lets unit tests drive the check via the `config`+ // object instead of reaching into `process.env`.+ const provider = config['SEARCH_PROVIDER'] as string | undefined;+ if (provider !== undefined && provider !== '' && !['auto', 'builtin-fts', 'none'].includes(provider)) {+ errors.push(`SEARCH_PROVIDER must be one of: auto, builtin-fts, none (got ${JSON.stringify(provider)})`);+ }+if (errors.length > 0) {throw new Error(`Invalid environment configuration:\n - ${errors.join('\n - ')}`);}diff --git a/src/core/hooks/hook.interfaces.spec.ts b/src/core/hooks/hook.interfaces.spec.tsnew file mode 100644index 000000000..04e78b7e5--- /dev/null+++ b/src/core/hooks/hook.interfaces.spec.ts@@ -0,0 +1,8 @@+import { isKnownHookEvent, KNOWN_HOOK_EVENTS } from './hook.interfaces';++describe('message:persisted hook event', () => {+ it('is a known event', () => {+ expect(isKnownHookEvent('message:persisted')).toBe(true);+ expect(KNOWN_HOOK_EVENTS.has('message:persisted')).toBe(true);+ });+});diff --git a/src/core/hooks/hook.interfaces.ts b/src/core/hooks/hook.interfaces.tsindex b0549243f..ad7e6ee77 100644--- a/src/core/hooks/hook.interfaces.ts+++ b/src/core/hooks/hook.interfaces.ts@@ -18,6 +18,7 @@ export type HookEvent =| 'message:sent'| 'message:failed'| 'message:ack'+ | 'message:persisted'// Webhook lifecycle| 'webhook:before'| 'webhook:queued' // After webhook job added to queue (queue mode only)@@ -44,6 +45,7 @@ const HOOK_EVENT_REGISTRY: Record<HookEvent, true> = {'message:sent': true,'message:failed': true,'message:ack': true,+ 'message:persisted': true,'webhook:before': true,'webhook:queued': true,'webhook:delivered': true,diff --git a/src/database/migrations/1782400000000-AddMessagesFts.ts b/src/database/migrations/1782400000000-AddMessagesFts.tsnew file mode 100644index 000000000..41fb11352--- /dev/null+++ b/src/database/migrations/1782400000000-AddMessagesFts.ts@@ -0,0 +1,79 @@+import { MigrationInterface, QueryRunner } from 'typeorm';++/**+ * Adds DB-native full-text search to `messages`:+ * - Postgres: a STORED generated `tsvector` column (config 'simple') + a GIN index.+ * The column is auto-maintained on INSERT/UPDATE, so revoke/delete stay in sync with zero app code.+ * - SQLite: an FTS5 external-content virtual table keyed on the implicit `rowid`, kept in sync by+ * triggers, backfilled once. (The PK is a UUID, so FTS keys on rowid and we join back for the id.)+ *+ * Non-CONCURRENTLY on PG (one-time blocking build). For very large `messages` tables, run the+ * upgrade during a maintenance window; set SEARCH_ENABLED=false to skip wiring (the migration still runs).+ */+export class AddMessagesFts1782400000000 implements MigrationInterface {+ name = 'AddMessagesFts1782400000000';++ async up(qr: QueryRunner): Promise<void> {+ const isPostgres = qr.connection.options.type === 'postgres';+ if (isPostgres) {+ // Lift the runtime statement_timeout (30000ms on the data pool — see app.module.ts) for this+ // migration transaction: the STORED generated column is a full-table rewrite, and the GIN index+ // build that follows is the heaviest boot migration. Without this, a large `messages` table can+ // exceed 30s and be aborted → boot crash. SET LOCAL is transaction-scoped (auto-reverts) and is+ // guarded by the dialect since SQLite rejects it syntactically. Mirrors 1781100000000 /+ // 1781300000000 / 1782200000000.+ await qr.query('SET LOCAL statement_timeout = 0');+ await qr.query(+ `ALTER TABLE "messages" ADD COLUMN IF NOT EXISTS "body_ts" tsvector GENERATED ALWAYS AS (to_tsvector('simple', coalesce(body, ''))) STORED`,+ );+ await qr.query(`CREATE INDEX IF NOT EXISTS "idx_messages_body_ts" ON "messages" USING GIN ("body_ts")`);+ return;+ }+ // SQLite FTS5 external-content — probe FTS5 first; skip (don't throw) if this build lacks it.+ const fts5 = (await qr.query(`SELECT sqlite_compileoption_used('ENABLE_FTS5') AS enabled`)) as Array<{+ enabled: number;+ }>;+ if (!Number(fts5?.[0]?.enabled)) {+ // FTS5 unavailable on this SQLite build — leave no FTS schema. The provider detects the absent+ // messages_fts table and 501s; OpenWA still boots. See Task 12.+ return;+ }+ await qr.query(+ `CREATE VIRTUAL TABLE IF NOT EXISTS "messages_fts" USING fts5(body, content='messages', content_rowid='rowid')`,+ );+ await qr.query(+ `INSERT INTO "messages_fts"("rowid", "body") SELECT "rowid", "body" FROM "messages" WHERE "body" IS NOT NULL`,+ );+ await qr.query(`DROP TRIGGER IF EXISTS messages_fts_ai`);+ await qr.query(`CREATE TRIGGER messages_fts_ai AFTER INSERT ON "messages" BEGIN+ INSERT INTO "messages_fts"("rowid", "body") VALUES (new."rowid", new."body");+ END`);+ await qr.query(`DROP TRIGGER IF EXISTS messages_fts_ad`);+ await qr.query(`CREATE TRIGGER messages_fts_ad AFTER DELETE ON "messages" BEGIN+ INSERT INTO "messages_fts"("messages_fts", "rowid", "body") VALUES ('delete', old."rowid", old."body");+ END`);+ await qr.query(`DROP TRIGGER IF EXISTS messages_fts_au`);+ // The WHEN clause limits re-indexing to body changes: without it every ack (SENT→DELIVERED→READ),+ // reaction, and status update does a redundant FTS delete+insert on the busiest message path for+ // zero search benefit (body didn't change). NULL-safe via `IS NOT` (SQLite's NULL-safe not-equal):+ // a NULL↔non-NULL body transition still fires, while ack-only updates skip. The INSERT and DELETE+ // triggers above are unchanged — only UPDATE gains the guard.+ await qr.query(`CREATE TRIGGER messages_fts_au AFTER UPDATE ON "messages" WHEN OLD.body IS NOT NEW.body BEGIN+ INSERT INTO "messages_fts"("messages_fts", "rowid", "body") VALUES ('delete', old."rowid", old."body");+ INSERT INTO "messages_fts"("rowid", "body") VALUES (new."rowid", new."body");+ END`);+ }++ async down(qr: QueryRunner): Promise<void> {+ const isPostgres = qr.connection.options.type === 'postgres';+ if (isPostgres) {+ await qr.query(`DROP INDEX IF EXISTS "idx_messages_body_ts"`);+ await qr.query(`ALTER TABLE "messages" DROP COLUMN IF EXISTS "body_ts"`);+ return;+ }+ await qr.query(`DROP TRIGGER IF EXISTS messages_fts_au`);+ await qr.query(`DROP TRIGGER IF EXISTS messages_fts_ad`);+ await qr.query(`DROP TRIGGER IF EXISTS messages_fts_ai`);+ await qr.query(`DROP TABLE IF EXISTS "messages_fts"`);+ }+}diff --git a/src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts b/src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.tsnew file mode 100644index 000000000..f73be2700--- /dev/null+++ b/src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts@@ -0,0 +1,126 @@+/* istanbul ignore file -- PG-gated: only runs under DATABASE_TYPE=postgres (test-postgres CI job);+ skipped in the default test job, so its lines would be unread and skew the global coverage gate. */+import 'reflect-metadata';+import { DataSource } from 'typeorm';+import { BuiltInFtsProvider } from '../../../modules/search/providers/builtin-fts.provider';+import { AddMessagesFts1782400000000 } from '../1782400000000-AddMessagesFts';++/**+ * Postgres runtime coverage for BuiltInFtsProvider. Companion to the SQLite spec+ * (builtin-fts.provider.spec.ts); asserts the same contract (match + rank + paginate, sessionIds+ * auth scope, sessionId filter, empty result, health) against the Postgres dialect branch, which+ * exercises `websearch_to_tsquery` + `ts_headline` against a STORED generated `body_ts` tsvector.+ *+ * Gating: this is the runtime proof the Task-6 provider works on PG — but local dev has no PG. The+ * repo's PG-migration harness (scripts/pg-uuid-smoke.js + the "Test (PostgreSQL migrations)" CI job)+ * keys off `DATABASE_TYPE=postgres` with DATABASE_HOST/PORT/USERNAME/PASSWORD/NAME; mirror that exact+ * convention here, and skip the whole suite unless DATABASE_TYPE=postgres is set. The CI job runs+ * this spec against a postgres:16 service; locally it skips cleanly.+ */+const POSTGRES_ENABLED = process.env.DATABASE_TYPE === 'postgres';++(POSTGRES_ENABLED ? describe : describe.skip)('BuiltInFtsProvider (postgres)', () => {+ let ds: DataSource;+ let provider: BuiltInFtsProvider;++ beforeEach(async () => {+ // Provision exactly like scripts/pg-uuid-smoke.js: DATABASE_* env, no ORM synchronize (we build+ // the messages table with raw DDL so the generated tsvector column comes from the migration+ // under test, not from entity metadata — and so no uuid-ossp/default dependency is introduced).+ ds = new DataSource({+ type: 'postgres',+ host: process.env.DATABASE_HOST || 'localhost',+ port: Number(process.env.DATABASE_PORT || 5432),+ username: process.env.DATABASE_USERNAME || 'openwa',+ password: process.env.DATABASE_PASSWORD || 'openwa',+ database: process.env.DATABASE_NAME || 'openwa',+ });+ await ds.initialize();++ // Drop any prior messages table (the CI job may share the service across steps) and build the+ // minimal shape BuiltInFtsProvider SELECTs against.+ await ds.query(`DROP TABLE IF EXISTS "messages" CASCADE`);+ await ds.query(+ `CREATE TABLE "messages" (` ++ `"id" varchar PRIMARY KEY NOT NULL, "sessionId" varchar NOT NULL, "waMessageId" varchar, ` ++ `"chatId" varchar NOT NULL, "from" varchar NOT NULL, "to" varchar NOT NULL, "body" text, ` ++ `"type" varchar NOT NULL DEFAULT 'text', "direction" varchar NOT NULL DEFAULT 'outgoing', ` ++ `"timestamp" bigint, "status" varchar NOT NULL DEFAULT 'sent', ` ++ `"createdAt" timestamp NOT NULL DEFAULT now())`,+ );+ // Adds the STORED generated `body_ts` tsvector + the GIN index — the exact objects the provider+ // relies on; running the migration (not hand-rolling DDL) is the point of this test.+ await new AddMessagesFts1782400000000().up(ds.createQueryRunner());++ provider = new BuiltInFtsProvider(ds);++ const insert = (id: string, sessionId: string, body: string, direction: string, ts: number) =>+ ds.query(+ `INSERT INTO "messages" ("id","sessionId","chatId","from","to","body","type","direction","timestamp") ` ++ `VALUES ($1,$2,$3,$4,$5,$6,'text',$7,$8)`,+ [id, sessionId, `${sessionId}-chat`, `${sessionId}-from`, '[email protected]', body, direction, ts],+ );+ await insert('m1', 's1', 'hello world', 'outgoing', 1);+ await insert('m2', 's1', 'goodbye world', 'outgoing', 2);+ await insert('m3', 's2', 'hello again', 'incoming', 3);+ });++ afterEach(async () => {+ if (ds && ds.isInitialized) {+ await ds.query(`DROP TABLE IF EXISTS "messages" CASCADE`).catch(() => undefined);+ await ds.destroy();+ }+ });++ it('matches by keyword via websearch_to_tsquery, ranks, and wraps the hit in <mark> via ts_headline', async () => {+ const res = await provider.search({ q: 'hello', limit: 10 });+ expect(res.provider).toBe('builtin-fts');+ expect(res.hits).toHaveLength(2);+ // ts_headline (configured with StartSel=<mark>,StopSel=</mark>) must delimit the match — the+ // dialect-agnostic snippet contract the SQLite path also upholds.+ expect(res.hits.every(h => h.snippet.includes('<mark>') && h.snippet.includes('</mark>'))).toBe(true);+ expect(res.hits.every(h => /hello/i.test(h.snippet))).toBe(true);+ expect(res.total).toBe(2);+ });++ it('scopes by sessionIds (auth) and by sessionId filter', async () => {+ const scoped = await provider.search({ q: 'hello', sessionIds: ['s1'] });+ expect(scoped.hits.every(h => h.sessionId === 's1')).toBe(true);+ expect(scoped.total).toBe(1);++ const one = await provider.search({ q: 'hello', sessionId: 's2' });+ expect(one.hits.map(h => h.sessionId)).toEqual(['s2']);+ });++ it('returns empty (not error) for no matches', async () => {+ const res = await provider.search({ q: 'zzzznomatch' });+ expect(res.hits).toEqual([]);+ expect(res.total).toBe(0);+ });++ it('reports healthy', async () => {+ expect((await provider.health()).ok).toBe(true);+ });++ // Task 12 PG carry-forward: prove the generated `body_ts` tsvector re-derives across the clear+re-+ // insert path that POST /infra/import-data performs (companion to the SQLite round-trip in+ // providers/search-dual-db.spec.ts). A STORED generated column is recomputed on every INSERT, so+ // re-inserted rows must re-enter the index with no stale or duplicate FTS entries.+ it('keeps FTS correct after a clear+re-insert (the import path), repeatedly', async () => {+ const insert = (id: string, sessionId: string, body: string) =>+ ds.query(+ `INSERT INTO "messages" ("id","sessionId","chatId","from","to","body","type","direction","timestamp") ` ++ `VALUES ($1,$2,$3,$4,$5,$6,'text','outgoing',$7)`,+ [id, sessionId, `${sessionId}-chat`, `${sessionId}-from`, '[email protected]', body, Date.now()],+ );+ for (let cycle = 0; cycle < 3; cycle++) {+ await ds.query(`DELETE FROM "messages"`);+ await insert(`m-alpha-${cycle}`, 's1', 'alpha beta');+ await insert(`m-gamma-${cycle}`, 's1', 'gamma delta');+ await insert(`m-alpha2-${cycle}`, 's1', 'alpha gamma');+ const res = await provider.search({ q: 'alpha', limit: 10 });+ expect(res.hits).toHaveLength(2); // 'alpha beta' + 'alpha gamma', never stale 'gamma delta'+ expect(res.total).toBe(2);+ }+ });+});diff --git a/src/database/migrations/__tests__/1782400000000-AddMessagesFts.spec.ts b/src/database/migrations/__tests__/1782400000000-AddMessagesFts.spec.tsnew file mode 100644index 000000000..5535edabb--- /dev/null+++ b/src/database/migrations/__tests__/1782400000000-AddMessagesFts.spec.ts@@ -0,0 +1,186 @@+import 'reflect-metadata';+import { DataSource, QueryRunner } from 'typeorm';+import { Message, MessageDirection } from '../../../modules/message/entities/message.entity';+import { Session } from '../../../modules/session/entities/session.entity';+import { AddMessagesFts1782400000000 } from '../1782400000000-AddMessagesFts';++/**+ * SQLite in-memory coverage for the AddMessagesFts migration:+ * - the FTS5 external-content table + 3 sync triggers are created and keep the index in sync on+ * insert/update (incl. the revoke path: clearing `body` drops the row from the index);+ * - re-running up() is a no-op (IF NOT EXISTS / DROP-then-CREATE idempotency);+ * - down() removes all four objects;+ * - the FTS5-absent build (probe returns 0) returns without creating anything and never throws.+ *+ * Postgres is exercised end-to-end in Task 7; the dialect branch is type-checked here via a stub.+ */+describe('AddMessagesFts migration (sqlite)', () => {+ let ds: DataSource;++ beforeEach(async () => {+ ds = new DataSource({+ type: 'sqlite',+ database: ':memory:',+ entities: [Session, Message],+ synchronize: true,+ migrations: [],+ });+ await ds.initialize();+ });+ afterEach(async () => {+ await ds.destroy();+ });++ it('creates messages_fts + triggers, keeps them in sync on insert, and drops rows on body clear', async () => {+ const runner = ds.createQueryRunner();+ await new AddMessagesFts1782400000000().up(runner);++ const repo = ds.getRepository(Message);+ await repo.insert({+ sessionId: 's1',+ chatId: 'c1',+ from: '[email protected]',+ to: '[email protected]',+ body: 'hello world',+ type: 'text',+ direction: MessageDirection.OUTGOING,+ timestamp: 1,+ });+ await repo.insert({+ sessionId: 's1',+ chatId: 'c1',+ from: '[email protected]',+ to: '[email protected]',+ body: 'banana',+ type: 'text',+ direction: MessageDirection.OUTGOING,+ timestamp: 2,+ });++ const rows = (await runner.query(+ `SELECT m.body FROM messages_fts JOIN messages m ON m.rowid = messages_fts.rowid WHERE messages_fts MATCH ?`,+ ['hello'],+ )) as Array<{ body: string }>;+ expect(rows.map(r => r.body)).toEqual(['hello world']);++ // revoke path: clearing body drops it from the index (AFTER UPDATE trigger issues the 'delete' command)+ await repo.update({ body: 'hello world' }, { body: '' });+ const after = (await runner.query(+ `SELECT count(*) AS n FROM messages_fts JOIN messages m ON m.rowid = messages_fts.rowid WHERE messages_fts MATCH ?`,+ ['hello'],+ )) as Array<{ n: number }>;+ expect(Number(after[0].n)).toBe(0);++ await runner.release();+ });++ it('is idempotent: re-running up() is a no-op and leaves exactly one messages_fts table', async () => {+ const runner = ds.createQueryRunner();+ const migration = new AddMessagesFts1782400000000();+ await migration.up(runner);+ await expect(migration.up(runner)).resolves.toBeUndefined();++ const tables = (await runner.query(+ `SELECT name FROM sqlite_master WHERE type='table' AND name='messages_fts'`,+ )) as Array<{ name: string }>;+ expect(tables).toHaveLength(1);+ for (const trig of ['messages_fts_ai', 'messages_fts_ad', 'messages_fts_au']) {+ const triggers = (await runner.query(`SELECT name FROM sqlite_master WHERE type='trigger' AND name=?`, [+ trig,+ ])) as Array<{ name: string }>;+ expect(triggers).toHaveLength(1);+ }+ await runner.release();+ });++ it('down() drops the virtual table and all three sync triggers', async () => {+ const runner = ds.createQueryRunner();+ const migration = new AddMessagesFts1782400000000();+ await migration.up(runner);+ await migration.down(runner);++ const table = (await runner.query(+ `SELECT name FROM sqlite_master WHERE type='table' AND name='messages_fts'`,+ )) as Array<{ name: string }>;+ expect(table).toHaveLength(0);+ const triggers = (await runner.query(+ `SELECT name FROM sqlite_master WHERE type='trigger' AND name IN ('messages_fts_ai','messages_fts_ad','messages_fts_au')`,+ )) as Array<{ name: string }>;+ expect(triggers).toHaveLength(0);+ await runner.release();+ });++ it('does not throw and leaves no FTS schema when FTS5 is unavailable (probe returns 0)', async () => {+ // Simulate a SQLite build compiled without ENABLE_FTS5: the probe returns enabled=0. up() must+ // return early (no CREATE VIRTUAL TABLE) so a non-FTS5 build doesn't crash boot.+ const calls: string[] = [];+ const stub = {+ connection: { options: { type: 'sqlite' as const } },+ query: jest.fn((stmt: string) => {+ calls.push(stmt);+ if (stmt.includes("sqlite_compileoption_used('ENABLE_FTS5')")) {+ return [{ enabled: 0 }];+ }+ throw new Error(`unexpected query on FTS5-absent path: ${stmt}`);+ }),+ } as unknown as QueryRunner;++ await expect(new AddMessagesFts1782400000000().up(stub)).resolves.toBeUndefined();+ // Only the probe should have been issued — no CREATE VIRTUAL TABLE / INSERT / trigger DDL.+ expect(calls).toHaveLength(1);+ expect(calls[0]).toContain('sqlite_compileoption_used');+ });+});++/**+ * Dual-DB safety (Task 12): the migration must tolerate repeated up()/down() cycling without leaving+ * partial state. Idempotency on a populated schema is covered above; this block adds the down→up+ * round-trip and asserts the FTS5 probe reports enabled on the actual test SQLite build (so the+ * absent-FTS5 branch is known to be the ONLY thing producing a 0 from that probe).+ */+describe('AddMessagesFts — dual-DB safety', () => {+ let ds: DataSource;++ beforeEach(async () => {+ ds = new DataSource({+ type: 'sqlite',+ database: ':memory:',+ entities: [Session, Message],+ synchronize: true,+ migrations: [],+ });+ await ds.initialize();+ });+ afterEach(async () => {+ await ds.destroy();+ });++ it('down() then up() round-trips cleanly (schema re-creatable after teardown)', async () => {+ const qr = ds.createQueryRunner();+ const m = new AddMessagesFts1782400000000();+ await m.up(qr);+ await m.down(qr);+ await m.up(qr);++ const tables = (await qr.query(+ `SELECT name FROM sqlite_master WHERE type='table' AND name='messages_fts'`,+ )) as Array<{ name: string }>;+ expect(tables).toHaveLength(1);+ for (const trig of ['messages_fts_ai', 'messages_fts_ad', 'messages_fts_au']) {+ const triggers = (await qr.query(`SELECT name FROM sqlite_master WHERE type='trigger' AND name=?`, [+ trig,+ ])) as Array<{ name: string }>;+ expect(triggers).toHaveLength(1);+ }+ await qr.release();+ });++ it('the FTS5 probe reports enabled on the test SQLite build', async () => {+ // The npm sqlite drivers ship with ENABLE_FTS5; this pins that assumption so the absent-FTS5 branch+ // (probe returns 0) is known to be the only path that produces a 0 here — not a stale assumption.+ const rows: Array<{ enabled: number }> = await ds.query(+ `SELECT sqlite_compileoption_used('ENABLE_FTS5') AS enabled`,+ );+ expect(Number(rows[0].enabled)).toBe(1);+ });+});diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.tsindex cbae076ff..380ae1c32 100644--- a/src/modules/message/message.service.spec.ts+++ b/src/modules/message/message.service.spec.ts@@ -189,6 +189,17 @@ describe('MessageService', () => {expect(hookManager.execute).not.toHaveBeenCalledWith('message:sent', expect.anything(), expect.anything());});+ it('emits message:persisted after saving an outbound message', async () => {+ await service.sendText('sess-1', { chatId: '[email protected]', text: 'hello' });++ const calls = (hookManager.execute as jest.Mock).mock.calls.filter(+ ([ev]: unknown[]) => ev === 'message:persisted',+ ) as unknown[][];+ expect(calls).toHaveLength(1);+ expect(calls[0][1]).toMatchObject({ sessionId: 'sess-1', message: { chatId: '[email protected]' } });+ expect(calls[0][2]).toMatchObject({ sessionId: 'sess-1', source: 'MessageService' });+ });+it('should throw BadRequestException when plugin blocks sending', async () => {(hookManager.execute as jest.Mock).mockResolvedValueOnce({ continue: false, data: {} });diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex a1dd6ceec..55b9b22b0 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -520,7 +520,13 @@ export class MessageService {status: data.status ?? MessageStatus.PENDING,metadata: data.metadata,});- return this.messageRepository.save(message);+ const saved = await this.messageRepository.save(message);+ // Fire-and-forget: a plugin handler must never break the send path. The built-in FTS search provider+ // is DB-synced and does NOT consume this; it exists for plugin providers (Spec 2) + general use.+ void this.hookManager+ .execute('message:persisted', { sessionId, message: saved }, { sessionId, source: 'MessageService' })+ .catch(() => undefined);+ return saved;}/**diff --git a/src/modules/search/dto/search-query.dto.spec.ts b/src/modules/search/dto/search-query.dto.spec.tsnew file mode 100644index 000000000..db03babf7--- /dev/null+++ b/src/modules/search/dto/search-query.dto.spec.ts@@ -0,0 +1,59 @@+import { validateSync } from 'class-validator';+import { plainToInstance } from 'class-transformer';+import { SearchQueryDto } from './search-query.dto';++describe('SearchQueryDto', () => {+ // Mirrors how the global ValidationPipe (transform:true + enableImplicitConversion) instantiates+ // the DTO from a query-string-shaped plain object: @Type(() => Number) coerces strings to numbers+ // before class-validator runs.+ const fromQuery = (query: Record<string, unknown>): SearchQueryDto => plainToInstance(SearchQueryDto, query);++ it('coerces numeric query-string fields to numbers', () => {+ const dto = fromQuery({ q: 'hello', limit: '5', offset: '10', dateFrom: '1000', dateTo: '2000' });+ expect(dto.limit).toBe(5);+ expect(dto.offset).toBe(10);+ expect(dto.dateFrom).toBe(1000);+ expect(dto.dateTo).toBe(2000);+ });++ it('rejects a non-numeric limit — the ?limit=abc → 400 path (Number(abc) is NaN, fails @IsNumber)', () => {+ const dto = fromQuery({ q: 'hello', limit: 'abc' });+ const errors = validateSync(dto);+ expect(errors.some(e => e.property === 'limit')).toBe(true);+ });++ it('rejects a non-numeric offset', () => {+ const dto = fromQuery({ q: 'hello', offset: 'xyz' });+ expect(validateSync(dto).some(e => e.property === 'offset')).toBe(true);+ });++ it('rejects limit < 1 (@Min(1))', () => {+ const dto = fromQuery({ q: 'hello', limit: '0' });+ expect(validateSync(dto).some(e => e.property === 'limit')).toBe(true);+ });++ it('rejects offset < 0 (@Min(0))', () => {+ const dto = fromQuery({ q: 'hello', offset: '-1' });+ expect(validateSync(dto).some(e => e.property === 'offset')).toBe(true);+ });++ it('rejects an invalid direction (@IsEnum(MessageDirection))', () => {+ const dto = fromQuery({ q: 'hello', direction: 'sideways' });+ expect(validateSync(dto).some(e => e.property === 'direction')).toBe(true);+ });++ it('accepts a valid direction', () => {+ const dto = fromQuery({ q: 'hello', direction: 'incoming' });+ expect(validateSync(dto)).toHaveLength(0);+ });++ it('rejects an empty q (@IsNotEmpty)', () => {+ const dto = fromQuery({ q: '' });+ expect(validateSync(dto).some(e => e.property === 'q')).toBe(true);+ });++ it('accepts a minimal valid query with only q', () => {+ const dto = fromQuery({ q: 'hello' });+ expect(validateSync(dto)).toHaveLength(0);+ });+});diff --git a/src/modules/search/dto/search-query.dto.ts b/src/modules/search/dto/search-query.dto.tsnew file mode 100644index 000000000..b1813d94d--- /dev/null+++ b/src/modules/search/dto/search-query.dto.ts@@ -0,0 +1,72 @@+import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';+import { IsString, IsNotEmpty, IsOptional, IsEnum, IsNumber, Min } from 'class-validator';+import { Type } from 'class-transformer';+import { MessageDirection } from '../../message/entities/message.entity';+import type { MessageType } from '../../../engine/interfaces/whatsapp-engine.interface';++/**+ * Request shape for GET /search. Numeric fields are coerced from query-string strings via+ * `@Type(() => Number)` and then validated with `@IsNumber()` — so `?limit=abc` (Number('abc') →+ * NaN) fails `@IsNumber()` and surfaces as a 400 from the global ValidationPipe, never reaching the+ * provider as a NaN SQL param. `sessionIds` is intentionally absent: scope is injected by+ * SearchService from the caller's API-key allowedSessions (never user-supplied).+ */+export class SearchQueryDto {+ @ApiProperty({ description: 'Search term (required, non-empty)' })+ @IsString()+ @IsNotEmpty()+ q: string;++ @ApiPropertyOptional({ description: 'Restrict to a single session' })+ @IsOptional()+ @IsString()+ sessionId?: string;++ @ApiPropertyOptional({ description: 'Restrict to a single chat id' })+ @IsOptional()+ @IsString()+ chatId?: string;++ @ApiPropertyOptional({ description: 'Sender filter' })+ @IsOptional()+ @IsString()+ from?: string;++ @ApiPropertyOptional({ enum: MessageDirection, description: 'incoming | outgoing' })+ @IsOptional()+ @IsEnum(MessageDirection)+ direction?: MessageDirection;++ @ApiPropertyOptional({ description: 'Message type filter (compared against stored messages.type)' })+ @IsOptional()+ @IsString()+ // `MessageType` is a string-literal union type alias, not a runtime enum, so @IsEnum can't validate+ // it. @IsString() accepts any string; the provider matches it against stored messages.type values.+ type?: MessageType;++ @ApiPropertyOptional({ description: 'Epoch-ms lower bound (inclusive)', type: Number })+ @IsOptional()+ @Type(() => Number)+ @IsNumber()+ dateFrom?: number;++ @ApiPropertyOptional({ description: 'Epoch-ms upper bound (inclusive)', type: Number })+ @IsOptional()+ @Type(() => Number)+ @IsNumber()+ dateTo?: number;++ @ApiPropertyOptional({ description: 'Max hits to return', type: Number })+ @IsOptional()+ @Type(() => Number)+ @IsNumber()+ @Min(1)+ limit?: number;++ @ApiPropertyOptional({ description: 'Pagination offset', type: Number })+ @IsOptional()+ @Type(() => Number)+ @IsNumber()+ @Min(0)+ offset?: number;+}diff --git a/src/modules/search/providers/builtin-fts.provider.spec.ts b/src/modules/search/providers/builtin-fts.provider.spec.tsnew file mode 100644index 000000000..e2e086ccc--- /dev/null+++ b/src/modules/search/providers/builtin-fts.provider.spec.ts@@ -0,0 +1,137 @@+import 'reflect-metadata';+import { BadRequestException } from '@nestjs/common';+import { DataSource } from 'typeorm';+import { Message, MessageDirection } from '../../../modules/message/entities/message.entity';+import { Session } from '../../../modules/session/entities/session.entity';+import { BuiltInFtsProvider } from './builtin-fts.provider';+import { AddMessagesFts1782400000000 } from '../../../database/migrations/1782400000000-AddMessagesFts';++describe('BuiltInFtsProvider (sqlite)', () => {+ let ds: DataSource;+ let provider: BuiltInFtsProvider;++ beforeEach(async () => {+ ds = new DataSource({ type: 'sqlite', database: ':memory:', entities: [Session, Message], synchronize: true });+ await ds.initialize();+ await new AddMessagesFts1782400000000().up(ds.createQueryRunner());+ provider = new BuiltInFtsProvider(ds);+ const repo = ds.getRepository(Message);+ await repo.insert([+ {+ sessionId: 's1',+ chatId: 'c1',+ from: '[email protected]',+ to: '[email protected]',+ body: 'hello world',+ type: 'text',+ direction: MessageDirection.OUTGOING,+ timestamp: 1,+ },+ {+ sessionId: 's1',+ chatId: 'c1',+ from: '[email protected]',+ to: '[email protected]',+ body: 'goodbye world',+ type: 'text',+ direction: MessageDirection.OUTGOING,+ timestamp: 2,+ },+ {+ sessionId: 's2',+ chatId: 'c2',+ from: '[email protected]',+ to: '[email protected]',+ body: 'hello again',+ type: 'text',+ direction: MessageDirection.INCOMING,+ timestamp: 3,+ },+ ]);+ });+ afterEach(() => ds.destroy());++ it('matches by keyword and ranks + paginates', async () => {+ const res = await provider.search({ q: 'hello', limit: 10 });+ expect(res.provider).toBe('builtin-fts');+ expect(res.hits.length).toBe(2);+ expect(res.hits.every(h => /hello/i.test(h.snippet))).toBe(true);+ expect(res.total).toBe(2);+ });++ it('scopes by sessionIds (auth) and by sessionId filter', async () => {+ const scoped = await provider.search({ q: 'hello', sessionIds: ['s1'] });+ expect(scoped.hits.every(h => h.sessionId === 's1')).toBe(true);+ const one = await provider.search({ q: 'hello', sessionId: 's2' });+ expect(one.hits.map(h => h.sessionId)).toEqual(['s2']);+ });++ it('returns empty (not error) for no matches', async () => {+ const res = await provider.search({ q: 'zzzznomatch' });+ expect(res.hits).toEqual([]);+ expect(res.total).toBe(0);+ });++ it('reports healthy', async () => {+ expect((await provider.health()).ok).toBe(true);+ });++ it('maps an FTS5 syntax error to a 400 (not an unhandled 500)', async () => {+ // SQLite FTS5 treats `"`, `(`, `*` as query grammar — an unbalanced quote is a syntax error,+ // which must surface as BadRequestException (400), never a raw 500. Postgres's+ // websearch_to_tsquery is tolerant and has no equivalent failure mode.+ await expect(provider.search({ q: '"unbalanced' })).rejects.toThrow(BadRequestException);+ await expect(provider.search({ q: '*foo' })).rejects.toThrow(BadRequestException);+ await expect(provider.search({ q: '(test' })).rejects.toThrow(BadRequestException);+ });++ it('treats dateFrom/dateTo as epoch-ms against a seconds timestamp column', async () => {+ // Contract (DTO + docs) is epoch-ms, but messages.timestamp stores epoch-seconds (WhatsApp+ // messageTimestamp). Seed a row at a known seconds value and assert: a dateFrom in ms that+ // covers it includes the hit, while a dateFrom one second later (also in ms) excludes it. This+ // pins the ms→seconds conversion at the bind boundary — without it `seconds >= ms` is false for+ // every modern row and dateFrom silently excludes all results.+ const repo = ds.getRepository(Message);+ const tsSeconds = 1_700_000_000;+ await repo.insert({+ sessionId: 's1',+ chatId: 'c1',+ from: '[email protected]',+ to: '[email protected]',+ body: 'datefilter probe term',+ type: 'text',+ direction: MessageDirection.OUTGOING,+ timestamp: tsSeconds,+ });++ const included = await provider.search({ q: 'datefilter', dateFrom: tsSeconds * 1000 });+ expect(included.hits.map(h => h.body)).toContain('datefilter probe term');++ const excluded = await provider.search({ q: 'datefilter', dateFrom: (tsSeconds + 1) * 1000 });+ expect(excluded.hits).toEqual([]);+ });++ it('the FTS UPDATE trigger carries a WHEN body-change guard (not fire on ack-only updates)', async () => {+ // The messages_fts_au trigger must be guarded so it only re-indexes when body actually changes.+ // Without the WHEN clause every ack (SENT→DELIVERED→READ) and reaction does a redundant FTS+ // delete+insert on the busiest message path. Assert the definition in sqlite_master includes the+ // WHEN guard so a future regression that drops it is caught here, not just in production write+ // amplification. The body-change re-index path itself is covered by the revoke test below.+ const rows: unknown[] = await ds.query(+ `SELECT sql FROM sqlite_master WHERE type='trigger' AND name='messages_fts_au'`,+ );+ expect(String((rows[0] as { sql?: string })?.sql ?? '')).toMatch(/WHEN\s+OLD\.body\s+IS\s+NOT\s+NEW\.body/i);+ });++ it('re-indexes on a body UPDATE (revoke path: body changes, FTS reflects the new value)', async () => {+ // A body UPDATE must still re-index — the WHEN guard must not suppress legitimate body changes.+ // The revoke flow sets body to empty; assert the FTS index reflects the new body and no longer+ // matches the old term, while a new search for a freshly-written body still hits.+ const repo = ds.getRepository(Message);+ await repo.update({ body: 'hello world' }, { body: 'goodbye updated' });+ const oldTerm = await provider.search({ q: 'hello' });+ expect(oldTerm.hits.map(h => h.body)).not.toContain('hello world');+ const newTerm = await provider.search({ q: 'goodbye' });+ expect(newTerm.hits.map(h => h.body)).toContain('goodbye updated');+ });+});diff --git a/src/modules/search/providers/builtin-fts.provider.ts b/src/modules/search/providers/builtin-fts.provider.tsnew file mode 100644index 000000000..b72522314--- /dev/null+++ b/src/modules/search/providers/builtin-fts.provider.ts@@ -0,0 +1,256 @@+import { BadRequestException, Injectable, NotImplementedException } from '@nestjs/common';+import { InjectDataSource } from '@nestjs/typeorm';+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';++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. */+interface FtsResultRow {+ id: string;+ wa_message_id: string | null;+ session_id: string;+ chat_id: string;+ from: string;+ body: string | null;+ timestamp: string | number | null;+ type: string;+ direction: string;+ snippet: string | null;+ score: number | string | null;+}++interface CountRow {+ n: number | string;+}++/** Returns the next placeholder token (`?` for SQLite, `$n` for Postgres). */+type PlaceholderFn = () => string;++/**+ * Built-in, DB-native full-text provider. Index sync is DB-level (generated tsvector / FTS5 triggers),+ * so this class ONLY queries — it never writes the index. See migration 1782400000000-AddMessagesFts.+ */+@Injectable()+export class BuiltInFtsProvider implements SearchProvider {+ readonly id = 'builtin-fts';+ readonly label = 'Built-in database full-text search';++ // OpenWA has two TypeORM connections (main: auth/audit SQLite, data: messages). Bind explicitly to+ // 'data' so the provider queries the connection that owns the `messages` table + the FTS migration,+ // never the default/`main` one. The bare `DataSource` type alone is ambiguous with two connections.+ constructor(@InjectDataSource('data') private readonly dataSource: DataSource) {}++ /**+ * Whether the DB-native FTS schema this provider queries is present. Cached per instance after the+ * first probe. The migration (1782400000000-AddMessagesFts) is what creates it; on a non-FTS5 SQLite+ * build the migration probes + skips, leaving the schema absent — in that state the provider must+ * 501 cleanly (see ensureFts) instead of crashing on a missing table / column.+ */+ private ftsAvailable: boolean | null = null;++ /**+ * Probes the FTS schema once per instance and caches the result. SQLite: look for the `messages_fts`+ * virtual table in sqlite_master. Postgres: look for the generated `body_ts` column in+ * information_schema. Safe to call repeatedly; only the first call hits the DB.+ */+ private async probeFts(): Promise<boolean> {+ if (this.ftsAvailable !== null) return this.ftsAvailable;+ if (this.dataSource.options.type === 'postgres') {+ const rows: unknown[] = await this.dataSource.query(+ `SELECT 1 FROM information_schema.columns WHERE table_name='messages' AND column_name='body_ts'`,+ );+ this.ftsAvailable = Array.isArray(rows) && rows.length === 1;+ } else {+ const rows: unknown[] = await this.dataSource.query(+ `SELECT name FROM sqlite_master WHERE type='table' AND name='messages_fts'`,+ );+ this.ftsAvailable = Array.isArray(rows) && rows.length === 1;+ }+ return this.ftsAvailable;+ }++ /**+ * Guards search(): if the FTS schema is absent (non-FTS5 SQLite build or a partial state), throw+ * NotImplementedException so the route surfaces 501 — never let a raw missing-table error escape.+ */+ private async ensureFts(): Promise<void> {+ const ok = await this.probeFts();+ if (!ok) {+ throw new NotImplementedException('Search is unavailable: the database has no full-text index.');+ }+ }++ async search(query: SearchQuery): Promise<SearchResults> {+ 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 offset = Math.max(0, query.offset ?? 0);++ const { sql, params } = isPostgres+ ? this.buildPostgres(query, limit, offset)+ : this.buildSqlite(query, limit, offset);++ // SQLite FTS5 treats `"`, `(`, `)`, `*`, and bare OR/AND/NOT/NEAR as query syntax, so a malformed+ // query (`?q="hello`, `?q=(test`, `?q=*foo`) raises one of three query-grammar errors at exec time+ // (`fts5: syntax error`, `unterminated string`, `unknown special query`). Surface those as a 400 —+ // matching Postgres's tolerant websearch_to_tsquery, which has no equivalent failure mode — never a+ // raw 500. Generic DB errors (`no such column`, connection drops) are rethrown unchanged.+ const fts5QueryError = /(fts5:\s*syntax\s*error|unterminated\s+string|unknown\s+special\s+query)/i;+ let rows: FtsResultRow[];+ try {+ rows = await this.dataSource.query<FtsResultRow[]>(sql, params);+ } catch (e) {+ if (!isPostgres && fts5QueryError.test(String(e))) {+ throw new BadRequestException('Malformed search query for SQLite full-text search.');+ }+ throw e;+ }+ const hits: SearchHit[] = rows.map(r => this.mapRow(r));+ const total = rows.length < limit && offset === 0 ? rows.length : await this.count(query, isPostgres);++ return { hits, total, tookMs: Date.now() - start, provider: this.id };+ }++ async health(): Promise<{ ok: boolean; detail?: string }> {+ // Reflects FTS availability (not just raw connectivity): a non-FTS5 build reports unhealthy here+ // so /health and the registry surface the true state. DB errors still map to { ok: false }.+ try {+ const ok = await this.probeFts();+ return { ok, detail: ok ? undefined : 'full-text index absent' };+ } catch (e) {+ return { ok: false, detail: e instanceof Error ? e.message : String(e) };+ }+ }++ private mapRow(r: FtsResultRow): SearchHit {+ return {+ messageId: r.id,+ waMessageId: r.wa_message_id ?? '',+ sessionId: r.session_id,+ chatId: r.chat_id,+ body: r.body ?? '',+ snippet: r.snippet ?? '',+ timestamp: Number(r.timestamp ?? 0),+ type: r.type as MessageType,+ direction: r.direction as MessageDirection,+ from: r.from,+ score: r.score == null ? undefined : Number(r.score),+ };+ }++ /**+ * Dialect-aware placeholder generator. SQLite binds `?` positionally by param-array order+ * (so we emit `?` regardless of slot). Postgres binds `$n` positional by the order tokens+ * APPEAR in the final SQL string — so each call returns the next `$n`, and callers MUST+ * invoke it in SQL-appearance order while pushing the matching param in the same step.+ */+ private static sqlitePlaceholder: PlaceholderFn = () => '?';+ private pgPlaceholder(): PlaceholderFn {+ let n = 0;+ return () => `$${++n}`;+ }++ // --- SQLite FTS5 -----------------------------------------------------------+ // SQL appearance order: MATCH term -> filters -> LIMIT -> OFFSET. Params pushed in that order.+ private buildSqlite(q: SearchQuery, limit: number, offset: number) {+ const ph = BuiltInFtsProvider.sqlitePlaceholder;+ const params: unknown[] = [];+ const where: string[] = [`messages_fts MATCH ${ph()}`];+ params.push(q.q);+ this.applyFilters(where, params, q, 'm.', ph);+ const cols = `m."id", m."waMessageId" AS wa_message_id, m."sessionId" AS session_id, m."chatId" AS chat_id, m."from" AS "from", m."body", m."timestamp", m."type", m."direction", snippet(messages_fts, 0, '<mark>', '</mark>', '…', ${MAX_SNIPPET_WORDS}) AS snippet, rank AS score`;+ const sql = `SELECT ${cols} FROM messages_fts JOIN messages m ON m."rowid" = messages_fts."rowid" WHERE ${where.join(' AND ')} ORDER BY rank, m."timestamp" DESC LIMIT ${ph()} OFFSET ${ph()}`;+ params.push(limit, offset);+ return { sql, params };+ }++ // --- Postgres tsvector -----------------------------------------------------+ // SQL appearance order: FTS term (in FROM clause) -> filters (in WHERE) -> LIMIT -> OFFSET.+ // The FTS term lives in `FROM messages m, websearch_to_tsquery('simple', $1) AS q(query)`,+ // which renders BEFORE the WHERE filters — so it must be `$1`, filters `$2..`, LIMIT/OFFSET last.+ // Params are pushed in the same order so the Nth param maps to `$N`.+ private buildPostgres(q: SearchQuery, limit: number, offset: number) {+ const ph = this.pgPlaceholder();+ const params: unknown[] = [];+ const ftsTerm = `websearch_to_tsquery('simple', ${ph()}) AS q(query)`;+ params.push(q.q);+ const where: string[] = [`m.body_ts @@ q.query`];+ this.applyFilters(where, params, q, 'm.', ph);+ // StartSel/StopSel are pinned to <mark>/</mark> to match the SQLite FTS5 snippet() output, so the+ // SearchHit.snippet contract stays dialect-agnostic (PG's ts_headline defaults to <b>/</b>).+ const cols = `m."id", m."waMessageId" AS wa_message_id, m."sessionId" AS session_id, m."chatId" AS chat_id, m."from", m."body", m."timestamp", m."type", m."direction", ts_headline('simple', m."body", q.query, 'MaxFragments=1, MaxWords=${MAX_SNIPPET_WORDS}, StartSel=<mark>, StopSel=</mark>') AS snippet, ts_rank(m.body_ts, q.query) AS score`;+ const sql = `SELECT ${cols} FROM messages m, ${ftsTerm} WHERE ${where.join(' AND ')} ORDER BY score DESC, m."timestamp" DESC LIMIT ${ph()} OFFSET ${ph()}`;+ params.push(limit, offset);+ return { sql, params };+ }++ /** Emits dialect-correct placeholders. For PG, MUST be called in SQL-appearance order. */+ private applyFilters(where: string[], params: unknown[], q: SearchQuery, prefix: string, ph: PlaceholderFn): void {+ if (q.sessionIds && q.sessionIds.length) {+ const placeholders = q.sessionIds.map(() => ph()).join(',');+ where.push(`${prefix}"sessionId" IN (${placeholders})`);+ params.push(...q.sessionIds);+ }+ if (q.sessionId) {+ where.push(`${prefix}"sessionId" = ${ph()}`);+ params.push(q.sessionId);+ }+ if (q.chatId) {+ where.push(`${prefix}"chatId" = ${ph()}`);+ params.push(q.chatId);+ }+ if (q.from) {+ where.push(`${prefix}"from" = ${ph()}`);+ params.push(q.from);+ }+ if (q.direction) {+ where.push(`${prefix}"direction" = ${ph()}`);+ params.push(q.direction);+ }+ if (q.type) {+ const types = Array.isArray(q.type) ? q.type : [q.type];+ const placeholders = types.map(() => ph()).join(',');+ where.push(`${prefix}"type" IN (${placeholders})`);+ params.push(...types);+ }+ // The public contract (DTO + docs) is epoch-ms, but messages.timestamp stores epoch-seconds+ // (WhatsApp messageTimestamp — see the inbound mappers in the engine adapters). Bind ms→seconds+ // at the boundary, otherwise `seconds >= ms` is false for every modern row and dateFrom/dateTo+ // silently exclude all results.+ if (q.dateFrom) {+ where.push(`${prefix}"timestamp" >= ${ph()}`);+ params.push(Math.floor(q.dateFrom / 1000));+ }+ if (q.dateTo) {+ where.push(`${prefix}"timestamp" <= ${ph()}`);+ params.push(Math.floor(q.dateTo / 1000));+ }+ }++ private async count(q: SearchQuery, isPostgres: boolean): Promise<number> {+ const where: string[] = [];+ const params: unknown[] = [];+ if (isPostgres) {+ const ph = this.pgPlaceholder();+ const ftsTerm = `websearch_to_tsquery('simple', ${ph()}) AS q(query)`;+ params.push(q.q);+ where.push(`m.body_ts @@ q.query`);+ this.applyFilters(where, params, q, 'm.', ph);+ const sql = `SELECT count(*)::int AS n FROM messages m, ${ftsTerm} WHERE ${where.join(' AND ')}`;+ const rows = await this.dataSource.query<CountRow[]>(sql, params);+ return Number(rows[0]?.n ?? 0);+ }+ const ph = BuiltInFtsProvider.sqlitePlaceholder;+ where.push(`messages_fts MATCH ${ph()}`);+ params.push(q.q);+ this.applyFilters(where, params, q, 'm.', ph);+ const sql = `SELECT count(*) AS n FROM messages_fts JOIN messages m ON m."rowid" = messages_fts."rowid" WHERE ${where.join(' AND ')}`;+ const rows = await this.dataSource.query<CountRow[]>(sql, params);+ return Number(rows[0]?.n ?? 0);+ }+}diff --git a/src/modules/search/providers/search-dual-db.spec.ts b/src/modules/search/providers/search-dual-db.spec.tsnew file mode 100644index 000000000..b6d68e6cb--- /dev/null+++ b/src/modules/search/providers/search-dual-db.spec.ts@@ -0,0 +1,88 @@+import 'reflect-metadata';+import { DataSource } from 'typeorm';+import { Message, MessageDirection } from '../../../modules/message/entities/message.entity';+import { Session } from '../../../modules/session/entities/session.entity';+import { AddMessagesFts1782400000000 } from '../../../database/migrations/1782400000000-AddMessagesFts';+import { BuiltInFtsProvider } from './builtin-fts.provider';++/**+ * Dual-DB switching + import/export round-trip safety (Task 12). OpenWA's `data` DB is SQLite-or-+ * Postgres and switchable; export/import performs `repo.clear()` + re-insert. DB-level sync (SQLite+ * FTS5 triggers / PG generated `body_ts` column) must keep the index correct across that clear+re-+ * insert — no stale or duplicate FTS rows. This is the SQLite runtime proof; the Postgres round-trip+ * is the same clear+re-insert cycle in 1782400000000-AddMessagesFts.pg.spec.ts.+ *+ * Also covers the FTS-absent safety net: if the FTS schema is missing (e.g. non-FTS5 SQLite build+ * where the migration skipped, or a partial state), the provider 501s cleanly instead of crashing on+ * a missing table — and the dialect branch reads `dataSource.options.type`.+ */+async function boot(): Promise<{ ds: DataSource; provider: BuiltInFtsProvider }> {+ const ds = new DataSource({+ type: 'sqlite',+ database: ':memory:',+ entities: [Session, Message],+ synchronize: true,+ });+ await ds.initialize();+ await new AddMessagesFts1782400000000().up(ds.createQueryRunner());+ return { ds, provider: new BuiltInFtsProvider(ds) };+}++// Minimal row factory. `to` is NOT NULL on the entity; including it keeps the insert from failing at+// runtime (the entity's TS type would flag the omission, but the brief's `as any` masked it).+const row = (body: string) => ({+ sessionId: 's1',+ chatId: 'c1',+ from: '[email protected]',+ to: '[email protected]',+ body,+ type: 'text',+ direction: MessageDirection.OUTGOING,+ timestamp: 1,+});++describe('search dual-DB + import/export round-trip safety (sqlite)', () => {+ it('keeps FTS correct after a clear+re-insert (the import path), repeatedly', async () => {+ const { ds, provider } = await boot();+ const repo = ds.getRepository(Message);++ // Seed before the cycling begins.+ await repo.insert([row('alpha beta'), row('gamma delta')]);++ // Simulate POST /infra/import-data: clear, then re-insert. The FTS5 external-content triggers+ // must re-derive every index row on re-insert, so no stale 'gamma delta' (only) entry survives+ // and no duplicates accumulate across cycles.+ for (let cycle = 0; cycle < 3; cycle++) {+ await repo.clear();+ await repo.insert([row('alpha beta'), row('gamma delta'), row('alpha gamma')]);+ const res = await provider.search({ q: 'alpha', limit: 10 });+ expect(res.hits).toHaveLength(2); // 'alpha beta' + 'alpha gamma', never the stale 'gamma delta'+ expect(res.total).toBe(2);+ }+ await ds.destroy();+ });++ it('the provider 501s (NotImplemented) when FTS is absent (no-FTS5 / partial-state simulation)', async () => {+ // Boot a DataSource WITHOUT running AddMessagesFts → messages_fts is absent. The provider must+ // detect this and throw NotImplementedException (→ HTTP 501), not crash on a missing table.+ const ds = new DataSource({+ type: 'sqlite',+ database: ':memory:',+ entities: [Session, Message],+ synchronize: true,+ });+ await ds.initialize();+ const provider = new BuiltInFtsProvider(ds);+ await expect(provider.search({ q: 'x' })).rejects.toThrow(/no full-text index/i);+ await ds.destroy();+ });++ it('uses the SQLite query path on a sqlite DataSource (dialect branch decision)', async () => {+ // Smoke: the provider reads dataSource.options.type and branches. The SQLite branch is exercised+ // end-to-end above (and in builtin-fts.provider.spec.ts); the PG branch lives in the PG-gated+ // spec. This pins the branch decision so a future refactor can't silently drop the dialect read.+ const sqlite = await boot();+ expect((sqlite.provider as unknown as { dataSource: DataSource }).dataSource.options.type).toBe('sqlite');+ await sqlite.ds.destroy();+ });+});diff --git a/src/modules/search/search-provider.contract.spec.ts b/src/modules/search/search-provider.contract.spec.tsnew file mode 100644index 000000000..3760855f9--- /dev/null+++ b/src/modules/search/search-provider.contract.spec.ts@@ -0,0 +1,112 @@+import 'reflect-metadata';+import { DataSource } from 'typeorm';+import { AddMessagesFts1782400000000 } from '../../database/migrations/1782400000000-AddMessagesFts';+import { Message, MessageDirection } from '../message/entities/message.entity';+import { Session } from '../session/entities/session.entity';+import { BuiltInFtsProvider } from './providers/builtin-fts.provider';+import type { SearchProvider } from './search.types';++/** A seed message the contract harness asks the provider-under-test to index. */+type ContractSeedMessage = { body: string; sessionId: string };++/** Environment a provider-under-test exposes to the contract harness. */+interface ContractEnv {+ provider: SearchProvider;+ /** Index the given messages (same bodies/sessionIds the harness asserts against). */+ seed: (messages: ContractSeedMessage[]) => Promise<void>;+}++/**+ * Contract every SearchProvider must satisfy. Run inside a `describe` from a provider's own spec+ * (Spec 2's Meilisearch plugin reuses this as its review gate):+ *+ * describe('MyProvider', () => { runProviderContract(async () => ({ provider, seed })); });+ *+ * The harness seeds a fixed 3-message set (two sessions, one shared term `hello`, one session-unique+ * `goodbye`) in `beforeEach`, then asserts the provider's `search`/`health` contract. `makeProvider`+ * is invoked fresh per test so each case starts from a clean index.+ */+export function runProviderContract(makeProvider: () => Promise<ContractEnv>): void {+ let provider: SearchProvider;+ let seed: (messages: ContractSeedMessage[]) => Promise<void>;++ beforeEach(async () => {+ const env = await makeProvider();+ provider = env.provider;+ seed = env.seed;+ await seed([+ { body: 'hello world', sessionId: 's1' },+ { body: 'goodbye world', sessionId: 's1' },+ { body: 'hello other', sessionId: 's2' },+ ]);+ });++ it('returns matching hits with a snippet, total, and provider id', async () => {+ const q = 'hello';+ const res = await provider.search({ q, limit: 10 });+ expect(res.provider).toBe(provider.id);+ expect(res.hits.length).toBe(2);+ // Snippet must actually reflect the query term — `length >= 0` is trivially true.+ expect(res.hits.every(h => h.snippet.toLowerCase().includes(q.toLowerCase()))).toBe(true);+ expect(res.total).toBeGreaterThanOrEqual(2);+ });++ it('honors sessionIds scoping', async () => {+ const res = await provider.search({ q: 'hello', sessionIds: ['s2'] });+ // The seed puts `hello other` in s2, so this MUST yield ≥1 hit — otherwise the `every`+ // predicate below is vacuously true on an empty hit set (zero-hit escape hatch).+ expect(res.hits.length).toBeGreaterThanOrEqual(1);+ expect(res.hits.every(h => h.sessionId === 's2')).toBe(true);+ });++ it('returns empty for no matches', async () => {+ const res = await provider.search({ q: 'zzzz' });+ expect(res.hits).toEqual([]);+ // For pagination correctness, total === 0 when no hits is part of the contract.+ expect(res.total).toBe(0);+ });++ it('reports health', async () => {+ const h = await provider.health();+ expect(typeof h.ok).toBe('boolean');+ });+}++// Wire the built-in provider into the contract: proves the harness is satisfiable and gives Spec 2's+// plugin a concrete example. The seed mirrors the FTS provider spec's message shape (Task 6).+describe('BuiltInFtsProvider satisfies the SearchProvider contract', () => {+ let ds: DataSource;++ afterEach(async () => {+ if (ds && ds.isInitialized) {+ await ds.destroy();+ }+ });++ runProviderContract(async () => {+ ds = new DataSource({+ type: 'sqlite',+ database: ':memory:',+ entities: [Session, Message],+ synchronize: true,+ });+ await ds.initialize();+ await new AddMessagesFts1782400000000().up(ds.createQueryRunner());+ const provider = new BuiltInFtsProvider(ds);+ const seed = async (messages: ContractSeedMessage[]): Promise<void> => {+ await ds.getRepository(Message).insert(+ messages.map(m => ({+ sessionId: m.sessionId,+ body: m.body,+ chatId: 'c',+ from: '[email protected]',+ to: '[email protected]',+ type: 'text',+ direction: MessageDirection.OUTGOING,+ timestamp: 1,+ })),+ );+ };+ return { provider, seed };+ });+});diff --git a/src/modules/search/search-provider.registry.spec.ts b/src/modules/search/search-provider.registry.spec.tsnew file mode 100644index 000000000..701f227f3--- /dev/null+++ b/src/modules/search/search-provider.registry.spec.ts@@ -0,0 +1,42 @@+import { SearchProviderRegistry } from './search-provider.registry';+import type { SearchProvider } from './search.types';++function mk(id: string): SearchProvider {+ return { id, label: id, search: jest.fn(), health: jest.fn() };+}++describe('SearchProviderRegistry', () => {+ it('returns null when nothing is registered', () => {+ expect(new SearchProviderRegistry().active()).toBeNull();+ });++ it('auto-selects the first registered provider as active', () => {+ const r = new SearchProviderRegistry();+ r.register(mk('a'));+ expect(r.active()?.id).toBe('a');+ });++ it('setActive selects among registered providers; register idempotent; unregister clears active', () => {+ const r = new SearchProviderRegistry();+ r.register(mk('a'));+ r.register(mk('b'));+ r.setActive('b');+ expect(r.active()?.id).toBe('b');+ r.unregister('b');+ expect(r.active()?.id).toBe('a');+ r.unregister('a');+ expect(r.active()).toBeNull();+ });++ it('list returns all registered providers', () => {+ const r = new SearchProviderRegistry();+ r.register(mk('a'));+ r.register(mk('b'));+ expect(+ r+ .list()+ .map(p => p.id)+ .sort(),+ ).toEqual(['a', 'b']);+ });+});diff --git a/src/modules/search/search-provider.registry.ts b/src/modules/search/search-provider.registry.tsnew file mode 100644index 000000000..0c3858b92--- /dev/null+++ b/src/modules/search/search-provider.registry.ts@@ -0,0 +1,38 @@+import { Injectable } from '@nestjs/common';+import type { SearchProvider } from './search.types';++/**+ * Holds the set of registered SearchProviders and the currently active one.+ * Core registers `builtin-fts` at bootstrap; plugins (Spec 2) register themselves.+ * active() returns null when nothing is registered → the route 501s.+ */+@Injectable()+export class SearchProviderRegistry {+ private readonly providers = new Map<string, SearchProvider>();+ private activeId: string | null = null;++ register(provider: SearchProvider): void {+ this.providers.set(provider.id, provider);+ if (this.activeId === null) this.activeId = provider.id;+ }++ unregister(id: string): void {+ this.providers.delete(id);+ if (this.activeId === id) {+ this.activeId = Array.from(this.providers.keys())[0] ?? null;+ }+ }++ setActive(id: string): void {+ if (!this.providers.has(id)) throw new Error(`unknown search provider: ${id}`);+ this.activeId = id;+ }++ active(): SearchProvider | null {+ return this.activeId === null ? null : (this.providers.get(this.activeId) ?? null);+ }++ list(): SearchProvider[] {+ return [...this.providers.values()];+ }+}diff --git a/src/modules/search/search.controller.spec.ts b/src/modules/search/search.controller.spec.tsnew file mode 100644index 000000000..7357b93bc--- /dev/null+++ b/src/modules/search/search.controller.spec.ts@@ -0,0 +1,64 @@+import { BadRequestException, NotImplementedException } from '@nestjs/common';+import { SearchController } from './search.controller';+import { SearchService } from './search.service';+import { SearchQueryDto } from './dto/search-query.dto';+import type { ApiKey } from '../auth/entities/api-key.entity';+import type { SearchResults } from './search.types';++describe('SearchController', () => {+ const search = jest.fn();+ const ctrl = new SearchController({ search } as unknown as SearchService);++ const ok = { hits: [], total: 0, tookMs: 1, provider: 'builtin-fts' } satisfies SearchResults;++ beforeEach(() => {+ search.mockReset();+ });++ it('throws 400 when q is empty', async () => {+ const dto: SearchQueryDto = { q: '' };+ await expect(ctrl.search(dto, undefined)).rejects.toBeInstanceOf(BadRequestException);+ });++ it('throws 400 when q is only whitespace', async () => {+ // @IsNotEmpty() on the DTO passes for ' ' (non-empty), so the controller's own trim guard is+ // what rejects whitespace-only q — this test pins that guard in place.+ const dto: SearchQueryDto = { q: ' ' };+ await expect(ctrl.search(dto, undefined)).rejects.toBeInstanceOf(BadRequestException);+ expect(search).not.toHaveBeenCalled();+ });++ it('returns results and forwards the key allowedSessions as callerSessionIds', async () => {+ search.mockResolvedValue(ok);+ const apiKey = { allowedSessions: ['s1', 's2'] } as unknown as ApiKey;+ const dto: SearchQueryDto = { q: 'hello', limit: 5 };+ const res = await ctrl.search(dto, apiKey);+ expect(search).toHaveBeenCalledWith(dto, ['s1', 's2']);+ expect(res).toBe(ok);+ });++ it('passes undefined (no scope) for an unrestricted key (null allowedSessions)', async () => {+ search.mockResolvedValue(ok);+ // A null/empty allowlist (e.g. ADMIN) sees all sessions — mirrors GET /webhooks behavior.+ const apiKey = { allowedSessions: null } as unknown as ApiKey;+ const dto: SearchQueryDto = { q: 'hello' };+ await ctrl.search(dto, apiKey);+ expect(search).toHaveBeenCalledWith(dto, undefined);+ });++ it('derives callerSessionIds only from the key, never from the query (anti-smuggling)', async () => {+ search.mockResolvedValue(ok);+ // `sessionIds` is not a field on SearchQueryDto, so it cannot be expressed in the query at all;+ // the global ValidationPipe (forbidNonWhitelisted) would reject it, and SearchService clobbers+ // any sessionIds at the provider boundary. The controller itself derives scope solely from the+ // key — here there is no key → undefined.+ const dto: SearchQueryDto = { q: 'hello' };+ await ctrl.search(dto, undefined);+ expect(search).toHaveBeenCalledWith(dto, undefined);+ });++ it('propagates 501 (NotImplementedException) from the service when no provider is active', async () => {+ search.mockRejectedValue(new NotImplementedException('none'));+ await expect(ctrl.search({ q: 'x' }, undefined)).rejects.toBeInstanceOf(NotImplementedException);+ });+});diff --git a/src/modules/search/search.controller.ts b/src/modules/search/search.controller.tsnew file mode 100644index 000000000..63ac6df09--- /dev/null+++ b/src/modules/search/search.controller.ts@@ -0,0 +1,41 @@+import { Controller, Get, Query, BadRequestException } from '@nestjs/common';+import { ApiTags, ApiOperation, ApiResponse, ApiQuery } from '@nestjs/swagger';+import { RequireRole, CurrentApiKey } from '../auth/decorators/auth.decorators';+import { ApiKey, ApiKeyRole } from '../auth/entities/api-key.entity';+import { SearchService } from './search.service';+import { SearchQueryDto } from './dto/search-query.dto';+import type { SearchResults } from './search.types';++@ApiTags('search')+@Controller('search')+export class SearchController {+ constructor(private readonly searchService: SearchService) {}++ @Get()+ @RequireRole(ApiKeyRole.OPERATOR)+ @ApiOperation({ summary: 'Search messages across sessions (active search provider)' })+ @ApiResponse({ status: 200, description: 'Search results from the active provider' })+ @ApiResponse({ status: 400, description: 'Empty or whitespace-only "q"' })+ @ApiResponse({ status: 501, description: 'No search provider configured' })+ @ApiQuery({ name: 'q', required: true, description: 'Search term (required, non-empty)' })+ @ApiQuery({ name: 'sessionId', required: false, description: 'Restrict to a single session' })+ @ApiQuery({ name: 'chatId', required: false, description: 'Restrict to a single chat id' })+ @ApiQuery({ name: 'direction', required: false, description: 'incoming | outgoing' })+ @ApiQuery({ name: 'type', required: false, description: 'Message type filter' })+ @ApiQuery({ name: 'from', required: false, description: 'Sender filter' })+ @ApiQuery({ name: 'dateFrom', required: false, description: 'Epoch-ms lower bound (inclusive)' })+ @ApiQuery({ name: 'dateTo', required: false, description: 'Epoch-ms upper bound (inclusive)' })+ @ApiQuery({ name: 'limit', required: false, type: Number, description: 'Max hits to return' })+ @ApiQuery({ name: 'offset', required: false, type: Number, description: 'Pagination offset' })+ async search(@Query() dto: SearchQueryDto, @CurrentApiKey() apiKey?: ApiKey): Promise<SearchResults> {+ if (!dto.q || !dto.q.trim()) {+ throw new BadRequestException('Query parameter "q" is required and must be non-empty.');+ }+ // callerSessionIds comes ONLY from the authenticated key's allowedSessions — never from the+ // query/body — so a scoped key cannot broaden its reach. A null/empty allowlist (e.g. ADMIN)+ // resolves to undefined → searches all sessions, mirroring GET /webhooks. The DTO carries no+ // `sessionIds` field (the global ValidationPipe's forbidNonWhitelisted would reject it anyway),+ // and SearchService makes scope authoritative by overwriting sessionIds at the provider boundary.+ return this.searchService.search(dto, apiKey?.allowedSessions ?? undefined);+ }+}diff --git a/src/modules/search/search.module.spec.ts b/src/modules/search/search.module.spec.tsnew file mode 100644index 000000000..a8ab1b417--- /dev/null+++ b/src/modules/search/search.module.spec.ts@@ -0,0 +1,39 @@+import { ConfigService } from '@nestjs/config';+import { bootstrapSearchProviders } from './search.module';+import { SearchProviderRegistry } from './search-provider.registry';+import { BuiltInFtsProvider } from './providers/builtin-fts.provider';+import type { SearchProvider } from './search.types';++/** A `builtin-fts`-shaped stand-in — avoids the DataSource dependency the real provider carries. */+function mkBuiltin(): BuiltInFtsProvider {+ const p: SearchProvider = { id: 'builtin-fts', label: 'Built-in FTS', search: jest.fn(), health: jest.fn() };+ return p as unknown as BuiltInFtsProvider;+}++function mockCfg(provider: string): ConfigService {+ return { get: jest.fn().mockReturnValue(provider) } as unknown as ConfigService;+}++describe('SearchModule bootstrap (SEARCH_PROVIDER gating)', () => {+ it('registers and activates builtin-fts for SEARCH_PROVIDER=auto', () => {+ const registry = new SearchProviderRegistry();+ bootstrapSearchProviders(registry, mkBuiltin(), mockCfg('auto'));+ expect(registry.active()?.id).toBe('builtin-fts');+ expect(registry.list().map(p => p.id)).toEqual(['builtin-fts']);+ });++ it('registers and activates builtin-fts for SEARCH_PROVIDER=builtin-fts', () => {+ const registry = new SearchProviderRegistry();+ bootstrapSearchProviders(registry, mkBuiltin(), mockCfg('builtin-fts'));+ expect(registry.active()?.id).toBe('builtin-fts');+ });++ it('does NOT register any provider for SEARCH_PROVIDER=none → active() is null (route 501, not live)', () => {+ // This is the fail-open guard: the route stays mounted, but with no active provider SearchService+ // throws NotImplementedException → /search returns 501 instead of serving results via builtin-fts.+ const registry = new SearchProviderRegistry();+ bootstrapSearchProviders(registry, mkBuiltin(), mockCfg('none'));+ expect(registry.active()).toBeNull();+ expect(registry.list()).toHaveLength(0);+ });+});diff --git a/src/modules/search/search.module.ts b/src/modules/search/search.module.tsnew file mode 100644index 000000000..a448ed887--- /dev/null+++ b/src/modules/search/search.module.ts@@ -0,0 +1,52 @@+import { Module } from '@nestjs/common';+import { ConfigModule, ConfigService } from '@nestjs/config';+import { SearchController } from './search.controller';+import { SearchService } from './search.service';+import { SearchProviderRegistry } from './search-provider.registry';+import { BuiltInFtsProvider } from './providers/builtin-fts.provider';++/**+ * Wires the global search feature: the route (SearchController), the service layer (SearchService),+ * the provider registry, and the built-in DB-native FTS provider. The `SEARCH_BOOTSTRAP` factory runs+ * at DI time via `bootstrapSearchProviders` to register `builtin-fts` and make it the active provider.+ *+ * `SEARCH_PROVIDER=none` is honored by leaving the registry empty: the module (and route) stay loaded+ * but `SearchService.search()` throws NotImplementedException → /search returns 501. This is distinct+ * from `SEARCH_ENABLED=false`, which omits the module entirely (route 404).+ *+ * The module is imported by AppModule only when `SEARCH_ENABLED !== 'false'`. Plugin providers+ * (Spec 2) will register themselves the same way and `auto` will select a healthy plugin over builtin.+ */+export function bootstrapSearchProviders(+ registry: SearchProviderRegistry,+ builtin: BuiltInFtsProvider,+ cfg: ConfigService,+): SearchProviderRegistry {+ const provider = cfg.get<string>('search.provider', 'auto');+ // `none` keeps the route mounted but registers no provider, so registry.active() is null and+ // SearchService.search() throws NotImplementedException → /search returns 501 (not live results).+ if (provider === 'none') return registry;+ registry.register(builtin);+ // register() auto-promotes the first provider to active; the explicit setActive is belt-and-braces+ // for `builtin-fts` (a no-op for `auto`, which register() already activated).+ if (provider === 'builtin-fts') {+ registry.setActive('builtin-fts');+ }+ return registry;+}++@Module({+ imports: [ConfigModule],+ controllers: [SearchController],+ providers: [+ SearchProviderRegistry,+ SearchService,+ BuiltInFtsProvider,+ {+ provide: 'SEARCH_BOOTSTRAP',+ inject: [SearchProviderRegistry, BuiltInFtsProvider, ConfigService],+ useFactory: bootstrapSearchProviders,+ },+ ],+})+export class SearchModule {}diff --git a/src/modules/search/search.service.spec.ts b/src/modules/search/search.service.spec.tsnew file mode 100644index 000000000..61c72ad5f--- /dev/null+++ b/src/modules/search/search.service.spec.ts@@ -0,0 +1,41 @@+import { NotImplementedException } from '@nestjs/common';+import { SearchService } from './search.service';+import { SearchProviderRegistry } from './search-provider.registry';+import type { SearchProvider, SearchResults } from './search.types';++function mkProvider(id: string, search: SearchProvider['search']): SearchProvider {+ return {+ id,+ label: id,+ health: jest.fn().mockResolvedValue({ ok: true }),+ search,+ };+}++const emptyResults = { hits: [], total: 0, tookMs: 1, provider: 'builtin-fts' } satisfies SearchResults;++describe('SearchService', () => {+ it('throws 501 (NotImplementedException) when no provider is active', async () => {+ const svc = new SearchService(new SearchProviderRegistry());+ await expect(svc.search({ q: 'x' })).rejects.toBeInstanceOf(NotImplementedException);+ });++ it('delegates to the active provider with sessionIds injected', 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' }, ['s1', 's2']);+ expect(search).toHaveBeenCalledWith(expect.objectContaining({ q: 'x', sessionIds: ['s1', 's2'] }));+ });++ it('does not let a caller override sessionIds', async () => {+ const reg = new SearchProviderRegistry();+ const search = jest.fn().mockResolvedValue(emptyResults);+ reg.register(mkProvider('builtin-fts', search));+ const svc = new SearchService(reg);+ // A smuggled `sessionIds` in the query body must be overwritten by the authoritative caller scope.+ await svc.search({ q: 'x', sessionIds: ['sneaky'] }, ['s1']);+ expect(search).toHaveBeenCalledWith(expect.objectContaining({ sessionIds: ['s1'] }));+ });+});diff --git a/src/modules/search/search.service.ts b/src/modules/search/search.service.tsnew file mode 100644index 000000000..46cd806cf--- /dev/null+++ b/src/modules/search/search.service.ts@@ -0,0 +1,22 @@+import { Injectable, NotImplementedException } from '@nestjs/common';+import { SearchProviderRegistry } from './search-provider.registry';+import type { SearchQuery, SearchResults } from './search.types';++@Injectable()+export class SearchService {+ constructor(private readonly registry: SearchProviderRegistry) {}++ async search(query: SearchQuery, callerSessionIds?: string[]): Promise<SearchResults> {+ 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 };+ return provider.search(scoped);+ }++ async health() {+ const provider = this.registry.active();+ if (!provider) return { ok: false, detail: 'no provider' };+ return provider.health();+ }+}diff --git a/src/modules/search/search.types.spec.ts b/src/modules/search/search.types.spec.tsnew file mode 100644index 000000000..caf2582aa--- /dev/null+++ b/src/modules/search/search.types.spec.ts@@ -0,0 +1,30 @@+import type { SearchProvider, SearchQuery, SearchResults, SearchHealth, SearchHit } from './search.types';+import { MessageDirection } from '../message/entities/message.entity';++describe('search.types', () => {+ it('compiles a valid SearchProvider fixture', () => {+ const query: SearchQuery = { q: 'hi' };+ const provider: SearchProvider = {+ id: 'test',+ label: 'Test',+ search: (): Promise<SearchResults> => Promise.resolve({ hits: [], total: 0, tookMs: 1, provider: 'test' }),+ health: (): Promise<SearchHealth> => Promise.resolve({ ok: true }),+ };+ const hit: SearchHit = {+ messageId: 'm1',+ waMessageId: 'w1',+ sessionId: 's1',+ chatId: 'c1',+ body: 'hi',+ snippet: '<mark>hi</mark>',+ timestamp: 1,+ type: 'text',+ direction: MessageDirection.OUTGOING,+ from: '[email protected]',+ score: 1,+ };+ expect(provider.id).toBe('test');+ expect(hit.body).toBe('hi');+ expect(query.q).toBe('hi');+ });+});diff --git a/src/modules/search/search.types.ts b/src/modules/search/search.types.tsnew file mode 100644index 000000000..b4cd03093--- /dev/null+++ b/src/modules/search/search.types.ts@@ -0,0 +1,59 @@+import type { MessageType } from '../../engine/interfaces/whatsapp-engine.interface';+import type { MessageDirection } from '../message/entities/message.entity';++/** A pluggable search backend. Indexing is intentionally NOT part of this interface —+ * each provider owns how its index stays current (DB-level for built-in, hook-driven for plugins). */+export interface SearchProvider {+ /** Stable id, e.g. 'builtin-fts'. */+ readonly id: string;+ /** Human label for dashboard/config. */+ readonly label: string;+ search(query: SearchQuery): Promise<SearchResults>;+ /** Registry/route use this; 503 when not ok. */+ health(): Promise<SearchHealth>;+}++export interface SearchHealth {+ ok: boolean;+ detail?: string;+}++export interface SearchQuery {+ q: string;+ /** Scoped by SearchService from the caller's API-key allowedSessions (not user-supplied). */+ sessionIds?: string[];+ sessionId?: string;+ chatId?: string;+ direction?: MessageDirection;+ type?: MessageType | MessageType[];+ from?: string;+ dateFrom?: number; // epoch ms+ dateTo?: number; // epoch ms+ limit?: number;+ offset?: number;+}++export interface SearchResults {+ hits: SearchHit[];+ /** Bounded exact count for pagination. */+ total: number;+ tookMs: number;+ /** Which provider answered (id). */+ provider: string;+}++export interface SearchHit {+ messageId: string;+ waMessageId: string;+ sessionId: string;+ chatId: string;+ body: string;+ /** Provider-generated excerpt with `<mark>` highlight markers; safe when rendered as text (the+ * dashboard renders it as text, never as HTML — do not `dangerouslySetInnerHTML`). */+ snippet: string;+ timestamp: number;+ type: MessageType;+ direction: MessageDirection;+ from: string;+ score?: number;+}diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 57a4fabba..81d489c13 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -63,9 +63,19 @@ describe('SessionService', () => {messageRepository = {find: jest.fn().mockResolvedValue([]),findOne: jest.fn().mockResolvedValue(null),- create: jest.fn(),+ // `create()` in TypeORM just builds the entity instance; it does NOT populate @PrimaryGeneratedColumn+ // or @CreateDateColumn. Mirror that: return the input as-is (no id/createdAt) so tests see the same+ // shape the production code does before the `insert()` generated-maps merge.+ create: jest.fn().mockImplementation((data: Partial<Message>) => ({ ...data }) as Message),save: jest.fn().mockResolvedValue(undefined),- insert: jest.fn().mockResolvedValue(undefined),+ // `insert()` returns an InsertResult; `identifiers[0]` carries the PK on both SQLite + Postgres.+ // `generatedMaps[0]` carries createdAt (Postgres yes; SQLite historically no — left absent here to+ // match the local SQLite default DB).+ insert: jest.fn().mockResolvedValue({+ identifiers: [{ id: 'gen-uuid-1' }],+ generatedMaps: [],+ raw: undefined,+ }),update: jest.fn().mockResolvedValue({ affected: 1 }),};@@ -1435,6 +1445,69 @@ describe('SessionService', () => {expect(dispatchedEvents('message.received')).toHaveLength(1);});+ it('emits message:persisted with a non-empty message.id on inbound (insert generated PK merged)', async () => {+ // Asymmetry guard: the inbound path uses `insert()` (the dedup oracle), which — unlike `save()` —+ // does NOT merge @PrimaryGeneratedColumn/@CreateDateColumn back onto the entity. Without the+ // identifiers/generatedMaps merge, `dbMessage.id` is undefined here, while the outbound path+ // (MessageService.saveOutgoingMessage) emits a real id via `save()`. A plugin subscribing to+ // `message:persisted` would see id=undefined on inbound but a real id on outbound. This pins the+ // inbound payload to carry the DB-generated id, mirroring the outbound emit test.+ const callbacks = await startAndCaptureCallbacks();++ callbacks.onMessage!(makeMessage({ id: 'wa-in-1', fromMe: false }));+ await flush();++ const persistedCalls = (hookManager.execute as jest.Mock).mock.calls.filter(+ ([ev]: unknown[]) => ev === 'message:persisted',+ ) as unknown[][];+ expect(persistedCalls).toHaveLength(1);+ const payload = persistedCalls[0][1] as { sessionId: string; message: { id?: string } };+ expect(payload.sessionId).toBe('sess-uuid-1');+ expect(payload.message.id).toBeTruthy(); // the DB-generated id, not undefined+ expect(payload.message.id).toBe('gen-uuid-1'); // merged from InsertResult.identifiers[0]+ expect(persistedCalls[0][2]).toMatchObject({ sessionId: 'sess-uuid-1', source: 'SessionService' });+ });++ it('does not emit message:persisted on a duplicate re-fire (loses the dedup insert race)', async () => {+ // The emit lives AFTER the dedup gate. A re-fire that hits the UNIQUE(sessionId, waMessageId)+ // constraint must not emit message:persisted — no row was durably stored on this attempt.+ const callbacks = await startAndCaptureCallbacks();+ // Emulate the SQLite UNIQUE-violation phrasing that `isUniqueConstraintError` matches via regex.+ (messageRepository.insert as jest.Mock).mockRejectedValueOnce(+ new Error('UNIQUE constraint failed: messages.sessionId, messages.waMessageId'),+ );++ callbacks.onMessage!(makeMessage({ id: 'wa-dup-1', fromMe: false }));+ await flush();++ const persistedCalls = (hookManager.execute as jest.Mock).mock.calls.filter(+ ([ev]: unknown[]) => ev === 'message:persisted',+ );+ expect(persistedCalls).toHaveLength(0);+ });++ it('does not emit message:persisted when insert throws a transient (non-unique) error', async () => {+ // Fail-open on transient DB errors (SQLITE_BUSY, lock-timeout, connection drop) is correct for+ // webhook/WS dispatch — a real inbound message must never be dropped. But the row was never+ // stored and dbMessage.id is undefined, so the message:persisted hook must NOT fire (it would+ // hand plugins an id-less payload for a row that isn't in the DB). The hook is gated on a+ // `persisted` flag set only after the generated-maps merge succeeds. Webhook/WS still dispatch.+ const callbacks = await startAndCaptureCallbacks();+ (messageRepository.insert as jest.Mock).mockRejectedValueOnce(new Error('SQLITE_BUSY: database is locked'));++ callbacks.onMessage!(makeMessage({ id: 'wa-busy-1', fromMe: false }));+ await flush();++ const persistedCalls = (hookManager.execute as jest.Mock).mock.calls.filter(+ ([ev]: unknown[]) => ev === 'message:persisted',+ );+ expect(persistedCalls).toHaveLength(0);+ // Fail-open: webhook still dispatched so the inbound message is not silently dropped. (The+ // payload is `{}` here because the hook mock returns `data: {}`; the point is that dispatch+ // fired at all on a transient DB error — only the message:persisted hook is gated on `persisted`.)+ expect(webhookService.dispatch).toHaveBeenCalledWith('sess-uuid-1', 'message.received', expect.anything());+ });+it('does not persist (no orphan row) when the session is deleted mid hook chain', async () => {// onMessage gates on isLiveEngine synchronously at entry, then awaits the message:received hook// chain before inserting. If delete() completes during that await (the engine leaves the livediff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex c4284819d..be04d8aab 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -803,8 +803,20 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// happen exactly once. Fail-open: a non-conflict DB error still dispatches, so a real// message is never dropped by a transient DB failure.let isNewMessage = true;+ let persisted = false;try {- await this.messageRepository.insert(dbMessage as unknown as QueryDeepPartialEntity<Message>);+ // `insert()` (not `save()`) is load-bearing: the UNIQUE(sessionId, waMessageId) constraint+ // makes a duplicate insert throw, which is the atomic dedup oracle for #464 re-fires.+ // Unlike `save()`, `insert()` does NOT merge DB-generated columns (@PrimaryGeneratedColumn,+ // @CreateDateColumn) back onto the entity instance — so merge them explicitly here, before+ // the `message:persisted` emit. `identifiers[0]` always carries the PK on both SQLite and+ // Postgres; `generatedMaps[0]` adds createdAt where the driver returns it (Postgres yes;+ // SQLite historically does not — acceptable; the PK is the load-bearing field for plugins).+ const result = await this.messageRepository.insert(+ dbMessage as unknown as QueryDeepPartialEntity<Message>,+ );+ Object.assign(dbMessage, result.identifiers[0] ?? {}, result.generatedMaps?.[0] ?? {});+ persisted = true;} catch (err) {if (isUniqueConstraintError(err)) {isNewMessage = false;@@ -816,6 +828,25 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatreturn; // duplicate re-fire — the original already persisted and dispatched}+ // Fire-and-forget: a plugin handler must never break the receive path. Both engine adapters+ // (wwjs `message` and Baileys `upsert`) converge on this persist, so one emit covers inbound.+ // The built-in FTS search provider is DB-synced and does NOT consume this; it exists for+ // plugin providers (Spec 2) + general use.+ // Gate ONLY the hook on `persisted`: on a non-unique insert error (transient SQLITE_BUSY /+ // lock-timeout / connection drop) the row was never stored and `dbMessage.id` is undefined,+ // so emitting `message:persisted` would hand plugins an id-less payload for a row that isn't+ // in the DB. The webhook/WS dispatch below stays fail-open — a real inbound message must+ // never be dropped on a transient DB failure; only the hook requires a durable row.+ if (persisted) {+ void this.hookManager+ .execute(+ 'message:persisted',+ { sessionId: id, message: dbMessage },+ { sessionId: id, source: 'SessionService' },+ )+ .catch(() => undefined);+ }+// Dispatch to webhooks with potentially modified messagevoid this.webhookService.dispatch(id, 'message.received', finalMessage);// Emit real-time event to WebSocket clientsdiff --git a/test/search.e2e-spec.ts b/test/search.e2e-spec.tsnew file mode 100644index 000000000..5cd2beabd--- /dev/null+++ b/test/search.e2e-spec.ts@@ -0,0 +1,176 @@+// archiver v8 is ESM-only and is pulled in transitively via the @Global StorageModule when+// AppModule boots; stub it so ts-jest (CommonJS) can load the module graph (same as other e2e specs).+jest.mock('archiver', () => ({ TarArchive: jest.fn() }));++// Seed the well-known dev-admin-key (ApiKeyRole.ADMIN, so it satisfies @RequireRole(OPERATOR))+// BEFORE AppModule is imported, mirroring integration-instance.e2e-spec.ts's env-first pattern.+process.env.ALLOW_DEV_API_KEY = 'true';++import { INestApplication, ValidationPipe } from '@nestjs/common';+import { Test } from '@nestjs/testing';+import { getDataSourceToken, getRepositoryToken } from '@nestjs/typeorm';+import { DataSource, Repository } from 'typeorm';+import request from 'supertest';+import { App } from 'supertest/types';+import { AppModule } from '../src/app.module';+import { Message, MessageDirection } from '../src/modules/message/entities/message.entity';+import { AddMessagesFts1782400000000 } from '../src/database/migrations/1782400000000-AddMessagesFts';+import { SearchController } from '../src/modules/search/search.controller';+import { SearchService } from '../src/modules/search/search.service';+import { SearchProviderRegistry } from '../src/modules/search/search-provider.registry';++/**+ * End-to-end coverage for the global search integration capstone (Task 10): the real /api/search+ * route → SearchController → SearchService → SearchProviderRegistry → BuiltInFtsProvider →+ * `messages` FTS schema (SQLite FTS5 here, Postgres tsvector in the provider's own spec). Bootstraps+ * the full AppModule so the SEARCH_BOOTSTRAP factory, the `@InjectDataSource('data')` wiring, and the+ * conditional `SEARCH_ENABLED` gate are all exercised exactly as production runs them.+ *+ * setup-e2e.ts sets DATABASE_SYNCHRONIZE=true, so TypeORM creates the `messages` table from the entity+ * but the FTS virtual table + triggers come from a MIGRATION that doesn't run under synchronize. The+ * spec applies that migration's up() manually after boot — proving the provider queries the FTS schema+ * the migration establishes, not a test-only stub.+ */+describe('GET /api/search (e2e)', () => {+ let app: INestApplication<App>;+ let messageRepo: Repository<Message>;++ beforeAll(async () => {+ const moduleFixture = await Test.createTestingModule({ imports: [AppModule] }).compile();+ app = moduleFixture.createNestApplication();+ app.setGlobalPrefix('api');+ app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));+ await app.init();++ // The FTS migration is gated behind migrationsRun (off under DATABASE_SYNCHRONIZE=true), so apply+ // it manually here against the 'data' connection that owns `messages`. This is the same shape the+ // provider's own spec uses, and proves the e2e path queries a real FTS index, not a stand-in.+ const dataSource = app.get<DataSource>(getDataSourceToken('data'));+ await new AddMessagesFts1782400000000().up(dataSource.createQueryRunner());++ messageRepo = app.get<Repository<Message>>(getRepositoryToken(Message, 'data'));+ await messageRepo.insert([+ {+ sessionId: 'sess-search-1',+ chatId: '[email protected]',+ from: '[email protected]',+ to: '[email protected]',+ body: 'hello world from search e2e',+ type: 'text',+ direction: MessageDirection.OUTGOING,+ timestamp: 1700000000000,+ },+ {+ sessionId: 'sess-search-1',+ chatId: '[email protected]',+ from: '[email protected]',+ to: '[email protected]',+ body: 'completely unrelated body text',+ type: 'text',+ direction: MessageDirection.INCOMING,+ timestamp: 1700000001000,+ },+ ]);+ });++ afterAll(async () => {+ try {+ await app?.close();+ } catch {+ /* ignore teardown-only multi-datasource quirk */+ }+ });++ it('returns matching hits over the full route → provider → FTS stack (200)', async () => {+ const res = await request(app.getHttpServer())+ .get('/api/search?q=hello')+ .set('X-API-Key', 'dev-admin-key')+ .expect(200);++ const body = res.body as {+ hits: Array<{ body: string; sessionId: string; snippet: string }>;+ total: number;+ provider: string;+ };+ expect(body.provider).toBe('builtin-fts');+ expect(body.total).toBe(1);+ expect(body.hits).toHaveLength(1);+ expect(body.hits[0].body).toContain('hello world');+ expect(body.hits[0].sessionId).toBe('sess-search-1');+ // The SQLite snippet() wrapper highlights the match term with <mark> — proves the FTS index answered.+ expect(body.hits[0].snippet).toContain('<mark>hello</mark>');+ });++ it('returns 400 for an empty / whitespace-only q', async () => {+ // The DTO's @IsNotEmpty() surfaces as a 400 via the global ValidationPipe before the controller's+ // own non-empty check runs; both paths converge on 400, which is the contract.+ await request(app.getHttpServer()).get('/api/search?q=').set('X-API-Key', 'dev-admin-key').expect(400);+ await request(app.getHttpServer()).get('/api/search?q=%20%20').set('X-API-Key', 'dev-admin-key').expect(400);+ });++ it('requires an API key (401 without one)', async () => {+ await request(app.getHttpServer()).get('/api/search?q=hello').expect(401);+ });++ it('returns an empty result page (not 501) for a non-matching term', async () => {+ const res = await request(app.getHttpServer())+ .get('/api/search?q=zzzznomatch')+ .set('X-API-Key', 'dev-admin-key')+ .expect(200);+ const body = res.body as { hits: unknown[]; total: number };+ expect(body.hits).toEqual([]);+ expect(body.total).toBe(0);+ });++ // Exercises the SEARCH_BOOTSTRAP factory + the `@InjectDataSource('data')` wiring: the controller,+ // service, registry, and an ACTIVE provider are all resolvable from the booted DI graph, and the+ // registry reports builtin-fts as active (so the route is live, not 501). This is the registration-+ // level proof that SearchModule's providers and bootstrap factory wired correctly.+ it('registers SearchModule with the built-in provider active (not 501)', () => {+ expect(() => app.get(SearchController)).not.toThrow();+ expect(() => app.get(SearchService)).not.toThrow();+ const registry = app.get(SearchProviderRegistry);+ expect(registry.active()?.id).toBe('builtin-fts');+ });+});++/**+ * 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.+ */+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;+ };++ 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('includes SearchModule when explicitly enabled', () => {+ process.env.SEARCH_ENABLED = 'true';+ expect(buildSearchImports()).toHaveLength(1);+ });++ it('omits SearchModule entirely when SEARCH_ENABLED=false (zero footprint)', () => {+ process.env.SEARCH_ENABLED = 'false';+ expect(buildSearchImports()).toHaveLength(0);+ });+});