feat(plugins): TREK_PLUGINS_IGNORE_TREK_RANGE turns the version gate into a warning (#2226)

* feat(plugins): TREK_PLUGINS_IGNORE_TREK_RANGE turns the version gate into a warning

A plugin whose author has not updated its `trek` range for the running TREK can
now be installed, updated and activated when the operator sets
TREK_PLUGINS_IGNORE_TREK_RANGE to a truthy value. Every gate (registry picker,
post-extraction re-check, sideload, dev-link, activation) warns instead of
refusing; a missing range is tolerated the same way; "install latest" takes the
newest published version. The plugin-API version gate is not lifted and the
Discover compatibility verdict stays truthful.

The admin is warned at every step: each bypass is logged, install/upload/link/
update responses carry a `trekRangeBypassed` marker, and both admin panels show
a "Version checks off" pill, an "Install anyway" confirm dialog before a
registry install, the same notice after a path that could not ask first, and a
persistent chip on the row while the plugin runs outside its range.

Nine new i18n keys in every locale; wiki pages updated (Environment-Variables,
Admin-Plugins, Plugin-Development, Security-Hardening).

* refactor(plugins): one useRangeBypass hook behind both admin shells

SonarQube flagged PR 2226 at 10.8% duplicated new code: the range-bypass
logic had been added to the desktop and phone plugin panels as identical
copies. The marker/warning types, the row chip, the "Install anyway" offer,
the dialog copy and the confirm-or-notice state now live in
useRangeBypass (next to useInstanceSettings, the existing shared-logic
precedent); each panel keeps only its own dialog/sheet markup.

* docs(claude): record the SonarQube gate rules and the no-English-placeholder i18n rule

The CI SonarCloud gate (Sonar way, on new code: >=80% coverage, <=3%
duplication, A ratings, hotspots reviewed) was only discoverable by waiting
20-25 minutes for the workflow. The root CLAUDE.md now states the conditions,
the desktop/mobile shell-mirror duplication trap and its shared-hook fix, and
how to check a PR with the sonarqube MCP first; client and server CLAUDE.md
point at it. shared/CLAUDE.md says every locale needs a real translation —
parity cannot tell an English placeholder from a translation.

* docs(claude): keep CLAUDE.md to commands, invariants, gates and philosophy

Verified every concrete claim in the five CLAUDE.md files against the code
and fixed the stale ones: the websocket server is the Nest realtime gateway,
MCP tools live in <domain>.mcp.ts files, the client "native shell" section
described code that was never written, offline maps also prefetch vector
basemaps, plus several renamed files and wrong table names.

Then trimmed everything that drifts on its own: dates, migration history,
counts, and inventories of stores, slices, domains, sync files and CLI
commands. What stays is the commands, the invariants with the file that
enforces each one, what CI actually runs, the reference implementations to
copy, and the rules for new code. Each file now opens with that rule.
This commit is contained in:
jubnl
2026-09-04 00:43:06 +02:00
committed by Maurice
parent fa406b708f
commit 61bef334d5
53 changed files with 1378 additions and 337 deletions
+44 -78
View File
@@ -1,108 +1,74 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Scope: the **`@trek/server`** workspace. See the repo-root `CLAUDE.md` for the monorepo-wide picture (shared contracts, client, conventions). This file covers server internals only.
Scope: the **`@trek/server`** workspace. See the repo-root `CLAUDE.md` for the monorepo picture and the philosophy. This file holds the server's commands, invariants and pitfalls; the code and `src/nest/README.md` hold the inventory.
## Commands (run from `server/`)
```bash
npm run dev # scripts/dev.mjs: tsc -w then node --watch dist/index.js (server on :3001)
npm run build # scripts/build.mjs — see "emit-anyway" note below
npm run typecheck # tsc --noEmit (the real type gate; build does NOT fail on type errors)
npm run build # scripts/build.mjs — emits even on type errors (see below)
npm run typecheck # tsc --noEmit — the real type gate
npm run typecheck:tests # tsc over tests/ — CI runs this too; vitest green does NOT mean typed mocks compile
npm run lint # eslint --fix on src/apps/libs/test
npm run lint:check # eslint, no fix
npm run test # vitest run (all of tests/**)
npm run test:unit # tests/unit
npm run test:integration # tests/integration
npm run test:ws # tests/websocket
npm run test:e2e # tests/e2e (boots Nest modules against a temp in-memory SQLite)
npm run test:coverage # istanbul coverage; per-domain ratchet over src/nest/** (floor ≥80%)
npm run lint # eslint --fix
npm run lint:check # eslint, no fix (CI)
npm run test # vitest run; also test:unit / test:integration / test:ws / test:e2e
npm run test:coverage # istanbul coverage; per-domain ratchet over src/nest/**
npm run gen:plugin-facts # regenerate the plugin-protocol tables into plugin-sdk/ + shared/
npm run check:plugin-facts # CI gate — fails if the generated copies drifted from envelope.ts
npm run check:plugin-facts # CI gate — fails if the generated copies drifted
node scripts/coverage-thresholds.mjs # after test:coverage — prints the ratchet block for vitest.config.ts
```
Single test:
Single test: `npx vitest run tests/unit/nest/weather.controller.test.ts`, or `npx vitest run -t "returns 401 without cookie"`.
```bash
npx vitest run tests/unit/nest/weather.controller.test.ts
npx vitest run -t "returns 401 without cookie"
npx vitest watch tests/unit/nest/auth-guard.test.ts
```
**Build emits even with type errors** (`scripts/build.mjs` catches `tsc` failures and warns). `npm run build` succeeding does **not** mean the code typechecks — run `npm run typecheck`.
**Build emits even with type errors** (`scripts/build.mjs` catches `tsc` failures and warns). So `npm run build` succeeding does **not** mean the code typechecks — always run `npm run typecheck` to gate types.
## Architecture invariants
## Architecture
Nest owns everything. Every domain is a DI module under `src/nest/<domain>/` (`controller` + `service` + `module`, registered in `src/nest/app.module.ts`); business logic lives in the injectable `.service.ts`, pure halves in `.helpers.ts`, SQL in a `.repository.ts` where one exists. There is no legacy service layer — ESLint errors on any `services/` import. **`weather/` is the reference module shape; `collections.controller.ts` is the reference for body validation and enumeration-safe access checks.**
Nest owns everything: the strangler migration **completed 2026-08-10**, and the last seam — the pre-`app.init()` MCP/OAuth mount — moved behind the container 2026-08-11, taking the final five `*.bridge.ts` files with it (**zero bridges remain**). Legacy `src/services/` is **deleted** — `eslint.config.mjs` errors on any import of it — and every domain is a DI module under `src/nest/<domain>/`. `src/nest/README.md` is the per-module blueprint and records the migration's design decisions. What still runs pre-init is path-prefixed plumbing only: global middleware, /uploads static+guarded routes, the DI-built discovery metadata middleware, production statics, api-docs, and the named body-parser wrappers. The websocket seam is gone: `/ws` is a Nest gateway (`src/nest/realtime/`), and `src/websocket.ts` is a re-export stub. The scheduler seam is gone: every cron is a domain provider on `@nestjs/schedule` (see `src/nest/scheduling/` below).
- **`src/bootstrap.ts` — `buildApp()`** is the single builder for production and the test harness. Everything on the raw Express instance (global middleware, uploads, discovery metadata, statics, the named `jsonParser`/`urlencodedParser` wrappers) is registered **before `app.init()`**, because Nest throws `NotFoundException` on unmatched routes and nothing after init is reachable. The wrappers exempt `/mcp` so the MCP SDK reads the raw stream — **never `@Body()` a `/mcp` route**. Don't add routes to that pre-init shell; it bypasses every global guard, interceptor and filter.
- **Realtime**: `/ws` is a Nest gateway in `src/nest/realtime/`. Inject `RealtimeService`; `src/websocket.ts` is a re-export stub for old call sites. Trip mutations forward `X-Socket-Id` so the originating client doesn't echo its own change.
- **MCP**: `src/nest-mcp/` is the decorator/registry layer (`@McpController`/`@Tool`/`@Resource`/`@Prompt`; see its `README.md`); tools live in `<domain>.mcp.ts` files beside each module; the HTTP transport is `src/nest/mcp-transport/`; `src/mcp/` holds process-wide state only (scopes, session manager, boot policy). Every tool invocation writes an audit row through the registry's `onInvoke` seam. MCP tools are adapters over the same services and permission checks as REST — a change on one side lands on the other in the same change.
- **Scheduling**: `src/nest/scheduling/` (`CronRegistrarService`) is the one way to schedule a cron. Jobs are `*.job.ts` providers in their owning domain. The registrar refuses to schedule under `NODE_ENV=test` (an integration test pins it). **Never use a `@Cron` decorator** — it bypasses that gate.
- **Plugins** (`src/nest/plugins/`): the child-process runtime (`supervisor/`, `runtime/plugin-host-entry.ts`, `protocol/envelope.ts`) is **intentionally not Nest** — it is the security boundary. `host/rpc-host.ts` registers an RPC method at spawn only if the plugin holds the unlocking permission (registration = authorization). Install-time gates live in `install/`; the manifest's `trek` version range fails closed, and `TREK_PLUGINS_IGNORE_TREK_RANGE` downgrades that to a warning. The protocol tables in `protocol/envelope.ts` (+ `src/plugin-event-sink.ts`) are **generated** into `plugin-sdk/` and `shared/` — run `gen:plugin-facts` after touching them and commit the output. `runtime/egress-policy.ts` is a hand-kept mirror guarded by a parity test in `plugin-sdk/`; change both sides together.
- **Storage**: `src/nest/storage/` is the upload driver abstraction (local / S3 / mirror behind one interface, with an admin surface and a usage job). Domain services never touch the filesystem or the S3 SDK directly.
- **DB** (`src/db/`): `better-sqlite3`, WAL, FK on; `database.ts` runs `schema.ts` → `migrations.ts` → `seeds.ts`. `NODE_ENV=test` ⇒ isolated `:memory:` DB per vitest worker; `TREK_DB_FILE` ⇒ explicit file DB (Playwright harness).
- **`src/index.ts`** — process entry: creates upload/data dirs, builds the app via `bootstrap.ts`, wires the WebSocket server onto the same HTTP server, prints the startup banner. Default port **3001**.
- **`src/bootstrap.ts` — `buildApp()`** — the single shared app builder for both prod and the test harness. **Registration order is load-bearing**: `applyGlobalMiddleware` → `applyPlatformUploads` → the discovery metadata middleware → `applyPlatformStatic` → the named body-parser wrappers all run on the raw Express instance **before `app.init()`**, because Nest throws `NotFoundException` on unmatched routes and won't fall through to anything registered after init. **`/mcp` bodies are raw by design**: the parser wrappers (`jsonParser`/`urlencodedParser` — the names suppress Nest's own init-time parsers) exempt `/mcp` so the MCP SDK reads the untouched stream. Never `@Body()` a `/mcp` route.
- **Domain modules** live in `src/nest/<domain>/` as `controller` + `service` + `module`, registered in `src/nest/app.module.ts`. **`weather/` is the reference implementation** — copy its shape. The Zod contract is in `shared/src/<domain>/`.
- **`src/services/` no longer exists** — deleted 2026-08-10 after the last fold; ESLint walls off any new import. Business logic lives in each domain's injectable `.service.ts`, with pure halves split into `.helpers.ts` plain modules and, in newer folds, SQL into a repository (`trek_photos` pattern).
- **`src/db/`** — `better-sqlite3` (WAL, FK on). `database.ts` boots and runs `schema.ts` → `migrations.ts` → `seeds.ts`. `NODE_ENV=test` ⇒ isolated `:memory:` DB per vitest worker; `TREK_DB_FILE` ⇒ explicit file DB (Playwright harness).
- **`src/websocket.ts`** — JWT-authed `ws` server on `/ws`, room-per-trip, heartbeat, per-connection rate limiting. Trip mutations forward `X-Socket-Id` so the originating client doesn't echo its own change.
- **`src/mcp/`** — process-wide MCP state (scopes, sessionManager, tuning knobs, rate-limit map, `nest-mcp-policy.ts` boot gate). The HTTP transport is `src/nest/mcp-transport/` (a `@Public` controller + service); the tools/resources/prompts live in decorator-driven `<domain>.mcp.ts` files under `src/nest/` — `src/mcp/tools.ts` is registry-attach-only. Every tool invocation writes an `mcp.tool_call` audit row (user, OAuth client, tool name, ip) via the nest-mcp `onInvoke` seam.
- **`src/nest-mcp/`** — the decorator/registry layer itself (`@McpController`/`@Tool`/`@Resource`/`@Prompt`, `McpRegistry`, `McpModule`, result helpers) that the `<domain>.mcp.ts` files build on. Formerly the standalone `@trek/nest-mcp` workspace, folded in 2026-08-22; see its `README.md` for the API and invariants (self-contained apart from a type-only `../mcp/scopes` import; no scope semantics of its own). Tests: `tests/unit/nest-mcp/`.
- **`src/nest/scheduling/`** — `CronRegistrarService`, the one way TREK schedules a cron (`@nestjs/schedule` + the `cron` package). Every job is a `*.job.ts` provider in its owning domain, registered from `onApplicationBootstrap`; the registrar refuses to schedule under `NODE_ENV=test` (the shared `buildApp()` harness must never tick — `tests/integration/scheduler-gate.test.ts` pins it) and stops everything on `nestApp.close()`. Never use a `@Cron` decorator — decorator jobs bypass the gate.
- **`src/nest/plugins/`** — sandboxed plugin runtime in three layers: `supervisor/` + `runtime/plugin-host-entry.ts` + `protocol/envelope.ts` (forked child per plugin, IPC envelopes, rate/RSS policing — **intentionally not Nest**, it's the security boundary); `host/rpc-host.ts` (enforcement: a method is registered at spawn only if the plugin holds the unlocking permission — registration = authorization); `host/plugin-host-deps.factory.ts` (dependency wiring — an `@Injectable()` factory injecting the domain services; the RPC surface is decorator-driven since 2026-08-09, with `PluginsModule` split into four and per-domain coverage gates) + `host/plugin-host-state.ts` (process-wide data-DB/budget maps, module-level on purpose). Install-time gates in `install/` (manifest, safe-extract, Ed25519 signature verify, egress). ⚠️ The protocol tables — permissions, RPC methods, hooks, and the core-event catalog — live in `protocol/envelope.ts` (+ `src/plugin-event-sink.ts` for the event families) and are **generated** into `plugin-sdk/src/generated/host-facts.ts` and `shared/src/plugin-permissions.ts` by `npm run gen:plugin-facts`; `check:plugin-facts` is the CI gate, so run it after touching any of them and commit the regenerated files. `runtime/egress-policy.ts` is still a hand-kept **byte-identical** mirror into `plugin-sdk/`, guarded by parity tests there — keep both sides in sync when touching either.
## Rules for new code
## Direction (post-migration guardrails, from the 2026 audit)
**Nest is the destination — and as of 2026-08-10 the code is there.** These rules now guard against regression rather than describe a migration in flight:
- **Follow the Nest philosophy, don't work against it.** New surfaces are real Nest modules: thin controller (HTTP shaping, guards, status codes) → injectable provider (business logic, DI-injected deps). The migration to this shape is complete — never resurrect a plain function-module service, and don't grow god services: when a domain outgrows one class, split it (the trips domain became `trips`/`trip-members`/`trip-membership`/`trip-invite`/`trip-read-model`/`calendar`; auth split into `auth` + profile + `tokens`).
- **Inject, don't reach for module globals.** No new imports of the global `db` proxy from `nest/` layers; no new code depending on the `ws` singleton or event-sink globals. Write new code so it can move to DI (`DatabaseModule`, injectable realtime/config/scheduler) without rework. New modules must be importable without side effects (no disk/DB access at module evaluation).
- **Don't add routes to the pre-`app.init()` Express shell** — it bypasses every global Nest guard/interceptor/filter. New routes go through Nest so cross-cutting controls actually apply.
- **Transactions are not optional.** Any multi-statement write goes in `db.transaction()`; never hand-roll `BEGIN`/`COMMIT` via `db.exec`. Bind values with `?`; identifiers only via a literal allow-list.
- **Thin controller → injectable provider.** Never resurrect a plain function-module service; don't grow god services — split a domain into several modules when it outgrows one class (trips and auth already are).
- **Inject, don't reach for module globals.** No new imports of the global `db` proxy from `nest/` layers; no new code depending on the `ws` singleton or event-sink globals. Modules must be importable without side effects.
- **Transactions are not optional.** Multi-statement writes go in `db.transaction()`; never hand-roll `BEGIN`/`COMMIT`. Bind values with `?`; identifiers only via a literal allow-list.
- **Migrations are append-only.** Identity is positional (array index == `schema_version`) — never reorder, insert mid-list, or delete; no env interpolation in SQL.
- **Every write endpoint validates.** `@Body()` must go through the Zod pipe with a schema from `@trek/shared` — no `Record<string, unknown>` + ad-hoc checks. Validating the caller's permission isn't enough: verify every referenced id (place/day/user) exists and belongs to the same trip.
- **Every outbound `fetch` gets a timeout (`AbortSignal`), a response-size cap, and boundary validation** — no `as`-casting provider responses, no silent `catch → null`. User-influenced URLs go through the SSRF guard. Never silently fall back to another user's API key.
- **Fail closed.** Unrecognized flag values mean OFF; sandbox/permission opt-outs must refuse in production; never select a less-safe code path based on the *absence* of a file. GET handlers must not write to the DB.
- **Don't fork the canonical paths.** Auth verification is `verifyJwtAndLoadUser` (with the `password_version` gate) — reuse it, never reimplement. MCP tools are adapters over the same services/`canAccessTrip`/`checkPermission`; a validation or permission change on a REST route must land in the parallel MCP tool in the same change.
- **Money rules**: integer-cent arithmetic; largest-remainder splits (`budgetService.splitEqualShares` is the reference); FX frozen at entry; explicit flags, never sentinel values (`rate === 1`, `scopes: null`); custom splits must reconcile (`Σ balances = 0`) before persisting.
- **Reference controllers**: `collections.controller.ts` (Zod pipe on every body + enumeration-safe owner checks) alongside `weather/` for module shape.
- **Every write endpoint validates** through the Zod pipe with a schema from `@trek/shared` — no `Record<string, unknown>` + ad-hoc checks. Also verify every referenced id exists and belongs to the same trip.
- **Every outbound `fetch`** gets a timeout, a response-size cap and boundary validation — no `as`-casting provider responses, no silent `catch → null`. User-influenced URLs go through the SSRF guard. Never fall back to another user's API key.
- **Fail closed.** Unrecognized flag values mean OFF; sandbox/permission opt-outs refuse in production; never pick a less-safe path based on the *absence* of a file. GET handlers must not write.
- **Don't fork canonical paths.** Auth verification is `verifyJwtAndLoadUser` (with the `password_version` gate) — reuse it.
- **Money**: integer cents; largest-remainder splits (`BudgetService.splitEqualShares` is the reference); FX frozen at entry; explicit flags, never sentinel values; custom splits must reconcile to zero before persisting.
## Configuration (app-config)
**Never read `process.env` directly in `src/**`** — ESLint errors on it. All env
access goes through `src/app-config/`:
**Never read `process.env` in `src/**`** — ESLint errors on it. All env access goes through `src/app-config/`:
- **Nest DI classes**: inject a boot-stable namespace token
(`@Inject(mcpConfig.KEY) private mcp: ConfigType<typeof mcpConfig>` from
`src/nest/app-config/`) for values frozen per app build, or use
`RuntimeEnvService` / `readEnv()` for runtime-toggled values (DEMO_MODE,
NODE_ENV, OIDC_*, …) that ~60 tests mutate mid-lifetime.
- **Everything else** (services, mcp, websocket, scheduler, db, middleware):
`readEnv()` from `src/app-config` — live, uncached, per call. Modules that
froze env in module-top consts keep that timing (read `readEnv()` at module
top, marked "frozen on purpose").
- **Validation is fail-fast at boot only** (`boot-validate.ts`, imported by
`index.ts` right after dotenv): present-but-malformed values abort startup;
unset/blank always defaults. Never wire validation into `buildApp()` or
`ConfigModule.forRoot` — and never enable `cache: true` or `load`-snapshot a
runtime-toggled value (breaks the env-mutating tests).
- **Booleans are unified**: every switch accepts true/1/on/yes vs false/0/off/no
(any casing) via `parseBool`. Everything else pins its exact legacy coercion —
parity quirks are documented in `src/app-config/README.md`, including the
exemption list for the ESLint ban (plugin child process, dynamic keys,
`config.ts` key material, scripts, tests).
- Nest classes inject a boot-stable namespace token from `src/nest/app-config/` for values frozen per app build, or use `RuntimeEnvService` / `readEnv()` for runtime-toggled values (DEMO_MODE, NODE_ENV, OIDC_*, …) that tests mutate mid-lifetime.
- Everything else calls `readEnv()` — live, uncached, per call.
- Validation is fail-fast at boot only (`boot-validate.ts`, imported by `index.ts` right after dotenv): malformed values abort startup; unset/blank defaults. Never wire validation into `buildApp()` or `ConfigModule.forRoot`, and never `cache`/snapshot a runtime-toggled value (it breaks the env-mutating tests).
- Booleans go through `parseBool` (true/1/on/yes vs false/0/off/no). Everything else pins its exact legacy coercion — quirks and the ESLint exemption list are in `src/app-config/README.md`.
## Cross-cutting Nest pieces
## Cross-cutting pieces
- **`src/nest/common/`**: `trek-exception.filter.ts` (global error envelope, `APP_FILTER`), `zod-validation.pipe.ts` (validates against `@trek/shared` schemas), `idempotency.interceptor.ts` (global `APP_INTERCEPTOR` replaying `X-Idempotency-Key` on mutations).
- **Auth is default-deny**: `src/nest/auth/global-auth.guard.ts` + `mfa-policy.guard.ts` run as `APP_GUARD`s; routes opt out with `@Public()`/`@OptionalAuth()` (`public.decorator.ts`), and `src/nest/common/validate-route-guards.ts` refuses at boot any public route not on `PUBLIC_ROUTE_ALLOW_LIST`. The global guard stands down for routes that declare their own guard chain (still resolving `req.user` for MFA), so per-controller `@UseGuards(JwtAuthGuard, ...)` stacks keep working. Other guards: `admin.guard.ts`, `addons/addon.guard.ts` (`@RequireAddon`), `permissions/trip-access.guard.ts` (`@RequirePermission` + `@Trip()` — the standard trip-scoped shape), `permissions/trip-owner.guard.ts`. Auth is cookie-based (`trek_session`); `@CurrentUser()` decorator. **Never gate a multipart upload with a guard** — guards run before the parser, so the client sees ECONNRESET instead of your 403; check in the handler (PROFILE-015).
- **`src/middleware/`** — only `globalMiddleware.ts` remains (helmet/CSP, CORS, HSTS, forced-HTTPS, logging, cookie-parser), applied in `bootstrap`. The old `mfaPolicy`/`tripAccess`/`idempotency`/`validate` middlewares are deleted — their jobs moved into the guards above and the Nest pipe/interceptor layer.
- **`src/nest/common/`**: the global exception filter (error envelope), the Zod validation pipe, the idempotency interceptor (`X-Idempotency-Key` replay), and `validate-route-guards.ts` (boot-time ratchet refusing any public route not on its allow-list).
- **Auth is default-deny**: the global auth guard and the MFA policy guard run as `APP_GUARD`s, followed by the managed-install guard (`managed.guard.ts`), which refuses the routes a centrally administered install withholds from its own admin — it runs last so strangers still get a 401, never a route-revealing 403. Routes opt out with `@Public()`/`@OptionalAuth()`. The global guard stands down for routes declaring their own guard chain, so `@UseGuards(JwtAuthGuard, TripAccessGuard)` + `@RequirePermission` stacks work. Session is a cookie (`trek_session`); `@CurrentUser()` reads the user. **Never gate a multipart upload with a guard** — guards run before the parser and the client sees ECONNRESET instead of your 403; check in the handler.
- **`src/middleware/globalMiddleware.ts`** is the only Express middleware left (helmet/CSP, CORS, HSTS, forced-HTTPS, logging, cookies).
## Tests
`tests/` is split into `unit/` (mirrors `src/`, incl. `unit/nest/<domain>.controller.test.ts` and `auth-guard.test.ts`), `integration/`, `e2e/` (one `<domain>.e2e.test.ts` per module, booting the real `JwtAuthGuard` against a temp DB via `tests/e2e/harness.ts` — `createTempDb`/`seedUser`/`sessionCookie`), and `websocket/`. Shared helpers in `tests/helpers/`, fixtures in `tests/fixtures/`, global setup in `tests/setup.ts`.
`tests/` is split into `unit/` (mirrors `src/`), `integration/`, `e2e/` (one `<domain>.e2e.test.ts` per module, booting the real guards against a temp DB via `tests/e2e/harness.ts`) and `websocket/`; helpers in `tests/helpers/`, fixtures in `tests/fixtures/`.
- **vitest uses the SWC plugin** (`vitest.config.ts`), not esbuild, because Nest's type-based DI needs emitted decorator metadata — esbuild drops it. Keep that config when touching test tooling. Pool is `forks` (isolated DBs per worker).
- **Coverage gate is a per-domain ratchet over `src/nest/**`** (statements/branches/functions/lines; ≥80% floor, most domains pinned higher — see `vitest.config.ts`); legacy code is intentionally ungated.
- The config also aliases `@modelcontextprotocol/sdk/*` to CJS dist files because the SDK's exports map uses unresolvable extension-less wildcards.
- **vitest uses the SWC plugin**, not esbuild, because Nest's DI needs emitted decorator metadata. Keep that in `vitest.config.ts`. Pool is `forks` (isolated DB per worker). The config also aliases `@modelcontextprotocol/sdk/*` to its CJS dist because the SDK's exports map is unresolvable.
- **Coverage is a per-domain ratchet over `src/nest/**`** (≥80% floor, most domains pinned higher). Regenerate the block with `scripts/coverage-thresholds.mjs` when coverage rises; never lower a threshold to land a change.
- CI also runs SonarCloud on the PR's new lines — see the root `CLAUDE.md`.
## Parity discipline (when adding/changing routes)
## Parity discipline (when adding or changing routes)
Routes must be **byte-identical** for the client: same URL, method, query/body, HTTP status, `Set-Cookie`, and JSON body — including bespoke error strings. Nest defaults POST to **201**; add `@HttpCode(200)` where the contract returns 200. Declare static sub-routes (e.g. `/reorder`, `/in-app/all`) **before** `:id` param routes. Trip-scoped handlers verify trip access (404) and permission (403) per handler.
Routes are **byte-identical** for the client: same URL, method, query/body, status, `Set-Cookie` and JSON body, including bespoke error strings reproduced in the controller. Nest defaults POST to **201** — add `@HttpCode(200)` where the contract returns 200. Declare static sub-routes (`/reorder`, `/in-app/all`) **before** `:id` param routes. Trip-scoped handlers verify trip access (404) and permission (403).
+1 -1
View File
@@ -78,7 +78,7 @@ below.)
**Runtime-toggled** (read live on every access via `readEnv()` /
`RuntimeEnvService`; tests mutate these mid-lifetime):
TREK_MANAGED, PLACES_API_BASE, PLACES_API_KEY, MAPBOX_ACCESS_TOKEN, CARTO_API_KEY, DEMO_MODE, NODE_ENV, APP_VERSION, APP_URL, TREK_API_DOCS_ENABLED,
TREK_PLUGINS_ENABLED / _DEV_LINK / _DIR / _DATA_DIR / TREK_PLUGIN_PERMISSIONS,
TREK_PLUGINS_ENABLED / _DEV_LINK / _IGNORE_TREK_RANGE / _DIR / _DATA_DIR / TREK_PLUGIN_PERMISSIONS,
OIDC_*, SMTP_*, FORCE_HTTPS, COOKIE_SECURE, HSTS_INCLUDE_SUBDOMAINS,
ALLOWED_ORIGINS, UNSPLASH_ACCESS_KEY, WEBAUTHN_*, TZ, ADMIN_EMAIL,
ADMIN_PASSWORD, IDEMPOTENCY_TTL_SECONDS, MCP_RATE_LIMIT (request-path check).
+6
View File
@@ -200,6 +200,12 @@ export function derivePlugins(raw: RawEnv) {
/** Kill-switch is default-on: only an explicit falsy value disables (plugins/kill-switch.ts). */
enabled: parseBool(raw.TREK_PLUGINS_ENABLED) !== false,
devLink: parseBool(raw.TREK_PLUGINS_DEV_LINK) === true,
/**
* Range bypass is default-OFF: only an explicit truthy value turns the TREK-version
* gates into warnings (plugins/install/host-compat.ts). Never inferred from any
* other switch — an admin has to ask for "install it anyway" by name.
*/
ignoreTrekRange: parseBool(raw.TREK_PLUGINS_IGNORE_TREK_RANGE) === true,
dir: raw.TREK_PLUGINS_DIR,
dataDir: raw.TREK_PLUGINS_DATA_DIR,
/** Permission jail is default-on: only an explicit falsy value turns it off. */
+1
View File
@@ -150,6 +150,7 @@ export const envSchema = z.object({
TREK_API_DOCS_ENABLED: boolStr,
TREK_PLUGINS_ENABLED: boolStr,
TREK_PLUGINS_DEV_LINK: boolStr,
TREK_PLUGINS_IGNORE_TREK_RANGE: boolStr,
TREK_PLUGINS_DIR: anyString,
TREK_PLUGINS_DATA_DIR: anyString,
TREK_PLUGIN_PERMISSIONS: boolStr,
@@ -105,3 +105,46 @@ export function hostSatisfies(range: string | null | undefined, host: string | n
if (!isValidTrekRange(range)) return false;
return semver.satisfies(release, range);
}
/**
* Whether TREK_PLUGINS_IGNORE_TREK_RANGE is set: the operator's explicit "install it
* anyway" for a plugin whose author has not updated its `trek` range. While it is on,
* every TREK-version gate (registry picker, post-extraction re-check, sideload, dev-link,
* activation) WARNS instead of refusing. Nothing else changes — {@link hostSatisfies}
* keeps telling the truth, so the admin UI can still say the plugin is running outside
* the range its author vouched for. Read live, like the other plugin switches.
*/
export function trekRangeBypassed(): boolean {
return readEnv().plugins.ignoreTrekRange;
}
/** What a bypassed gate reports back to the admin: the range that was ignored and the host it was ignored on. */
export interface TrekRangeBypass {
/** The plugin's declared range, or null when it declared none at all. */
trekRange: string | null;
hostVersion: string;
}
/**
* Non-null exactly when `range` would have been refused and only the bypass lets it
* through: the marker that makes an install/activate response say "this worked, but
* only because you told TREK to ignore the version check". Null for a normal install
* (the range fits) and null when the bypass is off (the gate refuses instead).
*/
export function bypassedRange(range: string | null | undefined): TrekRangeBypass | null {
if (hostSatisfies(range)) return null;
if (!trekRangeBypassed()) return null;
return { trekRange: range ?? null, hostVersion: hostVersion() };
}
/**
* The one log line every bypassed gate writes. It names the plugin, the range that was
* ignored and the host it was ignored on, so an operator reading the log after a plugin
* misbehaves can connect the two without the UI.
*/
export function warnRangeBypass(id: string, b: TrekRangeBypass): void {
const declared = b.trekRange ? `declares TREK ${b.trekRange}` : 'declares no TREK version range';
console.warn(
`[plugins] ${id} ${declared} — this is TREK ${b.hostVersion}; continuing because TREK_PLUGINS_IGNORE_TREK_RANGE is set. The author has not verified it on this version: it may not work, and it could corrupt TREK data.`,
);
}
+4 -2
View File
@@ -1,6 +1,6 @@
import semver from 'semver';
import { isKnownPermission, PLUGIN_API_VERSION } from '../protocol/envelope';
import { isValidTrekRange, minTrekOf } from './host-compat';
import { isValidTrekRange, minTrekOf, trekRangeBypassed } from './host-compat';
import {
MCP_TOOLS_MAX,
McpToolSchemaError,
@@ -252,7 +252,9 @@ export function parseManifest(raw: unknown, opts?: { requireTrek?: boolean }): P
const trek = optStr(m.trek);
const trekRange = isValidTrekRange(trek) ? trek : null;
if (opts?.requireTrek && !trekRange) {
// Under TREK_PLUGINS_IGNORE_TREK_RANGE a missing range is the same author oversight as a
// stale one, so it is reported by the gate (as a null range) instead of refused here.
if (opts?.requireTrek && !trekRange && !trekRangeBypassed()) {
throw new ManifestError(
trek
? `invalid "trek" version range "${trek}" (expected a satisfiable semver range, e.g. ">=3.2.0 <4.0.0")`
@@ -26,7 +26,8 @@ import { scanForNativeBinaries } from './install/native-scan';
import { devLinkEnabled, DEV_LINK_SOURCE } from './dev-link';
import { pluginCodeDir, pluginDataDir } from './paths';
import { assertHostCompatible, PluginRegistryService, RegistryError } from './registry/registry.service';
import { hostSatisfies, hostVersion } from './install/host-compat';
import { hostSatisfies, hostVersion, bypassedRange, warnRangeBypass } from './install/host-compat';
import type { TrekRangeBypass } from './install/host-compat';
import { keyFingerprint } from './signature-status';
import { AuditService } from '../audit/audit.service';
import { AddonsService } from '../addons/addons.service';
@@ -504,14 +505,18 @@ export class PluginRuntimeService implements OnApplicationBootstrap, OnModuleDes
// it would not make the plugin start. It is also the gate that catches the case
// install can't — TREK was upgraded PAST the plugin's declared upper bound, so code
// that was legitimately installed no longer supports the host it's sitting on.
if (!row.trek_range) {
const bypass = bypassedRange(row.trek_range);
if (bypass) {
// TREK_PLUGINS_IGNORE_TREK_RANGE: the operator chose to run it anyway. Say so in the
// log every time it starts — the plugin list carries the same marker for the UI.
warnRangeBypass(id, bypass);
} else if (!row.trek_range) {
throw new PluginDependencyError(
`plugin ${id} does not declare which TREK versions it supports`,
'TREK_VERSION_UNKNOWN',
{ trekRange: null, hostVersion: hostVersion() },
);
}
if (!hostSatisfies(row.trek_range)) {
} else if (!hostSatisfies(row.trek_range)) {
throw new PluginDependencyError(
`plugin ${id} requires TREK ${row.trek_range} — this is TREK ${hostVersion()}`,
'TREK_VERSION_INCOMPATIBLE',
@@ -679,7 +684,10 @@ export class PluginRuntimeService implements OnApplicationBootstrap, OnModuleDes
* Install runs first so a failed download/signature/integrity check leaves the
* currently-running child untouched (it keeps serving the old code from memory).
*/
async update(id: string, opts?: { version?: string; retrustKey?: string }): Promise<{ version: string; activated: boolean; newPermissions: string[]; newEgress: string[] }> {
async update(
id: string,
opts?: { version?: string; retrustKey?: string },
): Promise<{ version: string; activated: boolean; newPermissions: string[]; newEgress: string[]; trekRangeBypassed: TrekRangeBypass | null }> {
const before = this.db.prepare('SELECT enabled, granted_permissions, version FROM plugins WHERE id = ?').get(id) as
| { enabled: number; granted_permissions: string; version: string | null }
| undefined;
@@ -708,11 +716,11 @@ export class PluginRuntimeService implements OnApplicationBootstrap, OnModuleDes
if (wasEnabled) await this.deactivate(id); // stop the old child now that new code is in place
if (newGrants.length === 0 && wasEnabled) {
await this.activate(id); // no wider rights → transparent restart on the new code
return { version: res.version, activated: true, newPermissions, newEgress };
return { version: res.version, activated: true, newPermissions, newEgress, trekRangeBypassed: res.trekRangeBypassed };
}
// New rights requested (or it was already disabled): leave it inactive until
// an admin explicitly consents by activating it.
return { version: res.version, activated: false, newPermissions, newEgress };
return { version: res.version, activated: false, newPermissions, newEgress, trekRangeBypassed: res.trekRangeBypassed };
}
/**
@@ -788,7 +796,7 @@ export class PluginRuntimeService implements OnApplicationBootstrap, OnModuleDes
* commits it as an INACTIVE sideloaded plugin. Never auto-activates — the admin
* re-activates (and re-consents to permissions) explicitly.
*/
async sideload(bytes: Buffer): Promise<{ id: string; version: string; replaced: boolean }> {
async sideload(bytes: Buffer): Promise<{ id: string; version: string; replaced: boolean; trekRangeBypassed: TrekRangeBypass | null }> {
if (!this.registry) throw new Error('registry service unavailable');
const staged = this.registry.stageUpload(bytes);
try {
@@ -800,7 +808,7 @@ export class PluginRuntimeService implements OnApplicationBootstrap, OnModuleDes
// a plugin that isn't running.
if (replaced) await this.deactivate(staged.id);
this.registry.commitUpload(staged); // moves code + registers INACTIVE, then clears staging
return { id: staged.id, version: staged.version, replaced };
return { id: staged.id, version: staged.version, replaced, trekRangeBypassed: staged.trekRangeBypassed };
} catch (e) {
// A failure before commitUpload leaves staging behind — clean it up.
try { fs.rmSync(staged.stagingDir, { recursive: true, force: true }); } catch {}
@@ -816,13 +824,13 @@ export class PluginRuntimeService implements OnApplicationBootstrap, OnModuleDes
* and starts an fs.watch that re-forks on rebuild. Gated behind TREK_PLUGINS_DEV_LINK
* on top of the controller's admin + kill-switch gates — see dev-link.ts for why.
*/
async link(sourceDir: string): Promise<{ id: string; version: string; replaced: boolean }> {
async link(sourceDir: string): Promise<{ id: string; version: string; replaced: boolean; trekRangeBypassed: TrekRangeBypass | null }> {
if (!devLinkEnabled()) throw new Error('dev-link is disabled (set TREK_PLUGINS_DEV_LINK=1)');
if (!path.isAbsolute(sourceDir)) throw new Error('the dev-link path must be absolute');
const manifestPath = path.join(sourceDir, 'trek-plugin.json');
if (!fs.existsSync(manifestPath)) throw new Error(`no trek-plugin.json at ${sourceDir}`);
const manifest = parseManifest(parseJsonText(fs.readFileSync(manifestPath, 'utf8')), { requireTrek: true });
assertHostCompatible(manifest.trekRange, manifest.id);
const trekRangeBypassed = assertHostCompatible(manifest.trekRange, manifest.id);
if (!fs.existsSync(path.join(sourceDir, 'server', 'index.js'))) {
throw new Error('no built server/index.js — build the plugin first (the loader runs the compiled artifact, not TS source)');
}
@@ -852,7 +860,7 @@ export class PluginRuntimeService implements OnApplicationBootstrap, OnModuleDes
WHERE id = ?`,
).run(DEV_LINK_SOURCE, id);
this.watchLinked(id, sourceDir);
return { id, version: manifest.version, replaced };
return { id, version: manifest.version, replaced, trekRangeBypassed };
}
/**
+13 -4
View File
@@ -10,7 +10,8 @@ import { safeParseConfig as safeParse } from './plugin-config-parse';
import { isFilled, parseDefaultValue, settingDefaults } from './settings-defaults';
import { AddonsService } from '../addons/addons.service';
import { parseDependencies, disabledRequiredAddons, resolveDependencyState, type PluginDepRow, type PluginDependencies, type VersionMismatch } from './dependencies';
import { hostSatisfies, hostVersion } from './install/host-compat';
import { bypassedRange, hostSatisfies, hostVersion, trekRangeBypassed } from './install/host-compat';
import type { TrekRangeBypass } from './install/host-compat';
import type { PluginDependency } from './install/manifest';
import type { PluginSettingsField } from '@trek/shared';
@@ -90,6 +91,12 @@ export interface PluginListItem {
trekRange: string | null;
/** The running TREK, so the UI can say "needs X, you have Y" without doing semver. */
hostVersion: string;
/**
* Non-null when the plugin is outside its declared range (or declared none) and only
* TREK_PLUGINS_IGNORE_TREK_RANGE lets it activate. The card shows it as a warning
* rather than a blocker: the admin chose this, but must keep seeing what they chose.
*/
trekRangeBypassed: TrekRangeBypass | null;
/** The concrete blockers, so the UI can render chips + the resolve dialog. */
dependencyIssues: { disabledAddons: string[]; missing: PluginDependency[]; versionMismatch: VersionMismatch[] };
/**
@@ -149,7 +156,7 @@ export class PluginsService {
}
}
list(): { enabled: boolean; devLink: boolean; plugins: PluginListItem[] } {
list(): { enabled: boolean; devLink: boolean; ignoreTrekRange: boolean; plugins: PluginListItem[] } {
const rows = this.db
.prepare(
`SELECT id, name, description, type, icon, version, status, enabled, last_error, reviewed_at, source_repo,
@@ -168,7 +175,8 @@ export class PluginsService {
const state = resolveDependencyState(deps, installed);
// Mirrors the order of assertActivatable's gate, so the card explains the same
// blocker the activate call would hit rather than a second, lesser one.
const dependencyStatus: PluginDependencyStatus = !hostSatisfies(r.trek_range)
const trekBypass = bypassedRange(r.trek_range);
const dependencyStatus: PluginDependencyStatus = !hostSatisfies(r.trek_range) && !trekBypass
? 'hostIncompatible'
: disabledAddons.length
? 'addonDisabled'
@@ -196,6 +204,7 @@ export class PluginsService {
dependencyStatus,
trekRange: trek_range,
hostVersion: hostVersion(),
trekRangeBypassed: trekBypass,
dependencyIssues: { disabledAddons, missing: state.missing, versionMismatch: state.versionMismatch },
signed: !!author_pubkey,
keyFingerprint: keyFingerprint(author_pubkey),
@@ -205,7 +214,7 @@ export class PluginsService {
updateHold: update_hold === 1,
};
});
return { enabled: pluginsEnabled(), devLink: devLinkEnabled(), plugins };
return { enabled: pluginsEnabled(), devLink: devLinkEnabled(), ignoreTrekRange: trekRangeBypassed(), plugins };
}
/**
@@ -1,7 +1,8 @@
import { readEnv } from '../../../app-config';
import { DatabaseService } from '../../database/database.service';
import { discoverPlugins } from '../install/discovery';
import { hostSatisfies, hostVersion, normalizedHost } from '../install/host-compat';
import { bypassedRange, hostSatisfies, hostVersion, normalizedHost, trekRangeBypassed, warnRangeBypass } from '../install/host-compat';
import type { TrekRangeBypass } from '../install/host-compat';
import type { PluginDependency } from '../install/manifest';
import { parseJsonText, parseManifest } from '../install/manifest';
import { scanForNativeBinaries } from '../install/native-scan';
@@ -257,7 +258,9 @@ export class PluginRegistryService {
private hostCompat(entry: RegistryEntry): HostCompat {
const latest = entry.versions[0] ?? null;
const compatible = latest ? hostCompatible(latest, normalizedHost()) : false;
const fallback = compatible ? null : this.latestCompatible(entry);
// The verdict is the TRUTH, so it asks the strict predicate even when the picker is
// bypassed: "latest compatible" must keep naming a version the author vouched for.
const fallback = compatible ? null : this.latestCompatible(entry, undefined, hostCompatible);
return {
trek: latest?.trek ?? null,
hostVersion: hostVersion(),
@@ -358,12 +361,20 @@ export class PluginRegistryService {
return v;
}
/** The newest version of `entry` that satisfies `constraint` AND admits the running TREK. */
private latestCompatible(entry: RegistryEntry, constraint?: string): RegistryVersion | null {
/**
* The newest version of `entry` that satisfies `constraint` AND admits the running TREK.
* `admits` defaults to the picker's rule (which honours TREK_PLUGINS_IGNORE_TREK_RANGE);
* the UI verdict passes the strict {@link hostCompatible} instead.
*/
private latestCompatible(
entry: RegistryEntry,
constraint?: string,
admits: (v: RegistryVersion, host: string | null) => boolean = installable,
): RegistryVersion | null {
const host = normalizedHost();
const candidates = entry.versions.filter((v) => {
if (constraint && !semver.satisfies(v.version, constraint, { includePrerelease: true })) return false;
return hostCompatible(v, host);
return admits(v, host);
});
if (!candidates.length) return null;
return [...candidates].sort((a, b) => semver.rcompare(a.version, b.version))[0];
@@ -380,7 +391,7 @@ export class PluginRegistryService {
if (opts?.version) {
const ver = entry.versions.find((v) => v.version === opts.version);
if (!ver) throw new RegistryError(`version ${opts.version} not found for ${entry.id}`);
if (!hostCompatible(ver, normalizedHost())) {
if (!installable(ver, normalizedHost())) {
throw new RegistryError(
`${entry.id} ${ver.version} requires TREK ${trekRequirement(ver)} — this is TREK ${hostVersion()}`,
'TREK_VERSION_INCOMPATIBLE',
@@ -419,7 +430,7 @@ export class PluginRegistryService {
async install(
id: string,
opts?: { version?: string; constraint?: string; retrustKey?: string },
): Promise<{ id: string; version: string }> {
): Promise<{ id: string; version: string; trekRangeBypassed: TrekRangeBypass | null }> {
const reg = await this.fetchRegistry();
const entry = reg.plugins.find((p) => p.id === id);
if (!entry) throw new RegistryError(`plugin ${id} not in registry`);
@@ -459,7 +470,7 @@ export class PluginRegistryService {
// published entries usually carry a lower bound and no upper one at all, so a
// plugin that declares "<4.0.0" passes the pre-download filter on TREK 4 and is
// caught only here.
assertHostCompatible(manifest.trekRange, id);
const trekRangeBypassed = assertHostCompatible(manifest.trekRange, id);
if (scanForNativeBinaries(pluginRoot).length) throw new RegistryError('artifact contains native binaries');
// 6. atomic move into place
@@ -487,7 +498,7 @@ export class PluginRegistryService {
// The plugin is now on new code that passed every check — whatever refusal was
// recorded before no longer describes reality.
clearUpdateBlock(this.dbs.connection, id);
return { id, version: ver.version };
return { id, version: ver.version, trekRangeBypassed };
} finally {
fs.rmSync(staging, { recursive: true, force: true });
}
@@ -503,7 +514,8 @@ export class PluginRegistryService {
async installWithDependencies(
id: string,
constraint?: string,
): Promise<{ installed: string[]; requiredAddons: string[] }> {
): Promise<{ installed: string[]; requiredAddons: string[]; trekRangeBypassed: TrekRangeBypass | null }> {
let trekRangeBypassed: TrekRangeBypass | null = null;
const installedNow = new Set(
(this.db.prepare('SELECT id FROM plugins').all() as Array<{ id: string }>).map((r) => r.id),
);
@@ -519,7 +531,10 @@ export class PluginRegistryService {
// Install the version we just RESOLVED. Passing the range back (or nothing, for
// the root) made install() re-pick on its own and land on entry.versions[0] —
// so the compatible version resolveVersion had chosen was computed and discarded.
await this.install(pid, { version: ver.version });
const res = await this.install(pid, { version: ver.version });
// The admin asked for the root; that is the bypass they are warned about (a
// dependency's own bypass still lands in the log).
if (pid === id) trekRangeBypassed = res.trekRangeBypassed;
installed.push(pid);
installedNow.add(pid);
}
@@ -528,7 +543,7 @@ export class PluginRegistryService {
for (const dep of ver.pluginDependencies ?? []) await visit(dep.id, dep.version, [...stack, pid]);
};
await visit(id, constraint, []);
return { installed, requiredAddons: [...requiredAddons] };
return { installed, requiredAddons: [...requiredAddons], trekRangeBypassed };
}
/**
@@ -563,7 +578,7 @@ export class PluginRegistryService {
* binaries) — only the registry sha256/signature checks are absent, because a
* sideload has no registry entry. Throws (and self-cleans staging) on failure.
*/
stageUpload(bytes: Buffer): { id: string; version: string; root: string; stagingDir: string } {
stageUpload(bytes: Buffer): { id: string; version: string; root: string; stagingDir: string; trekRangeBypassed: TrekRangeBypass | null } {
if (bytes.length > MAX_UPLOAD_BYTES) throw new RegistryError('archive exceeds the 50MB limit');
const stagingDir = path.join(pluginsDataRoot(), '.staging', `upload-${Date.now()}`);
try {
@@ -573,9 +588,9 @@ export class PluginRegistryService {
const manifest = parseManifest(parseJsonText(fs.readFileSync(path.join(root, 'trek-plugin.json'), 'utf8')), {
requireTrek: true,
});
assertHostCompatible(manifest.trekRange, manifest.id);
const trekRangeBypassed = assertHostCompatible(manifest.trekRange, manifest.id);
if (scanForNativeBinaries(root).length) throw new RegistryError('artifact contains native binaries');
return { id: manifest.id, version: manifest.version, root, stagingDir };
return { id: manifest.id, version: manifest.version, root, stagingDir, trekRangeBypassed };
} catch (e) {
fs.rmSync(stagingDir, { recursive: true, force: true });
throw e;
@@ -746,13 +761,32 @@ function hostCompatible(v: RegistryVersion, host: string | null): boolean {
return true;
}
/**
* Whether the registry picker may offer `v`: it fits the host, or the operator set
* TREK_PLUGINS_IGNORE_TREK_RANGE and asked for the newest published version regardless.
* Only the PICKER uses this — the compat verdict the UI shows (hostCompat/detail) stays
* on {@link hostCompatible}, so a bypassed install is still labelled as outside its range.
*/
function installable(v: RegistryVersion, host: string | null): boolean {
return trekRangeBypassed() || hostCompatible(v, host);
}
/**
* Refuse an artifact whose declared TREK range doesn't admit the running host. Shared by
* every install front door (registry, sideload, dev-link) so they all fail the same way,
* with a code the admin UI can act on rather than prose it would have to string-match.
*
* Under TREK_PLUGINS_IGNORE_TREK_RANGE the refusal becomes a log warning, and the
* returned marker is what the front door hands back so the admin is told too. Null
* means the range fits and nothing was bypassed.
*/
export function assertHostCompatible(range: string | null, id: string): void {
if (hostSatisfies(range)) return;
export function assertHostCompatible(range: string | null, id: string): TrekRangeBypass | null {
if (hostSatisfies(range)) return null;
const bypass = bypassedRange(range);
if (bypass) {
warnRangeBypass(id, bypass);
return bypass;
}
throw new RegistryError(`${id} requires TREK ${range} — this is TREK ${hostVersion()}`, 'TREK_VERSION_INCOMPATIBLE');
}
@@ -103,6 +103,26 @@ describe('PluginRuntimeService dev-link', () => {
await expect(runtime.link(writeSource('nativeplug', { native: true }))).rejects.toThrow(/native/);
});
it('links a dir outside its TREK range when TREK_PLUGINS_IGNORE_TREK_RANGE is set, and says so', async () => {
process.env.APP_VERSION = '3.3.0';
process.env.TREK_PLUGINS_IGNORE_TREK_RANGE = '1';
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
await expect(runtime.link(writeSource('oldplug-bypass', { trek: '>=2.0.0 <3.0.0' }))).resolves.toMatchObject({
id: 'oldplug-bypass', trekRangeBypassed: { trekRange: '>=2.0.0 <3.0.0', hostVersion: '3.3.0' },
});
await expect(runtime.link(writeSource('rangeless-bypass', { trek: '' }))).resolves.toMatchObject({
id: 'rangeless-bypass', trekRangeBypassed: { trekRange: null, hostVersion: '3.3.0' },
});
// A dir that fits is a plain link — no marker to alarm anyone with.
await expect(runtime.link(writeSource('fits-bypass'))).resolves.toMatchObject({ trekRangeBypassed: null });
} finally {
warn.mockRestore();
delete process.env.APP_VERSION;
delete process.env.TREK_PLUGINS_IGNORE_TREK_RANGE;
}
});
it('rejects a local dir whose TREK range this server does not satisfy', async () => {
// Dev-link is the third install front door, and it hands TREK code to RUN against real
// data — the fact that the author is standing right there is not a reason to skip the
@@ -3,7 +3,7 @@
* HTTP route works through the host→child invoke path, using its own isolated
* db. Proves the full activate → route → deactivate loop.
*/
import { describe, it, expect, beforeAll, afterAll, afterEach, vi } from 'vitest';
import { describe, it, expect, beforeAll, afterAll, afterEach, beforeEach, vi } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
@@ -712,6 +712,36 @@ describe('TREK host-version gating', () => {
cleanup('boot-broken');
});
describe('with TREK_PLUGINS_IGNORE_TREK_RANGE set', () => {
beforeEach(() => { process.env.TREK_PLUGINS_IGNORE_TREK_RANGE = '1'; });
afterEach(() => { delete process.env.TREK_PLUGINS_IGNORE_TREK_RANGE; });
it('activates a plugin this TREK has outgrown, warning in the log instead of refusing', async () => {
process.env.APP_VERSION = '4.0.0';
seedRanged('outgrown-ok', '>=3.2.0 <4.0.0');
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const rt = createPluginRuntime(new DatabaseService(dbConn));
await rt.activate('outgrown-ok');
expect(rt.isActive('outgrown-ok')).toBe(true);
expect(warn.mock.calls.some((c) => /outgrown-ok.*>=3\.2\.0 <4\.0\.0.*4\.0\.0/.test(String(c[0])))).toBe(true);
warn.mockRestore();
await rt.deactivate('outgrown-ok');
cleanup('outgrown-ok');
});
it('activates a plugin that never declared a range', async () => {
process.env.APP_VERSION = '3.3.0';
seedRanged('undeclared-ok', null);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const rt = createPluginRuntime(new DatabaseService(dbConn));
await rt.activate('undeclared-ok');
expect(rt.isActive('undeclared-ok')).toBe(true);
warn.mockRestore();
await rt.deactivate('undeclared-ok');
cleanup('undeclared-ok');
});
});
it('checks the version BEFORE permissions — an unrunnable plugin gets no consent dialog', async () => {
// Consenting to permissions would not make it start, so offering the dialog is a lie.
process.env.APP_VERSION = '4.0.0';
@@ -749,6 +779,17 @@ describe('plugin-API version gating', () => {
cleanup('future-api');
});
it('still refuses a newer apiVersion when the TREK-range bypass is on — it is not a range problem', async () => {
process.env.TREK_PLUGINS_IGNORE_TREK_RANGE = '1';
try {
seedApi('future-api-bypass', 2);
await expect(createPluginRuntime(new DatabaseService(dbConn)).activate('future-api-bypass')).rejects.toMatchObject({ code: 'API_VERSION_INCOMPATIBLE' });
} finally {
delete process.env.TREK_PLUGINS_IGNORE_TREK_RANGE;
cleanup('future-api-bypass');
}
});
it('activates normally when apiVersion is within what this TREK supports', async () => {
seedApi('current-api', 1);
const rt = createPluginRuntime(new DatabaseService(dbConn));
@@ -387,7 +387,7 @@ describe('PluginRegistryService', () => {
safeDownload.mockResolvedValue({ bytes: artifact, sha256: sha });
const out = await svc.install('flight-tracker');
expect(out).toEqual({ id: 'flight-tracker', version: '1.0.0' });
expect(out).toEqual({ id: 'flight-tracker', version: '1.0.0', trekRangeBypassed: null });
// moved into place + registered inactive with provenance
expect(fs.existsSync(path.join(codeRoot, 'flight-tracker', 'trek-plugin.json'))).toBe(true);
@@ -496,7 +496,7 @@ describe('PluginRegistryService', () => {
it('installs a signed plugin and pins the author key (TOFU)', async () => {
const k = signingKey();
stageSignedArtifact(k.pubB64, k.sign);
await expect(svc.install('flight-tracker')).resolves.toEqual({ id: 'flight-tracker', version: '1.0.0' });
await expect(svc.install('flight-tracker')).resolves.toEqual({ id: 'flight-tracker', version: '1.0.0', trekRangeBypassed: null });
const row = testDb.prepare("SELECT author_pubkey FROM plugins WHERE id='flight-tracker'").get() as { author_pubkey: string };
expect(row.author_pubkey).toBe(k.pubB64);
});
@@ -865,6 +865,91 @@ describe('TREK-version gating on install', () => {
await expect(svc.install('multi')).rejects.toMatchObject({ code: 'TREK_VERSION_INCOMPATIBLE' });
});
/**
* TREK_PLUGINS_IGNORE_TREK_RANGE: the operator's explicit "install it anyway". Every gate
* above turns into a warning + a `trekRangeBypassed` marker in the response, so the admin
* is told the author never vouched for this TREK. The registry's compat VERDICT stays
* truthful — the UI needs it to say "outside its range" while still offering the button.
*/
describe('range bypass (TREK_PLUGINS_IGNORE_TREK_RANGE)', () => {
beforeEach(() => { process.env.TREK_PLUGINS_IGNORE_TREK_RANGE = '1'; });
afterEach(() => { delete process.env.TREK_PLUGINS_IGNORE_TREK_RANGE; });
it('install-latest fetches the newest PUBLISHED version and reports the ignored range', async () => {
process.env.APP_VERSION = '3.3.0'; stubMulti();
stageMulti('2.1.0', 0);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
await expect(svc.install('multi')).resolves.toEqual({
id: 'multi', version: '2.1.0', trekRangeBypassed: { trekRange: '>=3.4.0 <4.0.0', hostVersion: '3.3.0' },
});
expect(warn.mock.calls.some((c) => /multi.*>=3\.4\.0 <4\.0\.0.*3\.3\.0/.test(String(c[0])))).toBe(true);
warn.mockRestore();
});
it('installs an explicitly-pinned version this TREK cannot run', async () => {
process.env.APP_VERSION = '3.3.0'; stubMulti();
stageMulti('2.1.0', 0);
await expect(svc.install('multi', { version: '2.1.0' })).resolves.toMatchObject({
version: '2.1.0', trekRangeBypassed: { trekRange: '>=3.4.0 <4.0.0', hostVersion: '3.3.0' },
});
});
it('a version that fits is a normal install — no marker, nothing to warn about', async () => {
process.env.APP_VERSION = '3.5.0'; stubMulti();
stageMulti('2.1.0', 0);
await expect(svc.install('multi')).resolves.toEqual({ id: 'multi', version: '2.1.0', trekRangeBypassed: null });
});
it('browse keeps telling the truth about compatibility', async () => {
process.env.APP_VERSION = '3.3.0'; stubMulti();
const [item] = await svc.browse(true);
expect(item).toMatchObject({ compatible: false, latestCompatible: '2.0.0', hostVersion: '3.3.0' });
});
it("re-gate on the ARTIFACT's range warns instead of refusing, with the artifact's range", async () => {
process.env.APP_VERSION = '3.9.0';
__clearRegistryCacheForTests();
const artifact = makeArtifact({ id: 'flight-tracker', name: 'Flight', version: '1.0.0', type: 'widget', trek: '>=3.2.0 <3.4.0' });
const sha = createHash('sha256').update(artifact).digest('hex');
REGISTRY.plugins[0].versions[0].sha256 = sha;
safeDownload.mockResolvedValue({ bytes: artifact, sha256: sha });
await expect(svc.install('flight-tracker')).resolves.toMatchObject({
id: 'flight-tracker', trekRangeBypassed: { trekRange: '>=3.2.0 <3.4.0', hostVersion: '3.9.0' },
});
expect(fs.existsSync(path.join(codeRoot, 'flight-tracker'))).toBe(true);
});
it('installs an artifact that declares no range at all, saying so', async () => {
process.env.APP_VERSION = '3.9.0';
__clearRegistryCacheForTests();
const artifact = makeArtifact({ id: 'flight-tracker', name: 'Flight', version: '1.0.0', type: 'widget', trek: undefined });
const sha = createHash('sha256').update(artifact).digest('hex');
REGISTRY.plugins[0].versions[0].sha256 = sha;
safeDownload.mockResolvedValue({ bytes: artifact, sha256: sha });
await expect(svc.install('flight-tracker')).resolves.toMatchObject({
trekRangeBypassed: { trekRange: null, hostVersion: '3.9.0' },
});
});
it('sideload: stages an incompatible or rangeless archive and reports it', () => {
process.env.APP_VERSION = '3.9.0';
const old = svc.stageUpload(makeArtifact({ id: 'my-upload', name: 'Up', version: '1.0.0', type: 'integration', trek: '>=3.0.0 <3.5.0' }));
expect(old).toMatchObject({ id: 'my-upload', trekRangeBypassed: { trekRange: '>=3.0.0 <3.5.0', hostVersion: '3.9.0' } });
fs.rmSync(old.stagingDir, { recursive: true, force: true });
const rangeless = svc.stageUpload(makeArtifact({ id: 'my-upload', name: 'Up', version: '1.0.0', type: 'integration', trek: undefined }));
expect(rangeless).toMatchObject({ trekRangeBypassed: { trekRange: null, hostVersion: '3.9.0' } });
fs.rmSync(rangeless.stagingDir, { recursive: true, force: true });
const fits = svc.stageUpload(makeArtifact({ id: 'my-upload', name: 'Up', version: '1.0.0', type: 'integration' }));
expect(fits.trekRangeBypassed).toBeNull();
fs.rmSync(fits.stagingDir, { recursive: true, force: true });
});
it('does NOT lift the plugin-API version gate — that one is a real ABI break', () => {
const bytes = makeArtifact({ id: 'my-upload', name: 'Up', version: '1.0.0', type: 'integration', apiVersion: 2 });
expect(() => svc.stageUpload(bytes)).toThrow('plugin requires plugin-API v2; this TREK supports v1');
});
});
it('reports the newest version this TREK CAN run, so the UI can offer it', async () => {
process.env.APP_VERSION = '3.3.0'; stubMulti();
const [item] = await svc.browse(true);
@@ -188,6 +188,14 @@ describe('derivePlugins', () => {
expect(derivePlugins({}).permissionsOff).toBe(false);
});
it('ignoreTrekRange is off unless explicitly truthy — the version gate must never bypass by accident', () => {
expect(derivePlugins({}).ignoreTrekRange).toBe(false);
expect(derivePlugins({ TREK_PLUGINS_IGNORE_TREK_RANGE: '' }).ignoreTrekRange).toBe(false);
expect(derivePlugins({ TREK_PLUGINS_IGNORE_TREK_RANGE: 'off' }).ignoreTrekRange).toBe(false);
expect(derivePlugins({ TREK_PLUGINS_IGNORE_TREK_RANGE: '1' }).ignoreTrekRange).toBe(true);
expect(derivePlugins({ TREK_PLUGINS_IGNORE_TREK_RANGE: 'TRUE' }).ignoreTrekRange).toBe(true);
});
it('allowPrivateEgress is a bool (supervisor normalizes it to the literal "on" for the child)', () => {
expect(derivePlugins({ TREK_PLUGIN_ALLOW_PRIVATE_EGRESS: 'on' }).allowPrivateEgress).toBe(true);
expect(derivePlugins({ TREK_PLUGIN_ALLOW_PRIVATE_EGRESS: 'true' }).allowPrivateEgress).toBe(true);
@@ -5,6 +5,8 @@ import {
isValidTrekRange,
minTrekOf,
hostSatisfies,
trekRangeBypassed,
bypassedRange,
__resetHostWarningForTests,
} from '../../../src/nest/plugins/install/host-compat';
@@ -18,6 +20,7 @@ const APP_VERSION = process.env.APP_VERSION;
afterEach(() => {
if (APP_VERSION === undefined) delete process.env.APP_VERSION;
else process.env.APP_VERSION = APP_VERSION;
delete process.env.TREK_PLUGINS_IGNORE_TREK_RANGE;
__resetHostWarningForTests();
});
@@ -114,3 +117,40 @@ describe('hostSatisfies', () => {
expect(hostVersion()).toMatch(/^\d+\.\d+\.\d+/); // package.json
});
});
/**
* TREK_PLUGINS_IGNORE_TREK_RANGE: an operator's explicit "install it anyway" for a plugin
* whose author has not updated its `trek` range. The gates warn instead of refusing, but
* the truth (hostSatisfies) never changes — the UI still has to say the plugin is
* outside its range.
*/
describe('range bypass (TREK_PLUGINS_IGNORE_TREK_RANGE)', () => {
it('is off by default and only an explicit truthy value turns it on', () => {
expect(trekRangeBypassed()).toBe(false);
process.env.TREK_PLUGINS_IGNORE_TREK_RANGE = '0';
expect(trekRangeBypassed()).toBe(false);
process.env.TREK_PLUGINS_IGNORE_TREK_RANGE = '1';
expect(trekRangeBypassed()).toBe(true);
});
it('reports a bypassed mismatch only when the bypass is on AND the range does not admit the host', () => {
process.env.APP_VERSION = '3.3.0';
expect(bypassedRange('>=4.0.0')).toBeNull(); // off → the gate refuses, nothing to report
process.env.TREK_PLUGINS_IGNORE_TREK_RANGE = 'true';
expect(bypassedRange('>=4.0.0')).toEqual({ trekRange: '>=4.0.0', hostVersion: '3.3.0' });
expect(bypassedRange('>=3.2.0 <4.0.0')).toBeNull(); // fits → not a bypass, a normal install
});
it('covers a plugin that declared no range at all — the same author oversight', () => {
process.env.APP_VERSION = '3.3.0';
process.env.TREK_PLUGINS_IGNORE_TREK_RANGE = '1';
expect(bypassedRange(null)).toEqual({ trekRange: null, hostVersion: '3.3.0' });
expect(bypassedRange(undefined)).toEqual({ trekRange: null, hostVersion: '3.3.0' });
});
it('leaves hostSatisfies telling the truth while bypassed', () => {
process.env.APP_VERSION = '3.3.0';
process.env.TREK_PLUGINS_IGNORE_TREK_RANGE = '1';
expect(hostSatisfies('>=4.0.0')).toBe(false);
});
});
@@ -105,16 +105,16 @@ describe('signature refusal codes survive to the client', () => {
// must install exactly that one — the compat gate stays server-side in selectVersion.
describe('POST :id/update — explicit version', () => {
it('forwards the requested version to the runtime', async () => {
vi.mocked(runtime.update).mockResolvedValue({ version: '1.2.0', activated: true, newPermissions: [], newEgress: [] });
vi.mocked(runtime.update).mockResolvedValue({ version: '1.2.0', activated: true, newPermissions: [], newEgress: [], trekRangeBypassed: null });
const res = await controller.update('flight-tracker', { version: '1.2.0' });
expect(vi.mocked(runtime.update).mock.calls[0]).toEqual(['flight-tracker', { version: '1.2.0' }]);
expect(res).toEqual({ version: '1.2.0', activated: true, newPermissions: [], newEgress: [] });
expect(res).toEqual({ version: '1.2.0', activated: true, newPermissions: [], newEgress: [], trekRangeBypassed: null });
});
it('an omitted body keeps the default newest-compatible resolution', async () => {
vi.mocked(runtime.update).mockResolvedValue({ version: '2.0.0', activated: true, newPermissions: [], newEgress: [] });
vi.mocked(runtime.update).mockResolvedValue({ version: '2.0.0', activated: true, newPermissions: [], newEgress: [], trekRangeBypassed: null });
await controller.update('flight-tracker');
@@ -128,7 +128,7 @@ describe('POST :id/update — explicit version', () => {
// must not touch it.
describe('update hold wiring', () => {
it('an explicit-version update recomputes the hold as deliberate', async () => {
vi.mocked(runtime.update).mockResolvedValue({ version: '1.2.0', activated: true, newPermissions: [], newEgress: [] });
vi.mocked(runtime.update).mockResolvedValue({ version: '1.2.0', activated: true, newPermissions: [], newEgress: [], trekRangeBypassed: null });
await controller.update('flight-tracker', { version: '1.2.0' });
@@ -136,7 +136,7 @@ describe('update hold wiring', () => {
});
it('a default update recomputes as non-deliberate (clears a stale hold)', async () => {
vi.mocked(runtime.update).mockResolvedValue({ version: '2.0.0', activated: true, newPermissions: [], newEgress: [] });
vi.mocked(runtime.update).mockResolvedValue({ version: '2.0.0', activated: true, newPermissions: [], newEgress: [], trekRangeBypassed: null });
await controller.update('flight-tracker');
@@ -144,7 +144,7 @@ describe('update hold wiring', () => {
});
it('an explicit-version install recomputes the hold as deliberate', async () => {
vi.mocked(registry.install).mockResolvedValue({ id: 'flight-tracker', version: '1.2.0' });
vi.mocked(registry.install).mockResolvedValue({ id: 'flight-tracker', version: '1.2.0', trekRangeBypassed: null });
await controller.install({ id: 'flight-tracker', version: '1.2.0' });
@@ -152,7 +152,7 @@ describe('update hold wiring', () => {
});
it('a dependency-resolution install does NOT touch the hold', async () => {
vi.mocked(registry.installWithDependencies).mockResolvedValue({ installed: ['flight-tracker'], requiredAddons: [] });
vi.mocked(registry.installWithDependencies).mockResolvedValue({ installed: ['flight-tracker'], requiredAddons: [], trekRangeBypassed: null });
await controller.install({ id: 'flight-tracker', withDependencies: true });
@@ -48,6 +48,47 @@ describe('PluginsService.list', () => {
expect(out.plugins[0]).toMatchObject({ id: 'flight', name: 'Flight', status: 'inactive' });
});
describe('TREK-range bypass', () => {
const APP_VERSION = process.env.APP_VERSION;
afterEach(() => {
delete process.env.TREK_PLUGINS_IGNORE_TREK_RANGE;
if (APP_VERSION === undefined) delete process.env.APP_VERSION;
else process.env.APP_VERSION = APP_VERSION;
});
const seed = () =>
testDb
.prepare("INSERT INTO plugins (id, name, type, status, version, trek_range) VALUES ('old','Old','widget','inactive','1.0.0','>=3.0.0 <4.0.0')")
.run();
it('reports the switch off and an outgrown plugin as hostIncompatible by default', () => {
process.env.APP_VERSION = '4.1.0';
seed();
const out = new PluginsService(new DatabaseService(dbConn), new AddonsService(new DatabaseService(dbConn))).list();
expect(out.ignoreTrekRange).toBe(false);
expect(out.plugins[0]).toMatchObject({ dependencyStatus: 'hostIncompatible', trekRangeBypassed: null });
});
it('with the switch on, the plugin may activate but the row still says it is outside its range', () => {
process.env.APP_VERSION = '4.1.0';
process.env.TREK_PLUGINS_IGNORE_TREK_RANGE = '1';
seed();
const out = new PluginsService(new DatabaseService(dbConn), new AddonsService(new DatabaseService(dbConn))).list();
expect(out.ignoreTrekRange).toBe(true);
expect(out.plugins[0]).toMatchObject({
dependencyStatus: 'ok',
trekRangeBypassed: { trekRange: '>=3.0.0 <4.0.0', hostVersion: '4.1.0' },
});
});
it('a plugin inside its range carries no marker even with the switch on', () => {
process.env.APP_VERSION = '3.5.0';
process.env.TREK_PLUGINS_IGNORE_TREK_RANGE = '1';
seed();
const out = new PluginsService(new DatabaseService(dbConn), new AddonsService(new DatabaseService(dbConn))).list();
expect(out.plugins[0]).toMatchObject({ dependencyStatus: 'ok', trekRangeBypassed: null });
});
});
it('surfaces updateHold as a boolean (held plugins leave the update banner)', () => {
testDb
.prepare("INSERT INTO plugins (id, name, type, status, version, update_hold) VALUES ('held','Held','widget','inactive','1.0.0',1)")