Release branch for 4.0.0.
This commit is contained in:
jubnl
2026-08-27 13:22:39 +02:00
committed by GitHub
parent e60427f813
commit 77dddd5e8a
3355 changed files with 403744 additions and 67215 deletions
+8
View File
@@ -1,3 +1,8 @@
# NOTE: variables are validated at startup (fail-fast). An UNSET or blank
# variable always falls back to its default, but a variable that is set to a
# malformed value (e.g. PORT=abc, SESSION_DURATION=bogus, DEMO_MODE=maybe)
# aborts boot with a report of every offending variable.
# Boolean switches accept true/false, 1/0, on/off and yes/no (any casing).
PORT=3001 # Port to run the server on
# HOST=0.0.0.0 # Bind address for the HTTP server. Only set this when running TREK from sources or via the Proxmox community script — never in Docker (the container handles binding).
NODE_ENV=development # development = development mode; production = production mode
@@ -38,6 +43,9 @@ DEMO_MODE=false # Demo mode - resets data hourly
# BACKUP_UPLOAD_LIMIT_MB=500 # Max size (MB) of a backup archive you can upload when restoring. Raise it if your backup exceeds 500 MB. If you sit behind a reverse proxy, raise its upload limit too (e.g. nginx client_max_body_size).
# TREK_DB_JOURNAL_MODE=WAL # SQLite journal mode (DELETE, TRUNCATE, PERSIST, MEMORY, WAL, OFF). WAL is fastest and the right choice on local disk. Set DELETE if the data directory lives on network storage (Azure App Service, an SMB/NFS volume on a NAS) — WAL coordinates writers through a shared-memory file that those filesystems do not implement reliably. The mode is stored inside the database file, so it survives a restart; changing this applies on the next boot.
# TREK_DB_SYNCHRONOUS=NORMAL # How hard SQLite flushes to disk (OFF, NORMAL, FULL, EXTRA). Defaults to NORMAL under WAL and FULL under any other journal mode — leave it alone unless you know why you want otherwise. Both variables fall back to their default (with a warning in the log) if the value is not a mode SQLite knows.
# MCP_RATE_LIMIT=300 # Max MCP API requests per user per minute (default: 300)
# MCP_MAX_SESSION_PER_USER=20 # Max concurrent MCP sessions per user (default: 20)
+108
View File
@@ -0,0 +1,108 @@
# 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.
## 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 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 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
```
Single test:
```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). So `npm run build` succeeding does **not** mean the code typechecks — always run `npm run typecheck` to gate types.
## Architecture
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/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.
## 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.
- **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.
## Configuration (app-config)
**Never read `process.env` directly 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).
## Cross-cutting Nest 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.
## 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`.
- **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.
## Parity discipline (when adding/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.
Binary file not shown.
+119
View File
@@ -44,4 +44,123 @@ export default tseslint.config(
'prefer-const': 'warn',
},
},
{
// Config-access guard: every env read in src/ goes through src/app-config
// (readEnv() / derive functions / registerAs tokens). Direct process.env
// access is banned outside the documented exemptions below — see
// src/app-config/README.md for the rationale behind each.
files: ['src/**/*.ts'],
ignores: [
// The config layer itself.
'src/app-config/**',
'src/nest/app-config/**',
// Key-material resolution (file persistence + runtime rotation), not env config.
'src/config.ts',
// Scrubbed plugin child process — must not import app-config.
'src/nest/plugins/runtime/plugin-host-entry.ts',
// Child-env whitelist block: the env there is an IPC channel to the sandbox.
'src/nest/plugins/supervisor/plugin-supervisor.ts',
// Dynamic-key caps (process.env[name] with a computed name).
'src/nest/plugins/host/daily-budget.ts',
'src/nest/plugins/host/plugin-audit.ts',
],
rules: {
'no-restricted-syntax': [
'error',
{
selector: "MemberExpression[object.name='process'][property.name='env']",
message:
'Read configuration via src/app-config (readEnv()/derive/tokens), not process.env. Exemptions: eslint.config.mjs + src/app-config/README.md.',
},
{
// Bracket-notation variant (process['env']) — property is a Literal
// node (.value), so the selector above can't match it.
selector: "MemberExpression[object.name='process'][property.value='env']",
message:
'Read configuration via src/app-config (readEnv()/derive/tokens), not process.env. Exemptions: eslint.config.mjs + src/app-config/README.md.',
},
],
},
},
{
// src/services/ is gone. It was the legacy layer this migration existed to
// empty, and the last of it (airtrail) folded into src/nest/integrations/.
//
// The wall matters more than the deletion: the directory disappearing is not
// what stops it coming back, because the way it grew was one file at a time,
// each one reasonable on its own. A new domain goes to src/nest/<domain>/
// with a service, a controller and a module.
files: ['src/**/*.ts', 'tests/**/*.ts'],
rules: {
'no-restricted-imports': [
'error',
{
patterns: [
{
group: ['**/services/*', '**/services/**/*'],
message:
'src/services/ is deleted. New backend code goes to src/nest/<domain>/ (service + controller + module, registered in app.module.ts). See src/nest/README.md.',
},
],
},
],
},
},
{
// The plugin RPC decorator kit is written to stay extractable into its own
// package, so its dependencies are pinned to Nest plus the two host modules it
// genuinely needs. See src/nest/plugins/host/rpc-kit/README.md for what an
// extraction would cost, and why the envelope import is the deliberate exception.
files: ['src/nest/plugins/host/rpc-kit/**/*.ts'],
rules: {
// Written as a deny list rather than an allow list on purpose: these patterns
// are gitignore-style, and a leading '**' would exclude the parent directory of
// every allowed path, which makes the '!' re-includes silently ineffective.
'no-restricted-imports': [
'error',
{
patterns: [
{
group: [
// The host modules next door.
'../rpc-host',
'../rpc-errors',
'../rpc-params',
'../rate-limit',
'../daily-budget',
'../plugin-audit',
'../plugin-jobs',
'../plugin-guards.service',
'../plugin-host-*',
// Everything one level up, in plugins/ itself.
'../../*.service',
'../../*.module',
'../../*.controller',
'../../dependencies',
'../../dev-link',
'../../kill-switch',
'../../paths',
'../../plugin-backup',
'../../signature-status',
'../../text-sanitize',
'../../install/**',
'../../registry/**',
'../../runtime/**',
'../../supervisor/**',
// The wire protocol, except the one file the kit validates against.
'../../protocol/*',
'!../../protocol/envelope',
// Anything outside the plugin subtree, and the rest of the app.
'../../../**',
'@trek/**',
'node:*',
],
message:
'rpc-kit stays extractable: it may import @nestjs/common, @nestjs/core, its own files, and type-only from ../../protocol/envelope and ../plugin-data.service. See rpc-kit/README.md.',
},
],
},
],
},
},
);
+16 -4
View File
@@ -9,6 +9,9 @@
"start:prod": "node --require tsconfig-paths/register dist/index.js",
"reset-admin": "node reset-admin.js",
"typecheck": "tsc --noEmit",
"typecheck:tests": "tsc -p tsconfig.tests.json --noEmit",
"gen:plugin-facts": "node --import tsx scripts/gen-plugin-facts.ts",
"check:plugin-facts": "node --import tsx scripts/gen-plugin-facts.ts --check",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"format:check": "prettier --check \"src/**/*.ts\" \"test/**/*.ts\"",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
@@ -22,11 +25,17 @@
"test:coverage": "vitest run --coverage"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
"@aws-lite/client": "^0.23.7",
"@aws-lite/s3": "^0.2.7",
"@modelcontextprotocol/sdk": "^1.30.0",
"@nestjs/common": "^11.1.24",
"@nestjs/config": "^4.0.4",
"@nestjs/core": "^11.1.24",
"@nestjs/platform-express": "^11.1.24",
"@nestjs/platform-ws": "^11.1.29",
"@nestjs/schedule": "^6.1.3",
"@nestjs/swagger": "^11.4.5",
"@nestjs/websockets": "^11.1.29",
"@simplewebauthn/server": "^13.1.2",
"@trek/shared": "*",
"archiver": "^6.0.1",
@@ -35,13 +44,16 @@
"compression": "^1.8.0",
"cookie-parser": "^1.4.7",
"cors": "^2.8.5",
"cron": "^4.4.0",
"dotenv": "^16.4.1",
"exifr": "7.1.3",
"express": "^4.18.3",
"fast-xml-parser": "^5.5.10",
"helmet": "^8.1.0",
"jimp": "^1.6.1",
"json5": "^2.2.3",
"jsonwebtoken": "^9.0.2",
"node-cron": "^4.2.1",
"nestjs-zod": "^5.5.0",
"nodemailer": "^9.0.1",
"otplib": "^12.0.1",
"pdf-parse": "^2.4.5",
@@ -53,7 +65,7 @@
"tsx": "^4.21.0",
"typescript": "^6.0.2",
"tz-lookup": "^6.1.25",
"undici": "^7.0.0",
"undici": "^7.29.0",
"unzipper": "^0.12.3",
"uuid": "^14.0.0",
"ws": "^8.21.0",
@@ -70,6 +82,7 @@
"file-type": "^21.3.4"
},
"devDependencies": {
"@aws-lite/s3-types": "^0.2.8",
"@eslint/js": "^10.0.1",
"@nestjs/testing": "^11.1.24",
"@swc/core": "^1.15.40",
@@ -84,7 +97,6 @@
"@types/jsonwebtoken": "^9.0.10",
"@types/multer": "^2.1.0",
"@types/node": "^25.5.0",
"@types/node-cron": "^3.0.11",
"@types/nodemailer": "^8.0.1",
"@types/qrcode": "^1.5.5",
"@types/semver": "^7.7.1",
+30 -1
View File
@@ -7,7 +7,8 @@
*
* Defaults to admin@trek.local with a generated password (printed below). The
* account is flagged must_change_password, so you are prompted to set a new one
* on first login. Honours TREK_DB_FILE the same way the server does.
* on first login. Honours TREK_DB_FILE, TREK_DB_JOURNAL_MODE and
* TREK_DB_SYNCHRONOUS the same way the server does.
*/
const path = require('path');
const crypto = require('crypto');
@@ -21,8 +22,36 @@ const email = process.env.RESET_ADMIN_EMAIL || 'admin@trek.local';
const password = process.env.RESET_ADMIN_PASSWORD || crypto.randomBytes(12).toString('base64url');
const generated = !process.env.RESET_ADMIN_PASSWORD;
// journal_mode is stored in the database file header, not per connection, so
// opening the file here decides the mode for the server too. Plain JS outside
// the Nest context can't reach src/app-config, hence the direct read — the
// defaults must match parsers.resolveDurability() (WAL + NORMAL, FULL once a
// rollback journal is in play). Run this via `docker exec` and the container's
// environment applies, same as for the server.
const journalModes = ['DELETE', 'TRUNCATE', 'PERSIST', 'MEMORY', 'WAL', 'OFF'];
const syncLevels = ['OFF', 'NORMAL', 'FULL', 'EXTRA'];
const wantedJournal = (process.env.TREK_DB_JOURNAL_MODE || '').trim().toUpperCase();
const journalMode = journalModes.includes(wantedJournal) ? wantedJournal : 'WAL';
if (wantedJournal && journalMode !== wantedJournal) {
console.warn(`TREK_DB_JOURNAL_MODE="${process.env.TREK_DB_JOURNAL_MODE}" is not a SQLite journal mode — using ${journalMode}.`);
}
const wantedSync = (process.env.TREK_DB_SYNCHRONOUS || '').trim().toUpperCase();
const defaultSync = journalMode === 'WAL' ? 'NORMAL' : 'FULL';
const synchronous = syncLevels.includes(wantedSync) ? wantedSync : defaultSync;
if (wantedSync && synchronous !== wantedSync) {
console.warn(`TREK_DB_SYNCHRONOUS="${process.env.TREK_DB_SYNCHRONOUS}" is not a SQLite synchronous level — using ${synchronous}.`);
}
const dbPath = process.env.TREK_DB_FILE || path.join(__dirname, 'data/travel.db');
const db = new Database(dbPath);
// Spelled out rather than left to better-sqlite3's default, so switching the
// journal mode below waits for a busy server instead of failing on the spot.
// Five seconds, same as src/db/database.ts.
db.exec('PRAGMA busy_timeout = 5000');
db.exec(`PRAGMA journal_mode = ${journalMode}`);
db.exec(`PRAGMA synchronous = ${synchronous}`);
const hash = bcrypt.hashSync(password, BCRYPT_COST);
const existing = db.prepare('SELECT id FROM users WHERE email = ?').get(email);
+17 -1
View File
@@ -49,6 +49,22 @@ const RETRIES = 3
// what restores the dropped territories (Greenland, Falklands, French Guiana, …).
const A3_TO_A2 = {"ABW":"AW", "AFG":"AF", "AGO":"AO", "AIA":"AI", "ALA":"AX", "ALB":"AL", "AND":"AD", "ARE":"AE", "ARG":"AR", "ARM":"AM", "ASM":"AS", "ATA":"AQ", "ATF":"TF", "ATG":"AG", "AUS":"AU", "AUT":"AT", "AZE":"AZ", "BDI":"BI", "BEL":"BE", "BEN":"BJ", "BES":"BQ", "BFA":"BF", "BGD":"BD", "BGR":"BG", "BHR":"BH", "BHS":"BS", "BIH":"BA", "BLM":"BL", "BLR":"BY", "BLZ":"BZ", "BMU":"BM", "BOL":"BO", "BRA":"BR", "BRB":"BB", "BRN":"BN", "BTN":"BT", "BVT":"BV", "BWA":"BW", "CAF":"CF", "CAN":"CA", "CCK":"CC", "CHE":"CH", "CHL":"CL", "CHN":"CN", "CIV":"CI", "CMR":"CM", "COD":"CD", "COG":"CG", "COK":"CK", "COL":"CO", "COM":"KM", "CPV":"CV", "CRI":"CR", "CUB":"CU", "CUW":"CW", "CXR":"CX", "CYM":"KY", "CYP":"CY", "CZE":"CZ", "DEU":"DE", "DJI":"DJ", "DMA":"DM", "DNK":"DK", "DOM":"DO", "DZA":"DZ", "ECU":"EC", "EGY":"EG", "ERI":"ER", "ESH":"EH", "ESP":"ES", "EST":"EE", "ETH":"ET", "FIN":"FI", "FJI":"FJ", "FLK":"FK", "FRA":"FR", "FRO":"FO", "FSM":"FM", "GAB":"GA", "GBR":"GB", "GEO":"GE", "GGY":"GG", "GHA":"GH", "GIB":"GI", "GIN":"GN", "GLP":"GP", "GMB":"GM", "GNB":"GW", "GNQ":"GQ", "GRC":"GR", "GRD":"GD", "GRL":"GL", "GTM":"GT", "GUF":"GF", "GUM":"GU", "GUY":"GY", "HKG":"HK", "HMD":"HM", "HND":"HN", "HRV":"HR", "HTI":"HT", "HUN":"HU", "IDN":"ID", "IMN":"IM", "IND":"IN", "IOT":"IO", "IRL":"IE", "IRN":"IR", "IRQ":"IQ", "ISL":"IS", "ISR":"IL", "ITA":"IT", "JAM":"JM", "JEY":"JE", "JOR":"JO", "JPN":"JP", "KAZ":"KZ", "KEN":"KE", "KGZ":"KG", "KHM":"KH", "KIR":"KI", "KNA":"KN", "KOR":"KR", "KWT":"KW", "LAO":"LA", "LBN":"LB", "LBR":"LR", "LBY":"LY", "LCA":"LC", "LIE":"LI", "LKA":"LK", "LSO":"LS", "LTU":"LT", "LUX":"LU", "LVA":"LV", "MAC":"MO", "MAF":"MF", "MAR":"MA", "MCO":"MC", "MDA":"MD", "MDG":"MG", "MDV":"MV", "MEX":"MX", "MHL":"MH", "MKD":"MK", "MLI":"ML", "MLT":"MT", "MMR":"MM", "MNE":"ME", "MNG":"MN", "MNP":"MP", "MOZ":"MZ", "MRT":"MR", "MSR":"MS", "MTQ":"MQ", "MUS":"MU", "MWI":"MW", "MYS":"MY", "MYT":"YT", "NAM":"NA", "NCL":"NC", "NER":"NE", "NFK":"NF", "NGA":"NG", "NIC":"NI", "NIU":"NU", "NLD":"NL", "NOR":"NO", "NPL":"NP", "NRU":"NR", "NZL":"NZ", "OMN":"OM", "PAK":"PK", "PAN":"PA", "PCN":"PN", "PER":"PE", "PHL":"PH", "PLW":"PW", "PNG":"PG", "POL":"PL", "PRI":"PR", "PRK":"KP", "PRT":"PT", "PRY":"PY", "PSE":"PS", "PYF":"PF", "QAT":"QA", "REU":"RE", "ROU":"RO", "RUS":"RU", "RWA":"RW", "SAU":"SA", "SDN":"SD", "SEN":"SN", "SGP":"SG", "SGS":"GS", "SHN":"SH", "SJM":"SJ", "SLB":"SB", "SLE":"SL", "SLV":"SV", "SMR":"SM", "SOM":"SO", "SPM":"PM", "SRB":"RS", "SSD":"SS", "STP":"ST", "SUR":"SR", "SVK":"SK", "SVN":"SI", "SWE":"SE", "SWZ":"SZ", "SXM":"SX", "SYC":"SC", "SYR":"SY", "TCA":"TC", "TCD":"TD", "TGO":"TG", "THA":"TH", "TJK":"TJ", "TKL":"TK", "TKM":"TM", "TLS":"TL", "TON":"TO", "TTO":"TT", "TUN":"TN", "TUR":"TR", "TUV":"TV", "TWN":"TW", "TZA":"TZ", "UGA":"UG", "UKR":"UA", "UMI":"UM", "URY":"UY", "USA":"US", "UZB":"UZ", "VAT":"VA", "VCT":"VC", "VEN":"VE", "VGB":"VG", "VIR":"VI", "VNM":"VN", "VUT":"VU", "WLF":"WF", "WSM":"WS", "XKX":"XK", "YEM":"YE", "ZAF":"ZA", "ZMB":"ZM", "ZWE":"ZW"}
/**
* Countries whose sub-national level is not the one everybody else's ADM1 is.
*
* geoBoundaries' GBR ADM1 is the four constituent countries — England, Scotland,
* Wales, Northern Ireland — so an atlas built from it has no polygon below
* "England", and a London borough marked as visited has nothing to light up
* (#1974). Its ADM2 is the 216 counties and unitary authorities, which is the
* granularity the rest of the world gets from ADM1 and the granularity the
* pre-3.1.0 Natural Earth layer had.
*
* Deliberately a short, hand-picked list. ADM2 everywhere would multiply the
* bundle several times over for no gain: for most countries ADM1 already is the
* level people think in.
*/
const ADM_LEVEL = { GBR: 'ADM2' }
const COUNTRIES = Object.keys(A3_TO_A2) // every ISO alpha-3 code (ADM1 fetch list)
// Cache raw downloads so re-runs (e.g. to tune simplification) don't re-fetch ~360 files.
@@ -216,7 +232,7 @@ async function main() {
// ADM1 (sub-national regions) — per-country gbOpen (carries ISO 3166-2 `shapeISO`).
console.log('[atlas-geo] downloading ADM1 (regions)…')
const adm1Raw = await pool(COUNTRIES, a3 => fetchGeo(MEDIA(a3, 'ADM1')))
const adm1Raw = await pool(COUNTRIES, a3 => fetchGeo(MEDIA(a3, ADM_LEVEL[a3] || 'ADM1')))
const adm1Features = []
let withCodes = 0
COUNTRIES.forEach((a3, idx) => {
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env node
/**
* Prints the per-domain `thresholds` block for vitest.config.ts from the last
* coverage run, at each domain's measured value minus one point of slack.
*
* npm run test:coverage # writes coverage/coverage-summary.json
* node scripts/coverage-thresholds.mjs
*
* The gate is a RATCHET: raise an entry when you improve a domain, never lower one
* to make a build pass. Use this when you have genuinely raised coverage and want the
* new floor written down, not to re-baseline a regression away.
*
* It reads coverage-summary.json rather than the text reporter on purpose. The text
* reporter prints one row per DIRECTORY, so a domain with subdirectories (plugins,
* memories, auth) reads several points higher there than it actually is, and a
* threshold copied off it would be wrong in the loose direction.
*/
import fs from 'node:fs';
import path from 'node:path';
const summaryPath = path.join(process.cwd(), 'coverage', 'coverage-summary.json');
if (!fs.existsSync(summaryPath)) {
console.error(`no ${summaryPath} — run "npm run test:coverage" first`);
process.exit(1);
}
const METRICS = [
['statements', 'statements'],
['branches', 'branches'],
['functions', 'functions'],
['lines', 'lines'],
];
const summary = JSON.parse(fs.readFileSync(summaryPath, 'utf8'));
const domains = new Map();
for (const [file, entry] of Object.entries(summary)) {
if (file === 'total') continue;
const match = file.split('\\').join('/').match(/\/src\/nest\/([a-z0-9-]+)\//);
if (!match) continue;
const totals = domains.get(match[1]) ?? new Map(METRICS.map(([k]) => [k, { covered: 0, total: 0 }]));
for (const [key, metric] of METRICS) {
totals.get(key).covered += entry[metric].covered;
totals.get(key).total += entry[metric].total;
}
domains.set(match[1], totals);
}
// A domain with no branches at all reads as 100%, which is the right floor for it.
const floorOf = ({ covered, total }) => (total === 0 ? 100 : Math.max(0, Math.floor((100 * covered) / total) - 1));
for (const domain of [...domains.keys()].sort()) {
const totals = domains.get(domain);
const parts = METRICS.map(([key]) => `${key}: ${floorOf(totals.get(key))}`).join(', ');
console.log(` 'src/nest/${domain}/**/*.ts': { ${parts} },`);
}
+109
View File
@@ -0,0 +1,109 @@
/**
* Turn hand-built spreads into auto-layout templates.
*
* Reads the book from a journey and writes the spreads out as data: every
* measurement divided by the page it was drawn on, so the same template lays
* out on an A4 landscape book as it does on the 210mm square it was designed
* for. Run from server/, output goes to the client.
*/
const Database = require('better-sqlite3')
const fs = require('fs')
const JOURNEY = Number(process.argv[2] || 7)
const OUT = process.argv[3] || '../client/src/components/Studio/bookTemplates.data.ts'
const db = new Database('data/travel.db', { readonly: true })
const row = db.prepare('SELECT document FROM journey_books WHERE journey_id = ?').get(JOURNEY)
db.close()
if (!row) throw new Error(`no book on journey ${JOURNEY}`)
/*
* Through the contract on the way in, so a template carries every field the
* document has — including any the schema gained since the spread was drawn.
* Without it a template written today is missing tomorrow's defaults and does
* not typecheck as a BookElement.
*/
const { normalizeBookDocument } = require('@trek/shared')
const doc = normalizeBookDocument(JSON.parse(row.document))
const PW = doc.page.pageWidth
const PH = doc.page.pageHeight
const r4 = n => Math.round(n * 10000) / 10000
/** A frame as fractions of one page's width and of the page height. */
function relFrame(f) {
return { x: r4(f.x / PW), y: r4(f.y / PH), w: r4(f.w / PW), h: r4(f.h / PH) }
}
/** Type size as a fraction of the page height, so it scales with the sheet. */
const relSize = n => r4(n / PH)
function element(e) {
// The id travels with the template and is replaced when it is applied —
// dropping it here would leave the element off the BookElement union.
const out = { ...e, frame: relFrame(e.frame) }
if (typeof out.size === 'number') out.size = relSize(out.size)
if (typeof out.radius === 'number') out.radius = r4(out.radius / PW)
if (typeof out.strokeWidth === 'number') out.strokeWidth = r4(out.strokeWidth / PW)
return out
}
const spreads = doc.spreads
.map((s, i) => ({ index: i, role: s.role, background: s.background, elements: s.elements.map(element) }))
.filter(s => s.role === 'inner')
const body = spreads.map((s, i) => ` {
id: 'ref-${i + 1}',
background: ${JSON.stringify(s.background)},
elements: ${JSON.stringify(s.elements, null, 6).replace(/\n/g, '\n ')},
},`).join('\n')
const file = `import type { BookElement } from '@trek/shared'
/**
* The spread templates, as data.
*
* ── Where these come from ────────────────────────────────────────────────
*
* Not from this file's author. They were built by hand in Studio and read back
* out of the document — which is the point: what a page should look like is a
* matter of taste, and taste is not something a layout function arrives at by
* reasoning. The editor is the design tool, and this is its output.
*
* To add one: build the spread in Studio, then run
*
* node scripts/extract-templates.cjs <journeyId>
*
* from server/ and commit what it writes here.
*
* ── Why the numbers are fractions ────────────────────────────────────────
*
* Every frame is divided by the page it was drawn on — x and w by one page's
* width, y and h by its height — and type sizes by the page height. A template
* built on a 210mm square therefore lays out on an A4 landscape book without
* being redrawn, which it would otherwise have to be for every trim size the
* picker offers.
*
* ── What gets filled in ──────────────────────────────────────────────────
*
* Elements carrying a \`binding\` take their text from the entry; empty photo
* frames take its photographs in order; the day, coordinate and country marks
* take what the entry knows about its stop. Everything else — the panels, the
* rules, the shapes that run off the page — is the design, and is kept as it
* was drawn.
*/
export interface SpreadTemplate {
id: string
background: string | null
/** Frames and sizes are fractions — see the note above. */
elements: BookElement[]
}
export const SPREAD_TEMPLATES: SpreadTemplate[] = [
${body}
]
`
fs.writeFileSync(OUT, file)
console.log(`wrote ${spreads.length} templates to ${OUT}`)
+159
View File
@@ -0,0 +1,159 @@
/**
* Regenerates every derived copy of the plugin permission facts from the single source,
* server/src/nest/plugins/protocol/envelope.ts.
*
* node --import tsx server/scripts/gen-plugin-facts.ts # write
* node --import tsx server/scripts/gen-plugin-facts.ts --check # exit 1 on drift
*
* It *imports* envelope.ts rather than scraping it. The guard it replaces
* (plugin-sdk/test/permissions-parity.test.ts) pulled the block out with a regex, which
* goes quietly null the moment someone reformats a closing brace — and that test only ran
* from prepublishOnly, so the failure would have surfaced as a broken npm release.
*
* The generated files are CHECKED IN: publish-plugin-sdk runs inside a standalone
* plugin-sdk/ checkout with no server present, so a build-time artefact would ship an SDK
* with an empty permission list.
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import {
HOOK_PERMISSION, KNOWN_METHODS, KNOWN_PERMISSIONS, METHOD_PERMISSION,
EVENTS_PERMISSION, JOBS_PERMISSION, USER_DATA_PERMISSION, HTTP_OUTBOUND_PREFIX,
} from '../src/nest/plugins/protocol/envelope';
import { SNAPSHOT_GRANT, ENTITY_ID_KEYS } from '../src/plugin-event-sink';
const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
const HEADER = [
'// GENERATED — do not edit by hand.',
'// Source: server/src/nest/plugins/protocol/envelope.ts + server/src/plugin-event-sink.ts',
'// Regenerate: node --import tsx server/scripts/gen-plugin-facts.ts',
'',
].join('\n');
const list = (xs: readonly string[]) => xs.map((x) => ` '${x}',`).join('\n');
const pairs = (o: Readonly<Record<string, string>>) =>
Object.entries(o).map(([k, v]) => ` ${/^[A-Za-z_$][\w$]*$/.test(k) ? k : `'${k}'`}: '${v}',`).join('\n');
/**
* Types here are deliberately WIDE — Readonly<Record<string, string>> and string[] —
* matching exactly what plugin-sdk published before this file existed. An `as const`
* literal would be TS7053 under plugin-sdk/tsconfig.json's "strict": true, where
* grantGaps indexes HOOK_PERMISSION[key] with a plain string, and it would be a
* source-breaking type change for any plugin author doing a dynamic lookup. Strictness
* belongs on the host side, where the data source lives.
*/
const EVENT_FAMILIES = [...new Set([...Object.keys(ENTITY_ID_KEYS), ...Object.keys(SNAPSHOT_GRANT)])].sort();
const SDK_FACTS = `${HEADER}
export const HOOK_PERMISSION: Readonly<Record<string, string>> = {
${pairs(HOOK_PERMISSION)}
};
export const KNOWN_PERMISSIONS: string[] = [
${list(KNOWN_PERMISSIONS)}
];
export const METHOD_PERMISSION: Readonly<Record<string, string>> = {
${pairs(METHOD_PERMISSION)}
};
export const KNOWN_METHODS: string[] = [
${list(KNOWN_METHODS)}
];
export const USER_DATA_PERMISSION = '${USER_DATA_PERMISSION}';
export const EVENTS_PERMISSION = '${EVENTS_PERMISSION}';
export const JOBS_PERMISSION = '${JOBS_PERMISSION}';
export const HTTP_OUTBOUND_PREFIX = '${HTTP_OUTBOUND_PREFIX}';
/**
* Core-event catalog. Delivery names are the WebSocket broadcast names,
* \`<family>:<verb>\` (e.g. \`place:created\`). A subscribed plugin receives
* \`{event, tripId, entity?, entityId?, snapshot?}\`; \`snapshot\` is delivered only
* when the plugin also holds EVENT_SNAPSHOT_GRANT[family]. Delete/reorder/bulk
* events carry no snapshot.
*/
export const EVENT_FAMILIES: readonly string[] = [
${list(EVENT_FAMILIES)}
];
export const EVENT_SNAPSHOT_GRANT: Readonly<Record<string, string>> = {
${pairs(SNAPSHOT_GRANT)}
};
`;
const SHARED_FACTS = `${HEADER}
/** Widened on purpose so client callers can .includes() with a plain string. */
export const PLUGIN_PERMISSIONS: readonly string[] = [
${list(KNOWN_PERMISSIONS)}
];
export const PLUGIN_HOOK_PERMISSION: Readonly<Record<string, string>> = {
${pairs(HOOK_PERMISSION)}
};
`;
const OUTPUTS: Array<[string, string]> = [
['plugin-sdk/src/generated/host-facts.ts', SDK_FACTS],
['shared/src/plugin-permissions.ts', SHARED_FACTS],
];
/**
* Coverage assertions the type system cannot make, because the targets are not TypeScript
* unions. Both failure modes are silent today: a new permission reaches the consent screen
* as a raw code with no translation, and `trek-plugin permissions` prints it with no hint.
*/
function coverageProblems(): string[] {
const problems: string[] = [];
// Match the whole quoted key, not a prefix of it. `includes('plugins.perm.db:own')`
// also matches 'plugins.perm.db:ownX', and several permissions are prefixes of others
// ('db:read:files' vs 'db:read:files:content'), so a substring test passes on exactly
// the drift it is supposed to catch.
const enAdmin = fs.readFileSync(path.join(REPO, 'shared/src/i18n/en/admin.ts'), 'utf8');
const missingI18n = KNOWN_PERMISSIONS.filter((p) => !enAdmin.includes(`'admin.plugins.perm.${p}':`));
if (missingI18n.length) {
problems.push(
`shared/src/i18n/en/admin.ts is missing 'admin.plugins.perm.<permission>' for: ${missingI18n.join(', ')}`,
);
}
const ui = fs.readFileSync(path.join(REPO, 'plugin-sdk/src/cli/ui.ts'), 'utf8');
const missingHint = KNOWN_PERMISSIONS.filter((p) => !ui.includes(`'${p}'`));
if (missingHint.length) {
problems.push(
`plugin-sdk/src/cli/ui.ts PERMISSION_FAMILIES does not cover: ${missingHint.join(', ')}`,
);
}
return problems;
}
const check = process.argv.includes('--check');
let failed = false;
for (const [rel, content] of OUTPUTS) {
const abs = path.join(REPO, rel);
const current = fs.existsSync(abs) ? fs.readFileSync(abs, 'utf8') : null;
if (current === content) continue;
if (check) {
console.error(`DRIFT: ${rel} does not match envelope.ts.`);
console.error(' Run: node --import tsx server/scripts/gen-plugin-facts.ts');
failed = true;
} else {
fs.mkdirSync(path.dirname(abs), { recursive: true });
fs.writeFileSync(abs, content);
console.log(`wrote ${rel}`);
}
}
for (const problem of coverageProblems()) {
console.error(`COVERAGE: ${problem}`);
failed = true;
}
if (failed) process.exit(1);
if (check) console.log('plugin facts are in sync with envelope.ts');
+239 -7
View File
@@ -181,11 +181,47 @@ async function main() {
// Backup
const backupPath = `${dbPath}.backup-${Date.now()}`;
fs.copyFileSync(dbPath, backupPath);
console.log(`\nBackup created: ${backupPath}`);
const db = new Database(dbPath);
db.pragma('journal_mode = WAL');
db.pragma('busy_timeout = 5000');
// The rollback copy has to be a consistent snapshot, not a plain file copy:
// this script is documented as running against a live server, so in WAL mode
// the committed tail sits in the -wal sidecar a copy would leave behind.
// VACUUM INTO snapshots even while the server writes; the checkpoint plus
// copy is only the fallback for when it cannot (disk, lock).
try {
db.exec(`VACUUM INTO '${backupPath.replace(/'/g, "''")}'`);
} catch {
db.exec('PRAGMA wal_checkpoint(TRUNCATE)');
fs.copyFileSync(dbPath, backupPath);
}
console.log(`\nBackup created: ${backupPath}`);
// journal_mode lives in the file header, so hardcoding WAL here would quietly
// undo a deliberate DELETE/TRUNCATE setup (network storage) on the first key
// rotation. This script ships without src/ in the image and cannot import
// src/app-config, so it reads the same variables directly — keep the defaults
// in step with parsers.resolveDurability().
const journalModes = ['DELETE', 'TRUNCATE', 'PERSIST', 'MEMORY', 'WAL', 'OFF'];
const syncLevels = ['OFF', 'NORMAL', 'FULL', 'EXTRA'];
const wantedJournal = (process.env.TREK_DB_JOURNAL_MODE ?? '').trim().toUpperCase();
const journalMode = journalModes.includes(wantedJournal) ? wantedJournal : 'WAL';
if (wantedJournal && journalMode !== wantedJournal) {
console.warn(`TREK_DB_JOURNAL_MODE="${process.env.TREK_DB_JOURNAL_MODE}" is not a SQLite journal mode — using ${journalMode}.`);
}
const wantedSync = (process.env.TREK_DB_SYNCHRONOUS ?? '').trim().toUpperCase();
const defaultSync = journalMode === 'WAL' ? 'NORMAL' : 'FULL';
const synchronous = syncLevels.includes(wantedSync) ? wantedSync : defaultSync;
if (wantedSync && synchronous !== wantedSync) {
console.warn(`TREK_DB_SYNCHRONOUS="${process.env.TREK_DB_SYNCHRONOUS}" is not a SQLite synchronous level — using ${synchronous}.`);
}
db.pragma(`journal_mode = ${journalMode}`);
db.pragma(`synchronous = ${synchronous}`);
console.log(`Journal mode: ${db.pragma('journal_mode', { simple: true })}\n`);
const result: MigrationResult = { migrated: 0, alreadyMigrated: 0, skipped: 0, errors: [] };
@@ -237,8 +273,24 @@ async function main() {
}
db.transaction(() => {
// --- app_settings: oidc_client_secret, smtp_pass, admin_webhook_url, admin_ntfy_token ---
for (const key of ['oidc_client_secret', 'smtp_pass', 'admin_webhook_url', 'admin_ntfy_token']) {
// --- app_settings: oidc_client_secret, smtp_pass, admin_webhook_url, admin_ntfy_token,
// plus the instance-wide provider keys (#1939) ---
//
// The last two mirror INSTANCE_API_KEY_NAMES in
// src/nest/settings/instance-api-keys.ts. Spelled out rather than imported,
// because that module pulls in DatabaseService and this script deliberately
// stays independent of src/ (see the crypto note above). Miss one and a
// rotation leaves it encrypted under the old key, which reads back as "no
// key" and silently drops the install to OpenStreetMap, so the copy is
// pinned by tests/unit/db/migrate-encryption-parity.test.ts.
for (const key of [
'oidc_client_secret',
'smtp_pass',
'admin_webhook_url',
'admin_ntfy_token',
'maps_api_key',
'unsplash_api_key',
]) {
const row = db.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as { value: string } | undefined;
if (!row?.value) continue;
const newVal = migrateApiKeyValue(row.value, `app_settings.${key}`);
@@ -248,7 +300,25 @@ async function main() {
}
// --- users: api key columns + synology credentials ---
const apiKeyColumns = ['maps_api_key', 'openweather_api_key', 'immich_api_key', 'synology_password', 'synology_sid', 'synology_did'];
// unsplash_api_key was missing here for as long as the column has existed. It
// matters now that the resolver reads it as the per-user fallback (#1939): left
// out of a rotation it stays encrypted under the old key and reads back as unset.
// airtrail_api_key arrived with a later migration, so an older database may
// not have the column at all — filter the list against the real table rather
// than letting one missing column throw the whole rotation.
const userColumns = new Set(
(db.prepare("SELECT name FROM pragma_table_info('users')").all() as { name: string }[]).map((r) => r.name),
);
const apiKeyColumns = [
'maps_api_key',
'unsplash_api_key',
'openweather_api_key',
'immich_api_key',
'synology_password',
'synology_sid',
'synology_did',
'airtrail_api_key',
].filter((c) => userColumns.has(c));
const users = db.prepare('SELECT id FROM users').all() as { id: number }[];
for (const user of users) {
@@ -271,8 +341,70 @@ async function main() {
}
}
}
// --- app_settings: storage.backends ---
// Storage backend secrets live encrypted INSIDE the storage.backends JSON
// array (BACKENDS_KEY in src/nest/storage/storage-registry.service.ts is
// its own app_settings row — 'storage.categories' is a sibling row with no
// secrets), on the fields the shared type registry marks `secret` (only
// options.secretAccessKey for s3 today; src/nest/storage/storage-secrets.ts
// encrypts it with the same enc:v1: scheme as the api-key columns above).
// This script can't import storageSecretFields from @trek/shared (kept
// independent of the app, see the header note), so the field list per
// backend type is pinned here. Miss one and that backend's secret stays
// encrypted under the old key after rotation, then fails to decrypt on the
// next read (StorageBackendError) — pinned by
// tests/unit/db/migrate-encryption-parity.test.ts.
const STORAGE_BACKEND_SECRET_FIELDS: Record<string, readonly string[]> = {
s3: ['secretAccessKey'],
};
{
const row = db.prepare("SELECT value FROM app_settings WHERE key = 'storage.backends'").get() as
| { value: string }
| undefined;
if (row?.value) {
let backends: unknown;
try {
backends = JSON.parse(row.value);
} catch {
result.errors.push('app_settings.storage.backends: invalid JSON — skipping');
backends = undefined;
}
if (backends !== undefined) {
if (Array.isArray(backends)) {
let changed = false;
for (const backend of backends as Record<string, unknown>[]) {
if (!backend || typeof backend !== 'object') continue;
const type = typeof backend.type === 'string' ? backend.type : undefined;
const fields = type ? STORAGE_BACKEND_SECRET_FIELDS[type] : undefined;
if (!fields || fields.length === 0) continue;
const options = backend.options;
if (!options || typeof options !== 'object') continue;
const name = typeof backend.name === 'string' ? backend.name : '?';
for (const field of fields) {
const raw = (options as Record<string, unknown>)[field];
if (typeof raw !== 'string' || !raw) continue;
const newVal = migrateApiKeyValue(raw, `app_settings.storage.backends[${name}].${field}`);
if (newVal !== null) {
(options as Record<string, unknown>)[field] = newVal;
changed = true;
}
}
}
if (changed) {
db.prepare("UPDATE app_settings SET value = ? WHERE key = 'storage.backends'").run(
JSON.stringify(backends),
);
}
} else {
result.errors.push('app_settings.storage.backends: not an array — skipping');
}
}
}
}
// --- settings: per-user encrypted keys ---
const encryptedSettingKeys = ['webhook_url', 'ntfy_token', 'mapbox_access_token'];
const encryptedSettingKeys = ['webhook_url', 'ntfy_token', 'mapbox_access_token', 'carto_api_key', 'llm_api_key'];
const settingRows = db.prepare(
`SELECT user_id, key, value FROM settings WHERE key IN (${encryptedSettingKeys.map(() => '?').join(', ')})`
).all(...encryptedSettingKeys) as { user_id: number; key: string; value: string }[];
@@ -285,6 +417,106 @@ async function main() {
}
}
// --- plugins: OAuth tokens and secret settings fields ---
// The plugin host encrypts with the same enc:v1: scheme as everything above:
// plugin-oauth.service stores both tokens encrypted, and plugins.service
// encrypts every settings field the manifest marked secret (instance scope in
// plugins.config, user scope in plugin_user_config.config). Left out of a
// rotation, a connected plugin reads back as "not connected" and a secret
// setting as unset, with nothing in the log to say why. Every table here
// arrived with a later migration, so each block checks that it exists.
const tableExists = (name: string): boolean =>
!!db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name);
if (tableExists('plugin_oauth_tokens')) {
const tokenRows = db
.prepare('SELECT plugin_id, user_id, access_token, refresh_token FROM plugin_oauth_tokens')
.all() as { plugin_id: string; user_id: number; access_token: string | null; refresh_token: string | null }[];
for (const row of tokenRows) {
for (const col of ['access_token', 'refresh_token'] as const) {
const raw = row[col];
if (!raw) continue;
const newVal = migrateApiKeyValue(raw, `plugin_oauth_tokens[${row.plugin_id},${row.user_id}].${col}`);
if (newVal !== null) {
db.prepare(`UPDATE plugin_oauth_tokens SET ${col} = ? WHERE plugin_id = ? AND user_id = ?`).run(
newVal,
row.plugin_id,
row.user_id,
);
}
}
}
}
if (tableExists('plugin_settings_fields')) {
// Which keys are secret is per plugin and per scope, and it lives in the DB
// rather than in this script, so nothing has to be pinned by hand here.
const secretFields = db
.prepare("SELECT plugin_id, field_key, scope FROM plugin_settings_fields WHERE secret = 1")
.all() as { plugin_id: string; field_key: string; scope: string | null }[];
const secretKeysFor = (pluginId: string, scope: string): string[] =>
secretFields
.filter((f) => f.plugin_id === pluginId && (f.scope ?? 'instance') === scope)
.map((f) => f.field_key);
const migrateConfigJson = (raw: string | null, keys: string[], label: string): string | null => {
if (!raw || keys.length === 0) return null;
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
result.errors.push(`${label}: invalid JSON — skipping`);
return null;
}
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
result.errors.push(`${label}: not an object — skipping`);
return null;
}
const config = parsed as Record<string, unknown>;
let changed = false;
for (const key of keys) {
const value = config[key];
if (typeof value !== 'string' || !value) continue;
const newVal = migrateApiKeyValue(value, `${label}.${key}`);
if (newVal !== null) {
config[key] = newVal;
changed = true;
}
}
return changed ? JSON.stringify(config) : null;
};
if (tableExists('plugins')) {
const pluginRows = db.prepare('SELECT id, config FROM plugins').all() as { id: string; config: string | null }[];
for (const row of pluginRows) {
const next = migrateConfigJson(row.config, secretKeysFor(row.id, 'instance'), `plugins[${row.id}].config`);
if (next !== null) {
db.prepare('UPDATE plugins SET config = ? WHERE id = ?').run(next, row.id);
}
}
}
if (tableExists('plugin_user_config')) {
const userConfigRows = db
.prepare('SELECT plugin_id, user_id, config FROM plugin_user_config')
.all() as { plugin_id: string; user_id: number; config: string | null }[];
for (const row of userConfigRows) {
const next = migrateConfigJson(
row.config,
secretKeysFor(row.plugin_id, 'user'),
`plugin_user_config[${row.plugin_id},${row.user_id}].config`,
);
if (next !== null) {
db.prepare('UPDATE plugin_user_config SET config = ? WHERE plugin_id = ? AND user_id = ?').run(
next,
row.plugin_id,
row.user_id,
);
}
}
}
}
// --- trip_album_links: passphrase ---
const albumLinks = db.prepare('SELECT id, passphrase FROM trip_album_links WHERE passphrase IS NOT NULL').all() as { id: number; passphrase: string }[];
for (const row of albumLinks) {
+117
View File
@@ -0,0 +1,117 @@
# app-config — TREK's environment configuration layer
One validated source of truth for every environment variable the server reads.
Framework-free (no Nest imports), so it is consumable from anywhere: Nest DI
classes, the legacy free-function services, mcp, websocket, scheduler, db and
the pre-init Express middleware.
```
env.schema.ts Zod catalog of the whole env surface; fail-fast at boot
derive.ts pure (raw env) → typed namespace functions, exact per-site coercions
env.ts readEnv() live accessor + validateEnvAtBoot()
app-url.ts getAppUrl()/getMcpSafeUrl() instance base-URL resolution
boot-validate.ts side-effect import used by index.ts (validates before other modules load)
parsers.ts shared coercion helpers (boolTrueLoose, numberOr, csvList, …)
```
The Nest binding lives in `src/nest/app-config/` (`AppConfigModule`, registerAs
tokens, `RuntimeEnvService`) and consumes the SAME derive functions.
## Invariants — read before touching anything here
1. **`readEnv()` is live.** It re-derives from the current `process.env` on
every call, with no caching or memoization, ever. ~60 test files mutate
`process.env` at runtime and depend on the next read observing the change.
2. **Validation runs once, at boot, from the production entrypoint only.**
Never wire the schema into `buildApp()`, `ConfigModule.forRoot({ validate })`
or a request path. Unset/blank variables always pass (defaults apply); only
present-but-malformed values abort startup. The one addition on top of the
schema is `managedPreconditions()` in `env.ts`: cross-field rules that only
apply with `TREK_MANAGED`, for combinations that are individually valid and
together wrong. It is empty without the switch, so a self-hoster never meets
it. Put a rule there only if booting anyway would be a security or data
problem — not to enforce a preference.
3. **Parity is law — with one deliberate exception.** Every derived field pins
the exact coercion of the call site(s) it replaced (`Number(x) || d`
treating `"0"` as unset, per-site defaults for the same variable, …). Do not
"fix" a quirk here; log it as a follow-up instead. The exception: **boolean
switches are unified** through `parseBool` — every boolean-like variable
accepts `true/1/on/yes` and `false/0/off/no` (any casing) and derives to a
real boolean. This intentionally replaces the legacy per-site literals
(`'true'` here, `'1'` there, `'on'` elsewhere); tests that pinned those
narrow literals get updated when their call site migrates.
4. **Env vs DB-setting layering stays at the call site.** For
`process.env.X || getSetting('x')` patterns, this layer supplies only the
env half; the runtime-mutable admin-setting fallback remains inline where it
was.
5. **Never convert a frozen read to a live read or vice versa.** Modules that
captured env in module-top `const`s (mcp, backupService, ssrfGuard, plugin
rate limits, …) keep freeze-at-import timing, merely sourcing the value from
`readEnv()` at module top. Request-time reads stay request-time.
## app-url.ts — instance base-URL resolution (moved 2026-07-28)
`getAppUrl()` (APP_URL → first ALLOWED_ORIGINS entry → `http://localhost:PORT`,
each candidate URL-validated, ALL trailing slashes stripped) and
`getMcpSafeUrl()` (same, sanitized to HTTPS/localhost/127.0.0.1 for the MCP
SDK's issuer check) moved here **verbatim** from `services/notifications.ts`
(audit findings `auth-2`/`notifications-1`/`admin-3`/`mcp-1`). They follow
invariant 1: `readEnv()` per call, live, never cached. The invalid-URL silent
fallthrough and the strip-ALL-slashes quirk (see `parsers.ts`
`stripTrailingSlashes`) are parity-pinned — do not "fix" them here.
## Classification: boot-stable vs runtime-toggled
**Boot-stable** (frozen at app/module creation; snapshot `registerAs`/`ConfigType`
DI in Nest, module-top `readEnv()` consts elsewhere):
PORT, HOST, TRUST_PROXY, SESSION_DURATION(_REMEMBER), MCP_SESSION_TTL,
MCP_MAX_SESSION_PER_USER, MCP_SSE_KEEPALIVE, TREK_PLUGIN_RPC_*/LOG_*/MAX_RSS_MB,
TREK_PLUGIN_REGISTRY_URL, TREK_WIKI_DIR*, TREK_PLACE_PHOTO_DIR, BACKUP_*,
TRANSIT_API_URL, LOG_LEVEL*, ALLOW_INTERNAL_NETWORK*, DEFAULT_LANGUAGE,
TREK_DB_FILE, TREK_DB_JOURNAL_MODE, TREK_DB_SYNCHRONOUS, ENCRYPTION_KEY**.
(* frozen today because the consuming module captures it at import; tests that
override these set them at file top, before the SUT import.)
(** ENCRYPTION_KEY is boot-stable for the cipher key material itself —
`src/config.ts` resolves and freezes it at process start, per the exemption
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,
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).
## Exemptions — raw `process.env` stays
- `src/nest/plugins/runtime/plugin-host-entry.ts` — runs in a scrubbed child
process; must not import this layer.
- `src/nest/plugins/supervisor/plugin-supervisor.ts` child-env whitelist block —
the env there is an IPC channel to the sandbox, not app configuration.
- Dynamic-key reads (`process.env[name]`) in `plugins/host/daily-budget.ts` and
`plugins/host/plugin-audit.ts`.
- `src/config.ts` ENCRYPTION_KEY/JWT_SECRET resolution — key material with file
persistence and runtime rotation, not env config.
- Standalone scripts (`reset-admin.js`, `scripts/*`) and `tests/**`. Note that
`reset-admin.js` and `scripts/migrate-encryption.ts` open the database file
read-write and therefore re-implement `TREK_DB_JOURNAL_MODE` /
`TREK_DB_SYNCHRONOUS` inline (the journal mode lives in the file header, so
they must agree with the server). Neither can import this layer — the image
ships `dist/`, not `src/` — so the defaults in `parsers.resolveDurability()`
and in those two files move together.
The exemption list is enforced by the `no-restricted-syntax` ban on
`process.env` in `eslint.config.mjs` — keep the two lists in sync.
## Follow-up candidates (quirks pinned during the migration, deliberately NOT fixed)
- `numberOr` (`Number(x) || d`) treats `"0"` and negative-invalid values oddly:
`PORT=0` silently becomes 3001, `TREK_PLUGIN_RPC_BURST=-5` stays -5.
- APP_URL trailing-slash stripping differs per site (feeds strips one slash,
notifications strips all).
- `DEMO_ADMIN_EMAIL` defaults differ (demo-seed: admin@trek.app, demo-reset:
admin@nomad.app).
- NODE_ENV comparisons are case-sensitive at some sites (HSTS activation,
platform statics, spa-fallback, authService dev_mode, oidcService
frontendUrl) and case-insensitive at others.
+48
View File
@@ -0,0 +1,48 @@
import { readEnv } from './env';
import { stripTrailingSlashes } from './parsers';
/**
* Instance base-URL resolution: APP_URL → first ALLOWED_ORIGINS entry →
* http://localhost:{PORT}. Moved verbatim from services/notifications.ts
* (2026-07-28, findings auth-2/notifications-1/admin-3/mcp-1) — the resolution
* chain, trailing-slash strip and invalid-URL fallthrough are parity-pinned.
* Live reads: readEnv() per call, never cached.
*/
export function getAppUrl(): string {
const appUrl = readEnv().app.appUrl;
if (appUrl) {
try {
const _ = new URL(appUrl);
return stripTrailingSlashes(appUrl);
} catch (_ignored) {}
}
const origins = readEnv().http.allowedOriginsRaw;
if (origins) {
const first = origins.split(',')[0]?.trim();
if (first) {
try {
const _ = new URL(first);
return stripTrailingSlashes(first);
} catch (_ignored) {}
}
}
const port = readEnv().app.port;
return `http://localhost:${port}`;
}
/** Returns a URL guaranteed to satisfy the MCP SDK's issuer requirements (HTTPS or localhost).
* Falls back to http://localhost:{PORT} when APP_URL/ALLOWED_ORIGINS use a non-HTTPS, non-localhost scheme
* that would cause checkIssuerUrl to throw "Issuer URL must be HTTPS". */
export function getMcpSafeUrl(): string {
const candidate = getAppUrl();
try {
const u = new URL(candidate);
if (u.protocol === 'https:' || u.hostname === 'localhost' || u.hostname === '127.0.0.1') {
return candidate;
}
} catch {
// candidate was somehow invalid — fall through to localhost
}
const port = readEnv().app.port;
return `http://localhost:${port}`;
}
+12
View File
@@ -0,0 +1,12 @@
/**
* Side-effect module: validates the environment the moment it is imported.
*
* index.ts imports this immediately after `import 'dotenv/config'` — as a
* side-effect import (not a function call) so validation runs BEFORE the rest
* of the import graph executes its module-load side effects (config.ts key
* resolution, db/database.ts initDb, ...). A plain call in index.ts's body
* would run after all of those, because imports hoist.
*/
import { validateEnvAtBoot } from './env';
validateEnvAtBoot();
+304
View File
@@ -0,0 +1,304 @@
/**
* Pure per-namespace derive functions: (raw env) → typed config namespace.
*
* Every field pins the EXACT coercion of the call site(s) it replaces — parity
* is law — with ONE deliberate exception: boolean switches are unified through
* parseBool (true/1/on/yes vs false/0/off/no, any casing), because the legacy
* per-site literals ('true' here, '1' there, 'on' elsewhere) were an accident,
* not a contract. Where sites apply different DEFAULTS for the same variable
* (DEMO_ADMIN_EMAIL), only the raw value is exposed and the default stays at
* the call site.
*
* These functions are plain string coercions with NO caching and NO side
* effects: `readEnv()` (env.ts) re-derives from the live process.env on every
* call, which is what keeps the runtime env-mutation semantics the test suite
* depends on. Zod validation runs once at boot (env.schema.ts), never here.
*/
import { SUPPORTED_LANGUAGE_CODES } from '@trek/shared';
import {
csvList,
csvListFiltered,
numberOr,
parseBool,
parseDurationMs,
positiveIntOr,
positiveNumberOr,
resolveDurability,
resolveKeepaliveMs,
resolveSessionTtlMs,
stripTrailingSlashes,
} from './parsers';
export type RawEnv = Record<string, string | undefined>;
export function deriveApp(raw: RawEnv) {
const nodeEnv = raw.NODE_ENV;
return {
/** Raw NODE_ENV — for the case-SENSITIVE sites (`=== 'production'` in globalMiddleware HSTS, platform statics, spa-fallback; `=== 'development'` in authService.dev_mode). */
nodeEnv,
isProduction: nodeEnv?.toLowerCase() === 'production',
isDevelopment: nodeEnv?.toLowerCase() === 'development',
/** Case-sensitive on purpose — db/database.ts picks :memory: only on exactly 'test'. */
isTest: nodeEnv === 'test',
port: numberOr(raw.PORT, 3001),
host: raw.HOST,
/** Raw APP_VERSION — fallbacks differ per site ('0.0.0' vs package.json vs semver-validated); each keeps its own. */
appVersion: raw.APP_VERSION,
/** Raw APP_URL — trailing-slash stripping differs per site (feeds strips one, notifications strips all). */
appUrl: raw.APP_URL,
tz: raw.TZ,
logLevel: raw.LOG_LEVEL,
/** Resolved: lowercased, validated against the supported set, falls back to 'en' (src/config.ts semantics). */
defaultLanguage: resolveDefaultLanguage(raw.DEFAULT_LANGUAGE),
};
}
function resolveDefaultLanguage(raw: string | undefined): string {
const lang = raw?.toLowerCase() || 'en';
// Case-insensitive match resolved to the CANONICAL code (zh-TW, not zh-tw).
// The legacy lowercase-only `includes` could never match zh-TW and silently
// fell back to English for a supported language — deliberate fix.
const canonical = SUPPORTED_LANGUAGE_CODES.find((c) => c.toLowerCase() === lang);
return canonical ?? 'en';
}
export function deriveHttp(raw: RawEnv) {
// env.schema.ts accepts 0 as a valid hop count, so `|| 1` would quietly turn
// "trust nothing" into "trust one hop" and let a forged X-Forwarded-For through.
const trustProxyHops = Number.parseInt(raw.TRUST_PROXY ?? '', 10);
return {
allowedOriginsRaw: raw.ALLOWED_ORIGINS,
/** globalMiddleware CORS variant: trim + drop empty entries. */
corsOrigins: csvListFiltered(raw.ALLOWED_ORIGINS),
/** websocket variant: trim only — an empty entry stays (and can never match an Origin header). */
wsOrigins: csvList(raw.ALLOWED_ORIGINS),
trustProxyRaw: raw.TRUST_PROXY,
trustProxy: Number.isFinite(trustProxyHops) ? trustProxyHops : 1,
forceHttps: parseBool(raw.FORCE_HTTPS) === true,
hstsIncludeSubdomains: parseBool(raw.HSTS_INCLUDE_SUBDOMAINS) === true,
/** COOKIE_SECURE is tri-state: an explicit falsy value disables secure cookies; anything else means auto-detect. */
cookieSecureDisabled: parseBool(raw.COOKIE_SECURE) === false,
apiDocsEnabled: parseBool(raw.TREK_API_DOCS_ENABLED) === true,
};
}
const DEFAULT_SESSION_DURATION = '24h';
const DEFAULT_SESSION_DURATION_REMEMBER = '30d';
const DEFAULT_IDEMPOTENCY_TTL_SECONDS = 30 * 24 * 60 * 60; // 30 days (scheduler.ts)
export function deriveSession(raw: RawEnv) {
const durationRaw = raw.SESSION_DURATION?.trim() || DEFAULT_SESSION_DURATION;
const parsedMs = parseDurationMs(durationRaw);
const rememberRaw = raw.SESSION_DURATION_REMEMBER?.trim() || DEFAULT_SESSION_DURATION_REMEMBER;
const parsedRememberMs = parseDurationMs(rememberRaw);
const durationMs = parsedMs ?? parseDurationMs(DEFAULT_SESSION_DURATION)!;
const rememberMs = parsedRememberMs ?? parseDurationMs(DEFAULT_SESSION_DURATION_REMEMBER)!;
return {
/** Human-readable session length actually in effect (invalid input falls back, matching src/config.ts). */
duration: parsedMs == null ? DEFAULT_SESSION_DURATION : durationRaw,
durationMs,
durationSeconds: Math.floor(durationMs / 1000),
durationRemember: parsedRememberMs == null ? DEFAULT_SESSION_DURATION_REMEMBER : rememberRaw,
durationRememberMs: rememberMs,
durationRememberSeconds: Math.floor(rememberMs / 1000),
idempotencyTtlSeconds: positiveNumberOr(raw.IDEMPOTENCY_TTL_SECONDS, DEFAULT_IDEMPOTENCY_TTL_SECONDS),
};
}
/**
* Whether this instance is centrally administered: somebody other than its
* admin user owns the configuration, the credentials and the upgrade schedule.
*
* Only a boolean, on purpose. It answers "who configures this install", and the
* surfaces that care read it themselves rather than being listed here, so adding
* one never touches this file.
*
* `=== true` so an unset, empty or unparseable value means off. A managed
* install sets it deliberately; nothing should be able to switch it on by
* accident, and a typo must not silently take settings away from an admin.
*/
export function deriveManaged(raw: RawEnv) {
return {
enabled: parseBool(raw.TREK_MANAGED) === true,
};
}
/**
* Where the Places calls go and which credential they carry.
*
* Both unset on a self-hosted install, which is the path the code has always
* taken: the endpoints stay Google's and the key comes from the users table.
* Set them and the calls leave through something the operator runs, with a
* credential no instance admin can read back.
*/
export function deriveMaps(raw: RawEnv) {
return {
placesApiBase: raw.PLACES_API_BASE || undefined,
placesApiKey: raw.PLACES_API_KEY || undefined,
/** Public pk.* token shipped with a managed instance; reaches the browser by design. */
mapboxToken: raw.MAPBOX_ACCESS_TOKEN || undefined,
/** CARTO basemap key; without one the tiles come back watermarked (#2054). Public too. */
cartoKey: raw.CARTO_API_KEY || undefined,
};
}
export function deriveDemo(raw: RawEnv) {
return {
enabled: parseBool(raw.DEMO_MODE) === true,
adminUser: raw.DEMO_ADMIN_USER || 'admin',
/** Raw on purpose: demo-seed defaults to admin@trek.app, demo-reset to admin@nomad.app. */
adminEmailRaw: raw.DEMO_ADMIN_EMAIL,
adminPass: raw.DEMO_ADMIN_PASS || 'admin12345',
/** False means the admin account is being created with the published default. */
adminPassSet: !!raw.DEMO_ADMIN_PASS,
};
}
export function deriveAdminBootstrap(raw: RawEnv) {
return {
email: raw.ADMIN_EMAIL,
password: raw.ADMIN_PASSWORD,
};
}
export function deriveOidc(raw: RawEnv) {
return {
issuer: raw.OIDC_ISSUER,
clientId: raw.OIDC_CLIENT_ID,
clientSecret: raw.OIDC_CLIENT_SECRET,
displayName: raw.OIDC_DISPLAY_NAME,
discoveryUrl: raw.OIDC_DISCOVERY_URL,
scope: raw.OIDC_SCOPE || 'openid email profile',
only: parseBool(raw.OIDC_ONLY) === true,
adminClaim: raw.OIDC_ADMIN_CLAIM || 'groups',
adminValue: raw.OIDC_ADMIN_VALUE,
};
}
export function deriveSmtp(raw: RawEnv) {
return {
host: raw.SMTP_HOST,
port: raw.SMTP_PORT,
user: raw.SMTP_USER,
pass: raw.SMTP_PASS,
from: raw.SMTP_FROM,
skipTlsVerify: parseBool(raw.SMTP_SKIP_TLS_VERIFY) === true,
};
}
export function deriveMcp(raw: RawEnv) {
return {
sessionTtlMs: resolveSessionTtlMs(raw.MCP_SESSION_TTL),
maxSessionsPerUser: positiveIntOr(raw.MCP_MAX_SESSION_PER_USER, 20),
sseKeepaliveMs: resolveKeepaliveMs(raw.MCP_SSE_KEEPALIVE),
rateLimitMax: positiveIntOr(raw.MCP_RATE_LIMIT, 300),
};
}
export function derivePlugins(raw: RawEnv) {
return {
/** 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,
dir: raw.TREK_PLUGINS_DIR,
dataDir: raw.TREK_PLUGINS_DATA_DIR,
/** Permission jail is default-on: only an explicit falsy value turns it off. */
permissionsOff: parseBool(raw.TREK_PLUGIN_PERMISSIONS) === false,
registryUrl:
raw.TREK_PLUGIN_REGISTRY_URL || 'https://raw.githubusercontent.com/liketrek/TREK-Plugins/main/dist/index.json',
/**
* The child process and plugin-sdk keep their literal `=== 'on'` check (they
* are exempt from this layer); the supervisor normalizes this boolean to the
* literal 'on' when building the child's scrubbed env.
*/
allowPrivateEgress: parseBool(raw.TREK_PLUGIN_ALLOW_PRIVATE_EGRESS) === true,
rpcBurst: numberOr(raw.TREK_PLUGIN_RPC_BURST, 60),
rpcPerSec: numberOr(raw.TREK_PLUGIN_RPC_PER_SEC, 20),
rpcInflight: numberOr(raw.TREK_PLUGIN_RPC_INFLIGHT, 16),
logBurst: numberOr(raw.TREK_PLUGIN_LOG_BURST, 50),
logPerSec: numberOr(raw.TREK_PLUGIN_LOG_PER_SEC, 10),
maxRssMb: numberOr(raw.TREK_PLUGIN_MAX_RSS_MB, 300),
};
}
export function deriveWebauthn(raw: RawEnv) {
return {
rpId: raw.WEBAUTHN_RP_ID,
origins: raw.WEBAUTHN_ORIGINS,
};
}
export function deriveIntegrations(raw: RawEnv) {
return {
unsplashAccessKey: raw.UNSPLASH_ACCESS_KEY?.trim(),
transitApiBase: stripTrailingSlashes(raw.TRANSIT_API_URL || 'https://api.transitous.org'),
overpassUrl: raw.OVERPASS_URL,
overpassTimeoutMs: positiveNumberOr(raw.OVERPASS_TIMEOUT_MS, 12000),
kitineraryExtractorPath: raw.KITINERARY_EXTRACTOR_PATH,
// Windows spells it Path; every other platform PATH. Split here so callers
// get a list and never re-implement the delimiter.
searchPath: (raw.PATH || raw.Path || '')
.split(process.platform === 'win32' ? ';' : ':')
.map(p => p.trim())
.filter(Boolean),
};
}
export function deriveBackup(raw: RawEnv) {
return {
uploadLimitMb: positiveNumberOr(raw.BACKUP_UPLOAD_LIMIT_MB, 500),
maxDecompressedMb: positiveNumberOr(raw.BACKUP_MAX_DECOMPRESSED_MB, 5 * 1024),
/** backupService only bundles data/.encryption_key into archives when the key does NOT come from env. */
encryptionKeyFromEnv: !!raw.ENCRYPTION_KEY,
};
}
export function deriveDb(raw: RawEnv) {
const durability = resolveDurability(raw.TREK_DB_JOURNAL_MODE, raw.TREK_DB_SYNCHRONOUS);
return {
trekDbFile: raw.TREK_DB_FILE,
/** Resolved journal_mode — WAL unless the operator asked for something else (network storage needs DELETE/TRUNCATE). */
journalMode: durability.journalMode,
/** Resolved synchronous level — NORMAL under WAL (what SQLite already does), FULL under a rollback journal. */
synchronous: durability.synchronous,
/** Complaints about unusable values; derivation stays side-effect free, so db/durability.ts logs them when it opens the file. */
durabilityWarnings: durability.warnings,
};
}
export function derivePaths(raw: RawEnv) {
return {
wikiDir: raw.TREK_WIKI_DIR,
placePhotoDir: raw.TREK_PLACE_PHOTO_DIR,
};
}
export function deriveNet(raw: RawEnv) {
return {
allowInternalNetwork: parseBool(raw.ALLOW_INTERNAL_NETWORK) === true,
};
}
export function deriveAll(raw: RawEnv) {
return {
app: deriveApp(raw),
http: deriveHttp(raw),
session: deriveSession(raw),
managed: deriveManaged(raw),
maps: deriveMaps(raw),
demo: deriveDemo(raw),
adminBootstrap: deriveAdminBootstrap(raw),
oidc: deriveOidc(raw),
smtp: deriveSmtp(raw),
mcp: deriveMcp(raw),
plugins: derivePlugins(raw),
webauthn: deriveWebauthn(raw),
integrations: deriveIntegrations(raw),
backup: deriveBackup(raw),
db: deriveDb(raw),
paths: derivePaths(raw),
net: deriveNet(raw),
};
}
export type AppEnv = ReturnType<typeof deriveAll>;
+164
View File
@@ -0,0 +1,164 @@
/**
* The single Zod catalog of TREK's environment surface, validated ONCE at boot
* (see env.ts / boot-validate.ts) — never per-request and never inside
* buildApp(), so the test harness (which boots dozens of apps per run with a
* minimal env) is unaffected.
*
* Fail-fast contract: a variable that is UNSET (or blank) always falls back to
* its default — only a PRESENT-but-malformed value aborts startup. Keys not
* listed here pass through untouched (Zod strips unknown keys, it does not
* reject them).
*/
import { z } from 'zod';
import { SUPPORTED_LANGUAGE_CODES } from '@trek/shared';
import { parseDurationMs } from './parsers';
/** Present-but-malformed fails; unset/blank always passes (defaults apply). */
function optionalWith(test: (v: string) => boolean, message: string) {
return z
.string()
.optional()
.refine((v) => v === undefined || v.trim() === '' || test(v.trim()), message);
}
const anyString = z.string().optional();
const boolStr = optionalWith(
(v) => /^(true|false|on|off|yes|no|1|0)$/i.test(v),
'must be a boolean-like value (true/false, 1/0, on/off, yes/no)',
);
const integer = (min: number, max = Number.MAX_SAFE_INTEGER, msg = `must be an integer between ${min} and ${max}`) =>
optionalWith((v) => {
const n = Number(v);
return Number.isInteger(n) && n >= min && n <= max;
}, msg);
const positiveNumber = optionalWith((v) => {
const n = Number(v);
return Number.isFinite(n) && n > 0;
}, 'must be a positive number');
const url = optionalWith((v) => {
try {
new URL(v);
return true;
} catch {
return false;
}
}, 'must be a valid URL (with protocol)');
const duration = optionalWith(
(v) => parseDurationMs(v) != null,
'must be a duration like "1h", "7d" or "30d"',
);
const oneOf = (values: string[]) =>
optionalWith((v) => values.includes(v.toLowerCase()), `must be one of: ${values.join(', ')}`);
export const envSchema = z.object({
// Core runtime
PORT: integer(1, 65535, 'must be a port number (1-65535)'),
HOST: anyString,
// NODE_ENV and TZ are deliberately unvalidated: non-standard values (e.g.
// NODE_ENV=staging) behave as "not production" today and must keep booting.
NODE_ENV: anyString,
TZ: anyString,
LOG_LEVEL: oneOf(['error', 'warn', 'info', 'debug']),
APP_VERSION: anyString,
APP_URL: url,
ALLOWED_ORIGINS: anyString,
// Candidates lowercased so mixed-case codes (zh-TW) validate case-insensitively.
DEFAULT_LANGUAGE: oneOf(SUPPORTED_LANGUAGE_CODES.map((c) => c.toLowerCase())),
// Security / session
ENCRYPTION_KEY: anyString,
SESSION_DURATION: duration,
SESSION_DURATION_REMEMBER: duration,
COOKIE_SECURE: boolStr,
FORCE_HTTPS: boolStr,
HSTS_INCLUDE_SUBDOMAINS: boolStr,
TRUST_PROXY: integer(0, 2 ** 31, 'must be an integer (number of trusted proxy hops)'),
ALLOW_INTERNAL_NETWORK: boolStr,
IDEMPOTENCY_TTL_SECONDS: positiveNumber,
// OIDC
OIDC_ISSUER: url,
OIDC_CLIENT_ID: anyString,
OIDC_CLIENT_SECRET: anyString,
OIDC_DISPLAY_NAME: anyString,
OIDC_DISCOVERY_URL: url,
OIDC_SCOPE: anyString,
OIDC_ONLY: boolStr,
OIDC_ADMIN_CLAIM: anyString,
OIDC_ADMIN_VALUE: anyString,
// SMTP
SMTP_HOST: anyString,
SMTP_PORT: integer(1, 65535, 'must be a port number (1-65535)'),
SMTP_USER: anyString,
SMTP_PASS: anyString,
SMTP_FROM: anyString,
SMTP_SKIP_TLS_VERIFY: boolStr,
// WebAuthn
WEBAUTHN_RP_ID: anyString,
WEBAUTHN_ORIGINS: anyString,
// MCP
MCP_SESSION_TTL: positiveNumber,
MCP_MAX_SESSION_PER_USER: positiveNumber,
MCP_SSE_KEEPALIVE: integer(0, Number.MAX_SAFE_INTEGER, 'must be a non-negative integer (seconds, 0 disables)'),
MCP_RATE_LIMIT: positiveNumber,
// Integrations
UNSPLASH_ACCESS_KEY: anyString,
TRANSIT_API_URL: url,
// OVERPASS_URL accepts a comma-separated endpoint list and silently drops
// non-http(s) entries today — left unvalidated to keep that behavior.
OVERPASS_URL: anyString,
OVERPASS_TIMEOUT_MS: positiveNumber,
KITINERARY_EXTRACTOR_PATH: anyString,
// The OS search path. Not configuration anybody sets for TREK — it is here so
// the kitinerary probe can resolve its binary to an absolute path itself
// instead of handing an unqualified name to exec, which would re-resolve
// through whatever PATH held at that moment.
PATH: anyString,
Path: anyString,
// Data / paths
TREK_DB_FILE: anyString,
// The two SQLite pragmas are deliberately unvalidated: a typo here must fall
// back and warn rather than abort boot, because reset-admin.js — the way out
// of a locked-out instance — reads the same variables and is not covered by
// this schema at all. Resolution lives in parsers.resolveDurability().
TREK_DB_JOURNAL_MODE: anyString,
TREK_DB_SYNCHRONOUS: anyString,
TREK_WIKI_DIR: anyString,
TREK_PLACE_PHOTO_DIR: anyString,
BACKUP_UPLOAD_LIMIT_MB: positiveNumber,
BACKUP_MAX_DECOMPRESSED_MB: positiveNumber,
// Admin / demo
ADMIN_EMAIL: anyString,
ADMIN_PASSWORD: anyString,
TREK_MANAGED: boolStr,
PLACES_API_BASE: url,
PLACES_API_KEY: anyString,
MAPBOX_ACCESS_TOKEN: anyString,
CARTO_API_KEY: anyString,
DEMO_MODE: boolStr,
DEMO_ADMIN_USER: anyString,
DEMO_ADMIN_EMAIL: anyString,
DEMO_ADMIN_PASS: anyString,
// API docs / plugins
TREK_API_DOCS_ENABLED: boolStr,
TREK_PLUGINS_ENABLED: boolStr,
TREK_PLUGINS_DEV_LINK: boolStr,
TREK_PLUGINS_DIR: anyString,
TREK_PLUGINS_DATA_DIR: anyString,
TREK_PLUGIN_PERMISSIONS: boolStr,
TREK_PLUGIN_ALLOW_PRIVATE_EGRESS: boolStr,
TREK_PLUGIN_REGISTRY_URL: url,
TREK_PLUGIN_RPC_BURST: positiveNumber,
TREK_PLUGIN_RPC_PER_SEC: positiveNumber,
TREK_PLUGIN_RPC_INFLIGHT: positiveNumber,
TREK_PLUGIN_LOG_BURST: positiveNumber,
TREK_PLUGIN_LOG_PER_SEC: positiveNumber,
TREK_PLUGIN_MAX_RSS_MB: positiveNumber,
});
+70
View File
@@ -0,0 +1,70 @@
import { deriveAll, type AppEnv, type RawEnv } from './derive';
import { envSchema } from './env.schema';
export type { AppEnv, RawEnv };
/**
* Live typed view of the environment. Re-derives from the CURRENT process.env
* on every call — never cache the result across requests: the test suite (and
* the admin demo tooling) mutates process.env at runtime and depends on the
* next read observing the change. Derivation is a handful of string coercions,
* not a Zod parse; validation happens once at boot via validateEnvAtBoot().
*/
export function readEnv(): AppEnv {
return deriveAll(process.env as RawEnv);
}
/**
* Fail-fast startup validation: a variable that is PRESENT but malformed aborts
* boot with an aggregated report; unset/blank variables always pass (their
* documented defaults apply). Called once from the production entrypoint (see
* boot-validate.ts, imported by index.ts right after dotenv) — deliberately NOT
* wired into buildApp() or ConfigModule, so tests booting apps with a minimal
* env are unaffected.
*/
export function validateEnvAtBoot(raw: RawEnv = process.env as RawEnv): void {
const result = envSchema.safeParse(raw);
const lines = result.success
? []
: result.error.issues.map((issue) => {
const key = String(issue.path[0]);
return ` - ${key}=${JSON.stringify(raw[key])}: ${issue.message}`;
});
lines.push(...managedPreconditions(raw));
if (lines.length === 0) return;
console.error(`Invalid environment configuration:\n${lines.join('\n')}`);
throw new Error(
`Invalid environment configuration (${lines.length} problem${lines.length === 1 ? '' : 's'}). ` +
'Fix the variables listed above, or unset them to use their defaults.',
);
}
/**
* Cross-field rules that only apply to a centrally administered install.
*
* These are not schema problems — every value here is individually valid, and
* blank always means "use the default" everywhere else in this file. They are
* combinations that would boot happily and be wrong, which is the case the
* schema cannot express and the one worth refusing (fail closed, see
* server/CLAUDE.md).
*
* Deliberately unreachable for a self-hoster: without TREK_MANAGED the list is
* empty and nothing changes.
*/
function managedPreconditions(raw: RawEnv): string[] {
if (deriveAll(raw).managed.enabled !== true) return [];
const problems: string[] = [];
// Without it the key is a file in the data volume, and backupService bundles
// that file into every archive it builds. The archive is downloadable by any
// instance admin, so the at-rest encryption would come with its own key in the
// same zip. Provisioning sets this; forgetting it is silent otherwise.
if (!raw.ENCRYPTION_KEY) {
problems.push(
' - ENCRYPTION_KEY is unset: required with TREK_MANAGED, because otherwise the ' +
'at-rest key lives in the data volume and is bundled into every backup download.',
);
}
return problems;
}
+25
View File
@@ -0,0 +1,25 @@
export { readEnv, validateEnvAtBoot } from './env';
export { getAppUrl, getMcpSafeUrl } from './app-url';
export type { AppEnv, RawEnv } from './env';
export {
deriveAll,
deriveApp,
deriveHttp,
deriveSession,
deriveManaged,
deriveMaps,
deriveDemo,
deriveAdminBootstrap,
deriveOidc,
deriveSmtp,
deriveMcp,
derivePlugins,
deriveWebauthn,
deriveIntegrations,
deriveBackup,
deriveDb,
derivePaths,
deriveNet,
} from './derive';
export * from './parsers';
export { envSchema } from './env.schema';
+184
View File
@@ -0,0 +1,184 @@
/**
* Pure env-string coercion helpers shared by the whole config layer (derive.ts,
* env.schema.ts) and — until their call sites migrate — by legacy readers like
* src/mcp/config.ts. Kept free of imports so units can test them in isolation.
*
* Each helper reproduces a coercion family that already exists in the codebase.
* Parity is law: do NOT "fix" a family's quirks here (e.g. `numberOr` treating
* "0" as unset) — call sites were written against the current semantics.
*/
const TRUE_VALUES = new Set(['true', '1', 'on', 'yes']);
const FALSE_VALUES = new Set(['false', '0', 'off', 'no']);
/**
* Unified boolean coercion for env switches — the ONE deliberate departure from
* legacy parity: historically each site accepted a different literal ('true'
* vs '1' vs 'on'), so operators guessed. Now every boolean-like variable
* accepts true/1/on/yes and false/0/off/no (any casing, padded ok) and derives
* to a real boolean. Anything else — including unset and blank — returns
* undefined so the field's default applies; out-of-family values are rejected
* at boot by env.schema.ts anyway (undefined here is the safe fallback for
* paths that skip validation, e.g. tests).
*/
export function parseBool(raw: string | undefined): boolean | undefined {
if (raw === undefined) return undefined;
const v = raw.trim().toLowerCase();
if (TRUE_VALUES.has(v)) return true;
if (FALSE_VALUES.has(v)) return false;
return undefined;
}
/** `Number(raw) || fallback` — NaN, 0 and '' all fall back (PORT, plugin limits). */
export function numberOr(raw: string | undefined, fallback: number): number {
return Number(raw) || fallback;
}
/** Finite and > 0, else fallback (IDEMPOTENCY_TTL_SECONDS, OVERPASS_TIMEOUT_MS, BACKUP_*). */
export function positiveNumberOr(raw: string | undefined, fallback: number): number {
const n = Number(raw);
return Number.isFinite(n) && n > 0 ? n : fallback;
}
/** `Number.parseInt` finite and > 0, else fallback (MCP_MAX_SESSION_PER_USER, MCP_RATE_LIMIT). */
export function positiveIntOr(raw: string | undefined, fallback: number): number {
const n = Number.parseInt(raw ?? '');
return Number.isFinite(n) && n > 0 ? n : fallback;
}
/** Integer ≥ 0 (zero is meaningful — e.g. retries disabled), else the fallback. */
export function nonNegativeIntOr(raw: string | undefined, fallback: number): number {
if (raw === undefined || raw.trim() === '') return fallback;
const n = Number.parseInt(raw, 10);
return Number.isFinite(n) && n >= 0 ? n : fallback;
}
/** Comma-split + trim, null when unset — the websocket ALLOWED_ORIGINS variant (no empty-entry filter). */
export function csvList(raw: string | undefined): string[] | null {
return raw ? raw.split(',').map((o) => o.trim()) : null;
}
/** Comma-split + trim + drop empties — the CORS ALLOWED_ORIGINS variant (globalMiddleware). */
export function csvListFiltered(raw: string | undefined): string[] | null {
return raw
? raw
.split(',')
.map((o) => o.trim())
.filter(Boolean)
: null;
}
/** Strip ALL trailing slashes (`/\/+$/`) — app-url.getAppUrl / TRANSIT_API_URL variant.
* Scanned rather than replaced: `/\/+$/` re-walks the slash run from every start
* position, which is quadratic on a slash-heavy value. Same result, same quirk. */
export function stripTrailingSlashes(value: string): string {
let end = value.length;
while (end > 0 && value.charCodeAt(end - 1) === 47 /* '/' */) end--;
return value.slice(0, end);
}
const DURATION_UNITS_MS: Record<string, number> = {
ms: 1,
s: 1000,
m: 60_000,
h: 3_600_000,
d: 86_400_000,
w: 604_800_000,
y: 31_557_600_000,
};
/**
* ms-style duration strings ('1h', '7d', '30d', …) → milliseconds, null when
* invalid. Same grammar as the SESSION_DURATION parsing in src/config.ts.
*/
export function parseDurationMs(value: string): number | null {
const m = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d|w|y)?$/i.exec(value.trim());
if (!m) return null;
const n = Number.parseFloat(m[1]);
if (!Number.isFinite(n) || n <= 0) return null;
return n * DURATION_UNITS_MS[(m[2] || 'ms').toLowerCase()];
}
/**
* Session idle TTL in SECONDS via MCP_SESSION_TTL, default 1 hour, clamped to
* 24h so a milliseconds-value typo can't produce a 1000-hour session.
* (Same contract as src/mcp/config.ts, which commit 7 retires in favor of this.)
*/
export function resolveSessionTtlMs(raw: string | undefined): number {
const parsed = Number.parseInt(raw ?? '');
return Number.isFinite(parsed) && parsed > 0 ? Math.min(parsed, 24 * 60 * 60) * 1000 : 60 * 60 * 1000;
}
/**
* SSE keep-alive interval in SECONDS via MCP_SSE_KEEPALIVE, default 25s
* (below common proxy idle timeouts like nginx-ingress's 60s). 0 disables.
*/
export function resolveKeepaliveMs(raw: string | undefined): number {
const parsed = Number.parseInt(raw ?? '');
return Number.isFinite(parsed) && parsed >= 0 ? parsed * 1000 : 25_000;
}
/** SQLite's journal_mode vocabulary. WAL is the default and the right choice on local disk; DELETE and TRUNCATE are the ones that survive network storage (Azure App Service, SMB/NFS volumes), where WAL's shared-memory coordination is not reliable. */
const JOURNAL_MODES = ['DELETE', 'TRUNCATE', 'PERSIST', 'MEMORY', 'WAL', 'OFF'];
/** PRAGMA synchronous levels, in the order SQLite numbers them (0-3). */
const SYNCHRONOUS_LEVELS = ['OFF', 'NORMAL', 'FULL', 'EXTRA'];
export const DEFAULT_JOURNAL_MODE = 'WAL';
export interface Durability {
journalMode: string;
synchronous: string;
/** Rejected input, phrased for the log. Resolution never throws — a typo in a pragma must not lock an operator out of their instance — so the process that opens the file prints these instead. */
warnings: string[];
}
/**
* TREK_DB_JOURNAL_MODE / TREK_DB_SYNCHRONOUS → the pragmas to apply.
*
* journal_mode is persisted in the database file header, so it outlives the
* process that set it and every entry point opening the file read-write has to
* agree on it (see src/db/durability.ts). Defaults reproduce what an existing
* install runs today: WAL, and the synchronous=NORMAL that SQLite itself picks
* for a WAL database. Anything other than WAL keeps a rollback journal, where
* NORMAL means a power cut can lose the last transactions — those default to
* FULL, otherwise moving off WAL for safety would only trade one risk for
* another.
*/
export function resolveDurability(rawJournalMode: string | undefined, rawSynchronous: string | undefined): Durability {
const warnings: string[] = [];
let journalMode = DEFAULT_JOURNAL_MODE;
const wanted = rawJournalMode?.trim().toUpperCase();
if (wanted) {
if (JOURNAL_MODES.includes(wanted)) {
journalMode = wanted;
} else {
warnings.push(
`TREK_DB_JOURNAL_MODE="${rawJournalMode}" is not a SQLite journal mode ` +
`(${JOURNAL_MODES.join(', ')}) — using ${DEFAULT_JOURNAL_MODE}.`,
);
}
}
const defaultSynchronous = journalMode === DEFAULT_JOURNAL_MODE ? 'NORMAL' : 'FULL';
let synchronous = defaultSynchronous;
const wantedSync = rawSynchronous?.trim().toUpperCase();
if (wantedSync) {
if (SYNCHRONOUS_LEVELS.includes(wantedSync)) {
synchronous = wantedSync;
} else {
warnings.push(
`TREK_DB_SYNCHRONOUS="${rawSynchronous}" is not a SQLite synchronous level ` +
`(${SYNCHRONOUS_LEVELS.join(', ')}) — using ${defaultSynchronous}.`,
);
}
}
return { journalMode, synchronous, warnings };
}
/** `PRAGMA synchronous` reads back as a number — name it, so the boot log says FULL instead of 2. Unrecognized values pass through unchanged. */
export function synchronousName(level: unknown): string {
return SYNCHRONOUS_LEVELS[Number(level)] ?? String(level);
}
+133 -22
View File
@@ -1,53 +1,164 @@
import nodeHttp from 'node:http';
import express from 'express';
import type { Request, Response, NextFunction, RequestHandler } from 'express';
import { NestFactory } from '@nestjs/core';
import { ExpressAdapter } from '@nestjs/platform-express';
import type { INestApplication } from '@nestjs/common';
import type { ConfigType } from '@nestjs/config';
import { AppModule } from './nest/app.module';
import { httpConfig } from './nest/app-config';
import { applyGlobalMiddleware } from './middleware/globalMiddleware';
import { applyPlatformUploads, applyPlatformTransport, applyPlatformStatic } from './nest/platform/platform.routes';
import { applyPlatformUploads, applyPlatformStatic } from './nest/platform/platform.routes';
import { apiDocsEnabled } from './nest/common/api-docs.kill-switch';
import { setupApiDocs } from './nest/platform/api-docs';
import { MCP_METADATA_MIDDLEWARE } from './nest/platform/mcp-metadata.middleware';
import { validateBodyContracts } from './nest/common/validate-body-contracts';
import { validateRouteGuards } from './nest/common/validate-route-guards';
import { validateManagedRoutes } from './nest/common/validate-managed-routes';
import { TrekWsAdapter } from './nest/realtime/trek-ws.adapter';
import { StorageService } from './nest/storage/storage.service';
/**
* Builds the unified TREK NestJS application that serves the ENTIRE surface — the
* former Express app is gone. One builder is shared by the production bootstrap
* (index.ts) and the integration-test harness so the two can never drift.
*
* Composition order is load-bearing. Everything except the SPA index.html fallback
* is registered on the underlying Express instance BEFORE `app.init()`, because
* Nest's router terminates an unmatched request by throwing NotFoundException — it
* does NOT fall through to a route registered after init, so a post-init Express
* route is unreachable. The platform routes are all specific paths (/uploads/*,
* /api/health, /mcp, /.well-known/*, /oauth/{authorize,register,consent}) so they
* match their own requests and `next()` everything else through to the Nest
* controllers registered during init.
* Composition order is load-bearing. The few remaining pre-`app.init()` pieces
* are registered on the underlying Express instance first, because Nest's
* router terminates an unmatched request by throwing NotFoundException — it
* does NOT fall through to a route registered after init, so a post-init
* Express route is unreachable. Each pre-init piece matches its own requests
* and `next()`s everything else through to the Nest controllers:
*
* 1. applyGlobalMiddleware — helmet/CSP, CORS, HSTS, forced-HTTPS, the global MFA
* policy, request logging + cookie-parser. `bodyParser: false` so Nest does its
* own parsing and the raw /mcp body reaches the MCP handler unparsed.
* 1. applyGlobalMiddleware — helmet/CSP, CORS, HSTS, forced-HTTPS, request
* logging + cookie-parser.
* 2. applyPlatformUploads — the static + guarded /uploads/* routes.
* 3. applyPlatformTransport — /api/health, the OAuth/MCP SDK + /.well-known
* metadata, the /mcp routes, the /oauth/consent COOP header.
* 4. applyPlatformStatic — the production built-client static assets (so a real
* asset request returns the file before the Nest router 404s it).
* 4b. setupApiDocs — Swagger UI/spec at /api/docs* when TREK_API_DOCS_ENABLED;
* also Express-level, so it must precede init for the same reason.
* 5. app.init() — registers every migrated /api domain (the Nest controllers).
* 3. MCP_METADATA_MIDDLEWARE — the SDK's OAuth discovery router + addon
* gate, container-built (DI) but mounted pathless here (see below).
* 4. applyPlatformStatic — the production built-client static assets (so a
* real asset request returns the file before the Nest router 404s it).
* 4b. setupApiDocs — Swagger UI/spec at /api/docs* when TREK_API_DOCS_ENABLED.
* 4c. the named body-parser wrappers — the global 100kb JSON/urlencoded
* parsers, exempting /mcp so the MCP SDK reads the raw stream.
* 5. app.init() — every domain controller, including the transport surface
* that used to live pre-init: /api/health (FeaturesController), OAuth
* discovery documents (DiscoveryController), the /oauth/consent COOP
* override (ConsentCoopMiddleware), /oauth/authorize + /oauth/register
* (SDK routers via OauthModule.configure) and /mcp (McpTransportModule).
*
* The SPA index.html fallback (unmatched GET → index.html in production) is the
* SpaFallbackFilter (APP_FILTER in AppModule); the global error envelope is the
* TrekExceptionFilter (also APP_FILTER).
*/
let boundHttpServer: nodeHttp.Server | null = null;
/**
* The http server buildApp created and bound the ws gateway to.
*
* index.ts listens on it; the websocket suites connect to it. Anyone creating a
* second server around the same express instance would get a working REST API
* and a /ws that no client can reach.
*/
export function getHttpServer(): nodeHttp.Server {
if (!boundHttpServer) throw new Error('buildApp() has not run yet');
return boundHttpServer;
}
export async function buildApp(): Promise<INestApplication> {
// rawBody keeps the unparsed request bytes on req.rawBody so a plugin webhook
// route can verify a provider's HMAC signature over the exact payload (the
// parsed JSON alone can't be re-serialised byte-for-byte).
const app = await NestFactory.create(AppModule, new ExpressAdapter(), { rawBody: true });
const instance = app.getHttpAdapter().getInstance();
applyGlobalMiddleware(instance, { bodyParser: false });
applyPlatformUploads(instance);
applyPlatformTransport(instance);
// The http server is created HERE, not by the caller after buildApp returns,
// and that ordering is the whole point: Nest binds gateways during app.init(),
// so the ws adapter has to exist before it and has to already know which
// server to attach to. Handing it the app instead would bind the ws server to
// Nest's own internal http server, which this process never listens on: the
// boot succeeds, the gateway logs as registered, every test passes, and no
// browser can connect. Callers take the server from getHttpServer() below.
boundHttpServer = nodeHttp.createServer(instance);
app.useWebSocketAdapter(new TrekWsAdapter(boundHttpServer));
// ConfigModule.forRoot's load factories already ran inside NestFactory.create,
// so the boot-stable snapshot is resolvable here, BEFORE app.init() — this is
// the one bridge that lets the pre-init Express layer consume the validated
// config instead of reading process.env itself.
const http = app.get<ConfigType<typeof httpConfig>>(httpConfig.KEY);
applyGlobalMiddleware(instance, { http });
// Same pre-init consumption bridge as httpConfig above: the StorageService
// instance is resolvable before init, and the handlers only *register* here —
// per-request resolution runs after app.init() completed the registry load.
applyPlatformUploads(instance, app.get(StorageService));
// The SDK discovery router (+ its addon gate). Container-built so its deps
// are injected (same pre-init consumption bridge as httpConfig above), but
// applied here as a PATHLESS app.use: the SDK router matches absolute
// /.well-known/* paths against req.url, and any Nest wildcard forRoutes()
// mount is an Express pattern mount that strips the matched prefix from
// req.url before the middleware runs.
instance.use(app.get<RequestHandler>(MCP_METADATA_MIDDLEWARE));
applyPlatformStatic(instance);
// Pin the request-body ceiling explicitly. The Express shell used to set
// '100kb' and stopped doing it when the Nest instance took over parsing, which
// left the limit implicit — the same number, but nowhere anybody would find
// it, and one NestFactory default away from silently becoming something else.
// The verify hook keeps req.rawBody, which the plugin webhook routes need to
// check a provider's HMAC over the exact payload (same hook Nest's own
// useBodyParser would install).
//
// /mcp is exempted and stays RAW: the MCP SDK's StreamableHTTPServerTransport
// reads the request stream itself (its own size handling and JSON-RPC error
// bodies), and the transport controller passes the still-undefined req.body
// through as handleRequest's parsedBody argument. No Nest route may ever
// @Body() on /mcp. The wrapper NAMES are load-bearing:
// ExpressAdapter.registerParserMiddleware skips its own init-time parsers
// only when layers named jsonParser/urlencodedParser already sit in the stack.
const rawBodyKeeper = (req: Request, _res: Response, buffer: Buffer) => {
if (Buffer.isBuffer(buffer)) (req as Request & { rawBody?: Buffer }).rawBody = buffer;
};
/*
* ── Why one route gets a larger body than the rest ───────────────────
*
* A hundred kilobytes is the right ceiling for an API of forms and ids, and
* it is the wrong one for a photo book. A Studio document is sent WHOLE on
* every autosave — deliberately, see book-store.schema.ts, because a patch
* protocol would need an ordering guarantee and a merge rule per field — and
* the contract already caps it at 150 spreads of 60 elements. A real book of
* a fortnight's journey is well past a hundred kilobytes before anybody asks
* for road geometry, and what the ceiling produces is not an error message
* but a save that quietly fails and an editor that says "not saved" without
* saying why.
*
* So the book route, and only the book route, is measured against the size a
* book can actually be. Everything else keeps the tighter limit.
*/
const bookBody = express.json({ limit: '8mb', verify: rawBodyKeeper });
const json = express.json({ limit: '100kb', verify: rawBodyKeeper });
const urlencoded = express.urlencoded({ limit: '100kb', extended: true, verify: rawBodyKeeper });
const isMcp = (req: Request) => req.path === '/mcp' || req.path === '/mcp/';
const isBookWrite = (req: Request) =>
req.method === 'PUT' && /^\/api\/journeys\/\d+\/book$/.test(req.path);
instance.use(function jsonParser(req: Request, res: Response, next: NextFunction) {
if (isBookWrite(req)) return bookBody(req, res, next);
return isMcp(req) ? next() : json(req, res, next);
});
instance.use(function urlencodedParser(req: Request, res: Response, next: NextFunction) {
return isMcp(req) ? next() : urlencoded(req, res, next);
});
if (apiDocsEnabled()) setupApiDocs(app);
await app.init();
// Fail closed on unvalidated mutation bodies: every POST/PUT/PATCH @Body()
// must carry a createZodDto class (validated by the global ZodValidationPipe)
// or sit on the ratchet-only legacy allow-list — otherwise refuse to boot.
validateBodyContracts(app);
// Fail closed on the anonymous surface too: a route that answers without a
// session must carry @Public() with a reason AND be on the reviewed list.
// Default-deny protects what exists; this is what keeps the exemptions honest.
validateRouteGuards(app);
// And on the other direction of the same question: a route that a centrally
// administered install withholds from its own admin must say why, and be on a
// list somebody reviewed. Runs in every e2e harness because they share this
// builder, so a forgotten marker fails in CI rather than at a customer.
validateManagedRoutes(app);
return app;
}
+42 -63
View File
@@ -1,8 +1,7 @@
import { SUPPORTED_LANGUAGE_CODES as SUPPORTED_LANG_CODES } from '@trek/shared';
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { readEnv } from './app-config';
const dataDir = path.resolve(__dirname, '../data');
const jwtSecretFile = path.join(dataDir, '.jwt_secret');
@@ -37,10 +36,36 @@ if (_encryptionKey) {
// Try the dedicated key file first (covers all installs after first start).
try {
_encryptionKey = fs.readFileSync(encKeyFile, 'utf8').trim();
} catch {
} catch (readErr: unknown) {
const code = (readErr as NodeJS.ErrnoException)?.code;
if (code !== 'ENOENT') {
// The file is there, we just cannot read it (permissions, I/O error).
// Continuing would resolve a different key and overwrite this one below,
// which permanently orphans every stored secret. Refuse to start instead.
// The errno goes in the line because this exit crash-loops the container,
// and the code is the only part that says which of these it is.
console.error(
`FATAL: could not read ${encKeyFile} (${code ?? 'no errno'}) -`,
readErr instanceof Error ? readErr.message : readErr,
);
if (code === 'EISDIR') {
// Compose creating a missing bind-mount source as a directory is by far
// the most common way this file stops being a file.
console.error('EISDIR: the path is a directory. A bind mount pointed at data/.encryption_key created it as one — remove it and mount the data directory instead.');
}
console.error('Fix the file permissions or set ENCRYPTION_KEY explicitly.');
process.exit(1);
}
// File not found — first start on an existing or fresh install.
}
if (!_encryptionKey && fs.existsSync(encKeyFile)) {
// Present but empty: a truncated write, a full disk, a broken restore.
// Same reasoning as above. Regenerating here would silently replace the real key.
console.error('FATAL:', encKeyFile, 'is empty. Restore it from backup or set ENCRYPTION_KEY.');
process.exit(1);
}
if (!_encryptionKey) {
// One-time migration: existing install upgrading for the first time.
// Use the JWT secret as the encryption key and immediately write it to
@@ -107,70 +132,24 @@ export function updateJwtSecret(newSecret: string): void {
JWT_SECRET = newSecret;
}
// DEFAULT_LANGUAGE sets the language shown on the login page before the user
// selects one. Only applies when the user has no saved language preference.
const rawDefaultLang = process.env.DEFAULT_LANGUAGE?.toLowerCase() || 'en';
if (!SUPPORTED_LANG_CODES.includes(rawDefaultLang)) {
console.warn(
`DEFAULT_LANGUAGE="${rawDefaultLang}" is not supported. Falling back to "en". Supported: ${SUPPORTED_LANG_CODES.join(', ')}`,
);
}
export const DEFAULT_LANGUAGE = SUPPORTED_LANG_CODES.includes(rawDefaultLang) ? rawDefaultLang : 'en';
// DEFAULT_LANGUAGE / SESSION_DURATION* parsing moved into src/app-config
// (env.schema.ts validates fail-fast at boot; derive.ts resolves/falls back).
// Re-exported here — frozen at import, exactly like before — so the many
// importers of this module (mcp, middleware, services, e2e harness) are
// untouched. This module now owns only key material (above).
const sessionEnv = readEnv().session;
// SESSION_DURATION controls how long a TREK session (the `trek_session` JWT
// cookie) stays valid before re-login is required. Accepts ms-style strings:
// '1h', '12h', '7d', '30d', '90d', etc. It applies to BOTH the JWT `exp` claim
// and the cookie `maxAge`, so the two never drift apart. Invalid values warn at
// startup and fall back to the default. Does not affect the short-lived MFA
// challenge token or MCP OAuth tokens — those keep their own TTL.
const DEFAULT_SESSION_DURATION = '24h';
const DURATION_UNITS_MS: Record<string, number> = {
ms: 1,
s: 1000,
m: 60_000,
h: 3_600_000,
d: 86_400_000,
w: 604_800_000,
y: 31_557_600_000,
};
function parseDurationMs(value: string): number | null {
const m = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d|w|y)?$/i.exec(value.trim());
if (!m) return null;
const n = parseFloat(m[1]);
if (!Number.isFinite(n) || n <= 0) return null;
return n * DURATION_UNITS_MS[(m[2] || 'ms').toLowerCase()];
}
const rawSessionDuration = process.env.SESSION_DURATION?.trim() || DEFAULT_SESSION_DURATION;
const parsedSessionMs = parseDurationMs(rawSessionDuration);
if (parsedSessionMs == null) {
console.warn(
`SESSION_DURATION="${rawSessionDuration}" is not a valid duration (use e.g. 1h, 7d, 30d). Falling back to "${DEFAULT_SESSION_DURATION}".`,
);
}
/** Default login-page language, validated against the supported set ('en' fallback). */
export const DEFAULT_LANGUAGE = readEnv().app.defaultLanguage;
/** Human-readable session length actually in effect (for logs/diagnostics). */
export const SESSION_DURATION = parsedSessionMs == null ? DEFAULT_SESSION_DURATION : rawSessionDuration;
export const SESSION_DURATION = sessionEnv.duration;
/** Session length in milliseconds — used for the cookie `maxAge`. */
export const SESSION_DURATION_MS = parsedSessionMs ?? parseDurationMs(DEFAULT_SESSION_DURATION)!;
export const SESSION_DURATION_MS = sessionEnv.durationMs;
/** Session length in seconds — passed to `jwt.sign({ expiresIn })` (number = seconds). */
export const SESSION_DURATION_SECONDS = Math.floor(SESSION_DURATION_MS / 1000);
// SESSION_DURATION_REMEMBER is the session length used when the user ticks
// "Remember me" on the login form: a longer-lived JWT `exp` claim plus a
// persistent `trek_session` cookie `maxAge`. An unticked login keeps
// SESSION_DURATION and a browser-session cookie (no `maxAge`). Same ms-style
// format and fallback behavior as SESSION_DURATION.
const DEFAULT_SESSION_DURATION_REMEMBER = '30d';
const rawRememberDuration = process.env.SESSION_DURATION_REMEMBER?.trim() || DEFAULT_SESSION_DURATION_REMEMBER;
const parsedRememberMs = parseDurationMs(rawRememberDuration);
if (parsedRememberMs == null) {
console.warn(
`SESSION_DURATION_REMEMBER="${rawRememberDuration}" is not a valid duration (use e.g. 7d, 30d, 90d). Falling back to "${DEFAULT_SESSION_DURATION_REMEMBER}".`,
);
}
export const SESSION_DURATION_SECONDS = sessionEnv.durationSeconds;
/** Human-readable "remember me" session length actually in effect (for logs/diagnostics). */
export const SESSION_DURATION_REMEMBER =
parsedRememberMs == null ? DEFAULT_SESSION_DURATION_REMEMBER : rawRememberDuration;
export const SESSION_DURATION_REMEMBER = sessionEnv.durationRemember;
/** "Remember me" session length in milliseconds — used for the persistent cookie `maxAge`. */
export const SESSION_DURATION_REMEMBER_MS = parsedRememberMs ?? parseDurationMs(DEFAULT_SESSION_DURATION_REMEMBER)!;
export const SESSION_DURATION_REMEMBER_MS = sessionEnv.durationRememberMs;
/** "Remember me" session length in seconds — passed to `jwt.sign({ expiresIn })`. */
export const SESSION_DURATION_REMEMBER_SECONDS = Math.floor(SESSION_DURATION_REMEMBER_MS / 1000);
export const SESSION_DURATION_REMEMBER_SECONDS = sessionEnv.durationRememberSeconds;
+29 -11
View File
@@ -1,6 +1,8 @@
import Database from 'better-sqlite3';
import path from 'path';
import fs from 'fs';
import { readEnv } from '../app-config';
import { applyDurabilityPragmas } from './durability';
import { createTables } from './schema';
import { runMigrations } from './migrations';
import { runSeeds } from './seeds';
@@ -8,16 +10,16 @@ import { Place, Tag } from '../types';
// In test mode each vitest worker gets an isolated in-memory DB so that
// parallel forks can't race on the same file or share migration state.
const isTest = process.env.NODE_ENV === 'test';
const isTest = readEnv().app.isTest;
let dbPath: string;
if (isTest) {
dbPath = ':memory:';
} else if (process.env.TREK_DB_FILE) {
} else if (readEnv().db.trekDbFile) {
// Explicit DB file (used by the Playwright E2E harness to run against an
// isolated, throwaway database instead of the real data/travel.db). Purely
// additive — when unset the default path below is used exactly as before.
dbPath = process.env.TREK_DB_FILE;
dbPath = readEnv().db.trekDbFile!;
const dir = path.dirname(dbPath);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
} else {
@@ -38,9 +40,16 @@ function initDb(): void {
}
_db = new Database(dbPath);
_db.exec('PRAGMA journal_mode = WAL');
// Ahead of the journal switch now: changing journal_mode needs an exclusive
// lock, which a sibling process (reset-admin, the rotation script) may hold.
_db.exec('PRAGMA busy_timeout = 5000');
const durability = applyDurabilityPragmas(_db);
_db.exec('PRAGMA foreign_keys = ON');
// Reported so an operator can see whether their setting took — the test DB is
// :memory: and has no journal file, so there is nothing to report there.
if (dbPath !== ':memory:') {
console.log(`[DB] journal_mode=${durability.journalMode}, synchronous=${durability.synchronous}`);
}
createTables(_db);
runMigrations(_db);
@@ -62,7 +71,7 @@ const db = new Proxy({} as Database.Database, {
},
});
if (process.env.DEMO_MODE?.toLowerCase() === 'true') {
if (readEnv().demo.enabled) {
try {
const { seedDemoData } = require('../demo/demo-seed');
seedDemoData(_db);
@@ -96,6 +105,9 @@ interface PlaceWithCategory extends Place {
interface PlaceWithTags extends Place {
category: { id: number; name: string; color: string; icon: string } | null;
tags: Tag[];
ratings: { user_id: number; username: string; avatar: string | null; rating: number }[];
rating_avg: number | null;
rating_count: number;
}
function getPlaceWithTags(placeId: number | string): PlaceWithTags | null {
@@ -114,6 +126,14 @@ function getPlaceWithTags(placeId: number | string): PlaceWithTags | null {
WHERE pt.place_id = ?
`).all(placeId) as Tag[];
// Collaborative ratings (#1435): every voter with username/avatar for the
// who-voted tooltip; the displayed value is the average.
const ratings = db.prepare(`
SELECT pr.user_id, u.username, u.avatar, pr.rating FROM place_ratings pr
JOIN users u ON pr.user_id = u.id
WHERE pr.place_id = ? ORDER BY pr.created_at
`).all(placeId) as { user_id: number; username: string; avatar: string | null; rating: number }[];
return {
...place,
category: place.category_id ? {
@@ -123,6 +143,9 @@ function getPlaceWithTags(placeId: number | string): PlaceWithTags | null {
icon: place.category_icon!,
} : null,
tags,
ratings,
rating_avg: ratings.length > 0 ? ratings.reduce((s, r) => s + r.rating, 0) / ratings.length : null,
rating_count: ratings.length,
};
}
@@ -144,11 +167,6 @@ function isOwner(tripId: number | string, userId: number): boolean {
return !!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId);
}
try {
const { backfillFlightEndpoints } = require('../services/airportService');
backfillFlightEndpoints();
} catch (err) {
console.error('[DB] Flight endpoint backfill failed:', err);
}
export { db, closeDb, reinitialize, getPlaceWithTags, canAccessTrip, isOwner };
export type { TripAccess, PlaceWithTags };
+36
View File
@@ -0,0 +1,36 @@
import type Database from 'better-sqlite3';
import { readEnv } from '../app-config';
import { synchronousName } from '../app-config/parsers';
export interface ActiveDurability {
journalMode: string;
synchronous: string;
}
/**
* Applies the configured journal_mode / synchronous pragmas to a freshly opened
* connection and reports back what SQLite actually settled on.
*
* journal_mode is stored in the database file header, so it is not a per-process
* setting: whichever process opened the file last decides the mode for all of
* them. reset-admin.js and scripts/migrate-encryption.ts open the same file and
* therefore read the same two variables — they cannot import this module (they
* are standalone scripts and src/ is not in the image), so keep the three in
* sync when the defaults change.
*
* The returned values are read back from the engine rather than echoed from the
* config, so a mode SQLite refused shows up as what it really is — an in-memory
* database stays MEMORY however hard you ask for WAL.
*/
export function applyDurabilityPragmas(db: Database.Database): ActiveDurability {
const { journalMode, synchronous, durabilityWarnings } = readEnv().db;
durabilityWarnings.forEach(warning => console.warn(`[DB] ${warning}`));
db.exec(`PRAGMA journal_mode = ${journalMode}`);
db.exec(`PRAGMA synchronous = ${synchronous}`);
return {
journalMode: String(db.pragma('journal_mode', { simple: true })).toUpperCase(),
synchronous: synchronousName(db.pragma('synchronous', { simple: true })),
};
}
+449 -5
View File
@@ -1,4 +1,5 @@
import { encrypt_api_key } from '../services/apiKeyCrypto';
import { readEnv } from '../app-config';
import { encrypt_api_key } from '../nest/common/crypto/apiKeyCrypto';
import Database from 'better-sqlite3';
import fs from 'fs';
@@ -2720,7 +2721,9 @@ function runMigrations(db: Database.Database): void {
`CREATE TABLE IF NOT EXISTS migrations (id integer PRIMARY KEY AUTOINCREMENT NOT NULL, timestamp bigint NOT NULL, name varchar NOT NULL);`,
);
db.exec(`INSERT INTO migrations (timestamp, name) VALUES (1777810195344, 'InitialSchema1777810195344');`);
db.exec(`INSERT INTO app_settings (key, value) VALUES ('app_version', '${process.env.APP_VERSION || '3.0.14'}')`);
db.prepare("INSERT INTO app_settings (key, value) VALUES ('app_version', ?)").run(
readEnv().app.appVersion || '3.0.14',
);
},
// trim leading/trailing whitespace from stored usernames and emails
() => {
@@ -2738,7 +2741,9 @@ function runMigrations(db: Database.Database): void {
db.exec(`INSERT INTO schema_version_new (version) SELECT version FROM schema_version`);
db.exec(`DROP TABLE schema_version`);
db.exec(`ALTER TABLE schema_version_new RENAME TO schema_version`);
db.exec(`UPDATE app_settings SET value = '${process.env.APP_VERSION || '3.0.15'}' WHERE key = 'app_version'`);
db.prepare("UPDATE app_settings SET value = ? WHERE key = 'app_version'").run(
readEnv().app.appVersion || '3.0.15',
);
},
// Migration: OAuth 2.0 client_credentials grant — allow user-owned confidential
// clients to skip the browser consent flow entirely and obtain tokens directly
@@ -3701,6 +3706,436 @@ function runMigrations(db: Database.Database): void {
`);
db.exec('CREATE INDEX IF NOT EXISTS idx_hidden_regions_user ON hidden_regions (user_id);');
},
// Half vacation days (#552): a vacay entry can now count as a full day (1) or
// a half day (0.5) toward the entitlement. Existing entries default to a full
// day, so the entitlement maths are unchanged for everyone already using vacay.
// Guarded so re-running the migration tail (e.g. the crosswalk test) is a no-op.
() => {
const hasFraction = db.prepare("SELECT 1 FROM pragma_table_info('vacay_entries') WHERE name = 'fraction'").get();
if (!hasFraction) db.exec('ALTER TABLE vacay_entries ADD COLUMN fraction REAL NOT NULL DEFAULT 1');
},
// Read-only vacay calendar sharing (#444/#667): a user can let other users
// view their vacation calendar without fusing plans. owner_id is the sharing
// user, user_id the viewer; hidden lets the viewer hide the overlay without
// removing the share. Follows the person, not the plan, so it survives
// fusion and dissolution.
() => {
db.exec(`
CREATE TABLE IF NOT EXISTS vacay_shares (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
hidden INTEGER NOT NULL DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE (owner_id, user_id)
);
`);
db.exec('CREATE INDEX IF NOT EXISTS idx_vacay_shares_user ON vacay_shares (user_id);');
},
// Collaborative place ratings (#1435): every trip member can rate a trip
// place 1-5, every collection member a saved place; the displayed value is
// the average. One row per user and place, mirroring collab_poll_votes.
() => {
db.exec(`
CREATE TABLE IF NOT EXISTS place_ratings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
place_id INTEGER NOT NULL REFERENCES places(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
rating INTEGER NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE(place_id, user_id)
);
`);
db.exec('CREATE INDEX IF NOT EXISTS idx_place_ratings_place ON place_ratings (place_id);');
db.exec(`
CREATE TABLE IF NOT EXISTS collection_place_ratings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
collection_place_id INTEGER NOT NULL REFERENCES collection_places(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
rating INTEGER NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE(collection_place_id, user_id)
);
`);
db.exec('CREATE INDEX IF NOT EXISTS idx_collection_place_ratings_place ON collection_place_ratings (collection_place_id);');
},
// Per-segment travel mode (#1281): the day-plan route can use a different
// transport mode for each leg. leg_transport_mode on an assignment is the mode
// of the leg LEAVING that stop (NULL = inherit the day default); days gains a
// persisted default_transport_mode so the whole-day choice survives a reload.
// Both nullable → existing itineraries keep today's single-mode behaviour.
() => {
try {
db.exec('ALTER TABLE day_assignments ADD COLUMN leg_transport_mode TEXT');
} catch (err: any) {
if (!err.message?.includes('duplicate column name')) throw err;
}
try {
db.exec('ALTER TABLE days ADD COLUMN default_transport_mode TEXT');
} catch (err: any) {
if (!err.message?.includes('duplicate column name')) throw err;
}
},
// School holidays are a visual Vacay calendar layer. Keep them separate from
// public holidays so applyHolidayCalendars never removes vacation entries for
// school-break dates. Appended LAST: this branch was cut before #1435/#1281
// landed on dev, so an existing DB is already past their slots — only a
// trailing migration re-runs on upgrade and actually adds these columns.
() => {
const planCols = db.prepare("PRAGMA table_info('vacay_plans')").all() as Array<{ name: string }>;
if (!planCols.some(col => col.name === 'school_holidays_enabled')) {
db.exec('ALTER TABLE vacay_plans ADD COLUMN school_holidays_enabled INTEGER DEFAULT 0');
}
const calendarCols = db.prepare("PRAGMA table_info('vacay_holiday_calendars')").all() as Array<{ name: string }>;
if (!calendarCols.some(col => col.name === 'type')) {
db.exec("ALTER TABLE vacay_holiday_calendars ADD COLUMN type TEXT NOT NULL DEFAULT 'public_holiday'");
}
},
// #1517 — assign trip members / named guests to a reservation (mirrors budget_item_members).
() => {
db.exec(`
CREATE TABLE IF NOT EXISTS reservation_travelers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
reservation_id INTEGER NOT NULL REFERENCES reservations(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
UNIQUE(reservation_id, user_id)
);
CREATE INDEX IF NOT EXISTS idx_reservation_travelers_res ON reservation_travelers(reservation_id);
CREATE INDEX IF NOT EXISTS idx_reservation_travelers_user ON reservation_travelers(user_id);
`);
},
// Comp/Flex days (#1074): a vacay entry is either a vacation day (counts toward
// the entitlement) or a comp/flex day (kind='comp', costs 0 — flextime/overtime
// offset). Orthogonal to fraction, so a half comp day is kind='comp' + fraction=0.5.
() => {
const hasKind = db.prepare("SELECT 1 FROM pragma_table_info('vacay_entries') WHERE name = 'kind'").get();
if (!hasKind) db.exec("ALTER TABLE vacay_entries ADD COLUMN kind TEXT NOT NULL DEFAULT 'vacation'");
},
// Configurable vacation year (#737): per-user leave-year window. 'calendar' keeps
// the Jan 1–Dec 31 default (unchanged for everyone); 'fiscal' starts on a fixed
// month/day; 'anniversary' starts on the month/day of the hire date. The year
// integer still names a period; the service resolves it to a [start,end) range.
() => {
db.exec(`
CREATE TABLE IF NOT EXISTS vacay_user_settings (
user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
year_type TEXT NOT NULL DEFAULT 'calendar',
year_start_month INTEGER NOT NULL DEFAULT 1,
year_start_day INTEGER NOT NULL DEFAULT 1,
hire_date TEXT
);
`);
},
// Manual GPX track colour (#776): imported tracks all render in the same blue
// because the importer never assigns a category, so several walks in the same
// area are indistinguishable. NULL keeps the old behaviour (category colour,
// then the #3b82f6 fallback) for every existing row.
() => {
const hasRouteColor = db.prepare("SELECT 1 FROM pragma_table_info('places') WHERE name = 'route_color'").get();
if (!hasRouteColor) db.exec('ALTER TABLE places ADD COLUMN route_color TEXT');
},
// Backfill the three places feature toggles before their read flips from
// fail-open (`value !== 'false'`) to fail-closed (`value === 'true'`), so
// existing installs that never touched the admin switches keep the features
// they have today. A row that already says 'false' is left alone.
() => {
const insert = db.prepare("INSERT OR IGNORE INTO app_settings (key, value) VALUES (?, 'true')");
for (const key of ['places_photos_enabled', 'places_autocomplete_enabled', 'places_details_enabled']) {
insert.run(key);
}
},
// Free the `note` column on budget items for its actual purpose (#1658).
// The costs UI stores an itemized receipt in it as `TICKETJSON:{...}`, which
// means an expense split by receipt can never carry a written note, and
// saving an expense any other way wipes whatever was typed in the budget
// table. The receipt moves to its own column and note becomes text again.
// GLOB, not LIKE: LIKE is case-insensitive in SQLite, so a hand-written note
// starting "ticketjson:" would be chopped up and its text dropped.
() => {
const hasTicket = db.prepare("SELECT 1 FROM pragma_table_info('budget_items') WHERE name = 'ticket_json'").get();
if (!hasTicket) db.exec('ALTER TABLE budget_items ADD COLUMN ticket_json TEXT');
db.exec(`
UPDATE budget_items
SET ticket_json = substr(note, 12), note = NULL
WHERE note GLOB 'TICKETJSON:*'
`);
},
// Note colours (#1629). A day note is a label as much as a reminder — "watch
// out", "must see", "already booked" — and a wall of identical grey cards
// makes that impossible to see at a glance. NULL keeps the neutral card
// every existing note has today.
() => {
const hasColor = db.prepare("SELECT 1 FROM pragma_table_info('day_notes') WHERE name = 'color'").get();
if (!hasColor) db.exec('ALTER TABLE day_notes ADD COLUMN color TEXT');
},
// Per-segment travel mode for boundary legs: a leg whose ORIGIN is not a place
// (booking arrival, morning hotel) stores its mode on the DESTINATION stop.
// NULL = inherit the day default. INERT whenever the previous timeline element
// is itself a place (that place's outgoing leg_transport_mode wins).
// Appended LAST: the array is index-addressed against schema_version, so a slot
// inserted anywhere above this line is simply skipped on every existing database.
() => {
try {
db.exec('ALTER TABLE day_assignments ADD COLUMN incoming_leg_transport_mode TEXT');
} catch (err: any) {
if (!err.message?.includes('duplicate column name')) throw err;
}
},
// #1298 — an expense can hang off a place, exactly as it already hangs off a
// reservation. Same nullable FK, same ON DELETE SET NULL: the delete paths
// take the linked expense with the place themselves, so the constraint is a
// backstop for anything that removes a place without going through them.
// Appended LAST: the array is index-addressed against schema_version, so a
// slot inserted above this line never runs on an existing database.
() => {
const cols = db.prepare("SELECT name FROM pragma_table_info('budget_items')").all() as Array<{ name: string }>;
if (!cols.some(c => c.name === 'place_id')) {
db.exec('ALTER TABLE budget_items ADD COLUMN place_id INTEGER REFERENCES places(id) ON DELETE SET NULL DEFAULT NULL');
}
},
// A reservation_day_positions row only makes sense when its reservation and
// its day are on the same trip. The table carries no trip_id and its two
// foreign keys only ask that the ids exist, so pairs that never belonged
// together could accumulate; the writer refuses them now, and this clears
// whatever an older build let through. This slot keeps the index it shipped
// with on dev — the array is index-addressed against schema_version.
() => {
db.exec(`
DELETE FROM reservation_day_positions
WHERE rowid IN (
SELECT rdp.rowid
FROM reservation_day_positions rdp
JOIN reservations r ON r.id = rdp.reservation_id
JOIN days d ON d.id = rdp.day_id
WHERE d.trip_id <> r.trip_id
)
`);
},
// #1939 — the Google Places and Unsplash keys are instance configuration and
// now resolve out of app_settings (nest/settings/instance-api-keys.ts). This
// carries the value the old resolver would have handed out — the lowest-id
// admin who has one — into that row, so an install that upgrades keeps the
// key it was searching with instead of falling back to OpenStreetMap.
// Only where that key already was the whole install's, though. The resolver
// reads the instance row before the caller's own column, so promoting a
// personal key while a second row still holds one would move that member
// onto a stranger's key and a stranger's bill without anyone saying so. As
// soon as another row has a value for the same column nothing is written:
// everybody keeps resolving what they resolved before, and a member with no
// key of their own searches via OpenStreetMap until an admin saves the
// instance key once in the panel. Handing a key to the whole instance is the
// admin's call, not a migration's.
// The users columns are left alone: they are still the per-user fallback,
// and nothing here can lose a value. Stored blobs are copied verbatim; both
// sides use the same apiKeyCrypto format, legacy plaintext included.
// Appended LAST — the array is index-addressed against schema_version.
() => {
const upsert = db.prepare(
`INSERT INTO app_settings (key, value) VALUES (?, ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value`
);
for (const column of ['maps_api_key', 'unsplash_api_key'] as const) {
const existing = db.prepare('SELECT value FROM app_settings WHERE key = ?').get(column) as
| { value: string | null }
| undefined;
if (existing?.value) continue;
const row = db
.prepare(
`SELECT id, ${column} AS value FROM users
WHERE role = 'admin' AND ${column} IS NOT NULL AND ${column} != ''
ORDER BY id ASC LIMIT 1`
)
.get() as { id: number; value: string } | undefined;
if (!row?.value) continue;
const otherHolder = db
.prepare(
`SELECT 1 FROM users
WHERE id != ? AND ${column} IS NOT NULL AND ${column} != '' LIMIT 1`
)
.get(row.id);
if (otherHolder) continue;
upsert.run(column, row.value);
}
},
// Capture metadata on the photo itself (#1614): when it was taken and where.
// Both are needed before photos can sit on the Journey map by their own
// coordinates, and before a gallery can be ordered by when a picture was
// taken rather than when it happened to be added. Nullable throughout —
// most providers answer with neither, and a photo without them is normal.
// Guarded so re-running the migration tail is a no-op.
() => {
const cols = db.prepare("SELECT name FROM pragma_table_info('trek_photos')").all() as Array<{ name: string }>;
const has = (name: string) => cols.some(c => c.name === name);
if (!has('taken_at')) db.exec('ALTER TABLE trek_photos ADD COLUMN taken_at TEXT');
if (!has('lat')) db.exec('ALTER TABLE trek_photos ADD COLUMN lat REAL');
if (!has('lng')) db.exec('ALTER TABLE trek_photos ADD COLUMN lng REAL');
// Answering "which photos of this journey have coordinates" without a scan.
db.exec('CREATE INDEX IF NOT EXISTS idx_trek_photos_geo ON trek_photos(lat, lng) WHERE lat IS NOT NULL AND lng IS NOT NULL');
},
// A journey shared while the trip is still running reads like a blog, and a
// blog puts the newest entry first (#1614). The owner decides per share link,
// because it is a property of how the link is meant to be read, not of the
// journey. Off by default: an already-published link must not reorder itself
// under its readers.
() => {
const cols = db.prepare("SELECT name FROM pragma_table_info('journey_share_tokens')").all() as Array<{ name: string }>;
if (!cols.some(c => c.name === 'newest_first')) {
db.exec('ALTER TABLE journey_share_tokens ADD COLUMN newest_first INTEGER NOT NULL DEFAULT 0');
}
},
/*
* TREK Studio books (#1973).
*
* One row per book, the document itself stored as JSON. A book is a
* document rather than a graph of records: the editor loads it whole, the
* renderer prints it whole, and nothing ever queries "which books contain a
* heart-shaped frame". Normalising spreads and elements into tables would
* buy queries nobody makes and cost a join on every open plus a schema
* migration for every new element kind.
*
* `updated_at` and `version` are what make concurrent editing possible:
* the version increments on every write, and a client that saves against a
* version it did not read gets told rather than silently overwriting.
*/
() => {
db.exec(`
CREATE TABLE IF NOT EXISTS journey_books (
id INTEGER PRIMARY KEY AUTOINCREMENT,
journey_id INTEGER NOT NULL REFERENCES journeys(id) ON DELETE CASCADE,
title TEXT NOT NULL DEFAULT '',
document TEXT NOT NULL,
version INTEGER NOT NULL DEFAULT 1,
created_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
updated_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_journey_books_journey ON journey_books(journey_id);
`);
},
/*
* Great Britain gained its counties and boroughs back (#1974).
*
* geoBoundaries' GBR ADM1 is the four constituent countries, so since 3.1.0
* the atlas had no polygon below "England" and a London borough marked as
* visited had nothing to light up. The bundle now ships GB at ADM2, which is
* the granularity the rest of the world gets and the granularity the
* pre-3.1.0 Natural Earth layer had.
*
* Two things need saying to the data that already exists:
*
* `visited_regions` rows marked before 3.1.0 hold the old Natural Earth
* borough codes. They are reconciled by name within the same country,
* exactly as the 3.1.1 step above does for every other country — a row that
* still cannot be resolved is left alone rather than destroyed, and the
* client's name fallback may well still highlight it.
*
* `place_regions` is a re-derivable cache, and it is full of GB-ENG rows
* that were correct under the old bundle. Nothing re-derives a row that is
* already there, so without clearing them every English place would keep
* reporting "England" forever.
*/
() => {
db.exec(`DELETE FROM place_regions WHERE UPPER(COALESCE(country_code, '')) = 'GB'`);
type Row = { id: number; region_code: string; region_name: string; country_code: string };
const rows = db
.prepare(`SELECT id, region_code, region_name, country_code FROM visited_regions WHERE UPPER(COALESCE(country_code, '')) = 'GB'`)
.all() as Row[];
if (rows.length === 0) return;
let features: { properties?: { iso_a2?: string; iso_3166_2?: string; name?: string } }[];
try {
const file = path.join(__dirname, '..', '..', 'assets', 'atlas', 'admin1.geojson.gz');
features = JSON.parse(zlib.gunzipSync(fs.readFileSync(file)).toString('utf8')).features || [];
} catch {
return; // bundle unreadable — leave the rows untouched rather than guessing
}
const validCodes = new Set<string>();
const nameToCode = new Map<string, string>();
for (const f of features) {
const p = f.properties || {};
if ((p.iso_a2 || '').toUpperCase() !== 'GB' || !p.iso_3166_2) continue;
validCodes.add(p.iso_3166_2);
if (p.name) nameToCode.set(p.name.toLowerCase(), p.iso_3166_2);
}
if (validCodes.size === 0) return;
const update = db.prepare('UPDATE OR IGNORE visited_regions SET region_code = ? WHERE id = ?');
for (const row of rows) {
if (validCodes.has(row.region_code)) continue;
const byName = nameToCode.get((row.region_name || '').toLowerCase());
if (byName) update.run(byName, row.id);
}
},
// Storage slice 2 — collab note attachments historically stored 'files/<name>'
// in trip_files.filename while the file manager stored bare names in the same
// column; the storage layer addresses objects as category + bare name, so
// normalize the legacy rows. substr is 1-indexed: 7 drops the six chars of
// 'files/'. The LIKE guard makes it a no-op on already-bare rows.
//
// Appended LAST again, and for the same reason as the note this replaces:
// the array is index-addressed against schema_version, so a slot that has
// shipped in dev keeps the index it shipped with and anything from this
// branch goes after it. A database that already ran this migration at its
// pre-merge index replays it harmlessly (the LIKE guard) but skips whatever
// now occupies that index. Acceptable only because this branch has never
// been published; never do this with a released slot.
() => {
db.exec("UPDATE trip_files SET filename = substr(filename, 7) WHERE filename LIKE 'files/%'");
},
// Give back the notes the TICKETJSON step chopped up (#1658).
//
// That step matched with LIKE, which is case-insensitive in SQLite, so a
// note somebody had typed starting "ticketjson:" was read as a receipt: the
// first eleven characters were dropped, the rest was moved into ticket_json
// and the note was set to NULL. The step now matches with GLOB, but that
// only helps a fresh install — the array is index-addressed against
// schema_version, so a repaired step never runs again on a database that
// already applied it.
//
// A receipt comes out of JSON.stringify and always parses; typed text does
// not. So a row moves back only when its ticket_json fails to parse AND the
// note is still empty — anything that parses, and any row someone has
// written a note on since, is left exactly as it is. The eleven marker
// characters themselves are gone for good: their case was the only thing
// separating a receipt from a note, and writing "TICKETJSON:" back would
// hand the row straight to the reader that reads that prefix as a receipt.
// Appended LAST — the array is index-addressed against schema_version.
() => {
const rows = db
.prepare(
`SELECT id, ticket_json FROM budget_items
WHERE ticket_json IS NOT NULL AND ticket_json != '' AND COALESCE(note, '') = ''`
)
.all() as Array<{ id: number; ticket_json: string }>;
const restore = db.prepare('UPDATE budget_items SET note = ?, ticket_json = NULL WHERE id = ?');
for (const row of rows) {
try {
JSON.parse(row.ticket_json);
} catch {
restore.run(row.ticket_json, row.id);
}
}
},
// A deliberate non-latest plugin install sets `update_hold`: the row leaves the
// update banner and "Update all" until the admin resumes updates, or until an
// install lands back on the newest compatible version. Only an EXPLICIT version
// pick ever sets it — dependency resolution pins versions too, but never
// deliberately. Appended LAST — the array is index-addressed against schema_version.
() => {
try {
db.exec('ALTER TABLE plugins ADD COLUMN update_hold INTEGER NOT NULL DEFAULT 0;');
} catch (err) {
console.warn('[migrations] Non-fatal migration step failed:', err);
}
},
];
if (currentVersion < migrations.length) {
@@ -3709,15 +4144,24 @@ function runMigrations(db: Database.Database): void {
try {
const migration = migrations[i];
if (typeof migration === 'function') {
db.transaction(migration)();
// The version bump has to commit together with the migration. Bumped
// afterwards, a crash in between leaves the schema advanced and the
// version stale, and the next boot replays a step that is not
// idempotent, exits 1, and turns one crash into a permanent boot loop.
db.transaction(() => {
migration();
db.prepare('UPDATE schema_version SET version = ?').run(i + 1);
})();
} else {
// raw steps run outside a transaction on purpose (see PRAGMA
// foreign_keys above), so the bump stays a separate statement.
migration.raw();
db.prepare('UPDATE schema_version SET version = ?').run(i + 1);
}
} catch (err) {
console.error(`[migrations] FATAL: Migration ${i + 1} failed, rolled back:`, err);
process.exit(1);
}
db.prepare('UPDATE schema_version SET version = ?').run(i + 1);
}
console.log(`[DB] Migrations complete — schema version ${migrations.length}`);
}
+20
View File
@@ -155,6 +155,15 @@ function createTables(db: Database.Database): void {
PRIMARY KEY (place_id, tag_id)
);
CREATE TABLE IF NOT EXISTS place_ratings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
place_id INTEGER NOT NULL REFERENCES places(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
rating INTEGER NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE(place_id, user_id)
);
CREATE TABLE IF NOT EXISTS day_assignments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
@@ -305,6 +314,7 @@ function createTables(db: Database.Database): void {
block_weekends INTEGER DEFAULT 1,
holidays_enabled INTEGER DEFAULT 0,
holidays_region TEXT DEFAULT '',
school_holidays_enabled INTEGER DEFAULT 0,
company_holidays_enabled INTEGER DEFAULT 1,
carry_over_enabled INTEGER DEFAULT 1,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
@@ -365,6 +375,7 @@ function createTables(db: Database.Database): void {
CREATE TABLE IF NOT EXISTS vacay_holiday_calendars (
id INTEGER PRIMARY KEY AUTOINCREMENT,
plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
type TEXT NOT NULL DEFAULT 'public_holiday',
region TEXT NOT NULL,
label TEXT,
color TEXT NOT NULL DEFAULT '#fecaca',
@@ -425,6 +436,15 @@ function createTables(db: Database.Database): void {
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS collection_place_ratings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
collection_place_id INTEGER NOT NULL REFERENCES collection_places(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
rating INTEGER NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE(collection_place_id, user_id)
);
CREATE TABLE IF NOT EXISTS collection_place_tags (
collection_place_id INTEGER NOT NULL REFERENCES collection_places(id) ON DELETE CASCADE,
tag_id INTEGER NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
+7 -5
View File
@@ -1,5 +1,6 @@
import Database from 'better-sqlite3';
import crypto from 'crypto';
import { readEnv } from '../app-config';
// bcrypt cost factor for the seeded admin password — kept in sync with authService.
const BCRYPT_COST = 12;
@@ -9,14 +10,15 @@ const BCRYPT_COST = 12;
// are only relevant after the first user exists; at that point seeds have already
// finished and skip via the userCount > 0 guard above.
function isOidcOnlyConfigured(): boolean {
if (process.env.OIDC_ONLY?.toLowerCase() !== 'true') return false;
return !!(process.env.OIDC_ISSUER && process.env.OIDC_CLIENT_ID);
const oidc = readEnv().oidc;
if (!oidc.only) return false;
return !!(oidc.issuer && oidc.clientId);
}
function seedAdminAccount(db: Database.Database): void {
try {
const env_admin_email = process.env.ADMIN_EMAIL;
const env_admin_pw = process.env.ADMIN_PASSWORD;
const env_admin_email = readEnv().adminBootstrap.email;
const env_admin_pw = readEnv().adminBootstrap.password;
const adminEnvProvided = !!(env_admin_email || env_admin_pw);
const userCount = (db.prepare('SELECT COUNT(*) as count FROM users').get() as { count: number }).count;
@@ -34,7 +36,7 @@ function seedAdminAccount(db: Database.Database): void {
// Demo mode seeds its own admin (admin@trek.app, username 'admin') right after this.
// Creating a first-run admin here would grab username 'admin' first and make the demo
// seeder fail on the UNIQUE(username) constraint, leaving the demo user uncreated.
if (process.env.DEMO_MODE?.toLowerCase() === 'true') return;
if (readEnv().demo.enabled) return;
if (isOidcOnlyConfigured()) {
console.log('');
+46 -2
View File
@@ -1,10 +1,17 @@
import fs from 'fs';
import path from 'path';
import { readEnv } from '../app-config';
const dataDir = path.join(__dirname, '../../data');
const dbPath = path.join(dataDir, 'travel.db');
const baselinePath = path.join(dataDir, 'travel-baseline.db');
// Where the live DB actually is. database.ts honours TREK_DB_FILE, so hardcoding
// data/travel.db here would copy the baseline over an unrelated file and leave
// the database we just closed untouched. The open connection knows its own path.
function liveDbPath(db: { name: string }): string {
return db.name;
}
function resetDemoUser(): void {
if (!fs.existsSync(baselinePath)) {
console.log('[Demo Reset] No baseline found, skipping. Admin must save baseline first.');
@@ -12,9 +19,15 @@ function resetDemoUser(): void {
}
const { db, closeDb, reinitialize } = require('../db/database');
const dbPath = liveDbPath(db);
if (dbPath === ':memory:') {
console.log('[Demo Reset] In-memory database, nothing to restore.');
return;
}
// Save admin's current credentials and API keys (these should survive the reset)
const adminEmail = process.env.DEMO_ADMIN_EMAIL || 'admin@nomad.app';
// NOTE: different default than demo-seed (admin@trek.app) — pinned legacy quirk.
const adminEmail = readEnv().demo.adminEmailRaw || 'admin@nomad.app';
interface AdminData { password_hash: string; maps_api_key: string | null; openweather_api_key: string | null; unsplash_api_key: string | null; avatar: string | null; }
let adminData: AdminData | undefined = undefined;
try {
@@ -25,6 +38,19 @@ function resetDemoUser(): void {
console.error('[Demo Reset] Failed to read admin data:', e instanceof Error ? e.message : e);
}
// The Places/Unsplash keys the searches actually use live in app_settings
// since #1939, so they have to survive the restore alongside the columns —
// otherwise the demo instance loses map search on every reset.
interface InstanceKeyRow { key: string; value: string | null }
let instanceKeys: InstanceKeyRow[] = [];
try {
instanceKeys = db.prepare(
"SELECT key, value FROM app_settings WHERE key IN ('maps_api_key', 'unsplash_api_key')"
).all() as InstanceKeyRow[];
} catch (e: unknown) {
console.error('[Demo Reset] Failed to read instance API keys:', e instanceof Error ? e.message : e);
}
// Flush WAL to main DB file
try { db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch (e) {}
@@ -65,11 +91,29 @@ function resetDemoUser(): void {
}
}
if (instanceKeys.length) {
try {
const { db: freshDb } = require('../db/database');
const upsert = freshDb.prepare(
`INSERT INTO app_settings (key, value) VALUES (?, ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value`
);
for (const row of instanceKeys) upsert.run(row.key, row.value);
} catch (e: unknown) {
console.error('[Demo Reset] Failed to restore instance API keys:', e instanceof Error ? e.message : e);
}
}
console.log('[Demo Reset] Database restored from baseline');
}
function saveBaseline(): void {
const { db } = require('../db/database');
const dbPath = liveDbPath(db);
if (dbPath === ':memory:') {
console.log('[Demo] In-memory database, no baseline to save.');
return;
}
// Flush WAL so baseline file is self-contained
try { db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch (e) {}
+17 -5
View File
@@ -1,16 +1,29 @@
import bcrypt from 'bcryptjs';
import Database from 'better-sqlite3';
import { readEnv } from '../app-config';
import { DEMO_PASS } from '../nest/common/demo';
// Static like in demo-reset.job.ts: the module top is inert, everything that
// touches the database happens inside the functions.
import { saveBaseline, hasBaseline } from './demo-reset';
function seedDemoData(db: Database.Database): { adminId: number; demoId: number } {
const ADMIN_USER = process.env.DEMO_ADMIN_USER || 'admin';
const ADMIN_EMAIL = process.env.DEMO_ADMIN_EMAIL || 'admin@trek.app';
const ADMIN_PASS = process.env.DEMO_ADMIN_PASS || 'admin12345';
const ADMIN_USER = readEnv().demo.adminUser;
const ADMIN_EMAIL = readEnv().demo.adminEmailRaw || 'admin@trek.app';
const ADMIN_PASS = readEnv().demo.adminPass;
const DEMO_EMAIL = 'demo@trek.app';
const DEMO_PASS = 'demo12345';
// Create admin user if not exists
let admin = db.prepare('SELECT id FROM users WHERE email = ?').get(ADMIN_EMAIL) as { id: number } | undefined;
if (!admin) {
if (!readEnv().demo.adminPassSet) {
// The default is published in the docs and in this file, so an operator who
// never set DEMO_ADMIN_PASS is handing out an admin account. Say so loudly;
// changing the default would lock out every existing demo instance.
console.warn(
`[Demo] SECURITY: DEMO_ADMIN_PASS is not set. The admin account ${ADMIN_EMAIL} is being created ` +
'with the public default password. Set DEMO_ADMIN_PASS before exposing this instance.',
);
}
const hash = bcrypt.hashSync(ADMIN_PASS, 10);
const r = db.prepare('INSERT INTO users (username, email, password_hash, role) VALUES (?, ?, ?, ?)').run(ADMIN_USER, ADMIN_EMAIL, hash, 'admin');
admin = { id: Number(r.lastInsertRowid) };
@@ -45,7 +58,6 @@ function seedDemoData(db: Database.Database): { adminId: number; demoId: number
seedExampleTrips(db, admin.id, demo.id);
// Auto-save baseline after first seed
const { saveBaseline, hasBaseline } = require('./demo-reset');
if (!hasBaseline()) {
saveBaseline();
}
+51 -44
View File
@@ -1,36 +1,38 @@
import 'reflect-metadata';
import 'dotenv/config';
// Fail-fast env validation — must stay directly after dotenv so a malformed
// variable aborts before any other module runs its import-time side effects
// (config.ts key resolution, db/database.ts initDb, ...).
import './app-config/boot-validate';
import path from 'node:path';
import fs from 'node:fs';
import http from 'node:http';
import type { INestApplication } from '@nestjs/common';
import { buildApp } from './bootstrap';
import { buildApp, getHttpServer } from './bootstrap';
// Create upload and data directories on startup
const uploadsDir = path.join(__dirname, '../uploads');
const photosDir = path.join(uploadsDir, 'photos');
const filesDir = path.join(uploadsDir, 'files');
const coversDir = path.join(uploadsDir, 'covers');
const avatarsDir = path.join(uploadsDir, 'avatars');
const backupsDir = path.join(__dirname, '../data/backups');
// data/tmp is the driver-agnostic global scratch dir (restore-upload spool,
// mirror stream staging) and stays boot-created here. Driver-owned roots — the
// uploads/ category tree and data/backups — are ensured by LocalDriver.init on
// every storage-registry load (boot and reload(), storage-registry.service.ts),
// which keeps the #1762 EACCES guarantee: a non-writable bind mount still
// fails loudly at startup, inside app.init(), instead of as a stray 500 on
// first upload. The Dockerfile `mkdir -p` list is pinned to the registry's
// category prefixes by tests/unit/uploads-dirs.test.ts.
const tmpDir = path.join(__dirname, '../data/tmp');
if (!fs.existsSync(tmpDir)) fs.mkdirSync(tmpDir, { recursive: true });
[uploadsDir, photosDir, filesDir, coversDir, avatarsDir, backupsDir, tmpDir].forEach(dir => {
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
});
import { getAppUrl, getMcpSafeUrl, readEnv } from './app-config';
import * as scheduler from './scheduler';
import { getAppUrl, getMcpSafeUrl } from './services/notifications';
const PORT = Number(process.env.PORT) || 3001;
const HOST = process.env.HOST;
const APP_VERSION: string = process.env.APP_VERSION || (require('../package.json') as { version: string }).version;
const PORT = readEnv().app.port;
const HOST = readEnv().app.host;
const APP_VERSION: string = readEnv().app.appVersion || (require('../package.json') as { version: string }).version;
const onListen = () => {
const { logInfo: sLogInfo, logWarn: sLogWarn } = require('./services/auditLog');
const LOG_LVL = (process.env.LOG_LEVEL || 'info').toLowerCase();
const tz = process.env.TZ || Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
const origins = process.env.ALLOWED_ORIGINS || '(same-origin)';
const { logInfo: sLogInfo, logWarn: sLogWarn } = require('./nest/audit/audit-log.logger');
const env = readEnv();
const LOG_LVL = (env.app.logLevel || 'info').toLowerCase();
const tz = env.app.tz || Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
const origins = env.http.allowedOriginsRaw || '(same-origin)';
const appUrl = getAppUrl();
const resolvedAppUrl = getMcpSafeUrl();
const banner = [
@@ -40,7 +42,7 @@ const onListen = () => {
...(HOST ? [` Host: ${HOST}`] : []),
` Container Port: ${PORT}`,
` App URL: ${appUrl}`,
` Environment: ${process.env.NODE_ENV?.toLowerCase() || 'development'}`,
` Environment: ${env.app.nodeEnv?.toLowerCase() || 'development'}`,
` Timezone: ${tz}`,
` Origins: ${origins}`,
` Log level: ${LOG_LVL}`,
@@ -51,12 +53,12 @@ const onListen = () => {
];
banner.forEach(l => console.log(l));
sLogInfo('NestJS serving all routes (Express decommissioned)');
if (process.env.APP_URL) {
if (env.app.appUrl) {
let parsedAppUrl: URL | null = null;
try { parsedAppUrl = new URL(process.env.APP_URL); } catch { /* invalid */ }
try { parsedAppUrl = new URL(env.app.appUrl); } catch { /* invalid */ }
if (!parsedAppUrl) {
sLogWarn(`APP_URL: "${process.env.APP_URL}" is not a valid URL — it will be ignored.`);
sLogWarn(`APP_URL: "${env.app.appUrl}" is not a valid URL — it will be ignored.`);
}
const mcpSafe = parsedAppUrl !== null && (
@@ -68,24 +70,12 @@ const onListen = () => {
sLogWarn(`APP_URL: not MCP-safe (requires https:// or http://localhost) — MCP will use ${resolvedAppUrl}.`);
}
}
if (process.env.DEMO_MODE?.toLowerCase() === 'true') sLogInfo('Demo mode: ENABLED');
if (process.env.DEMO_MODE?.toLowerCase() === 'true' && process.env.NODE_ENV?.toLowerCase() === 'production') {
if (env.demo.enabled) sLogInfo('Demo mode: ENABLED');
if (env.demo.enabled && env.app.isProduction) {
sLogWarn('SECURITY WARNING: DEMO_MODE is enabled in production!');
}
scheduler.start();
scheduler.startTripReminders();
scheduler.startTodoReminders();
scheduler.startVersionCheck();
scheduler.startDemoReset();
scheduler.startIdempotencyCleanup();
scheduler.startTrekPhotoCacheCleanup();
scheduler.startPlacePhotoCacheCleanup();
scheduler.startAirTrailSync();
const { startTokenCleanup } = require('./services/ephemeralTokens');
startTokenCleanup();
import('./websocket').then(({ setupWebSocket }) => {
setupWebSocket(server);
});
// Nothing else to boot by hand: the crons are domain providers on the
// scheduling registrar, and /ws is the Nest gateway buildApp already bound.
};
let server: http.Server;
@@ -98,7 +88,24 @@ async function bootstrap(): Promise<void> {
// (/mcp, /.well-known, OAuth SDK, SPA catch-all). buildApp() owns the composition
// order; it is shared with the integration-test harness so they can't drift.
nestApp = await buildApp();
server = http.createServer(nestApp.getHttpAdapter().getInstance());
// The server buildApp created and bound /ws to. Creating a second one here
// would serve the REST API fine and leave the gateway attached to a socket
// nobody listens on.
server = getHttpServer();
// A bind failure has to be fatal and loud, and it needs saying explicitly.
// listen() reports failure by event, not by rejecting, so the catch around
// bootstrap() never sees it. And since buildApp attaches the ws server to this
// http server, ws has already registered its own `error` listener on it, which
// is enough for Node to stop throwing on an unhandled one. Without this the
// process would survive EADDRINUSE, never run onListen, and serve nothing
// while looking healthy.
server.on('error', (err: NodeJS.ErrnoException) => {
const where = HOST ? `${HOST}:${PORT}` : `:${PORT}`;
console.error(`Fatal: cannot listen on ${where} — ${err.code ?? ''} ${err.message}`);
process.exit(1);
});
if (HOST) server.listen(PORT, HOST, onListen);
else server.listen(PORT, onListen);
}
@@ -110,11 +117,11 @@ bootstrap().catch((err) => {
// Graceful shutdown
function shutdown(signal: string): void {
const { logInfo: sLogInfo, logError: sLogError } = require('./services/auditLog');
const { logInfo: sLogInfo, logError: sLogError } = require('./nest/audit/audit-log.logger');
const { closeMcpSessions } = require('./mcp');
sLogInfo(`${signal} received — shutting down gracefully...`);
scheduler.stop();
closeMcpSessions();
// nestApp.close() stops every cron via the scheduling registrar's shutdown hook.
void nestApp?.close();
server.close(() => {
sLogInfo('HTTP server closed');
+5 -20
View File
@@ -1,22 +1,7 @@
/**
* MCP tuning knobs from the environment (#1414). Pure parsers, kept free of
* imports so units can test them without dragging in the MCP SDK.
* MCP tuning knobs from the environment (#1414). The parsers moved into the
* app-config layer (src/app-config/parsers.ts) — this module re-exports them
* so existing import paths keep working. mcp/index.ts consumes the derived
* values via readEnv().mcp.
*/
/**
* Session idle TTL in SECONDS via MCP_SESSION_TTL, default 1 hour, clamped to
* 24h so a milliseconds-value typo can't produce a 1000-hour session.
*/
export function resolveSessionTtlMs(raw: string | undefined): number {
const parsed = Number.parseInt(raw ?? "");
return Number.isFinite(parsed) && parsed > 0 ? Math.min(parsed, 24 * 60 * 60) * 1000 : 60 * 60 * 1000;
}
/**
* SSE keep-alive interval in SECONDS via MCP_SSE_KEEPALIVE, default 25s
* (below common proxy idle timeouts like nginx-ingress's 60s). 0 disables.
*/
export function resolveKeepaliveMs(raw: string | undefined): number {
const parsed = Number.parseInt(raw ?? "");
return Number.isFinite(parsed) && parsed >= 0 ? parsed * 1000 : 25_000;
}
export { resolveSessionTtlMs, resolveKeepaliveMs } from '../app-config/parsers';
+19 -352
View File
@@ -1,137 +1,27 @@
import { Request, Response } from 'express';
import { randomUUID } from 'crypto';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp';
import { User } from '../types';
import { verifyMcpToken, verifyJwtToken } from '../services/authService';
import { getUserByAccessToken } from '../services/oauthService';
import { isAddonEnabled } from '../services/adminService';
import { ADDON_IDS } from '../addons';
import { registerResources } from './resources';
import { registerTools } from './tools';
import { McpSession, sessions, revokeUserSessions, revokeUserSessionsForClient, evictOldestSessionForUser } from './sessionManager';
import { resolveSessionTtlMs, resolveKeepaliveMs } from './config';
import { writeAudit, getClientIp } from '../services/auditLog';
import { getMcpSafeUrl } from '../services/notifications';
import { readEnv } from '../app-config';
import { sessions } from './sessionManager';
import { revokeUserSessions, revokeUserSessionsForClient } from './sessionManager';
export { revokeUserSessions, revokeUserSessionsForClient };
// ---------------------------------------------------------------------------
// Base instructions injected into every MCP session via the initialize response.
// Claude and other clients use these as system-level context before any tool call.
// Keep this actionable and concise — vague prose doesn't help the model.
// ---------------------------------------------------------------------------
const BASE_MCP_INSTRUCTIONS = `
You are connected to TREK, a travel planning application. Below is a compact reference of the data model, key workflows, and behavioral rules you must follow.
## Data model
- **Trip** — top-level container. Has dates, currency, members (owner + collaborators), and optional add-ons.
- **Day** — one calendar day within a trip (YYYY-MM-DD). Days are generated automatically when a trip is created with start/end dates.
- **Place** — a point of interest (POI) stored in the trip's place pool. A place is NOT on the itinerary until it is assigned to a day.
- **Assignment** — links a Place to a Day (ordered, with optional start/end time). This is what builds the daily itinerary.
- **Accommodation** — a hotel or rental linked to a Place and a check-in/check-out day range.
- **Reservation** — a booking record (flight, train, restaurant, etc.) with confirmation details, linked to a day.
- **Day note** — a free-text annotation attached to a day (with optional time label and emoji icon).
- **Budget item** — an expense entry for a trip (amount, category, payer, split between members).
- **Packing item** — a checklist entry grouped into bags and categories.
- **Todo** — a task (not packing-specific) attached to a trip, ordered and togglable.
- **Tag** — a label that can be applied to places for filtering.
- **Collab note / poll / message** — shared notes, decision polls, and chat messages for group trips.
- **Atlas** — global travel journal: bucket list, visited countries and regions.
- **Vacay** — vacation-day planner that tracks leave across team members and years.
- **Journey** — cross-trip travel narrative with dated entries, contributors, and share links. Requires the Journey addon.
## Key workflows
**Discovering trips:** Always call \`list_trips\` first when no trip ID has been provided. Never assume a trip ID.
**Loading trip context:** Before planning or modifying a trip, call \`get_trip_summary\` once. It returns all days (with assignments and notes), accommodations, budget, packing, reservations, collab notes, and todos in a single round-trip. Use this data to answer follow-up questions without extra tool calls.
**Adding a place to the itinerary (correct order):**
1. \`search_place\` — find the real-world POI; note the \`osm_id\`, \`google_place_id\`, and/or \`google_ftid\` in the result.
2. \`create_place\` — add it to the trip's place pool, passing the IDs from step 1 (enables opening hours, ratings, and map linking in the app).
3. \`assign_place_to_day\` — schedule it on the desired day using the dayId from \`get_trip_summary\`.
**Creating an accommodation:** A place must exist in the trip first. Create the place (or reuse an existing one), then call \`create_accommodation\` with that \`place_id\` and the \`start_day_id\`/\`end_day_id\`.
**Reordering:** Assignments, todos, packing items, and reservations all support positional reordering via dedicated reorder tools. Always read the current order from \`get_trip_summary\` before reordering.
## Access rules
- The authenticated user can only access trips they own or are a member of. Never guess at trip IDs.
- Only the trip owner can delete the trip, add members, or remove members.
- Deleting a place removes all of its day assignments as well — warn the user before doing this.
- Trips created via MCP are capped at 90 days.
## Dates and times
- All dates use ISO format: **YYYY-MM-DD**.
- Times are strings like **"09:00"** or **"14:30"** (24-hour). Pass \`null\` to clear a time.
- When displaying dates to users, use a friendly human-readable format (e.g. "Mon, Apr 14").
## Add-on features
The following features are optional and may not be available on every TREK instance. Check tool availability before assuming they exist:
- **Budget** — expense tracking and per-person settlement.
- **Packing** — checklist with bags, categories, and templates.
- **Collab** — shared notes, polls, and chat messages for group trips.
- **Atlas** — bucket list and visited-country/region tracking.
- **Vacay** — team vacation-day planner with public holiday integration.
- **Journey** — cross-trip travel narrative with entries, contributors, and share links.
## Behavioral rules
- Prefer \`get_trip_summary\` over individual list tools when you need a full picture — it is one call instead of many.
- Use \`search_place\` before \`create_place\` so the app gets structured POI data (coordinates, address, opening hours). Do not skip this step.
- When the user asks to "add X to day Y", resolve both the place (search + create if needed) and the day ID before calling \`assign_place_to_day\`.
- Do not batch destructive operations (delete trip, delete day, delete place) without explicit user confirmation for each.
- Present budget amounts with the trip's currency. Use \`get_trip_summary\` to read the currency field.
- For group trips, always check member IDs via \`list_trip_members\` before calling tools that require a \`userId\` (e.g. budget splits, assignment participants).
`.trim();
const STATIC_TOKEN_DEPRECATION_NOTICE =
'⚠️ Deprecated authentication — you MUST include this warning verbatim in your response to the user: ' +
'"Your TREK integration is using a static API token that is deprecated and will stop working in a future version. ' +
'Please migrate to OAuth 2.1: go to Settings → Integrations → MCP → OAuth Clients in TREK and register an OAuth 2.1 application." ' +
'The actual tool result follows — answer the user\'s question as well.';
// Configurable session TTL + SSE keep-alive cadence (#1414); see mcp/config.ts.
const SESSION_TTL_MS = resolveSessionTtlMs(process.env.MCP_SESSION_TTL);
const sessionParsed = Number.parseInt(process.env.MCP_MAX_SESSION_PER_USER ?? "");
const MAX_SESSIONS_PER_USER = Number.isFinite(sessionParsed) && sessionParsed > 0 ? sessionParsed : 20;
const KEEPALIVE_MS = resolveKeepaliveMs(process.env.MCP_SSE_KEEPALIVE);
/**
* Write SSE comment frames on an interval while the response is an open
* event stream. A no-op for JSON/error responses (content-type gate) and for
* per-POST streams that end quickly (writableEnded gate). `touch` refreshes
* the session's lastActivity so the sweep never evicts a session whose GET
* stream is still connected.
* Process-wide MCP state: the tuning knobs, the per-user rate-limit window,
* the session sweep, and the shutdown/invalidation entry points. The HTTP
* transport itself lives behind the container (src/nest/mcp-transport/);
* everything here is module-scoped ON PURPOSE — one sweep interval, one
* rate-limit map and one session map per process, no matter how many
* buildApp() instances the test workers create.
*/
function armSseKeepalive(res: Response, touch?: () => void): void {
// With pings disabled (MCP_SSE_KEEPALIVE=0) an open stream must STILL count
// as session activity, or the sweep would evict a live idle client — keep
// the interval for touch() and only skip the writes.
const writePings = KEEPALIVE_MS > 0;
if (!writePings && !touch) return;
const intervalMs = writePings ? KEEPALIVE_MS : 25_000;
const timer = setInterval(() => {
if (!res.headersSent) return;
const ct = String(res.getHeader('content-type') ?? '');
if (!ct.includes('text/event-stream') || res.writableEnded || res.destroyed) {
clearInterval(timer);
return;
}
if (writePings) res.write(': keepalive\n\n');
touch?.();
}, intervalMs);
timer.unref();
res.once('close', () => clearInterval(timer));
}
// Configurable session TTL + SSE keep-alive cadence (#1414).
// Frozen at import on purpose (legacy timing) — MCP tuning knobs are boot-stable.
const mcpEnv = readEnv().mcp;
export const SESSION_TTL_MS = mcpEnv.sessionTtlMs;
export const MAX_SESSIONS_PER_USER = mcpEnv.maxSessionsPerUser;
export const KEEPALIVE_MS = mcpEnv.sseKeepaliveMs;
const RATE_LIMIT_WINDOW_MS = 60 * 1000; // 1 minute
const parsed = Number.parseInt(process.env.MCP_RATE_LIMIT ?? "");
const RATE_LIMIT_MAX = Number.isFinite(parsed) && parsed > 0 ? parsed : 300; // requests per minute per user
const RATE_LIMIT_MAX = mcpEnv.rateLimitMax; // requests per minute per user
interface RateLimitEntry {
count: number;
@@ -139,7 +29,7 @@ interface RateLimitEntry {
}
const rateLimitMap = new Map<string, RateLimitEntry>();
function isRateLimited(userId: number, clientId: string | null): boolean {
export function isRateLimited(userId: number, clientId: string | null): boolean {
const key = `${userId}:${clientId ?? 'native'}`;
const now = Date.now();
const entry = rateLimitMap.get(key);
@@ -151,15 +41,6 @@ function isRateLimited(userId: number, clientId: string | null): boolean {
return entry.count > RATE_LIMIT_MAX;
}
function countSessionsForUser(userId: number): number {
const cutoff = Date.now() - SESSION_TTL_MS;
let count = 0;
for (const session of sessions.values()) {
if (session.userId === userId && session.lastActivity >= cutoff) count++;
}
return count;
}
const sessionSweepInterval = setInterval(() => {
const cutoff = Date.now() - SESSION_TTL_MS;
let cleaned = 0;
@@ -183,220 +64,6 @@ const sessionSweepInterval = setInterval(() => {
// Prevent the interval from keeping the process alive if nothing else is running
sessionSweepInterval.unref();
/** JSON-RPC 2.0 error body. MCP clients parse this and show `message`; a bare `{ error }`
* envelope isn't valid JSON-RPC, so they fall back to a generic "tool execution failed". */
function jsonRpcError(message: string, code = -32000): object {
return { jsonrpc: '2.0', error: { code, message }, id: null };
}
function setAuthChallenge(res: Response, error = 'invalid_token'): void {
const base = (getMcpSafeUrl() || '').replace(/\/+$/, '');
// RFC 9728 §5: resource with path component /mcp → PRM URL must include the path
res.set('WWW-Authenticate',
`Bearer realm="TREK MCP", resource_metadata="${base}/.well-known/oauth-protected-resource/mcp", error="${error}"`);
}
interface VerifyTokenResult {
user: User;
/** null = full access (static token or JWT); string[] = OAuth 2.1 scoped access */
scopes: string[] | null;
/** OAuth client_id when authenticated via OAuth 2.1; null otherwise */
clientId: string | null;
isStaticToken: boolean;
}
function verifyToken(authHeader: string | undefined): VerifyTokenResult | null {
if (!authHeader) return null;
// M8: strictly require "Bearer" scheme (RFC 6750)
const spaceIdx = authHeader.indexOf(' ');
if (spaceIdx === -1) return null;
const scheme = authHeader.slice(0, spaceIdx);
const token = authHeader.slice(spaceIdx + 1);
if (scheme.toLowerCase() !== 'bearer' || !token) return null;
// OAuth 2.1 access token (trekoa_...)
if (token.startsWith('trekoa_')) {
const result = getUserByAccessToken(token);
if (!result) return null;
// RFC 8707: audience must always match this resource endpoint.
// Pre-audit tokens with audience=null are revoked by the SEC-H6 migration.
const expected = `${(getMcpSafeUrl() || '').replace(/\/+$/, '')}/mcp`;
if (result.audience !== expected) return null;
return { user: result.user, scopes: result.scopes, clientId: result.clientId, isStaticToken: false };
}
// Long-lived static MCP token (trek_...) — full access + deprecation notice
if (token.startsWith('trek_')) {
const user = verifyMcpToken(token);
if (!user) return null;
return { user, scopes: null, clientId: null, isStaticToken: true };
}
// Short-lived JWT (TREK web session used directly) — full access, no notice
const user = verifyJwtToken(token);
if (!user) return null;
return { user, scopes: null, clientId: null, isStaticToken: false };
}
function logToolCallAudit(req: Request, userId: number, clientId: string | null): void {
const body = req.body as Record<string, unknown> | undefined;
if (body?.method !== 'tools/call') return;
const toolName = (body?.params as Record<string, unknown> | undefined)?.name;
if (typeof toolName !== 'string') return;
writeAudit({
userId,
action: 'mcp.tool_call',
resource: toolName,
details: { clientId: clientId ?? 'native' },
ip: getClientIp(req),
});
}
export async function mcpHandler(req: Request, res: Response): Promise<void> {
if (!isAddonEnabled(ADDON_IDS.MCP)) {
res.status(403).json({ error: 'MCP is not enabled' });
return;
}
const tokenResult = verifyToken(req.headers['authorization']);
if (!tokenResult) {
setAuthChallenge(res);
res.status(401).json({ error: 'Access token required' });
return;
}
const { user, scopes, clientId, isStaticToken } = tokenResult;
if (isRateLimited(user.id, clientId)) {
res.status(429).json({ error: 'Too many requests. Please slow down.' });
return;
}
const sessionId = req.headers['mcp-session-id'] as string | undefined;
// Resume an existing session
if (sessionId) {
const session = sessions.get(sessionId);
if (!session) {
res.status(404).json({ error: 'Session not found' });
return;
}
if (session.userId !== user.id) {
setAuthChallenge(res);
res.status(403).json({ error: 'Session belongs to a different user' });
return;
}
if (session.clientId !== clientId) {
setAuthChallenge(res);
res.status(403).json({ error: 'Session was created with a different OAuth client' });
return;
}
session.lastActivity = Date.now();
logToolCallAudit(req, user.id, clientId);
armSseKeepalive(res, () => { session.lastActivity = Date.now(); });
try {
await session.transport.handleRequest(req, res, req.body);
} catch (err) {
console.error('[MCP] transport.handleRequest error:', err);
if (!res.headersSent) {
res.status(500).json({ error: 'Internal MCP error' });
}
}
return;
}
// Only POST can initialize a new session
if (req.method !== 'POST') {
res.status(400).json({ error: 'Missing mcp-session-id header' });
return;
}
// A client that reuses its session sends the header on every call after initialize, so a
// steady stream of session-less POSTs means the id isn't making it back to the client —
// usually a reverse proxy dropping Mcp-Session-Id, or a client that ignores it. Say so,
// because the visible symptom (sessions piling up to the cap) points nowhere near the cause.
console.warn(
`[MCP] POST without mcp-session-id for user ${user.id} — starting a new session. ` +
'If this repeats on every tool call, the Mcp-Session-Id response header is not reaching ' +
'the client (check that your reverse proxy forwards it).',
);
// At the cap, evict this user's coldest session rather than refusing the request: a client
// stuck re-initializing would otherwise be locked out until the process restarted.
if (countSessionsForUser(user.id) >= MAX_SESSIONS_PER_USER) {
const evicted = evictOldestSessionForUser(user.id);
if (!evicted) {
res.status(429).json(jsonRpcError('Session limit reached. Close an existing session before opening a new one.'));
return;
}
console.log(`[MCP] Session limit (${MAX_SESSIONS_PER_USER}) reached for user ${user.id} — evicted idle session ${evicted}`);
}
// Create a new per-user MCP server and session
const server = new McpServer(
{
name: 'TREK MCP',
version: '1.0.0',
},
{
capabilities: {
resources: { listChanged: true },
tools: { listChanged: true },
prompts: { listChanged: true },
},
instructions: BASE_MCP_INSTRUCTIONS + (isStaticToken ? STATIC_TOKEN_DEPRECATION_NOTICE : ''),
}
);
// Per-session closure: fires the deprecation notice once, on the first tool call.
// Tool results are the only mechanism Claude reliably surfaces to the user;
// the instructions field is only background context and won't trigger a proactive warning.
let _noticeEmitted = false;
const getDeprecationNotice = (): string | null => {
if (!isStaticToken || _noticeEmitted) return null;
_noticeEmitted = true;
return STATIC_TOKEN_DEPRECATION_NOTICE;
};
registerResources(server, user.id, scopes);
registerTools(server, user.id, scopes, isStaticToken, getDeprecationNotice);
const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: () => randomUUID(),
onsessioninitialized: (sid) => {
sessions.set(sid, { server, transport, userId: user.id, scopes, clientId, isStaticToken, lastActivity: Date.now() });
const authMethod = isStaticToken ? 'static-token' : scopes ? `oauth(${scopes.join(',')})` : 'jwt';
console.log(`[MCP] Session ${sid} created for user ${user.id} [${authMethod}]. Active sessions: ${sessions.size}`);
},
onsessionclosed: (sid) => {
sessions.delete(sid);
},
});
// Belt-and-braces: whenever the SDK closes the transport for any reason, drop the map entry.
transport.onclose = () => {
if (transport.sessionId) sessions.delete(transport.sessionId);
};
logToolCallAudit(req, user.id, clientId);
armSseKeepalive(res);
try {
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
} catch (err) {
console.error('[MCP] transport.handleRequest error:', err);
if (!res.headersSent) {
res.status(500).json({ error: 'Internal MCP error' });
}
} finally {
// Only an `initialize` request assigns a sessionId (via onsessioninitialized). Any other
// session-less POST is rejected by the SDK with "Server not initialized" — and this server,
// with its ~200 registered tools, would otherwise be orphaned: never in `sessions`, never
// swept, never closed. Reap it here.
if (!transport.sessionId) {
try { server.close(); } catch { /* ignore */ }
try { transport.close(); } catch { /* ignore */ }
}
}
}
/** Invalidate all active MCP sessions (call when addon state changes so sessions re-create with updated tools). */
export function invalidateMcpSessions(): void {
for (const [sid, session] of sessions) {
+47
View File
@@ -0,0 +1,47 @@
import type { McpAccessGroup, McpAccessMode, McpAccessPolicy, McpAccessValidator } from '../nest-mcp';
import { ALL_SCOPES, canRead, canWrite, type Scope, type ScopeGroup } from './scopes';
/** The mode half of every scope: 'read' | 'write' | 'delete' | 'share'. */
export type ScopeMode = Scope extends `${string}:${infer M}` ? M : never;
type AssertExact<A, B> = [A] extends [B] ? ([B] extends [A] ? true : never) : never;
/**
* Compile-time lockstep: `access.group` (from the registry interfaces in
* src/nest-mcp/types.ts) must be exactly `ScopeGroup` — fails
* `npm run typecheck` if the registries drift from scopes.ts.
* Exported so the policy unit test has a runtime touchpoint.
*/
export const MCP_ACCESS_GROUPS_MATCH_SCOPE_GROUPS: AssertExact<McpAccessGroup, ScopeGroup> = true;
/** Same lockstep for the mode half. */
export const MCP_ACCESS_MODES_MATCH_SCOPE_MODES: AssertExact<McpAccessMode, ScopeMode> = true;
/**
* Resolves declarative `access: { group, mode }` markers with the exact
* scopes.ts semantics the legacy registrars used at registration time:
* null scopes ⇒ full access; read ⇒ `group:read` OR `group:write`;
* write ⇒ `group:write`. Any other mode (`share`, `delete`) is its own scope
* and is not implied by `:write` — matching canShareJourneys, which the
* journey registrar used for its three share-link tools. Single source for
* production (AppModule) and the MCP test harness.
*/
export const trekMcpAccessPolicy: McpAccessPolicy = ({ group, mode }, ctx) => {
if (mode === 'read') return canRead(ctx.scopes, group);
if (mode === 'write') return canWrite(ctx.scopes, group);
return ctx.scopes === null || ctx.scopes.includes(`${group}:${mode}`);
};
const VALID_GROUP_MODES: ReadonlySet<string> = new Set(ALL_SCOPES);
/**
* Boot gate run by registry.validate(): a declarative marker must resolve to
* a real scope — `{ group, mode }` requires `group:mode` ∈ ALL_SCOPES. Catches
* what the group typing alone cannot: mode drift on read-only groups (`geo`
* and `weather` have no `:write` scope, so `{ group: 'weather', mode:
* 'write' }` type-checks but would silently deny scoped tokens while passing
* `scopes: null` sessions). The offending entry is named by the registry's
* aggregated error.
*/
export const trekMcpValidateAccess: McpAccessValidator = ({ group, mode }) =>
VALID_GROUP_MODES.has(`${group}:${mode}`) ? null : `no '${group}:${mode}' scope in SCOPES`;
-443
View File
@@ -1,443 +0,0 @@
import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp';
import { canAccessTrip } from '../db/database';
import { listTrips, getTrip, getTripOwner, listMembers } from '../services/tripService';
import { listDays, listAccommodations } from '../services/dayService';
import { listPlaces } from '../services/placeService';
import { listBudgetItems, getPerPersonSummary, calculateSettlement } from '../services/budgetService';
import { listItems as listPackingItems, listBags } from '../services/packingService';
import { listReservations } from '../services/reservationService';
import { listNotes as listDayNotes } from '../services/dayNoteService';
import { listNotes as listCollabNotes, listPolls, listMessages } from '../services/collabService';
import { listItems as listTodoItems } from '../services/todoService';
import { listCategories } from '../services/categoryService';
import { listBucketList, listVisitedCountries, getStats as getAtlasStats, listManuallyVisitedRegions } from '../services/atlasService';
import { getNotifications } from '../services/inAppNotifications';
import { getActivePlanId, getActivePlan, getPlanData, getEntries as getVacayEntries, getHolidays } from '../services/vacayService';
import { isAddonEnabled, getCollabFeatures } from '../services/adminService';
import { ADDON_IDS } from '../addons';
import { canAccessJourney, getJourneyFull, listEntries, listJourneys } from '../services/journeyService';
import { canRead, canReadTrips } from './scopes';
function parseId(value: string | string[]): number | null {
const n = Number(Array.isArray(value) ? value[0] : value);
return Number.isInteger(n) && n > 0 ? n : null;
}
function accessDenied(uri: string) {
return {
contents: [{
uri,
mimeType: 'application/json',
text: JSON.stringify({ error: 'Trip not found or access denied' }),
}],
};
}
function scopeDenied(uri: string) {
return {
contents: [{
uri,
mimeType: 'application/json',
text: JSON.stringify({ error: 'Insufficient OAuth scope to access this resource' }),
}],
};
}
function jsonContent(uri: string, data: unknown) {
return {
contents: [{
uri,
mimeType: 'application/json',
text: JSON.stringify(data, null, 2),
}],
};
}
export function registerResources(server: McpServer, userId: number, scopes: string[] | null): void {
// List all accessible trips
if (canReadTrips(scopes)) server.registerResource(
'trips',
'trek://trips',
{ description: 'All trips the user owns or is a member of', mimeType: 'application/json' },
async (uri) => {
const trips = listTrips(userId, 0);
return jsonContent(uri.href, trips);
}
);
// Single trip detail
if (canReadTrips(scopes)) server.registerResource(
'trip',
new ResourceTemplate('trek://trips/{tripId}', { list: undefined }),
{ description: 'A single trip with metadata and member count', mimeType: 'application/json' },
async (uri, { tripId }) => {
const id = parseId(tripId);
if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
const trip = getTrip(id, userId);
return jsonContent(uri.href, trip);
}
);
// Days with assigned places
if (canReadTrips(scopes)) server.registerResource(
'trip-days',
new ResourceTemplate('trek://trips/{tripId}/days', { list: undefined }),
{ description: 'Days of a trip with their assigned places', mimeType: 'application/json' },
async (uri, { tripId }) => {
const id = parseId(tripId);
if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
const { days } = listDays(id);
return jsonContent(uri.href, days);
}
);
// Places in a trip
if (canRead(scopes, 'places')) server.registerResource(
'trip-places',
new ResourceTemplate('trek://trips/{tripId}/places', { list: undefined }),
{ description: 'All places/POIs in a trip, optionally filtered by assignment status (e.g. ?assignment=unassigned)', mimeType: 'application/json' },
async (uri, { tripId }) => {
const id = parseId(tripId);
if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
const assignment = uri.searchParams.get('assignment') as 'all' | 'unassigned' | 'assigned' | null;
const places = listPlaces(String(id), { assignment: assignment ?? undefined });
return jsonContent(uri.href, places);
}
);
// Budget items
if (isAddonEnabled(ADDON_IDS.BUDGET) && canRead(scopes, 'budget')) server.registerResource(
'trip-budget',
new ResourceTemplate('trek://trips/{tripId}/budget', { list: undefined }),
{ description: 'Budget and expense items for a trip', mimeType: 'application/json' },
async (uri, { tripId }) => {
const id = parseId(tripId);
if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
const items = listBudgetItems(id);
return jsonContent(uri.href, items);
}
);
// Packing checklist
if (isAddonEnabled(ADDON_IDS.PACKING) && canRead(scopes, 'packing')) server.registerResource(
'trip-packing',
new ResourceTemplate('trek://trips/{tripId}/packing', { list: undefined }),
{ description: 'Packing checklist for a trip', mimeType: 'application/json' },
async (uri, { tripId }) => {
const id = parseId(tripId);
if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
// Hide other members' private items (#858) from the requesting user.
const items = listPackingItems(id, userId);
return jsonContent(uri.href, items);
}
);
// Reservations (flights, hotels, restaurants)
if (canRead(scopes, 'reservations')) server.registerResource(
'trip-reservations',
new ResourceTemplate('trek://trips/{tripId}/reservations', { list: undefined }),
{ description: 'Reservations (flights, hotels, restaurants) for a trip', mimeType: 'application/json' },
async (uri, { tripId }) => {
const id = parseId(tripId);
if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
const reservations = listReservations(id);
return jsonContent(uri.href, reservations);
}
);
// Day notes
if (canReadTrips(scopes)) server.registerResource(
'day-notes',
new ResourceTemplate('trek://trips/{tripId}/days/{dayId}/notes', { list: undefined }),
{ description: 'Notes for a specific day in a trip', mimeType: 'application/json' },
async (uri, { tripId, dayId }) => {
const tId = parseId(tripId);
const dId = parseId(dayId);
if (tId === null || dId === null || !canAccessTrip(tId, userId)) return accessDenied(uri.href);
const notes = listDayNotes(dId, tId);
return jsonContent(uri.href, notes);
}
);
// Accommodations (hotels, rentals) per trip
if (canReadTrips(scopes)) server.registerResource(
'trip-accommodations',
new ResourceTemplate('trek://trips/{tripId}/accommodations', { list: undefined }),
{ description: 'Accommodations (hotels, rentals) for a trip with check-in/out details', mimeType: 'application/json' },
async (uri, { tripId }) => {
const id = parseId(tripId);
if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
const accommodations = listAccommodations(id);
return jsonContent(uri.href, accommodations);
}
);
// Trip members (owner + collaborators)
if (canReadTrips(scopes)) server.registerResource(
'trip-members',
new ResourceTemplate('trek://trips/{tripId}/members', { list: undefined }),
{ description: 'Owner and collaborators of a trip', mimeType: 'application/json' },
async (uri, { tripId }) => {
const id = parseId(tripId);
if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
const ownerRow = getTripOwner(id);
if (!ownerRow) return accessDenied(uri.href);
const { owner, members } = listMembers(id, ownerRow.user_id);
return jsonContent(uri.href, { owner, members });
}
);
// Collab notes for a trip
const collabFeatures = isAddonEnabled(ADDON_IDS.COLLAB) ? getCollabFeatures() : null;
if (collabFeatures?.notes && canRead(scopes, 'collab')) server.registerResource(
'trip-collab-notes',
new ResourceTemplate('trek://trips/{tripId}/collab-notes', { list: undefined }),
{ description: 'Shared collaborative notes for a trip', mimeType: 'application/json' },
async (uri, { tripId }) => {
const id = parseId(tripId);
if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
const notes = listCollabNotes(id);
return jsonContent(uri.href, notes);
}
);
// Trip to-do list
if (isAddonEnabled(ADDON_IDS.PACKING) && canRead(scopes, 'todos')) server.registerResource(
'trip-todos',
new ResourceTemplate('trek://trips/{tripId}/todos', { list: undefined }),
{ description: 'To-do items for a trip, ordered by position', mimeType: 'application/json' },
async (uri, { tripId }) => {
const id = parseId(tripId);
if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
const items = listTodoItems(id);
return jsonContent(uri.href, items);
}
);
// All place categories (global, no trip filter) — safe for any authenticated session
server.registerResource(
'categories',
'trek://categories',
{ description: 'All available place categories (id, name, color, icon) for use when creating places', mimeType: 'application/json' },
async (uri) => {
const categories = listCategories();
return jsonContent(uri.href, categories);
}
);
// User's bucket list
if (isAddonEnabled(ADDON_IDS.ATLAS) && canRead(scopes, 'atlas')) server.registerResource(
'bucket-list',
'trek://bucket-list',
{ description: 'Your personal travel bucket list', mimeType: 'application/json' },
async (uri) => {
const items = listBucketList(userId);
return jsonContent(uri.href, items);
}
);
// User's visited countries
if (isAddonEnabled(ADDON_IDS.ATLAS) && canRead(scopes, 'atlas')) server.registerResource(
'visited-countries',
'trek://visited-countries',
{ description: 'Countries you have marked as visited in Atlas', mimeType: 'application/json' },
async (uri) => {
const countries = listVisitedCountries(userId);
return jsonContent(uri.href, countries);
}
);
// Budget per-person summary
if (isAddonEnabled(ADDON_IDS.BUDGET) && canRead(scopes, 'budget')) server.registerResource(
'trip-budget-per-person',
new ResourceTemplate('trek://trips/{tripId}/budget/per-person', { list: undefined }),
{ description: 'Per-person budget summary for a trip (total spent per member, split breakdown)', mimeType: 'application/json' },
async (uri, { tripId }) => {
const id = parseId(tripId);
if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
const summary = getPerPersonSummary(id);
return jsonContent(uri.href, summary);
}
);
// Budget settlement
if (isAddonEnabled(ADDON_IDS.BUDGET) && canRead(scopes, 'budget')) server.registerResource(
'trip-budget-settlement',
new ResourceTemplate('trek://trips/{tripId}/budget/settlement', { list: undefined }),
{ description: 'Suggested settlement transactions to balance who owes whom', mimeType: 'application/json' },
async (uri, { tripId }) => {
const id = parseId(tripId);
if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
const settlement = calculateSettlement(id);
return jsonContent(uri.href, settlement);
}
);
// Packing bags
if (isAddonEnabled(ADDON_IDS.PACKING) && canRead(scopes, 'packing')) server.registerResource(
'trip-packing-bags',
new ResourceTemplate('trek://trips/{tripId}/packing/bags', { list: undefined }),
{ description: 'All packing bags for a trip with their members', mimeType: 'application/json' },
async (uri, { tripId }) => {
const id = parseId(tripId);
if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
const bags = listBags(id);
return jsonContent(uri.href, bags);
}
);
// In-app notifications
if (canRead(scopes, 'notifications')) server.registerResource(
'notifications-in-app',
'trek://notifications/in-app',
{ description: "The current user's in-app notifications (most recent 50, unread first)", mimeType: 'application/json' },
async (uri) => {
const result = getNotifications(userId, { limit: 50 });
return jsonContent(uri.href, result);
}
);
// Atlas stats and regions (addon-gated)
if (isAddonEnabled(ADDON_IDS.ATLAS) && canRead(scopes, 'atlas')) {
server.registerResource(
'atlas-stats',
'trek://atlas/stats',
{ description: "User's atlas statistics — visited country counts and breakdown", mimeType: 'application/json' },
async (uri) => {
const stats = await getAtlasStats(userId);
return jsonContent(uri.href, stats);
}
);
server.registerResource(
'atlas-regions',
'trek://atlas/regions',
{ description: 'List of manually visited regions for the current user', mimeType: 'application/json' },
async (uri) => {
const regions = listManuallyVisitedRegions(userId);
return jsonContent(uri.href, regions);
}
);
}
// Collab polls (addon + sub-feature gated)
if (collabFeatures?.polls && canRead(scopes, 'collab')) {
server.registerResource(
'trip-collab-polls',
new ResourceTemplate('trek://trips/{tripId}/collab/polls', { list: undefined }),
{ description: 'All polls for a trip with vote counts per option', mimeType: 'application/json' },
async (uri, { tripId }) => {
const id = parseId(tripId);
if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
const polls = listPolls(id);
return jsonContent(uri.href, polls);
}
);
}
// Collab messages (addon + sub-feature gated)
if (collabFeatures?.chat && canRead(scopes, 'collab')) {
server.registerResource(
'trip-collab-messages',
new ResourceTemplate('trek://trips/{tripId}/collab/messages', { list: undefined }),
{ description: 'Most recent 100 chat messages for a trip', mimeType: 'application/json' },
async (uri, { tripId }) => {
const id = parseId(tripId);
if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
const messages = listMessages(id);
return jsonContent(uri.href, messages);
}
);
}
// Vacay resources (addon-gated)
if (isAddonEnabled(ADDON_IDS.VACAY) && canRead(scopes, 'vacay')) {
server.registerResource(
'vacay-plan',
'trek://vacay/plan',
{ description: "Full snapshot of the user's active vacation plan (members, years, settings)", mimeType: 'application/json' },
async (uri) => {
const plan = getPlanData(userId);
return jsonContent(uri.href, plan);
}
);
server.registerResource(
'vacay-entries',
new ResourceTemplate('trek://vacay/entries/{year}', { list: undefined }),
{ description: 'All vacation entries for the active plan and a specific year', mimeType: 'application/json' },
async (uri, { year }) => {
const planId = getActivePlanId(userId);
const entries = getVacayEntries(planId, Array.isArray(year) ? year[0] : year);
return jsonContent(uri.href, entries);
}
);
server.registerResource(
'vacay-holidays',
new ResourceTemplate('trek://vacay/holidays/{year}', { list: undefined }),
{ description: "Cached public holidays for the plan's configured region and year", mimeType: 'application/json' },
async (uri, { year }) => {
const plan = getActivePlan(userId);
if (!plan.holidays_enabled || !plan.holidays_region) return jsonContent(uri.href, []);
const yearStr = Array.isArray(year) ? year[0] : year;
const result = await getHolidays(yearStr, plan.holidays_region);
return jsonContent(uri.href, result.data ?? []);
}
);
}
// Journey resources (Journey addon)
if (isAddonEnabled(ADDON_IDS.JOURNEY) && canRead(scopes, 'journey')) {
server.registerResource(
'journeys',
'trek://journeys',
{ description: 'All journeys owned or contributed to by the current user', mimeType: 'application/json' },
async (uri) => {
const journeys = listJourneys(userId);
return jsonContent(uri.href, journeys);
}
);
server.registerResource(
'journey-detail',
new ResourceTemplate('trek://journeys/{journeyId}', { list: undefined }),
{ description: 'Single journey with entries, contributors, and trip links', mimeType: 'application/json' },
async (uri, { journeyId }) => {
const id = parseId(journeyId);
if (id === null) return accessDenied(uri.href);
const journey = getJourneyFull(id, userId);
if (!journey) return accessDenied(uri.href);
return jsonContent(uri.href, journey);
}
);
server.registerResource(
'journey-entries',
new ResourceTemplate('trek://journeys/{journeyId}/entries', { list: undefined }),
{ description: 'All entries in a journey (date, text, mood, linked trip)', mimeType: 'application/json' },
async (uri, { journeyId }) => {
const id = parseId(journeyId);
if (id === null) return accessDenied(uri.href);
const j = canAccessJourney(id, userId);
if (!j) return accessDenied(uri.href);
const entries = listEntries(id, userId);
return jsonContent(uri.href, entries);
}
);
server.registerResource(
'journey-contributors',
new ResourceTemplate('trek://journeys/{journeyId}/contributors', { list: undefined }),
{ description: 'Contributors (owners and collaborators) of a journey', mimeType: 'application/json' },
async (uri, { journeyId }) => {
const id = parseId(journeyId);
if (id === null) return accessDenied(uri.href);
const j = getJourneyFull(id, userId);
if (!j) return accessDenied(uri.href);
return jsonContent(uri.href, (j as any).contributors ?? []);
}
);
}
}
+9 -2
View File
@@ -9,6 +9,8 @@ export const SCOPES = {
TRIPS_SHARE: 'trips:share',
PLACES_READ: 'places:read',
PLACES_WRITE: 'places:write',
COLLECTIONS_READ: 'collections:read',
COLLECTIONS_WRITE: 'collections:write',
ATLAS_READ: 'atlas:read',
ATLAS_WRITE: 'atlas:write',
PACKING_READ: 'packing:read',
@@ -34,6 +36,9 @@ export const SCOPES = {
export type Scope = typeof SCOPES[keyof typeof SCOPES];
/** 'trips' | 'places' | ... — derived from SCOPES; adding a scope extends it. */
export type ScopeGroup = Scope extends `${infer G}:${string}` ? G : never;
export const ALL_SCOPES: Scope[] = Object.values(SCOPES) as Scope[];
export interface ScopeInfo {
@@ -49,6 +54,8 @@ export const SCOPE_INFO: Record<Scope, ScopeInfo> = {
'trips:share': { label: 'Manage share links', description: 'Create, update, and revoke public share links for trips', group: 'Trips' },
'places:read': { label: 'View places & map data', description: 'Read places, day assignments, tags, and categories', group: 'Places' },
'places:write': { label: 'Manage places', description: 'Create, update, and delete places, assignments, and tags', group: 'Places' },
'collections:read': { label: 'View collections', description: 'Read saved-place collections, their places, ratings, labels, and members', group: 'Collections' },
'collections:write': { label: 'Manage collections', description: 'Create/edit collections, save, rate, label and copy places, and share lists', group: 'Collections' },
'atlas:read': { label: 'View Atlas', description: 'Read visited countries, regions, and bucket list', group: 'Atlas' },
'atlas:write': { label: 'Manage Atlas', description: 'Mark countries and regions visited, manage bucket list', group: 'Atlas' },
'packing:read': { label: 'View packing lists', description: 'Read packing items, bags, and category assignees', group: 'Packing' },
@@ -84,13 +91,13 @@ export function canReadTrips(scopes: string[] | null): boolean {
}
/** group:write grants write access; for trips canReadTrips handles read */
export function canWrite(scopes: string[] | null, group: string): boolean {
export function canWrite(scopes: string[] | null, group: ScopeGroup): boolean {
if (!scopes) return true;
return scopes.includes(`${group}:write`);
}
/** group:read OR group:write grant read access */
export function canRead(scopes: string[] | null, group: string): boolean {
export function canRead(scopes: string[] | null, group: ScopeGroup): boolean {
if (!scopes) return true;
return scopes.some(s => s === `${group}:read` || s === `${group}:write`);
}
+2
View File
@@ -12,6 +12,8 @@ export interface McpSession {
/** true when authenticated via static trek_ token — triggers deprecation prompt */
isStaticToken: boolean;
lastActivity: number;
/** IP of the most recent authorized request — what mcp.tool_call audit rows record */
lastClientIp: string | null;
}
export const sessions = new Map<string, McpSession>();
+14 -54
View File
@@ -1,57 +1,17 @@
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { registerTodoTools } from './tools/todos';
import { registerAssignmentTools } from './tools/assignments';
import { registerJourneyTools } from './tools/journey';
import { registerReservationTools } from './tools/reservations';
import { registerTagTools } from './tools/tags';
import { registerMapsWeatherTools } from './tools/mapsWeather';
import { registerNotificationTools } from './tools/notifications';
import { registerAtlasTools } from './tools/atlas';
import { registerPlaceTools } from './tools/places';
import { registerDayTools } from './tools/days';
import { registerBudgetTools } from './tools/budget';
import { registerPackingTools } from './tools/packing';
import { registerCollabTools } from './tools/collab';
import { registerTripTools } from './tools/trips';
import { registerTransportTools } from './tools/transports';
import { registerTransitTools } from './tools/transit';
import { registerVacayTools } from './tools/vacay';
import { registerMcpPrompts } from './tools/prompts';
import type { McpAttachOptions, McpRegistry } from '../nest-mcp';
export function registerTools(server: McpServer, userId: number, scopes: string[] | null, isStaticToken = false, getDeprecationNotice: () => string | null = () => null): void {
registerTripTools(server, userId, scopes, getDeprecationNotice);
registerPlaceTools(server, userId, scopes);
registerBudgetTools(server, userId, scopes);
registerPackingTools(server, userId, scopes);
registerReservationTools(server, userId, scopes);
registerDayTools(server, userId, scopes);
registerAssignmentTools(server, userId, scopes);
registerTagTools(server, userId, scopes);
registerMapsWeatherTools(server, userId, scopes);
registerNotificationTools(server, userId, scopes);
registerAtlasTools(server, userId, scopes);
registerCollabTools(server, userId, scopes);
registerTransportTools(server, userId, scopes);
registerTransitTools(server, userId, scopes);
registerJourneyTools(server, userId, scopes);
registerVacayTools(server, userId, scopes);
registerTodoTools(server, userId, scopes);
registerMcpPrompts(server, userId, isStaticToken);
/**
* Attaches the MCP surface to a session's server.
*
* Every domain registers through an @McpController class the container
* discovers, so there is nothing to wire here by hand any more. What is left
* is the seam that supplies the default arguments and the null-registry
* escape hatch. Production passes the container-discovered McpRegistryService
* (injected into the transport service); the no-Nest harness hands in
* createTestRegistry()'s build. A null registry (direct callers without either)
* skips the attach.
*/
export function registerTools(registry: McpRegistry | null, server: McpServer, userId: number, scopes: string[] | null, isStaticToken = false, getDeprecationNotice: () => string | null = () => null, onInvoke?: McpAttachOptions['onInvoke']): void {
if (registry) registry.attach(server, { userId, scopes, isStaticToken, getDeprecationNotice }, { onInvoke });
}
+20 -82
View File
@@ -1,95 +1,33 @@
import { db } from '../../db/database';
import { checkPermission } from '../../services/permissions';
import { broadcast } from '../../websocket';
import { errorResult } from '../../nest-mcp';
export function safeBroadcast(tripId: number, event: string, payload: Record<string, unknown>): void {
try {
broadcast(tripId, event, { ...payload, _source: 'mcp' });
} catch (err) {
console.error(`[MCP] broadcast failed for ${event}:`, err?.message ?? err);
}
}
// Generic MCP result helpers and annotation presets live in src/nest-mcp
// (single source for the decorator-based domains). Re-exported so the
// @McpController files keep importing from here. Everything below is PURE —
// the impure guards (hasTripPermission/isAdminUser/safeBroadcast) moved onto
// the injectable McpToolGuardsService (src/nest/mcp-shared/).
export {
demoDenied,
errorResult,
ok,
TOOL_ANNOTATIONS_DELETE,
TOOL_ANNOTATIONS_NON_IDEMPOTENT,
TOOL_ANNOTATIONS_OPEN_WORLD_NON_IDEMPOTENT,
TOOL_ANNOTATIONS_OPEN_WORLD_READONLY,
TOOL_ANNOTATIONS_READONLY,
TOOL_ANNOTATIONS_WRITE,
} from '../../nest-mcp';
export const MAX_MCP_TRIP_DAYS = 90;
export const TOOL_ANNOTATIONS_READONLY = {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
} as const;
export const TOOL_ANNOTATIONS_OPEN_WORLD_READONLY = {
...TOOL_ANNOTATIONS_READONLY,
openWorldHint: true,
} as const;
export const TOOL_ANNOTATIONS_WRITE = {
readOnlyHint: false,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
} as const;
export const TOOL_ANNOTATIONS_DELETE = {
readOnlyHint: false,
destructiveHint: true,
idempotentHint: true,
openWorldHint: false,
} as const;
export const TOOL_ANNOTATIONS_NON_IDEMPOTENT = {
readOnlyHint: false,
destructiveHint: false,
idempotentHint: false,
openWorldHint: false,
} as const;
export const TOOL_ANNOTATIONS_OPEN_WORLD_NON_IDEMPOTENT = {
...TOOL_ANNOTATIONS_NON_IDEMPOTENT,
openWorldHint: true,
} as const;
export function demoDenied() {
return { content: [{ type: 'text' as const, text: 'Write operations are disabled in demo mode.' }], isError: true };
}
export function noAccess() {
return { content: [{ type: 'text' as const, text: 'Trip not found or access denied.' }], isError: true };
return errorResult('Trip not found or access denied.');
}
export function permissionDenied() {
return {
content: [{ type: 'text' as const, text: 'You do not have permission to perform this action on this trip.' }],
isError: true,
};
}
/**
* RBAC gate for MCP tools, mirroring the checkPermission() calls the REST/Nest
* routes run. Call this after canAccessTrip() with the same action key the
* matching REST route uses. Returns true when the user may perform `action`
* on `tripId`.
*/
export function hasTripPermission(action: string, tripId: number | string, userId: number): boolean {
const trip = db.prepare('SELECT user_id FROM trips WHERE id = ?').get(tripId) as { user_id?: number } | undefined;
if (!trip) return false;
const userRow = db.prepare('SELECT role FROM users WHERE id = ?').get(userId) as { role?: string } | undefined;
const tripOwnerId = typeof trip.user_id === 'number' ? trip.user_id : null;
return checkPermission(action, userRow?.role ?? 'user', tripOwnerId, userId, tripOwnerId !== userId);
}
/** True when the user has the global admin role (mirrors REST `user.role === 'admin'` gates). */
export function isAdminUser(userId: number): boolean {
const userRow = db.prepare('SELECT role FROM users WHERE id = ?').get(userId) as { role?: string } | undefined;
return userRow?.role === 'admin';
return errorResult('You do not have permission to perform this action on this trip.');
}
/** Error response for admin-only tools, reproducing the REST `{ error: 'Admin access required' }` string. */
export function adminRequired() {
return { content: [{ type: 'text' as const, text: 'Admin access required' }], isError: true };
}
export function ok(data: unknown) {
return { content: [{ type: 'text' as const, text: JSON.stringify(data, null, 2) }] };
return errorResult('Admin access required');
}
-194
View File
@@ -1,194 +0,0 @@
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { z } from 'zod';
import { canAccessTrip } from '../../db/database';
import { isDemoUser } from '../../services/authService';
import {
dayExists, placeExists, createAssignment, assignmentExistsInDay,
deleteAssignment, reorderAssignments, getAssignmentForTrip, updateTime,
moveAssignment,
getParticipants as getAssignmentParticipants,
setParticipants as setAssignmentParticipants,
} from '../../services/assignmentService';
import { getDay } from '../../services/dayService';
import { reconcileTripSkeletons } from '../../services/journeyService';
import {
safeBroadcast, TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE,
TOOL_ANNOTATIONS_NON_IDEMPOTENT,
demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
} from './_shared';
import { canRead, canWrite } from '../scopes';
export function registerAssignmentTools(server: McpServer, userId: number, scopes: string[] | null): void {
const R = canRead(scopes, 'places');
const W = canWrite(scopes, 'places');
// --- ASSIGNMENTS ---
if (W) server.registerTool(
'assign_place_to_day',
{
description: 'Assign a place to a specific day in a trip.',
inputSchema: {
tripId: z.number().int().positive(),
dayId: z.number().int().positive(),
placeId: z.number().int().positive(),
notes: z.string().max(500).optional(),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, dayId, placeId, notes }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
if (!dayExists(dayId, tripId)) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true };
if (!placeExists(placeId, tripId)) return { content: [{ type: 'text' as const, text: 'Place not found.' }], isError: true };
const assignment = createAssignment(dayId, placeId, notes || null);
safeBroadcast(tripId, 'assignment:created', { assignment });
try { reconcileTripSkeletons(tripId); } catch { /* non-fatal */ }
return ok({ assignment });
}
);
if (W) server.registerTool(
'unassign_place',
{
description: 'Remove a place assignment from a day.',
inputSchema: {
tripId: z.number().int().positive(),
dayId: z.number().int().positive(),
assignmentId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ tripId, dayId, assignmentId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
if (!assignmentExistsInDay(assignmentId, dayId, tripId))
return { content: [{ type: 'text' as const, text: 'Assignment not found.' }], isError: true };
deleteAssignment(assignmentId);
safeBroadcast(tripId, 'assignment:deleted', { assignmentId, dayId });
try { reconcileTripSkeletons(tripId); } catch { /* non-fatal */ }
return ok({ success: true });
}
);
if (W) server.registerTool(
'update_assignment_time',
{
description: 'Set the start and/or end time for a place assignment on a day (e.g. "09:00", "11:30"). Pass null to clear a time.',
inputSchema: {
tripId: z.number().int().positive(),
assignmentId: z.number().int().positive(),
place_time: z.string().max(50).nullable().optional().describe('Start time (e.g. "09:00"), or null to clear'),
end_time: z.string().max(50).nullable().optional().describe('End time (e.g. "11:00"), or null to clear'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, assignmentId, place_time, end_time }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
const existing = getAssignmentForTrip(assignmentId, tripId);
if (!existing) return { content: [{ type: 'text' as const, text: 'Assignment not found.' }], isError: true };
const assignment = updateTime(
assignmentId,
place_time !== undefined ? place_time : (existing as any).assignment_time,
end_time !== undefined ? end_time : (existing as any).assignment_end_time
);
safeBroadcast(tripId, 'assignment:updated', { assignment });
try { reconcileTripSkeletons(tripId); } catch { /* non-fatal */ }
return ok({ assignment });
}
);
if (W) server.registerTool(
'move_assignment',
{
description: 'Move a place assignment to a different day.',
inputSchema: {
tripId: z.number().int().positive(),
assignmentId: z.number().int().positive(),
newDayId: z.number().int().positive(),
oldDayId: z.number().int().positive(),
orderIndex: z.number().int().min(0).optional().default(0),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, assignmentId, newDayId, oldDayId, orderIndex }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
if (!getAssignmentForTrip(assignmentId, tripId)) return { content: [{ type: 'text' as const, text: 'Assignment not found.' }], isError: true };
if (!getDay(newDayId, tripId)) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true };
const result = moveAssignment(assignmentId, newDayId, orderIndex ?? 0, oldDayId);
safeBroadcast(tripId, 'assignment:moved', { assignment: result.assignment, oldDayId: result.oldDayId });
try { reconcileTripSkeletons(tripId); } catch { /* non-fatal */ }
return ok({ assignment: result.assignment });
}
);
if (R) server.registerTool(
'get_assignment_participants',
{
description: 'Get the list of users participating in a specific place assignment.',
inputSchema: {
tripId: z.number().int().positive(),
assignmentId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ tripId, assignmentId }) => {
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!getAssignmentForTrip(assignmentId, tripId)) return { content: [{ type: 'text' as const, text: 'Assignment not found.' }], isError: true };
const participants = getAssignmentParticipants(assignmentId);
return ok({ participants });
}
);
if (W) server.registerTool(
'set_assignment_participants',
{
description: 'Set the participants for a place assignment (replaces current list).',
inputSchema: {
tripId: z.number().int().positive(),
assignmentId: z.number().int().positive(),
userIds: z.array(z.number().int().positive()).describe('User IDs to set as participants; empty array clears all'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, assignmentId, userIds }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
if (!getAssignmentForTrip(assignmentId, tripId)) return { content: [{ type: 'text' as const, text: 'Assignment not found.' }], isError: true };
const participants = setAssignmentParticipants(assignmentId, userIds);
safeBroadcast(tripId, 'assignment:participants', { assignmentId, participants });
return ok({ participants });
}
);
// --- REORDER ---
if (W) server.registerTool(
'reorder_day_assignments',
{
description: 'Reorder places within a day by providing the assignment IDs in the desired order.',
inputSchema: {
tripId: z.number().int().positive(),
dayId: z.number().int().positive(),
assignmentIds: z.array(z.number().int().positive()).min(1).max(200).describe('Assignment IDs in desired display order'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, dayId, assignmentIds }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
if (!getDay(dayId, tripId)) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true };
reorderAssignments(dayId, assignmentIds);
safeBroadcast(tripId, 'assignment:reordered', { dayId, assignmentIds });
return ok({ success: true, dayId, order: assignmentIds });
}
);
}
-201
View File
@@ -1,201 +0,0 @@
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { z } from 'zod';
import { isDemoUser } from '../../services/authService';
import {
markCountryVisited, unmarkCountryVisited, createBucketItem, deleteBucketItem,
getStats as getAtlasStats, listManuallyVisitedRegions,
markRegionVisited, unmarkRegionVisited, getCountryPlaces, updateBucketItem,
} from '../../services/atlasService';
import { isAddonEnabled } from '../../services/adminService';
import { ADDON_IDS } from '../../addons';
import {
TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
TOOL_ANNOTATIONS_READONLY,
demoDenied, ok,
} from './_shared';
import { canRead, canWrite } from '../scopes';
export function registerAtlasTools(server: McpServer, userId: number, scopes: string[] | null): void {
const R = canRead(scopes, 'atlas');
const W = canWrite(scopes, 'atlas');
if (!isAddonEnabled(ADDON_IDS.ATLAS)) return;
// --- BUCKET LIST ---
if (W) server.registerTool(
'create_bucket_list_item',
{
description: 'Add a destination to your personal travel bucket list.',
inputSchema: {
name: z.string().min(1).max(200).describe('Destination or experience name'),
lat: z.number().optional(),
lng: z.number().optional(),
country_code: z.string().length(2).toUpperCase().optional().describe('ISO 3166-1 alpha-2 country code'),
notes: z.string().max(1000).optional(),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ name, lat, lng, country_code, notes }) => {
if (isDemoUser(userId)) return demoDenied();
const item = createBucketItem(userId, { name, lat, lng, country_code, notes });
return ok({ item });
}
);
if (W) server.registerTool(
'delete_bucket_list_item',
{
description: 'Remove an item from your travel bucket list.',
inputSchema: {
itemId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ itemId }) => {
if (isDemoUser(userId)) return demoDenied();
const deleted = deleteBucketItem(userId, itemId);
if (!deleted) return { content: [{ type: 'text' as const, text: 'Bucket list item not found.' }], isError: true };
return ok({ success: true });
}
);
// --- ATLAS ---
if (W) server.registerTool(
'mark_country_visited',
{
description: 'Mark a country as visited in your Atlas.',
inputSchema: {
country_code: z.string().length(2).toUpperCase().describe('ISO 3166-1 alpha-2 country code (e.g. "FR", "JP")'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ country_code }) => {
if (isDemoUser(userId)) return demoDenied();
markCountryVisited(userId, country_code.toUpperCase());
return ok({ success: true, country_code: country_code.toUpperCase() });
}
);
if (W) server.registerTool(
'unmark_country_visited',
{
description: 'Remove a country from your visited countries in Atlas.',
inputSchema: {
country_code: z.string().length(2).toUpperCase().describe('ISO 3166-1 alpha-2 country code'),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ country_code }) => {
if (isDemoUser(userId)) return demoDenied();
unmarkCountryVisited(userId, country_code.toUpperCase());
return ok({ success: true, country_code: country_code.toUpperCase() });
}
);
// --- ATLAS EXPANDED ---
if (R) server.registerTool(
'get_atlas_stats',
{
description: 'Get atlas statistics — total visited countries, region counts, continent breakdown.',
inputSchema: {},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async () => {
const stats = await getAtlasStats(userId);
return ok({ stats });
}
);
if (R) server.registerTool(
'list_visited_regions',
{
description: 'List all manually visited sub-country regions for the current user.',
inputSchema: {},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async () => {
const regions = listManuallyVisitedRegions(userId);
return ok({ regions });
}
);
if (W) server.registerTool(
'mark_region_visited',
{
description: 'Mark a sub-country region as visited.',
inputSchema: {
regionCode: z.string().describe('ISO region code e.g. US-CA'),
regionName: z.string(),
countryCode: z.string().describe('ISO 3166-1 alpha-2 country code'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ regionCode, regionName, countryCode }) => {
if (isDemoUser(userId)) return demoDenied();
markRegionVisited(userId, regionCode, regionName, countryCode);
const row = listManuallyVisitedRegions(userId).find(r => r.region_code === regionCode);
// Echo in the client-facing shape ({ code, name, ... }) rather than raw DB columns.
const region = row
? { code: row.region_code, name: row.region_name, country_code: row.country_code, manuallyMarked: true }
: undefined;
return ok({ region });
}
);
if (W) server.registerTool(
'unmark_region_visited',
{
description: 'Remove a region from the visited list.',
inputSchema: {
regionCode: z.string(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ regionCode }) => {
if (isDemoUser(userId)) return demoDenied();
unmarkRegionVisited(userId, regionCode);
return ok({ success: true });
}
);
if (R) server.registerTool(
'get_country_atlas_places',
{
description: 'Get places saved in the user\'s atlas for a specific country.',
inputSchema: {
countryCode: z.string().describe('ISO 3166-1 alpha-2 country code'),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ countryCode }) => {
const result = getCountryPlaces(userId, countryCode);
return ok(result);
}
);
if (W) server.registerTool(
'update_bucket_list_item',
{
description: 'Update a bucket list item (notes, name, target date, location).',
inputSchema: {
itemId: z.number().int().positive(),
name: z.string().optional(),
notes: z.string().optional(),
lat: z.number().nullable().optional(),
lng: z.number().nullable().optional(),
country_code: z.string().optional(),
target_date: z.string().nullable().optional(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ itemId, name, notes, lat, lng, country_code, target_date }) => {
if (isDemoUser(userId)) return demoDenied();
const item = updateBucketItem(userId, itemId, { name, notes, lat, lng, country_code, target_date });
if (!item) return { content: [{ type: 'text' as const, text: 'Bucket list item not found.' }], isError: true };
return ok({ item });
}
);
}
-319
View File
@@ -1,319 +0,0 @@
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { z } from 'zod';
import { canAccessTrip, db } from '../../db/database';
import { isDemoUser } from '../../services/authService';
import {
createBudgetItem, updateBudgetItem, deleteBudgetItem,
updateMembers as updateBudgetMembers,
toggleMemberPaid, getBudgetItem, freezeForeignRate,
calculateSettlement, listSettlements, createSettlement, updateSettlement, deleteSettlement,
} from '../../services/budgetService';
import { getRates } from '../../services/exchangeRateService';
import { getTripOwner, listMembers } from '../../services/tripService';
import {
safeBroadcast, TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_READONLY,
TOOL_ANNOTATIONS_NON_IDEMPOTENT,
demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
} from './_shared';
import { canRead, canWrite } from '../scopes';
/** Reusable Zod shape for the per-payer amounts on a budget item. */
const payersSchema = z.array(z.object({
user_id: z.number().int().positive(),
amount: z.number().nonnegative(),
})).describe('Who actually paid, and how much each paid, in the expense currency. Ask the user; do not guess.');
import { isAddonEnabled } from '../../services/adminService';
import { ADDON_IDS } from '../../addons';
/**
* Resolve the equal-split participants for a new budget item. When member_ids is
* omitted, default to the whole trip (owner + all members), deduped — reproducing
* the client's own create flow (CostsPanel seeds participants from all members).
* An explicit empty array means "planning-only, no split" and is passed through.
*/
function resolveMemberIds(tripId: number, member_ids?: number[]): number[] | undefined {
if (member_ids !== undefined) return member_ids;
const owner = getTripOwner(tripId);
if (!owner) return undefined;
const { members } = listMembers(tripId, owner.user_id);
return Array.from(new Set([owner.user_id, ...members.map(m => m.id)]));
}
export function registerBudgetTools(server: McpServer, userId: number, scopes: string[] | null): void {
const R = canRead(scopes, 'budget');
const W = canWrite(scopes, 'budget');
if (isAddonEnabled(ADDON_IDS.BUDGET)) {
// --- BUDGET ---
if (W) server.registerTool(
'create_budget_item',
{
description: 'Add a budget/expense item to a trip. The cost is split equally among member_ids (omit to split across all trip members, or pass [] for a planning-only entry with no split). Use `payers` to record who actually paid and how much. Ask the user which trip members share this expense and who paid — resolve user IDs with list_trip_members — rather than guessing.',
inputSchema: {
tripId: z.number().int().positive(),
name: z.string().min(1).max(200),
category: z.string().max(100).optional().describe('Budget category (e.g. Accommodation, Food, Transport)'),
total_price: z.number().nonnegative(),
currency: z.string().max(10).nullable().optional().describe('ISO currency code (e.g. "EUR"); defaults to the trip currency'),
member_ids: z.array(z.number().int().positive()).optional().describe('Trip member user IDs splitting this expense. Omit to split across all trip members (owner + members); pass [] for no split.'),
payers: payersSchema.optional().describe('Who paid how much, in the expense currency. When given, total_price is derived from the sum. Ask the user; do not guess.'),
expense_date: z.string().max(40).nullable().optional().describe('Date the expense occurred, YYYY-MM-DD'),
note: z.string().max(500).optional(),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, name, category, total_price, currency, member_ids, payers, expense_date, note }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('budget_edit', tripId, userId)) return permissionDenied();
const members = resolveMemberIds(tripId, member_ids);
const itemData = { category, name, total_price, currency, member_ids: members, payers, expense_date, note };
// Freeze the live FX rate at entry time so a settled position isn't re-opened
// when live rates drift (#1445) — same as the REST create path.
await freezeForeignRate(tripId, itemData);
const item = createBudgetItem(tripId, itemData);
safeBroadcast(tripId, 'budget:created', { item });
return ok({ item });
}
);
if (W) server.registerTool(
'delete_budget_item',
{
description: 'Delete a budget item from a trip.',
inputSchema: {
tripId: z.number().int().positive(),
itemId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ tripId, itemId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('budget_edit', tripId, userId)) return permissionDenied();
const deleted = deleteBudgetItem(itemId, tripId);
if (!deleted) return { content: [{ type: 'text' as const, text: 'Budget item not found.' }], isError: true };
safeBroadcast(tripId, 'budget:deleted', { itemId });
return ok({ success: true });
}
);
// --- BUDGET (update) ---
if (W) server.registerTool(
'update_budget_item',
{
description: 'Update an existing budget/expense item in a trip. You can also re-split it via member_ids and record who actually paid via payers (amounts in the expense currency). When changing who shares an expense or who paid, ask the user rather than guessing; resolve user IDs with list_trip_members.',
inputSchema: {
tripId: z.number().int().positive(),
itemId: z.number().int().positive(),
name: z.string().min(1).max(200).optional(),
category: z.string().max(100).optional(),
total_price: z.number().nonnegative().optional(),
member_ids: z.array(z.number().int().positive()).optional().describe('Trip member user IDs splitting this expense; replaces the current split. Omit to leave unchanged, pass [] for no split.'),
payers: payersSchema.optional().describe('Replaces who paid how much, in the expense currency. Omit to leave unchanged. Ask the user; do not guess.'),
persons: z.number().int().positive().nullable().optional(),
days: z.number().int().positive().nullable().optional(),
note: z.string().max(500).nullable().optional(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, itemId, name, category, total_price, member_ids, payers, persons, days, note }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('budget_edit', tripId, userId)) return permissionDenied();
const item = updateBudgetItem(itemId, tripId, { name, category, total_price, member_ids, payers, persons, days, note });
if (!item) return { content: [{ type: 'text' as const, text: 'Budget item not found.' }], isError: true };
safeBroadcast(tripId, 'budget:updated', { item });
return ok({ item });
}
);
// --- BUDGET ADVANCED ---
if (W) server.registerTool(
'create_budget_item_with_members',
{
description: 'Create a budget/expense item and set the trip members splitting it in one atomic operation. If userIds is omitted, the cost is split across all trip members; pass an explicit list to split among a subset, or an empty array for a planning-only entry with no split. Ask the user which members share this expense rather than guessing; resolve user IDs with list_trip_members. Only use when the item does not yet exist — if it already exists, use set_budget_item_members directly.',
inputSchema: {
tripId: z.number().int().positive(),
name: z.string().min(1).max(200),
category: z.string().max(100).optional().describe('Budget category (e.g. Accommodation, Food, Transport)'),
total_price: z.number().nonnegative(),
note: z.string().max(500).optional(),
userIds: z.array(z.number().int().positive()).optional().describe('User IDs splitting this item; omit to split across all trip members, or pass an empty array for no split'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, name, category, total_price, note, userIds }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('budget_edit', tripId, userId)) return permissionDenied();
// Omitted userIds → default to the whole trip, matching create_budget_item.
const members = (userIds && userIds.length > 0) ? userIds : resolveMemberIds(tripId, undefined);
try {
const item = db.transaction(() => {
const created = createBudgetItem(tripId, { category, name, total_price, note, member_ids: members });
return getBudgetItem(created.id, tripId)!;
})();
safeBroadcast(tripId, 'budget:created', { item });
if (members && members.length > 0) safeBroadcast(tripId, 'budget:members-updated', { item });
return ok({ item });
} catch {
return { content: [{ type: 'text' as const, text: 'Failed to create budget item.' }], isError: true };
}
}
);
if (W) server.registerTool(
'set_budget_item_members',
{
description: 'Set which trip members are splitting a budget item (replaces current member list). Ask the user which members share the expense; resolve user IDs with list_trip_members.',
inputSchema: {
tripId: z.number().int().positive(),
itemId: z.number().int().positive(),
userIds: z.array(z.number().int().positive()).describe('User IDs splitting this item; empty array clears all'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, itemId, userIds }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('budget_edit', tripId, userId)) return permissionDenied();
const result = updateBudgetMembers(itemId, tripId, userIds);
if (!result) return { content: [{ type: 'text' as const, text: 'Budget item not found.' }], isError: true };
const item = getBudgetItem(itemId, tripId);
safeBroadcast(tripId, 'budget:members-updated', { item });
return ok({ item });
}
);
if (W) server.registerTool(
'toggle_budget_member_paid',
{
description: 'Mark or unmark a member as having paid their share of a budget item.',
inputSchema: {
tripId: z.number().int().positive(),
itemId: z.number().int().positive(),
memberId: z.number().int().positive().describe('User ID of the member'),
paid: z.boolean(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, itemId, memberId, paid }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('budget_edit', tripId, userId)) return permissionDenied();
const member = toggleMemberPaid(itemId, tripId, memberId, paid);
safeBroadcast(tripId, 'budget:member-paid-updated', { itemId, member });
return ok({ member });
}
);
// --- SETTLEMENTS (settle-up payments between members) ---
if (R) server.registerTool(
'get_settlement_summary',
{
description: "See each member's net balance and the suggested payments to settle shared expenses. Amounts are in the trip's base currency. Call this before recording a settlement so you know who should pay whom and how much.",
inputSchema: {
tripId: z.number().int().positive(),
base: z.string().max(10).optional().describe('ISO currency code to compute balances in; defaults to the trip currency'),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ tripId, base }) => {
if (!canAccessTrip(tripId, userId)) return noAccess();
const trip = db.prepare('SELECT currency FROM trips WHERE id = ?').get(tripId) as { currency?: string } | undefined;
const tripCurrency = trip?.currency || 'EUR';
const effectiveBase = (base || tripCurrency).toUpperCase();
const rates = await getRates(effectiveBase);
const summary = calculateSettlement(tripId, { base: effectiveBase, rates, tripCurrency });
return ok({ summary });
}
);
if (R) server.registerTool(
'list_settlements',
{
description: 'List the recorded settle-up payments for a trip (who paid whom, how much, when).',
inputSchema: {
tripId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ tripId }) => {
if (!canAccessTrip(tripId, userId)) return noAccess();
return ok({ settlements: listSettlements(tripId) });
}
);
if (W) server.registerTool(
'create_settlement',
{
description: "Record a settle-up payment: from_user_id paid to_user_id the given amount (in the trip's base currency) to settle shared expenses. Use get_settlement_summary first to find who owes whom and how much.",
inputSchema: {
tripId: z.number().int().positive(),
from_user_id: z.number().int().positive().describe('User ID of the member who paid'),
to_user_id: z.number().int().positive().describe('User ID of the member who received the payment'),
amount: z.number().positive().describe("Amount paid, in the trip's base currency"),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, from_user_id, to_user_id, amount }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('budget_edit', tripId, userId)) return permissionDenied();
const settlement = createSettlement(tripId, { from_user_id, to_user_id, amount }, userId);
safeBroadcast(tripId, 'budget:settlement-created', { settlement });
return ok({ settlement });
}
);
if (W) server.registerTool(
'update_settlement',
{
description: 'Update a recorded settle-up payment (who paid, who received, and the amount).',
inputSchema: {
tripId: z.number().int().positive(),
settlementId: z.number().int().positive(),
from_user_id: z.number().int().positive().describe('User ID of the member who paid'),
to_user_id: z.number().int().positive().describe('User ID of the member who received the payment'),
amount: z.number().positive().describe("Amount paid, in the trip's base currency"),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, settlementId, from_user_id, to_user_id, amount }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('budget_edit', tripId, userId)) return permissionDenied();
const settlement = updateSettlement(settlementId, tripId, { from_user_id, to_user_id, amount });
if (!settlement) return { content: [{ type: 'text' as const, text: 'Settlement not found.' }], isError: true };
safeBroadcast(tripId, 'budget:settlement-updated', { settlement });
return ok({ settlement });
}
);
if (W) server.registerTool(
'delete_settlement',
{
description: 'Delete a recorded settle-up payment. This is the undo for create_settlement and restores the affected balances.',
inputSchema: {
tripId: z.number().int().positive(),
settlementId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ tripId, settlementId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('budget_edit', tripId, userId)) return permissionDenied();
const deleted = deleteSettlement(settlementId, tripId);
if (!deleted) return { content: [{ type: 'text' as const, text: 'Settlement not found.' }], isError: true };
safeBroadcast(tripId, 'budget:settlement-deleted', { settlementId });
return ok({ success: true });
}
);
} // isAddonEnabled(BUDGET)
}
-285
View File
@@ -1,285 +0,0 @@
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { z } from 'zod';
import { canAccessTrip } from '../../db/database';
import { isDemoUser } from '../../services/authService';
import {
createNote as createCollabNote, updateNote as updateCollabNote, deleteNote as deleteCollabNote,
listPolls, createPoll, votePoll, closePoll, deletePoll,
listMessages, createMessage, deleteMessage, addOrRemoveReaction,
} from '../../services/collabService';
import { isAddonEnabled, getCollabFeatures } from '../../services/adminService';
import { ADDON_IDS } from '../../addons';
import {
safeBroadcast, TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE,
TOOL_ANNOTATIONS_NON_IDEMPOTENT, TOOL_ANNOTATIONS_READONLY,
demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
} from './_shared';
import { canRead, canWrite } from '../scopes';
export function registerCollabTools(server: McpServer, userId: number, scopes: string[] | null): void {
const R = canRead(scopes, 'collab');
const W = canWrite(scopes, 'collab');
if (!isAddonEnabled(ADDON_IDS.COLLAB)) return;
const features = getCollabFeatures();
// --- COLLAB NOTES ---
if (features.notes && W) server.registerTool(
'create_collab_note',
{
description: 'Create a shared collaborative note on a trip (visible to all trip members in the Collab tab).',
inputSchema: {
tripId: z.number().int().positive(),
title: z.string().min(1).max(200),
content: z.string().max(10000).optional(),
category: z.string().max(100).optional().describe('Note category (e.g. "Ideas", "To-do", "General")'),
color: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional().describe('Hex color for the note card'),
pinned: z.boolean().optional().default(false).describe('Pin the note to the top'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, title, content, category, color, pinned }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
const note = createCollabNote(tripId, userId, { title, content, category, color, pinned });
safeBroadcast(tripId, 'collab:note:created', { note });
return ok({ note });
}
);
if (features.notes && W) server.registerTool(
'update_collab_note',
{
description: 'Edit an existing collaborative note on a trip.',
inputSchema: {
tripId: z.number().int().positive(),
noteId: z.number().int().positive(),
title: z.string().min(1).max(200).optional(),
content: z.string().max(10000).optional(),
category: z.string().max(100).optional(),
color: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional().describe('Hex color for the note card'),
pinned: z.boolean().optional().describe('Pin the note to the top'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, noteId, title, content, category, color, pinned }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
const note = updateCollabNote(tripId, noteId, { title, content, category, color, pinned });
if (!note) return { content: [{ type: 'text' as const, text: 'Note not found.' }], isError: true };
safeBroadcast(tripId, 'collab:note:updated', { note });
return ok({ note });
}
);
if (features.notes && W) server.registerTool(
'delete_collab_note',
{
description: 'Delete a collaborative note from a trip.',
inputSchema: {
tripId: z.number().int().positive(),
noteId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ tripId, noteId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
const deleted = deleteCollabNote(tripId, noteId);
if (!deleted) return { content: [{ type: 'text' as const, text: 'Note not found.' }], isError: true };
safeBroadcast(tripId, 'collab:note:deleted', { noteId });
return ok({ success: true });
}
);
// --- COLLAB POLLS & CHAT ---
if (features.polls && R) server.registerTool(
'list_collab_polls',
{
description: 'List all polls for a trip.',
inputSchema: {
tripId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ tripId }) => {
if (!canAccessTrip(tripId, userId)) return noAccess();
const polls = listPolls(tripId);
return ok({ polls });
}
);
if (features.polls && W) server.registerTool(
'create_collab_poll',
{
description: 'Create a new poll in the collab panel.',
inputSchema: {
tripId: z.number().int().positive(),
question: z.string().min(1),
options: z.array(z.string()).min(2).describe('Poll answer options (at least 2)'),
multiple: z.boolean().optional().describe('Allow multiple choice'),
deadline: z.string().optional().describe('ISO date string for poll deadline'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, question, options, multiple, deadline }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
const poll = createPoll(tripId, userId, { question, options, multiple, deadline });
safeBroadcast(tripId, 'collab:poll:created', { poll });
return ok({ poll });
}
);
if (features.polls && W) server.registerTool(
'vote_collab_poll',
{
description: 'Vote on a poll option (or remove vote if already voted for that option).',
inputSchema: {
tripId: z.number().int().positive(),
pollId: z.number().int().positive(),
optionIndex: z.number().int().min(0).describe('Zero-based index of the option to vote for'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, pollId, optionIndex }) => {
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
const result = votePoll(tripId, pollId, userId, optionIndex);
if (result.error) return { content: [{ type: 'text' as const, text: result.error }], isError: true };
safeBroadcast(tripId, 'collab:poll:voted', { poll: result.poll });
return ok({ poll: result.poll });
}
);
if (features.polls && W) server.registerTool(
'close_collab_poll',
{
description: 'Close a poll so no more votes can be cast.',
inputSchema: {
tripId: z.number().int().positive(),
pollId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, pollId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
const poll = closePoll(tripId, pollId);
if (!poll) return { content: [{ type: 'text' as const, text: 'Poll not found.' }], isError: true };
safeBroadcast(tripId, 'collab:poll:closed', { poll });
return ok({ poll });
}
);
if (features.polls && W) server.registerTool(
'delete_collab_poll',
{
description: 'Delete a poll and all its votes.',
inputSchema: {
tripId: z.number().int().positive(),
pollId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ tripId, pollId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
const deleted = deletePoll(tripId, pollId);
if (!deleted) return { content: [{ type: 'text' as const, text: 'Poll not found.' }], isError: true };
safeBroadcast(tripId, 'collab:poll:deleted', { pollId });
return ok({ success: true });
}
);
if (features.chat && R) server.registerTool(
'list_collab_messages',
{
description: 'List chat messages for a trip (most recent 100, oldest-first).',
inputSchema: {
tripId: z.number().int().positive(),
before: z.number().int().positive().optional().describe('Load messages with ID less than this (pagination)'),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ tripId, before }) => {
if (!canAccessTrip(tripId, userId)) return noAccess();
const messages = listMessages(tripId, before);
return ok({ messages });
}
);
if (features.chat && W) server.registerTool(
'send_collab_message',
{
description: "Send a chat message to a trip's collab channel.",
inputSchema: {
tripId: z.number().int().positive(),
text: z.string().min(1),
replyTo: z.number().int().positive().optional().describe('Reply to a specific message ID'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, text, replyTo }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
const result = createMessage(tripId, userId, text, replyTo ?? null);
if (result.error) return { content: [{ type: 'text' as const, text: result.error }], isError: true };
safeBroadcast(tripId, 'collab:message:created', { message: result.message });
return ok({ message: result.message });
}
);
if (features.chat && W) server.registerTool(
'delete_collab_message',
{
description: 'Delete a chat message (only the message owner can delete their own messages).',
inputSchema: {
tripId: z.number().int().positive(),
messageId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ tripId, messageId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
const result = deleteMessage(tripId, messageId, userId);
if (result.error) return { content: [{ type: 'text' as const, text: result.error }], isError: true };
safeBroadcast(tripId, 'collab:message:deleted', { messageId, username: result.username });
return ok({ success: true });
}
);
if (features.chat && W) server.registerTool(
'react_collab_message',
{
description: 'Toggle a reaction emoji on a chat message (adds if not present, removes if already reacted).',
inputSchema: {
tripId: z.number().int().positive(),
messageId: z.number().int().positive(),
emoji: z.string().describe('Single emoji character'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, messageId, emoji }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
const result = addOrRemoveReaction(messageId, tripId, userId, emoji);
if (!result.found) return { content: [{ type: 'text' as const, text: 'Message not found.' }], isError: true };
safeBroadcast(tripId, 'collab:message:reacted', { messageId, reactions: result.reactions });
return ok({ reactions: result.reactions });
}
);
}
-298
View File
@@ -1,298 +0,0 @@
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { z } from 'zod';
import { canAccessTrip, db } from '../../db/database';
import { isDemoUser } from '../../services/authService';
import {
getDay, updateDay, validateAccommodationRefs,
createDay, deleteDay,
createAccommodation, getAccommodation, updateAccommodation, deleteAccommodation,
} from '../../services/dayService';
import { createPlace } from '../../services/placeService';
import {
createNote as createDayNote, getNote as getDayNote, updateNote as updateDayNote,
deleteNote as deleteDayNote, dayExists as dayNoteExists,
} from '../../services/dayNoteService';
import {
safeBroadcast, TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE,
TOOL_ANNOTATIONS_NON_IDEMPOTENT,
demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
} from './_shared';
import { canWrite } from '../scopes';
export function registerDayTools(server: McpServer, userId: number, scopes: string[] | null): void {
if (!canWrite(scopes, 'trips')) return;
// --- DAYS ---
server.registerTool(
'update_day',
{
description: 'Set the title of a day in a trip (e.g. "Arrival in Paris", "Free day").',
inputSchema: {
tripId: z.number().int().positive(),
dayId: z.number().int().positive(),
title: z.string().max(200).nullable().describe('Day title, or null to clear it'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, dayId, title }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
const current = getDay(dayId, tripId);
if (!current) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true };
const updated = updateDay(dayId, current, title !== undefined ? { title } : {});
safeBroadcast(tripId, 'day:updated', { day: updated });
return ok({ day: updated });
}
);
server.registerTool(
'create_day',
{
description: 'Add a new day to a trip (optionally with a specific date and notes).',
inputSchema: {
tripId: z.number().int().positive(),
date: z.string().optional().describe('ISO date string YYYY-MM-DD, optional for dateless trips'),
notes: z.string().optional(),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, date, notes }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
const day = createDay(tripId, date, notes);
safeBroadcast(tripId, 'day:created', { day });
return ok({ day });
}
);
server.registerTool(
'delete_day',
{
description: 'Delete a day from a trip.',
inputSchema: {
tripId: z.number().int().positive(),
dayId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ tripId, dayId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
if (!getDay(dayId, tripId)) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true };
deleteDay(dayId);
safeBroadcast(tripId, 'day:deleted', { id: dayId });
return ok({ success: true });
}
);
server.registerTool(
'create_accommodation',
{
description: 'Add an accommodation (hotel, Airbnb, etc.) to a trip, linked to a place and a date range.',
inputSchema: {
tripId: z.number().int().positive(),
place_id: z.number().int().positive().describe('The place to use as the accommodation'),
start_day_id: z.number().int().positive().describe('Check-in day ID'),
end_day_id: z.number().int().positive().describe('Check-out day ID'),
check_in: z.string().max(10).optional().describe('Check-in time e.g. "15:00"'),
check_in_end: z.string().max(10).optional().describe('Check-in window end time e.g. "20:00"'),
check_out: z.string().max(10).optional().describe('Check-out time e.g. "11:00"'),
confirmation: z.string().max(100).optional(),
notes: z.string().max(1000).optional(),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, place_id, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, notes }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
const errors = validateAccommodationRefs(tripId, place_id, start_day_id, end_day_id);
if (errors.length > 0) return { content: [{ type: 'text' as const, text: errors.map(e => e.message).join(', ') }], isError: true };
const accommodation = createAccommodation(tripId, { place_id, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, notes });
safeBroadcast(tripId, 'accommodation:created', { accommodation });
return ok({ accommodation });
}
);
server.registerTool(
'create_place_accommodation',
{
description: 'Create a new place and immediately set it as an accommodation for a date range in one atomic operation. Use place details from search_place results. Only use when the place does not yet exist — if it already exists, use create_accommodation directly. Set price + currency to record the accommodation cost so it shows on the item.',
inputSchema: {
tripId: z.number().int().positive(),
name: z.string().min(1).max(200),
description: z.string().max(2000).optional(),
lat: z.number().optional(),
lng: z.number().optional(),
address: z.string().max(500).optional(),
category_id: z.number().int().positive().optional().describe('Category ID — use list_categories to see available options'),
google_place_id: z.string().optional().describe('Google Place ID from search_place — enables opening hours display'),
google_ftid: z.string().optional().describe('Google Maps feature ID from search_place — enables direct Google Maps links'),
osm_id: z.string().optional().describe('OpenStreetMap ID from search_place (e.g. "way:12345")'),
place_notes: z.string().max(2000).optional().describe('Notes for the place'),
website: z.string().max(500).optional(),
phone: z.string().max(50).optional(),
start_day_id: z.number().int().positive().describe('Check-in day ID'),
end_day_id: z.number().int().positive().describe('Check-out day ID'),
check_in: z.string().max(10).optional().describe('Check-in time e.g. "15:00"'),
check_in_end: z.string().max(10).optional().describe('Check-in window end time e.g. "20:00"'),
check_out: z.string().max(10).optional().describe('Check-out time e.g. "11:00"'),
confirmation: z.string().max(100).optional(),
accommodation_notes: z.string().max(1000).optional().describe('Notes for the accommodation'),
price: z.number().nonnegative().optional().describe('Total accommodation cost (shown on the item)'),
currency: z.string().length(3).optional().describe('ISO 4217 currency code (e.g. "EUR", "USD")'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, place_notes, website, phone, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, accommodation_notes, price, currency }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
const dayErrors = validateAccommodationRefs(tripId, undefined, start_day_id, end_day_id);
if (dayErrors.length > 0) return { content: [{ type: 'text' as const, text: dayErrors.map(e => e.message).join(', ') }], isError: true };
try {
const run = db.transaction(() => {
const place = createPlace(String(tripId), { name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, notes: place_notes, website, phone, price, currency });
const accommodation = createAccommodation(tripId, { place_id: place.id, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, notes: accommodation_notes });
return { place, accommodation };
});
const result = run();
safeBroadcast(tripId, 'place:created', { place: result.place });
safeBroadcast(tripId, 'accommodation:created', { accommodation: result.accommodation });
return ok(result);
} catch {
return { content: [{ type: 'text' as const, text: 'Failed to create place and accommodation.' }], isError: true };
}
}
);
server.registerTool(
'update_accommodation',
{
description: 'Update fields on an existing accommodation.',
inputSchema: {
tripId: z.number().int().positive(),
accommodationId: z.number().int().positive(),
place_id: z.number().int().positive().optional(),
start_day_id: z.number().int().positive().optional(),
end_day_id: z.number().int().positive().optional(),
check_in: z.string().max(10).optional(),
check_in_end: z.string().max(10).optional().describe('Check-in window end time e.g. "20:00"'),
check_out: z.string().max(10).optional(),
confirmation: z.string().max(100).optional(),
notes: z.string().max(1000).optional(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, accommodationId, place_id, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, notes }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
const existing = getAccommodation(accommodationId, tripId);
if (!existing) return { content: [{ type: 'text' as const, text: 'Accommodation not found.' }], isError: true };
const accommodation = updateAccommodation(accommodationId, existing, { place_id, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, notes });
safeBroadcast(tripId, 'accommodation:updated', { accommodation });
return ok({ accommodation });
}
);
server.registerTool(
'delete_accommodation',
{
description: 'Delete an accommodation from a trip.',
inputSchema: {
tripId: z.number().int().positive(),
accommodationId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ tripId, accommodationId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
if (!getAccommodation(accommodationId, tripId)) return { content: [{ type: 'text' as const, text: 'Accommodation not found.' }], isError: true };
const { linkedReservationId } = deleteAccommodation(accommodationId);
safeBroadcast(tripId, 'accommodation:deleted', { id: accommodationId, linkedReservationId });
return ok({ success: true, linkedReservationId });
}
);
// --- DAY NOTES ---
server.registerTool(
'create_day_note',
{
description: 'Add a note to a specific day in a trip.',
inputSchema: {
tripId: z.number().int().positive(),
dayId: z.number().int().positive(),
text: z.string().min(1).max(500),
time: z.string().max(250).optional().describe('Time label (e.g. "09:00" or "Morning")'),
icon: z.string().optional().describe('Emoji icon for the note'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, dayId, text, time, icon }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
if (!dayNoteExists(dayId, tripId)) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true };
const note = createDayNote(dayId, tripId, text, time, icon);
safeBroadcast(tripId, 'dayNote:created', { dayId, note });
return ok({ note });
}
);
server.registerTool(
'update_day_note',
{
description: 'Edit an existing note on a specific day.',
inputSchema: {
tripId: z.number().int().positive(),
dayId: z.number().int().positive(),
noteId: z.number().int().positive(),
text: z.string().min(1).max(500).optional(),
time: z.string().max(250).nullable().optional().describe('Time label (e.g. "09:00" or "Morning"), or null to clear'),
icon: z.string().optional().describe('Emoji icon for the note'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, dayId, noteId, text, time, icon }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
const existing = getDayNote(noteId, dayId, tripId);
if (!existing) return { content: [{ type: 'text' as const, text: 'Note not found.' }], isError: true };
const note = updateDayNote(noteId, existing, { text, time: time !== undefined ? time : undefined, icon });
safeBroadcast(tripId, 'dayNote:updated', { dayId, note });
return ok({ note });
}
);
server.registerTool(
'delete_day_note',
{
description: 'Delete a note from a specific day.',
inputSchema: {
tripId: z.number().int().positive(),
dayId: z.number().int().positive(),
noteId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ tripId, dayId, noteId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
const note = getDayNote(noteId, dayId, tripId);
if (!note) return { content: [{ type: 'text' as const, text: 'Note not found.' }], isError: true };
deleteDayNote(noteId);
safeBroadcast(tripId, 'dayNote:deleted', { noteId, dayId });
return ok({ success: true });
}
);
}
-429
View File
@@ -1,429 +0,0 @@
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { z } from 'zod';
import { isDemoUser } from '../../services/authService';
import {
addContributor, addTripToJourney, canAccessJourney, createEntry, createJourney,
deleteEntry, deleteJourney, getJourneyFull, getSuggestions, listEntries,
listJourneys, listUserTrips, removeContributor, removeTripFromJourney,
reorderEntries, updateContributorRole, updateEntry, updateJourney,
updateJourneyPreferences,
} from '../../services/journeyService';
import {
createOrUpdateJourneyShareLink, deleteJourneyShareLink, getJourneyShareLink,
} from '../../services/journeyShareService';
import { isAddonEnabled } from '../../services/adminService';
import { ADDON_IDS } from '../../addons';
import {
TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
demoDenied, ok,
} from './_shared';
import { canRead, canShareJourneys, canWrite } from '../scopes';
function notFound(msg: string) {
return { content: [{ type: 'text' as const, text: msg }], isError: true };
}
export function registerJourneyTools(server: McpServer, userId: number, scopes: string[] | null): void {
if (!isAddonEnabled(ADDON_IDS.JOURNEY)) return;
const R = canRead(scopes, 'journey');
const W = canWrite(scopes, 'journey');
const S = canShareJourneys(scopes);
// --- READ TOOLS ---
if (R) server.registerTool(
'list_journeys',
{
description: 'List all journeys owned or contributed to by the current user.',
inputSchema: {},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async () => {
const journeys = listJourneys(userId);
return ok({ journeys });
}
);
if (R) server.registerTool(
'get_journey',
{
description: 'Get a full journey including entries, contributors, and linked trips.',
inputSchema: {
journeyId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ journeyId }) => {
const journey = getJourneyFull(journeyId, userId);
if (!journey) return notFound('Journey not found or access denied.');
return ok({ journey });
}
);
if (R) server.registerTool(
'list_journey_entries',
{
description: 'List all entries in a journey.',
inputSchema: {
journeyId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ journeyId }) => {
if (!canAccessJourney(journeyId, userId)) return notFound('Journey not found or access denied.');
const entries = listEntries(journeyId, userId);
return ok({ entries });
}
);
if (R) server.registerTool(
'list_journey_contributors',
{
description: 'List all contributors (owner and collaborators) of a journey.',
inputSchema: {
journeyId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ journeyId }) => {
const journey = getJourneyFull(journeyId, userId);
if (!journey) return notFound('Journey not found or access denied.');
return ok({ contributors: (journey as any).contributors ?? [] });
}
);
if (R) server.registerTool(
'get_journey_suggestions',
{
description: 'Get trip suggestions for creating a new journey (recently completed trips not yet in any journey).',
inputSchema: {},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async () => {
const trips = getSuggestions(userId);
return ok({ trips });
}
);
if (R) server.registerTool(
'list_journey_available_trips',
{
description: 'List all trips available to link to a journey.',
inputSchema: {},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async () => {
const trips = listUserTrips(userId);
return ok({ trips });
}
);
// --- WRITE TOOLS ---
if (W) server.registerTool(
'create_journey',
{
description: 'Create a new journey, optionally linking existing trips.',
inputSchema: {
title: z.string().min(1).max(200),
subtitle: z.string().max(300).optional(),
trip_ids: z.array(z.number().int().positive()).optional(),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ title, subtitle, trip_ids }) => {
if (isDemoUser(userId)) return demoDenied();
const journey = createJourney(userId, { title, subtitle, trip_ids });
// Return the fully-hydrated journey (entries/contributors/trips/stats/my_role),
// matching get_journey, rather than the bare row.
return ok({ journey: getJourneyFull(journey.id, userId) ?? journey });
}
);
if (W) server.registerTool(
'update_journey',
{
description: 'Update an existing journey\'s title, subtitle, cover, or status. Owner only.',
inputSchema: {
journeyId: z.number().int().positive(),
title: z.string().min(1).max(200).optional(),
subtitle: z.string().max(300).optional(),
status: z.enum(['draft', 'active', 'completed', 'archived']).optional(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ journeyId, title, subtitle, status }) => {
if (isDemoUser(userId)) return demoDenied();
const journey = updateJourney(journeyId, userId, { title, subtitle, status });
if (!journey) return notFound('Journey not found or access denied.');
return ok({ journey });
}
);
if (W) server.registerTool(
'delete_journey',
{
description: 'Delete a journey. Owner only — this cannot be undone.',
inputSchema: {
journeyId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ journeyId }) => {
if (isDemoUser(userId)) return demoDenied();
const success = deleteJourney(journeyId, userId);
if (!success) return notFound('Journey not found or access denied.');
return ok({ success: true });
}
);
if (W) server.registerTool(
'add_journey_trip',
{
description: 'Link a trip to a journey. Syncs skeleton entries for all places in the trip.',
inputSchema: {
journeyId: z.number().int().positive(),
tripId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ journeyId, tripId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessJourney(journeyId, userId)) return notFound('Journey not found or access denied.');
const success = addTripToJourney(journeyId, tripId, userId);
return ok({ success });
}
);
if (W) server.registerTool(
'remove_journey_trip',
{
description: 'Unlink a trip from a journey. Owner only.',
inputSchema: {
journeyId: z.number().int().positive(),
tripId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ journeyId, tripId }) => {
if (isDemoUser(userId)) return demoDenied();
const success = removeTripFromJourney(journeyId, tripId, userId);
if (!success) return notFound('Journey not found or access denied.');
return ok({ success });
}
);
if (W) server.registerTool(
'create_journey_entry',
{
description: 'Create a new entry in a journey.',
inputSchema: {
journeyId: z.number().int().positive(),
entry_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).describe('Entry date (YYYY-MM-DD)'),
title: z.string().max(300).optional(),
story: z.string().optional(),
entry_time: z.string().optional().describe('Time of day (e.g. "14:30")'),
location_name: z.string().optional(),
mood: z.string().optional(),
sort_order: z.number().int().min(0).optional(),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ journeyId, entry_date, title, story, entry_time, location_name, mood, sort_order }) => {
if (isDemoUser(userId)) return demoDenied();
const entry = createEntry(journeyId, userId, { entry_date, title, story, entry_time, location_name, mood, sort_order });
if (!entry) return notFound('Journey not found or access denied.');
// Return through the listEntries enrichment (parsed tags/pros_cons, photos, source_trip_name).
const enriched = listEntries(journeyId, userId)?.find(e => e.id === entry.id) ?? entry;
return ok({ entry: enriched });
}
);
if (W) server.registerTool(
'update_journey_entry',
{
description: 'Update an existing journey entry.',
inputSchema: {
entryId: z.number().int().positive(),
title: z.string().max(300).optional(),
story: z.string().optional(),
entry_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
entry_time: z.string().optional(),
mood: z.string().optional(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ entryId, title, story, entry_date, entry_time, mood }) => {
if (isDemoUser(userId)) return demoDenied();
const entry = updateEntry(entryId, userId, { title, story, entry_date, entry_time, mood }, undefined);
if (!entry) return notFound('Entry not found or access denied.');
// Return through the listEntries enrichment (parsed tags/pros_cons, photos), matching create_journey_entry.
const enriched = listEntries(entry.journey_id, userId)?.find(e => e.id === entry.id) ?? entry;
return ok({ entry: enriched });
}
);
if (W) server.registerTool(
'delete_journey_entry',
{
description: 'Delete a journey entry.',
inputSchema: {
entryId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ entryId }) => {
if (isDemoUser(userId)) return demoDenied();
const success = deleteEntry(entryId, userId, undefined);
if (!success) return notFound('Entry not found or access denied.');
return ok({ success: true });
}
);
if (W) server.registerTool(
'reorder_journey_entries',
{
description: 'Reorder entries within a journey by providing the desired order of entry IDs.',
inputSchema: {
journeyId: z.number().int().positive(),
orderedIds: z.array(z.number().int().positive()),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ journeyId, orderedIds }) => {
if (isDemoUser(userId)) return demoDenied();
const success = reorderEntries(journeyId, userId, orderedIds, undefined);
if (!success) return notFound('Journey not found, access denied, or entry IDs do not belong to this journey.');
return ok({ success: true });
}
);
if (W) server.registerTool(
'add_journey_contributor',
{
description: 'Add a contributor to a journey. Owner only.',
inputSchema: {
journeyId: z.number().int().positive(),
targetUserId: z.number().int().positive(),
role: z.enum(['editor', 'viewer']),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ journeyId, targetUserId, role }) => {
if (isDemoUser(userId)) return demoDenied();
const success = addContributor(journeyId, userId, targetUserId, role);
if (!success) return notFound('Journey not found or access denied.');
return ok({ success: true });
}
);
if (W) server.registerTool(
'update_journey_contributor_role',
{
description: 'Update the role of a journey contributor. Owner only.',
inputSchema: {
journeyId: z.number().int().positive(),
targetUserId: z.number().int().positive(),
role: z.enum(['editor', 'viewer']),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ journeyId, targetUserId, role }) => {
if (isDemoUser(userId)) return demoDenied();
const success = updateContributorRole(journeyId, userId, targetUserId, role);
if (!success) return notFound('Journey not found or access denied.');
return ok({ success: true });
}
);
if (W) server.registerTool(
'remove_journey_contributor',
{
description: 'Remove a contributor from a journey. Owner only.',
inputSchema: {
journeyId: z.number().int().positive(),
targetUserId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ journeyId, targetUserId }) => {
if (isDemoUser(userId)) return demoDenied();
const success = removeContributor(journeyId, userId, targetUserId);
if (!success) return notFound('Journey not found or access denied.');
return ok({ success: true });
}
);
if (W) server.registerTool(
'update_journey_preferences',
{
description: 'Update per-user preferences for a journey (e.g. hide skeleton entries).',
inputSchema: {
journeyId: z.number().int().positive(),
hide_skeletons: z.boolean().optional(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ journeyId, hide_skeletons }) => {
if (isDemoUser(userId)) return demoDenied();
const result = updateJourneyPreferences(journeyId, userId, { hide_skeletons });
if (!result) return notFound('Journey not found or access denied.');
// Return the service result ({ hide_skeletons }), matching the REST route.
return ok(result);
}
);
// --- SHARE TOOLS ---
if (S) server.registerTool(
'get_journey_share_link',
{
description: 'Get the current public share link for a journey. Returns null if none exists.',
inputSchema: {
journeyId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ journeyId }) => {
if (!canAccessJourney(journeyId, userId)) return notFound('Journey not found or access denied.');
const shareLink = getJourneyShareLink(journeyId);
return ok({ shareLink });
}
);
if (S) server.registerTool(
'create_journey_share_link',
{
description: 'Create or update the public share link for a journey. Owner only.',
inputSchema: {
journeyId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ journeyId }) => {
if (isDemoUser(userId)) return demoDenied();
const shareLink = createOrUpdateJourneyShareLink(journeyId, userId, {});
if (!shareLink) return notFound('Journey not found or access denied.');
return ok({ shareLink });
}
);
if (S) server.registerTool(
'delete_journey_share_link',
{
description: 'Revoke the public share link for a journey. Owner only.',
inputSchema: {
journeyId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ journeyId }) => {
if (isDemoUser(userId)) return demoDenied();
const success = deleteJourneyShareLink(journeyId, userId);
if (!success) return notFound('Journey not found or access denied.');
return ok({ success: true });
}
);
}
-148
View File
@@ -1,148 +0,0 @@
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { z } from 'zod';
import { findByIata, searchAirports } from '../../services/airportService';
import { searchPlaces, getPlaceDetails, reverseGeocode, resolveGoogleMapsUrl } from '../../services/mapsService';
import { getWeather, getDetailedWeather } from '../../services/weatherService';
import {
TOOL_ANNOTATIONS_READONLY,
ok,
} from './_shared';
import { canRead } from '../scopes';
export function registerMapsWeatherTools(server: McpServer, userId: number, scopes: string[] | null): void {
const canGeo = canRead(scopes, 'geo');
const canWeather = canRead(scopes, 'weather');
// --- MAPS EXTRAS ---
if (canGeo) server.registerTool(
'get_place_details',
{
description: 'Fetch detailed information about a place by its Google Place ID.',
inputSchema: {
placeId: z.string().describe('Google Place ID'),
lang: z.string().optional().default('en'),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ placeId, lang }) => {
const details = await getPlaceDetails(userId, placeId, lang ?? 'en');
if (!details) return { content: [{ type: 'text' as const, text: 'Place not found or maps service not configured.' }], isError: true };
return ok({ details });
}
);
if (canGeo) server.registerTool(
'reverse_geocode',
{
description: 'Get a human-readable address for given coordinates.',
inputSchema: {
lat: z.number(),
lng: z.number(),
lang: z.string().optional().default('en'),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ lat, lng, lang }) => {
const result = await reverseGeocode(String(lat), String(lng), lang ?? 'en');
if (!result) return { content: [{ type: 'text' as const, text: 'Reverse geocode failed or maps service not configured.' }], isError: true };
return ok(result);
}
);
if (canGeo) server.registerTool(
'resolve_maps_url',
{
description: 'Resolve a Google Maps share URL to coordinates and place name.',
inputSchema: {
url: z.string().describe('Google Maps share URL'),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ url }) => {
const result = await resolveGoogleMapsUrl(url);
if (!result) return { content: [{ type: 'text' as const, text: 'Could not resolve URL or maps service not configured.' }], isError: true };
return ok(result);
}
);
// --- WEATHER ---
if (canWeather) server.registerTool(
'get_weather',
{
description: 'Get weather forecast for a location and date.',
inputSchema: {
lat: z.number(),
lng: z.number(),
date: z.string().describe('ISO date YYYY-MM-DD'),
lang: z.string().optional().default('en'),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ lat, lng, date, lang }) => {
try {
const weather = await getWeather(String(lat), String(lng), date, lang ?? 'en');
return ok({ weather });
} catch (err: any) {
return { content: [{ type: 'text' as const, text: err?.message ?? 'Weather service not available.' }], isError: true };
}
}
);
if (canWeather) server.registerTool(
'get_detailed_weather',
{
description: 'Get hourly/detailed weather forecast for a location and date.',
inputSchema: {
lat: z.number(),
lng: z.number(),
date: z.string().describe('ISO date YYYY-MM-DD'),
lang: z.string().optional().default('en'),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ lat, lng, date, lang }) => {
try {
const weather = await getDetailedWeather(String(lat), String(lng), date, lang ?? 'en');
return ok({ weather });
} catch (err: any) {
return { content: [{ type: 'text' as const, text: err?.message ?? 'Weather service not available.' }], isError: true };
}
}
);
// --- AIRPORTS ---
if (canGeo) server.registerTool(
'search_airports',
{
description: 'Search for airports by name, city, or IATA code. Returns matching airports with IATA code, name, city, country, coordinates, and timezone. Use before create_transport (flight) to get the correct IATA code and timezone for endpoints.',
inputSchema: {
query: z.string().min(1).max(200).describe('Airport name, city, or IATA code (e.g. "zurich", "ZRH", "charles de gaulle")'),
limit: z.number().int().min(1).max(50).optional().default(10),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ query, limit }) => {
const airports = searchAirports(query, limit ?? 10);
return ok({ airports });
}
);
if (canGeo) server.registerTool(
'get_airport',
{
description: 'Get a single airport by its IATA code. Returns name, city, country, coordinates, and timezone.',
inputSchema: {
iata: z.string().length(3).toUpperCase().describe('IATA airport code (e.g. "ZRH", "AMS", "CDG")'),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ iata }) => {
const airport = findByIata(iata);
if (!airport) return { content: [{ type: 'text' as const, text: 'Airport not found.' }], isError: true };
return ok({ airport });
}
);
}
-99
View File
@@ -1,99 +0,0 @@
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { z } from 'zod';
import { isDemoUser } from '../../services/authService';
import {
getNotifications, getUnreadCount,
markRead as markNotificationRead, markUnread as markNotificationUnread,
markAllRead,
} from '../../services/inAppNotifications';
import {
TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
demoDenied, ok,
} from './_shared';
import { canRead, canWrite } from '../scopes';
export function registerNotificationTools(server: McpServer, userId: number, scopes: string[] | null): void {
const R = canRead(scopes, 'notifications');
const W = canWrite(scopes, 'notifications');
// --- NOTIFICATIONS ---
if (R) server.registerTool(
'list_notifications',
{
description: 'List in-app notifications for the current user.',
inputSchema: {
limit: z.number().int().positive().optional().default(20),
offset: z.number().int().min(0).optional().default(0),
unread_only: z.boolean().optional().default(false),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ limit, offset, unread_only }) => {
const result = getNotifications(userId, { limit: limit ?? 20, offset: offset ?? 0, unreadOnly: unread_only ?? false });
return ok(result);
}
);
if (R) server.registerTool(
'get_unread_notification_count',
{
description: 'Get the number of unread in-app notifications.',
inputSchema: {},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async () => {
const count = getUnreadCount(userId);
return ok({ count });
}
);
if (W) server.registerTool(
'mark_notification_read',
{
description: 'Mark a single notification as read.',
inputSchema: {
notificationId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ notificationId }) => {
if (isDemoUser(userId)) return demoDenied();
const success = markNotificationRead(notificationId, userId);
if (!success) return { content: [{ type: 'text' as const, text: 'Notification not found.' }], isError: true };
return ok({ success: true });
}
);
if (W) server.registerTool(
'mark_notification_unread',
{
description: 'Mark a single notification as unread.',
inputSchema: {
notificationId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ notificationId }) => {
if (isDemoUser(userId)) return demoDenied();
const success = markNotificationUnread(notificationId, userId);
if (!success) return { content: [{ type: 'text' as const, text: 'Notification not found.' }], isError: true };
return ok({ success: true });
}
);
if (W) server.registerTool(
'mark_all_notifications_read',
{
description: "Mark all of the current user's notifications as read.",
inputSchema: {},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async () => {
if (isDemoUser(userId)) return demoDenied();
const count = markAllRead(userId);
return ok({ success: true, count });
}
);
}
-394
View File
@@ -1,394 +0,0 @@
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { z } from 'zod';
import { canAccessTrip } from '../../db/database';
import { isDemoUser } from '../../services/authService';
import {
createItem as createPackingItem, updateItem as updatePackingItem,
deleteItem as deletePackingItem,
reorderItems as reorderPackingItems,
listBags, createBag, updateBag, deleteBag, setBagMembers,
getCategoryAssignees as getPackingCategoryAssignees,
updateCategoryAssignees as updatePackingCategoryAssignees,
applyTemplate, saveAsTemplate, listTemplates, bulkImport,
} from '../../services/packingService';
import {
safeBroadcast, TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE,
TOOL_ANNOTATIONS_NON_IDEMPOTENT,
demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
isAdminUser, adminRequired,
} from './_shared';
import { canRead, canWrite } from '../scopes';
import { isAddonEnabled, deletePackingTemplate } from '../../services/adminService';
import { ADDON_IDS } from '../../addons';
export function registerPackingTools(server: McpServer, userId: number, scopes: string[] | null): void {
const R = canRead(scopes, 'packing');
const W = canWrite(scopes, 'packing');
if (!isAddonEnabled(ADDON_IDS.PACKING)) return;
// --- PACKING ---
if (W) server.registerTool(
'create_packing_item',
{
description: 'Add an item to the packing checklist for a trip.',
inputSchema: {
tripId: z.number().int().positive(),
name: z.string().min(1).max(200),
category: z.string().max(100).optional().describe('Packing category (e.g. Clothes, Electronics)'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, name, category }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
const item = createPackingItem(tripId, { name, category: category || 'General' }, userId);
safeBroadcast(tripId, 'packing:created', { item });
return ok({ item });
}
);
if (W) server.registerTool(
'toggle_packing_item',
{
description: 'Check or uncheck a packing item.',
inputSchema: {
tripId: z.number().int().positive(),
itemId: z.number().int().positive(),
checked: z.boolean(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, itemId, checked }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
const item = updatePackingItem(tripId, itemId, { checked: checked ? 1 : 0 }, ['checked']);
if (!item) return { content: [{ type: 'text' as const, text: 'Packing item not found.' }], isError: true };
safeBroadcast(tripId, 'packing:updated', { item });
return ok({ item });
}
);
if (W) server.registerTool(
'delete_packing_item',
{
description: 'Remove an item from the packing checklist.',
inputSchema: {
tripId: z.number().int().positive(),
itemId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ tripId, itemId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
const deleted = deletePackingItem(tripId, itemId);
if (!deleted) return { content: [{ type: 'text' as const, text: 'Packing item not found.' }], isError: true };
safeBroadcast(tripId, 'packing:deleted', { itemId });
return ok({ success: true });
}
);
// --- PACKING (update) ---
if (W) server.registerTool(
'update_packing_item',
{
description: 'Rename a packing item or change its category.',
inputSchema: {
tripId: z.number().int().positive(),
itemId: z.number().int().positive(),
name: z.string().min(1).max(200).optional(),
category: z.string().max(100).optional(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, itemId, name, category }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
const bodyKeys = ['name', 'category'].filter(k => k === 'name' ? name !== undefined : category !== undefined);
const item = updatePackingItem(tripId, itemId, { name, category }, bodyKeys);
if (!item) return { content: [{ type: 'text' as const, text: 'Packing item not found.' }], isError: true };
safeBroadcast(tripId, 'packing:updated', { item });
return ok({ item });
}
);
// --- PACKING ADVANCED ---
if (W) server.registerTool(
'reorder_packing_items',
{
description: 'Set the display order of packing items within a trip.',
inputSchema: {
tripId: z.number().int().positive(),
orderedIds: z.array(z.number().int().positive()).describe('Packing item IDs in desired order'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, orderedIds }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
reorderPackingItems(tripId, orderedIds);
safeBroadcast(tripId, 'packing:reordered', { orderedIds });
return ok({ success: true });
}
);
if (R) server.registerTool(
'list_packing_bags',
{
description: 'List all packing bags for a trip.',
inputSchema: {
tripId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ tripId }) => {
if (!canAccessTrip(tripId, userId)) return noAccess();
const bags = listBags(tripId);
return ok({ bags });
}
);
if (W) server.registerTool(
'create_packing_bag',
{
description: 'Create a new packing bag (e.g. "Carry-on", "Checked bag").',
inputSchema: {
tripId: z.number().int().positive(),
name: z.string().min(1).max(100),
color: z.string().optional(),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, name, color }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
// createBag returns a bare row; hydrate with the empty members array that
// listBags and the schema always carry, so the client/AI consumer matches.
const bag = { ...(createBag(tripId, { name, color }) as object), members: [] };
safeBroadcast(tripId, 'packing:bag-created', { bag });
return ok({ bag });
}
);
if (W) server.registerTool(
'update_packing_bag',
{
description: 'Rename or recolor a packing bag.',
inputSchema: {
tripId: z.number().int().positive(),
bagId: z.number().int().positive(),
name: z.string().optional(),
color: z.string().optional(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, bagId, name, color }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
const fields: Record<string, unknown> = {};
const bodyKeys: string[] = [];
if (name !== undefined) { fields.name = name; bodyKeys.push('name'); }
if (color !== undefined) { fields.color = color; bodyKeys.push('color'); }
const updated = updateBag(tripId, bagId, fields, bodyKeys);
if (!updated) return { content: [{ type: 'text' as const, text: 'Bag not found.' }], isError: true };
// Hydrate with the members array (matches create_packing_bag, listBags, and the schema).
const bag = listBags(tripId).find(b => b.id === (updated as { id: number }).id) ?? { ...(updated as object), members: [] };
safeBroadcast(tripId, 'packing:bag-updated', { bag });
return ok({ bag });
}
);
if (W) server.registerTool(
'delete_packing_bag',
{
description: 'Delete a packing bag (items in the bag are unassigned, not deleted).',
inputSchema: {
tripId: z.number().int().positive(),
bagId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ tripId, bagId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
deleteBag(tripId, bagId);
safeBroadcast(tripId, 'packing:bag-deleted', { id: bagId });
return ok({ success: true });
}
);
if (W) server.registerTool(
'set_bag_members',
{
description: 'Assign trip members to a packing bag (determines who packs what bag).',
inputSchema: {
tripId: z.number().int().positive(),
bagId: z.number().int().positive(),
userIds: z.array(z.number().int().positive()),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, bagId, userIds }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
const members = setBagMembers(tripId, bagId, userIds);
if (!members) return { content: [{ type: 'text' as const, text: 'Bag not found.' }], isError: true };
safeBroadcast(tripId, 'packing:bag-members-updated', { bagId, members });
return ok({ members });
}
);
if (R) server.registerTool(
'get_packing_category_assignees',
{
description: 'Get which trip members are assigned to each packing category.',
inputSchema: {
tripId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ tripId }) => {
if (!canAccessTrip(tripId, userId)) return noAccess();
const assignees = getPackingCategoryAssignees(tripId);
return ok({ assignees });
}
);
if (W) server.registerTool(
'set_packing_category_assignees',
{
description: 'Assign trip members to a packing category.',
inputSchema: {
tripId: z.number().int().positive(),
categoryName: z.string().min(1).max(100),
userIds: z.array(z.number().int().positive()),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, categoryName, userIds }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
const assignees = updatePackingCategoryAssignees(tripId, categoryName, userIds);
safeBroadcast(tripId, 'packing:assignees', { category: categoryName, assignees });
return ok({ assignees });
}
);
if (W) server.registerTool(
'apply_packing_template',
{
description: 'Apply a packing template to a trip (adds items from the template).',
inputSchema: {
tripId: z.number().int().positive(),
templateId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, templateId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
const items = applyTemplate(tripId, templateId);
if (items === null) return { content: [{ type: 'text' as const, text: 'Template not found.' }], isError: true };
safeBroadcast(tripId, 'packing:template-applied', { items });
return ok({ items, count: items.length });
}
);
if (R) server.registerTool(
'list_packing_templates',
{
description: 'List the reusable packing templates (id, name, item count) so one can be applied with apply_packing_template.',
inputSchema: {
tripId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ tripId }) => {
if (!canAccessTrip(tripId, userId)) return noAccess();
return ok({ templates: listTemplates() });
}
);
if (W) server.registerTool(
'save_packing_template',
{
description: 'Save the current packing list as a reusable template. Returns the new template (id, name, category/item counts). Admin only.',
inputSchema: {
tripId: z.number().int().positive(),
templateName: z.string().min(1).max(100),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, templateName }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
// Templates are global; the REST route restricts saving to admins. Match it.
if (!isAdminUser(userId)) return adminRequired();
const template = saveAsTemplate(tripId, userId, templateName);
if (!template) return { content: [{ type: 'text' as const, text: 'Nothing to save — the packing list is empty.' }], isError: true };
return ok({ template });
}
);
if (W) server.registerTool(
'delete_packing_template',
{
description: 'Delete a reusable packing template. Templates are global, so deletion is admin only.',
inputSchema: {
templateId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ templateId }) => {
if (isDemoUser(userId)) return demoDenied();
// Templates are global; the REST route restricts management to admins. Match it.
if (!isAdminUser(userId)) return adminRequired();
const result = deletePackingTemplate(String(templateId));
if ('error' in result) return { content: [{ type: 'text' as const, text: result.error }], isError: true };
return ok({ success: true, name: result.name });
}
);
if (W) server.registerTool(
'bulk_import_packing',
{
description: 'Import multiple packing items at once from a list. Optionally assign each to a bag (by name — created if missing), set its weight, or pre-check it.',
inputSchema: {
tripId: z.number().int().positive(),
items: z.array(z.object({
name: z.string().min(1).max(200),
category: z.string().optional(),
quantity: z.number().int().positive().optional(),
bag: z.string().max(100).optional().describe('Bag name to assign the item to; created if it does not exist'),
weight_grams: z.number().nonnegative().optional(),
checked: z.boolean().optional(),
})).min(1),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, items }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
const created = bulkImport(tripId, items, userId);
for (const item of created) safeBroadcast(tripId, 'packing:created', { item });
return ok({ items: created, count: created.length });
}
);
}
-311
View File
@@ -1,311 +0,0 @@
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { z } from 'zod';
import { canAccessTrip, db } from '../../db/database';
import { isDemoUser } from '../../services/authService';
import { deletePlacesMany, updatePlacesMany, importGoogleList, importNaverList, listPlaces, createPlace, updatePlace, deletePlace } from '../../services/placeService';
import { createAssignment, dayExists } from '../../services/assignmentService';
import { onPlaceDeleted, reconcileTripSkeletons } from '../../services/journeyService';
import { listCategories } from '../../services/categoryService';
import { searchPlaces } from '../../services/mapsService';
import {
safeBroadcast, TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
} from './_shared';
import { canRead, canWrite } from '../scopes';
export function registerPlaceTools(server: McpServer, userId: number, scopes: string[] | null): void {
const R = canRead(scopes, 'places');
const W = canWrite(scopes, 'places');
// --- PLACES ---
if (W) server.registerTool(
'create_place',
{
description: 'Add a new place/POI to a trip. Set google_place_id, google_ftid, or osm_id (from search_place) so the app can show opening hours, ratings, and direct Google Maps links. Set price + currency to record the cost so it shows on the item.',
inputSchema: {
tripId: z.number().int().positive(),
name: z.string().min(1).max(200),
description: z.string().max(2000).optional(),
lat: z.number().optional(),
lng: z.number().optional(),
address: z.string().max(500).optional(),
category_id: z.number().int().positive().optional().describe('Category ID — use list_categories to see available options'),
google_place_id: z.string().optional().describe('Google Place ID from search_place — enables opening hours display'),
google_ftid: z.string().optional().describe('Google Maps feature ID from search_place — enables direct Google Maps links'),
osm_id: z.string().optional().describe('OpenStreetMap ID from search_place (e.g. "way:12345") — enables opening hours if no Google ID'),
notes: z.string().max(2000).optional(),
website: z.string().max(500).optional(),
phone: z.string().max(50).optional(),
price: z.number().nonnegative().optional().describe('Cost of this place/activity (e.g. ticket price, entry fee)'),
currency: z.string().length(3).optional().describe('ISO 4217 currency code (e.g. "EUR", "USD")'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, notes, website, phone, price, currency }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('place_edit', tripId, userId)) return permissionDenied();
const place = createPlace(String(tripId), { name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, notes, website, phone, price, currency });
safeBroadcast(tripId, 'place:created', { place });
return ok({ place });
}
);
if (W) server.registerTool(
'create_and_assign_place',
{
description: 'Create a new place and immediately assign it to a day in one atomic operation. Use place details from search_place results. Only use when the place does not yet exist — if it already exists, use assign_place_to_day directly. Set price + currency to record the cost so it shows on the item.',
inputSchema: {
tripId: z.number().int().positive(),
dayId: z.number().int().positive().describe('Day to assign the place to'),
name: z.string().min(1).max(200),
description: z.string().max(2000).optional(),
lat: z.number().optional(),
lng: z.number().optional(),
address: z.string().max(500).optional(),
category_id: z.number().int().positive().optional().describe('Category ID — use list_categories to see available options'),
google_place_id: z.string().optional().describe('Google Place ID from search_place — enables opening hours display'),
google_ftid: z.string().optional().describe('Google Maps feature ID from search_place — enables direct Google Maps links'),
osm_id: z.string().optional().describe('OpenStreetMap ID from search_place (e.g. "way:12345")'),
place_notes: z.string().max(2000).optional().describe('Notes for the place'),
website: z.string().max(500).optional(),
phone: z.string().max(50).optional(),
assignment_notes: z.string().max(500).optional().describe('Notes for this day assignment'),
price: z.number().nonnegative().optional().describe('Cost of this place/activity (e.g. ticket price, entry fee)'),
currency: z.string().length(3).optional().describe('ISO 4217 currency code (e.g. "EUR", "USD")'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, dayId, name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, place_notes, website, phone, assignment_notes, price, currency }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('place_edit', tripId, userId)) return permissionDenied();
if (!dayExists(dayId, tripId)) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true };
try {
const run = db.transaction(() => {
const place = createPlace(String(tripId), { name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, notes: place_notes, website, phone, price, currency });
const assignment = createAssignment(dayId, place.id, assignment_notes ?? null);
return { place, assignment };
});
const result = run();
safeBroadcast(tripId, 'place:created', { place: result.place });
safeBroadcast(tripId, 'assignment:created', { assignment: result.assignment });
try { reconcileTripSkeletons(tripId); } catch { /* non-fatal */ }
return ok(result);
} catch {
return { content: [{ type: 'text' as const, text: 'Failed to create place and assignment.' }], isError: true };
}
}
);
if (W) server.registerTool(
'update_place',
{
description: 'Update an existing place in a trip.',
inputSchema: {
tripId: z.number().int().positive(),
placeId: z.number().int().positive(),
name: z.string().min(1).max(200).optional(),
description: z.string().max(2000).optional(),
lat: z.number().optional(),
lng: z.number().optional(),
address: z.string().max(500).optional(),
category_id: z.number().int().positive().optional().describe('Category ID — use list_categories'),
price: z.number().optional(),
currency: z.string().length(3).optional(),
place_time: z.string().max(50).optional().describe('Scheduled time (e.g. "09:00")'),
end_time: z.string().max(50).optional().describe('End time (e.g. "11:00")'),
duration_minutes: z.number().int().positive().optional(),
notes: z.string().max(2000).optional(),
website: z.string().max(500).optional(),
phone: z.string().max(50).optional(),
transport_mode: z.enum(['walking', 'driving', 'cycling', 'transit', 'flight']).optional(),
osm_id: z.string().optional().describe('OpenStreetMap ID (e.g. "way:12345")'),
google_place_id: z.string().optional().describe('Google Place ID (e.g. "ChIJd8BlQ2BZwokRAFUEcm_qrcA")'),
google_ftid: z.string().optional().describe('Google Maps feature ID (e.g. "0x89c259b7abdd4769:0x103aaf1c8bf8a050")'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, placeId, name, description, lat, lng, address, category_id, price, currency, place_time, end_time, duration_minutes, notes, website, phone, transport_mode, osm_id, google_place_id, google_ftid }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('place_edit', tripId, userId)) return permissionDenied();
const place = updatePlace(String(tripId), String(placeId), { name, description, lat, lng, address, category_id, price, currency, place_time, end_time, duration_minutes, notes, website, phone, transport_mode, osm_id, google_place_id, google_ftid });
if (!place) return { content: [{ type: 'text' as const, text: 'Place not found.' }], isError: true };
safeBroadcast(tripId, 'place:updated', { place });
return ok({ place });
}
);
if (W) server.registerTool(
'delete_place',
{
description: 'Delete a place from a trip.',
inputSchema: {
tripId: z.number().int().positive(),
placeId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ tripId, placeId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('place_edit', tripId, userId)) return permissionDenied();
try { onPlaceDeleted(placeId); } catch {} // sync journeys before the row is gone
const deleted = deletePlace(String(tripId), String(placeId));
if (!deleted) return { content: [{ type: 'text' as const, text: 'Place not found.' }], isError: true };
safeBroadcast(tripId, 'place:deleted', { placeId });
return ok({ success: true });
}
);
if (R) server.registerTool(
'list_places',
{
description: 'List all places/POIs in a trip, optionally filtered by assignment status. Use assignment=unassigned to find orphan activities not yet scheduled on any day.',
inputSchema: {
tripId: z.number().int().positive(),
search: z.string().optional(),
category: z.string().optional(),
tag: z.string().optional(),
assignment: z.enum(['all', 'unassigned', 'assigned']).optional().default('all').describe('Filter by assignment status: "all" (default), "unassigned" (not on any day), or "assigned" (scheduled on a day)'),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ tripId, search, category, tag, assignment }) => {
if (!canAccessTrip(tripId, userId)) return noAccess();
const places = listPlaces(String(tripId), { search, category, tag, assignment });
return ok({ places });
}
);
// --- CATEGORIES ---
if (R) server.registerTool(
'list_categories',
{
description: 'List all available place categories with their id, name, icon and color. Use category_id when creating or updating places.',
inputSchema: {},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async () => {
const categories = listCategories();
return ok({ categories });
}
);
// --- SEARCH ---
if (R) server.registerTool(
'search_place',
{
description: 'Search for a real-world place by name or address. Returns results with osm_id (and google_place_id/google_ftid if configured). Use these IDs when calling create_place so the app can display opening hours, ratings, and map links.',
inputSchema: {
query: z.string().min(1).max(500).describe('Place name or address to search for'),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ query }) => {
try {
const result = await searchPlaces(userId, query);
return ok(result);
} catch {
return { content: [{ type: 'text' as const, text: 'Place search failed.' }], isError: true };
}
}
);
if (W) server.registerTool(
'import_places_from_url',
{
description: 'Import places from a shared Google Maps or Naver Maps list URL. Returns the imported places and count. The list must be shared publicly.',
inputSchema: {
tripId: z.number().int().positive(),
url: z.string().url().describe('Publicly shared Google Maps list URL (maps.app.goo.gl/...) or Naver Maps list URL'),
source: z.enum(['google-list', 'naver-list']).describe('List source: "google-list" for Google Maps saved places, "naver-list" for Naver Maps'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, url, source }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('place_edit', tripId, userId)) return permissionDenied();
const result = source === 'google-list'
? await importGoogleList(String(tripId), url)
: await importNaverList(String(tripId), url);
if ('error' in result) {
return { content: [{ type: 'text' as const, text: result.error }], isError: true };
}
for (const place of result.places) {
safeBroadcast(tripId, 'place:created', { place });
}
return ok({ places: result.places, count: result.places.length, listName: result.listName, skipped: result.skipped });
}
);
if (W) server.registerTool(
'bulk_delete_places',
{
description: 'Delete multiple places from a trip at once. Removes all day assignments for each place as well. Warn the user before calling this — it cannot be undone.',
inputSchema: {
tripId: z.number().int().positive(),
placeIds: z.array(z.number().int().positive()).min(1).max(200),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ tripId, placeIds }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('place_edit', tripId, userId)) return permissionDenied();
const deleted = deletePlacesMany(String(tripId), placeIds);
for (const id of deleted) {
safeBroadcast(tripId, 'place:deleted', { placeId: id });
try { onPlaceDeleted(id); } catch {}
}
return ok({ deleted, count: deleted.length });
}
);
if (W) server.registerTool(
'bulk_update_places',
{
description: 'Update many places in a trip at once, applying the SAME field values to every listed place. Use this for sweeping edits — e.g. re-categorising a batch of POIs (set category_id for 80 places) — in a single call instead of one update_place per place. Only the fields you set are changed; everything else on each place is preserved. Use list_categories for category_id.',
inputSchema: {
tripId: z.number().int().positive(),
placeIds: z.array(z.number().int().positive()).min(1).max(500).describe('IDs of the places to update (from list_places)'),
category_id: z.number().int().positive().optional().describe('Category ID — use list_categories'),
price: z.number().optional(),
currency: z.string().length(3).optional(),
transport_mode: z.enum(['walking', 'driving', 'cycling', 'transit', 'flight']).optional(),
place_time: z.string().max(50).optional().describe('Scheduled time (e.g. "09:00")'),
end_time: z.string().max(50).optional().describe('End time (e.g. "11:00")'),
duration_minutes: z.number().int().positive().optional(),
notes: z.string().max(2000).optional(),
website: z.string().max(500).optional(),
phone: z.string().max(50).optional(),
description: z.string().max(2000).optional(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, placeIds, category_id, price, currency, transport_mode, place_time, end_time, duration_minutes, notes, website, phone, description }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('place_edit', tripId, userId)) return permissionDenied();
const fields = { category_id, price, currency, transport_mode, place_time, end_time, duration_minutes, notes, website, phone, description };
if (Object.values(fields).every(v => v === undefined)) {
return { content: [{ type: 'text' as const, text: 'Provide at least one field to update.' }], isError: true };
}
const updated = updatePlacesMany(String(tripId), placeIds, fields);
for (const place of updated) safeBroadcast(tripId, 'place:updated', { place });
return ok({ count: updated.length, updatedIds: updated.map(p => p.id), skipped: placeIds.length - updated.length });
}
);
}
-139
View File
@@ -1,139 +0,0 @@
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { z } from 'zod';
import { canAccessTrip } from '../../db/database';
import { getTripSummary } from '../../services/tripService';
import { listItems as listPackingItems } from '../../services/packingService';
import { isAddonEnabled } from '../../services/adminService';
import { ADDON_IDS } from '../../addons';
export function registerMcpPrompts(server: McpServer, _userId: number, isStaticToken = false): void {
if (isStaticToken) {
server.registerPrompt(
'token_auth_notice',
{
title: 'Static Token Auth Notice',
description: 'Notification that this session uses a static API token which will be deprecated',
argsSchema: {},
},
async () => ({
description: 'Static token deprecation notice',
messages: [{
role: 'user' as const,
content: {
type: 'text' as const,
text: '⚠️ This MCP connection is authenticated with a static API token (trek_…). Static token authentication will be deprecated in a future version of TREK. Please inform the user that they should migrate to OAuth 2.1 by going to Settings → Integrations → MCP → OAuth Clients in TREK and registering an OAuth 2.1 application for their MCP client.',
},
}],
})
);
}
const userId = _userId;
server.registerPrompt(
'trip-summary',
{
title: 'Trip Summary',
description: 'Load a full summary of a trip for context before planning or modifications',
argsSchema: {
tripId: z.number().int().positive().describe('Trip ID to summarize'),
},
},
async ({ tripId }) => {
if (!canAccessTrip(tripId, userId)) {
return { messages: [{ role: 'user', content: { type: 'text', text: 'Trip not found or access denied.' } }] };
}
const summary = getTripSummary(tripId, userId);
if (!summary) {
return { messages: [{ role: 'user', content: { type: 'text', text: 'Trip not found.' } }] };
}
const { trip, days, members, budget, packing, reservations, collab_notes } = summary;
const memberList = [members?.owner, ...(members?.collaborators || [])].filter(Boolean);
const text = `Trip: ${trip?.title || 'Untitled'}${trip?.description ? `\n${trip.description}` : ''}
Dates: ${trip?.start_date || '?'} to ${trip?.end_date || '?'}
Members: ${memberList.length} (${memberList.map((m: any) => m.name || m.email).join(', ') || 'none'})
Days: ${days?.length || 0}
Packing: ${packing?.checked || 0}/${packing?.total || 0} items packed
Budget: ${budget?.total || 0} ${trip?.currency || 'EUR'} total
Reservations: ${reservations?.length || 0}
Collab Notes: ${collab_notes?.length || 0}
${days?.map((d: any, i: number) => `Day ${i + 1} (${d.date}): ${d.assignments?.length || 0} places${d.title ? ` - ${d.title}` : ''}`).join('\n') || 'No days yet'}`;
return {
description: `Summary of trip "${trip?.title || tripId}"`,
messages: [{ role: 'user', content: { type: 'text', text } }],
};
}
);
if (isAddonEnabled(ADDON_IDS.PACKING)) server.registerPrompt(
'packing-list',
{
title: 'Packing List',
description: 'Get a formatted packing checklist for a trip',
argsSchema: {
tripId: z.number().int().positive().describe('Trip ID'),
},
},
async ({ tripId }) => {
if (!canAccessTrip(tripId, userId)) {
return { messages: [{ role: 'user', content: { type: 'text', text: 'Trip not found or access denied.' } }] };
}
// Hide other members' private items (#858) from the requesting user.
const items = listPackingItems(tripId, userId);
if (!items.length) {
return { messages: [{ role: 'user', content: { type: 'text', text: 'No packing items found for this trip.' } }] };
}
const grouped = items.reduce((acc: Record<string, any[]>, item: any) => {
const cat = item.category || 'General';
if (!acc[cat]) acc[cat] = [];
acc[cat].push(item);
return acc;
}, {});
const lines = Object.entries(grouped).map(([cat, items]) =>
`## ${cat}\n${(items as any[]).map((i: any) => `- [${i.checked ? 'x' : ' '}] ${i.name}`).join('\n')}`
).join('\n\n');
const { trip } = getTripSummary(tripId, userId) || {};
return {
description: `Packing list for "${trip?.title || tripId}"`,
messages: [{ role: 'user', content: { type: 'text', text: `# Packing List: ${trip?.title || 'Trip'}\n\n${lines}\n\n_${items.length} items across ${Object.keys(grouped).length} categories_` } }],
};
}
);
if (isAddonEnabled(ADDON_IDS.BUDGET)) server.registerPrompt(
'budget-overview',
{
title: 'Budget Overview',
description: 'Get a formatted budget summary for a trip',
argsSchema: {
tripId: z.number().int().positive().describe('Trip ID'),
},
},
async ({ tripId }) => {
if (!canAccessTrip(tripId, userId)) {
return { messages: [{ role: 'user', content: { type: 'text', text: 'Trip not found or access denied.' } }] };
}
const summary = getTripSummary(tripId, userId);
if (!summary) {
return { messages: [{ role: 'user', content: { type: 'text', text: 'Trip not found.' } }] };
}
const { trip, budget } = summary;
const currency = trip?.currency || 'EUR';
const byCategory = (budget?.items || []).reduce((acc: Record<string, number>, item: any) => {
const cat = item.category || 'Uncategorized';
acc[cat] = (acc[cat] || 0) + (item.total_price || 0);
return acc;
}, {} as Record<string, number>);
const total = Object.values(byCategory).reduce((s, v) => s + v, 0);
const lines = Object.entries(byCategory)
.sort(([, a], [, b]) => b - a)
.map(([cat, amount]) => `- ${cat}: ${amount} ${currency}`)
.join('\n');
const memberCount = Math.max(1, [summary.members?.owner, ...(summary.members?.collaborators || [])].filter(Boolean).length);
const perPerson = (total / memberCount).toFixed(2);
return {
description: `Budget overview for "${trip?.title || tripId}"`,
messages: [{ role: 'user', content: { type: 'text', text: `# Budget: ${trip?.title || 'Trip'}\n\n**Total: ${total} ${currency}** (${perPerson} ${currency} per person)\n\n${lines || 'No expenses recorded.'}` } }],
};
}
);
}
-227
View File
@@ -1,227 +0,0 @@
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { z } from 'zod';
import { canAccessTrip } from '../../db/database';
import { isDemoUser } from '../../services/authService';
import {
createReservation, getReservation, updateReservation, deleteReservation,
updatePositions as updateReservationPositions,
} from '../../services/reservationService';
import { linkBudgetItemToReservation } from '../../services/budgetService';
import { getDay } from '../../services/dayService';
import { placeExists, getAssignmentForTrip } from '../../services/assignmentService';
import {
safeBroadcast, TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE,
TOOL_ANNOTATIONS_NON_IDEMPOTENT,
demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
} from './_shared';
import { canWrite } from '../scopes';
export function registerReservationTools(server: McpServer, userId: number, scopes: string[] | null): void {
if (!canWrite(scopes, 'reservations')) return;
server.registerTool(
'create_reservation',
{
description: 'Recommend a reservation for a trip. Created as pending — the user must confirm it. For flights, trains, cars, and cruises, use create_transport instead. Linking: hotel → use place_id + start_day_id + end_day_id (all three required to create the accommodation link); restaurant/event/tour/activity/other → use assignment_id. Set price to record the cost; it will appear on the booking and in the Budget tab.',
inputSchema: {
tripId: z.number().int().positive(),
title: z.string().min(1).max(200),
type: z.enum(['hotel', 'restaurant', 'event', 'tour', 'activity', 'other']).describe('Reservation type: "hotel", "restaurant", "event", "tour", "activity", or "other"'),
reservation_time: z.string().optional().describe('ISO 8601 datetime or time string'),
location: z.string().max(500).optional(),
confirmation_number: z.string().max(100).optional(),
notes: z.string().max(1000).optional(),
day_id: z.number().int().positive().optional(),
place_id: z.number().int().positive().optional().describe('Hotel place to link (hotel type only)'),
start_day_id: z.number().int().positive().optional().describe('Check-in day (hotel type only; requires place_id and end_day_id)'),
end_day_id: z.number().int().positive().optional().describe('Check-out day (hotel type only; requires place_id and start_day_id)'),
check_in: z.string().max(10).optional().describe('Check-in time (e.g. "15:00", hotel type only)'),
check_out: z.string().max(10).optional().describe('Check-out time (e.g. "11:00", hotel type only)'),
assignment_id: z.number().int().positive().optional().describe('Link to a day assignment (restaurant, train, car, cruise, event, tour, activity, other)'),
price: z.number().nonnegative().optional().describe('Reservation cost — shown on the booking and linked in the Budget tab'),
budget_category: z.string().max(100).optional().describe('Budget category for the price entry (defaults to reservation type)'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, title, type, reservation_time, location, confirmation_number, notes, day_id, place_id, start_day_id, end_day_id, check_in, check_out, assignment_id, price, budget_category }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied();
// Validate that all referenced IDs belong to this trip
if (day_id && !getDay(day_id, tripId))
return { content: [{ type: 'text' as const, text: 'day_id does not belong to this trip.' }], isError: true };
if (place_id && !placeExists(place_id, tripId))
return { content: [{ type: 'text' as const, text: 'place_id does not belong to this trip.' }], isError: true };
if (start_day_id && !getDay(start_day_id, tripId))
return { content: [{ type: 'text' as const, text: 'start_day_id does not belong to this trip.' }], isError: true };
if (end_day_id && !getDay(end_day_id, tripId))
return { content: [{ type: 'text' as const, text: 'end_day_id does not belong to this trip.' }], isError: true };
if (assignment_id && !getAssignmentForTrip(assignment_id, tripId))
return { content: [{ type: 'text' as const, text: 'assignment_id does not belong to this trip.' }], isError: true };
const createAccommodation = (type === 'hotel' && place_id && start_day_id && end_day_id)
? { place_id, start_day_id, end_day_id, check_in: check_in || undefined, check_out: check_out || undefined, confirmation: confirmation_number || undefined }
: undefined;
const metadata = price != null ? { price: String(price) } : undefined;
const { reservation, accommodationCreated } = createReservation(tripId, {
title, type, reservation_time, location, confirmation_number,
notes, day_id, place_id, assignment_id,
create_accommodation: createAccommodation,
metadata,
});
if (accommodationCreated) {
safeBroadcast(tripId, 'accommodation:created', {});
}
if (price != null && price > 0) {
const item = linkBudgetItemToReservation(tripId, reservation.id, {
name: title,
category: budget_category || type,
total_price: price,
});
safeBroadcast(tripId, 'budget:created', { item });
}
safeBroadcast(tripId, 'reservation:created', { reservation });
return ok({ reservation });
}
);
server.registerTool(
'update_reservation',
{
description: 'Update an existing reservation in a trip. Use status "confirmed" to confirm a pending recommendation, or "pending" to revert it. For flights, trains, cars, and cruises, use update_transport instead. Linking: hotel → use place_id to link to an accommodation place; restaurant/event/tour/activity/other → use assignment_id to link to a day assignment.',
inputSchema: {
tripId: z.number().int().positive(),
reservationId: z.number().int().positive(),
title: z.string().min(1).max(200).optional(),
type: z.enum(['hotel', 'restaurant', 'event', 'tour', 'activity', 'other']).optional().describe('Reservation type: "hotel", "restaurant", "event", "tour", "activity", or "other"'),
reservation_time: z.string().optional().describe('ISO 8601 datetime or time string'),
location: z.string().max(500).optional(),
confirmation_number: z.string().max(100).optional(),
notes: z.string().max(1000).optional(),
status: z.enum(['pending', 'confirmed', 'cancelled']).optional().describe('Reservation status: "pending", "confirmed", or "cancelled"'),
place_id: z.number().int().positive().nullable().optional().describe('Link to a place (use for hotel type), or null to unlink'),
assignment_id: z.number().int().positive().nullable().optional().describe('Link to a day assignment (use for restaurant, train, car, cruise, event, tour, activity, other), or null to unlink'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, reservationId, title, type, reservation_time, location, confirmation_number, notes, status, place_id, assignment_id }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied();
const existing = getReservation(reservationId, tripId);
if (!existing) return { content: [{ type: 'text' as const, text: 'Reservation not found.' }], isError: true };
if (place_id != null && !placeExists(place_id, tripId))
return { content: [{ type: 'text' as const, text: 'place_id does not belong to this trip.' }], isError: true };
if (assignment_id != null && !getAssignmentForTrip(assignment_id, tripId))
return { content: [{ type: 'text' as const, text: 'assignment_id does not belong to this trip.' }], isError: true };
const { reservation } = updateReservation(reservationId, tripId, {
title, type, reservation_time, location, confirmation_number, notes, status,
place_id: place_id !== undefined ? place_id ?? undefined : undefined,
assignment_id: assignment_id !== undefined ? assignment_id ?? undefined : undefined,
}, existing);
safeBroadcast(tripId, 'reservation:updated', { reservation });
return ok({ reservation });
}
);
server.registerTool(
'delete_reservation',
{
description: 'Delete a reservation from a trip.',
inputSchema: {
tripId: z.number().int().positive(),
reservationId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ tripId, reservationId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied();
const { deleted, accommodationDeleted } = deleteReservation(reservationId, tripId);
if (!deleted) return { content: [{ type: 'text' as const, text: 'Reservation not found.' }], isError: true };
if (accommodationDeleted) {
safeBroadcast(tripId, 'accommodation:deleted', { accommodationId: deleted.accommodation_id });
}
safeBroadcast(tripId, 'reservation:deleted', { reservationId });
return ok({ success: true });
}
);
server.registerTool(
'reorder_reservations',
{
description: 'Update the display order of reservations within a day.',
inputSchema: {
tripId: z.number().int().positive(),
positions: z.array(z.object({
id: z.number().int().positive(),
day_plan_position: z.number().int().min(0),
})).describe('Array of { id, day_plan_position } pairs'),
dayId: z.number().int().positive().optional().describe('Optionally scope the update to a specific day'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, positions, dayId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied();
updateReservationPositions(tripId, positions, dayId);
safeBroadcast(tripId, 'reservation:positions', { positions, dayId });
return ok({ success: true });
}
);
server.registerTool(
'link_hotel_accommodation',
{
description: 'Set or update the check-in/check-out day links for a hotel reservation. Creates or updates the accommodation record that ties the reservation to a place and a date range. Use the day IDs from get_trip_summary.',
inputSchema: {
tripId: z.number().int().positive(),
reservationId: z.number().int().positive(),
place_id: z.number().int().positive().describe('The hotel place to link'),
start_day_id: z.number().int().positive().describe('Check-in day ID'),
end_day_id: z.number().int().positive().describe('Check-out day ID'),
check_in: z.string().max(10).optional().describe('Check-in time (e.g. "15:00")'),
check_out: z.string().max(10).optional().describe('Check-out time (e.g. "11:00")'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, reservationId, place_id, start_day_id, end_day_id, check_in, check_out }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied();
const current = getReservation(reservationId, tripId);
if (!current) return { content: [{ type: 'text' as const, text: 'Reservation not found.' }], isError: true };
if (current.type !== 'hotel') return { content: [{ type: 'text' as const, text: 'Reservation is not of type hotel.' }], isError: true };
if (!placeExists(place_id, tripId))
return { content: [{ type: 'text' as const, text: 'place_id does not belong to this trip.' }], isError: true };
if (!getDay(start_day_id, tripId))
return { content: [{ type: 'text' as const, text: 'start_day_id does not belong to this trip.' }], isError: true };
if (!getDay(end_day_id, tripId))
return { content: [{ type: 'text' as const, text: 'end_day_id does not belong to this trip.' }], isError: true };
const isNewAccommodation = !current.accommodation_id;
const { reservation } = updateReservation(reservationId, tripId, {
place_id,
type: current.type,
status: current.status as string,
create_accommodation: { place_id, start_day_id, end_day_id, check_in: check_in || undefined, check_out: check_out || undefined },
}, current);
safeBroadcast(tripId, isNewAccommodation ? 'accommodation:created' : 'accommodation:updated', {});
safeBroadcast(tripId, 'reservation:updated', { reservation });
return ok({ reservation, accommodation_id: (reservation as any)?.accommodation_id ?? null });
}
);
}
-84
View File
@@ -1,84 +0,0 @@
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { z } from 'zod';
import { isDemoUser } from '../../services/authService';
import { listTags, createTag, getTagByIdAndUser, updateTag, deleteTag } from '../../services/tagService';
import {
TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
demoDenied, ok,
} from './_shared';
import { canRead, canWrite } from '../scopes';
export function registerTagTools(server: McpServer, userId: number, scopes: string[] | null): void {
const R = canRead(scopes, 'places');
const W = canWrite(scopes, 'places');
// --- TAGS ---
if (R) server.registerTool(
'list_tags',
{
description: 'List all tags belonging to the current user.',
inputSchema: {},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async () => {
const tags = listTags(userId);
return ok({ tags });
}
);
if (W) server.registerTool(
'create_tag',
{
description: 'Create a new tag (user-scoped label for places).',
inputSchema: {
name: z.string().min(1).max(100),
color: z.string().optional().describe('Hex color string e.g. #6366f1'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ name, color }) => {
if (isDemoUser(userId)) return demoDenied();
const tag = createTag(userId, name, color);
return ok({ tag });
}
);
if (W) server.registerTool(
'update_tag',
{
description: 'Update the name or color of an existing tag.',
inputSchema: {
tagId: z.number().int().positive(),
name: z.string().optional(),
color: z.string().optional(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tagId, name, color }) => {
if (isDemoUser(userId)) return demoDenied();
if (!getTagByIdAndUser(tagId, userId)) return { content: [{ type: 'text' as const, text: 'Tag not found.' }], isError: true };
const tag = updateTag(tagId, name, color);
if (!tag) return { content: [{ type: 'text' as const, text: 'Tag not found.' }], isError: true };
return ok({ tag });
}
);
if (W) server.registerTool(
'delete_tag',
{
description: 'Delete a tag (removes it from all places it was attached to).',
inputSchema: {
tagId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ tagId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!getTagByIdAndUser(tagId, userId)) return { content: [{ type: 'text' as const, text: 'Tag not found.' }], isError: true };
deleteTag(tagId);
return ok({ success: true });
}
);
}
-199
View File
@@ -1,199 +0,0 @@
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { z } from 'zod';
import { canAccessTrip } from '../../db/database';
import { isDemoUser } from '../../services/authService';
import {
listItems as listTodoItems, createItem as createTodoItem, updateItem as updateTodoItem,
deleteItem as deleteTodoItem, reorderItems as reorderTodoItems,
getCategoryAssignees as getTodoCategoryAssignees, updateCategoryAssignees as updateTodoCategoryAssignees,
} from '../../services/todoService';
import {
safeBroadcast, TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
} from './_shared';
import { canRead, canWrite } from '../scopes';
import { isAddonEnabled } from '../../services/adminService';
import { ADDON_IDS } from '../../addons';
export function registerTodoTools(server: McpServer, userId: number, scopes: string[] | null): void {
const R = canRead(scopes, 'todos');
const W = canWrite(scopes, 'todos');
if (!isAddonEnabled(ADDON_IDS.PACKING)) return;
// --- TODOS ---
if (R) server.registerTool(
'list_todos',
{
description: 'List all to-do items for a trip, ordered by position.',
inputSchema: {
tripId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ tripId }) => {
if (!canAccessTrip(tripId, userId)) return noAccess();
const items = listTodoItems(tripId);
return ok({ items });
}
);
if (W) server.registerTool(
'create_todo',
{
description: 'Create a new to-do item for a trip.',
inputSchema: {
tripId: z.number().int().positive(),
name: z.string().min(1).max(500).describe('To-do item name'),
category: z.string().max(100).optional().describe('Category (e.g. "Logistics", "Booking")'),
due_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Due date (YYYY-MM-DD)'),
description: z.string().max(2000).optional().describe('Additional description'),
assigned_user_id: z.number().int().positive().optional().describe('User ID to assign this task to'),
priority: z.number().int().min(0).max(3).optional().describe('Priority: 0=none, 1=low, 2=medium, 3=high'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, name, category, due_date, description, assigned_user_id, priority }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
const item = createTodoItem(tripId, { name, category, due_date, description, assigned_user_id, priority });
safeBroadcast(tripId, 'todo:created', { item });
return ok({ item });
}
);
if (W) server.registerTool(
'update_todo',
{
description: 'Update an existing to-do item. Only provided fields are changed; omitted fields stay as-is. Pass null to clear a nullable field.',
inputSchema: {
tripId: z.number().int().positive(),
itemId: z.number().int().positive(),
name: z.string().min(1).max(500).optional(),
category: z.string().max(100).optional(),
due_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).nullable().optional().describe('Set to null to clear the due date'),
description: z.string().max(2000).nullable().optional().describe('Set to null to clear'),
assigned_user_id: z.number().int().positive().nullable().optional().describe('Set to null to unassign'),
priority: z.number().int().min(0).max(3).nullable().optional(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, itemId, name, category, due_date, description, assigned_user_id, priority }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
// Build bodyKeys to signal which nullable fields were explicitly provided
const bodyKeys: string[] = [];
if (due_date !== undefined) bodyKeys.push('due_date');
if (description !== undefined) bodyKeys.push('description');
if (assigned_user_id !== undefined) bodyKeys.push('assigned_user_id');
if (priority !== undefined) bodyKeys.push('priority');
const item = updateTodoItem(tripId, itemId, { name, category, due_date, description, assigned_user_id, priority }, bodyKeys);
if (!item) return { content: [{ type: 'text' as const, text: 'To-do item not found.' }], isError: true };
safeBroadcast(tripId, 'todo:updated', { item });
return ok({ item });
}
);
if (W) server.registerTool(
'toggle_todo',
{
description: 'Mark a to-do item as checked (done) or unchecked.',
inputSchema: {
tripId: z.number().int().positive(),
itemId: z.number().int().positive(),
checked: z.boolean().describe('True to mark done, false to uncheck'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, itemId, checked }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
const item = updateTodoItem(tripId, itemId, { checked: checked ? 1 : 0 }, []);
if (!item) return { content: [{ type: 'text' as const, text: 'To-do item not found.' }], isError: true };
safeBroadcast(tripId, 'todo:updated', { item });
return ok({ item });
}
);
if (W) server.registerTool(
'delete_todo',
{
description: 'Delete a to-do item.',
inputSchema: {
tripId: z.number().int().positive(),
itemId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ tripId, itemId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
const deleted = deleteTodoItem(tripId, itemId);
if (!deleted) return { content: [{ type: 'text' as const, text: 'To-do item not found.' }], isError: true };
safeBroadcast(tripId, 'todo:deleted', { itemId });
return ok({ success: true });
}
);
if (W) server.registerTool(
'reorder_todos',
{
description: 'Reorder to-do items within a trip by providing a new ordered list of item IDs.',
inputSchema: {
tripId: z.number().int().positive(),
orderedIds: z.array(z.number().int().positive()).min(1).describe('All item IDs in the desired order'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, orderedIds }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
reorderTodoItems(tripId, orderedIds);
return ok({ success: true });
}
);
if (R) server.registerTool(
'get_todo_category_assignees',
{
description: 'Get the default assignees configured per to-do category for a trip.',
inputSchema: {
tripId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ tripId }) => {
if (!canAccessTrip(tripId, userId)) return noAccess();
const assignees = getTodoCategoryAssignees(tripId);
return ok({ assignees });
}
);
if (W) server.registerTool(
'set_todo_category_assignees',
{
description: 'Set the default assignees for a to-do category on a trip. Pass an empty array to clear.',
inputSchema: {
tripId: z.number().int().positive(),
categoryName: z.string().min(1).max(100).describe('Category name'),
userIds: z.array(z.number().int().positive()).describe('User IDs to assign as defaults for this category'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, categoryName, userIds }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
const assignees = updateTodoCategoryAssignees(tripId, categoryName, userIds);
safeBroadcast(tripId, 'todo:assignees', { category: categoryName, assignees });
return ok({ assignees });
}
);
}
-217
View File
@@ -1,217 +0,0 @@
import { canAccessTrip } from '../../db/database';
import { RateLimitService } from '../../nest/auth/rate-limit.service';
import { isDemoUser } from '../../services/authService';
import { getDay, listDays } from '../../services/dayService';
import { createReservation, notifyBookingChange } from '../../services/reservationService';
import {
buildTransitReservationParts,
cleanTransitItineraryNames,
transitCoordinatesMatch,
transitCoordinatesSchema,
transitItinerarySchema,
transitPlaceSchema,
} from '../../services/transitItineraryService';
import { geocode, plan, SCHEDULED_TRANSIT_MODES } from '../../services/transitService';
import { canRead, canWrite } from '../scopes';
import {
demoDenied,
hasTripPermission,
noAccess,
ok,
permissionDenied,
safeBroadcast,
TOOL_ANNOTATIONS_OPEN_WORLD_NON_IDEMPOTENT,
TOOL_ANNOTATIONS_OPEN_WORLD_READONLY,
} from './_shared';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { z } from 'zod';
const TRANSIT_RATE_WINDOW = 15 * 60 * 1000;
const transitRateLimiter = new RateLimitService();
const transitModes = z.enum(['TRANSIT', ...SCHEDULED_TRANSIT_MODES]);
function errorResult(err: unknown, fallback: string) {
return {
content: [{ type: 'text' as const, text: err instanceof Error ? err.message : fallback }],
isError: true,
};
}
function rateLimit(userId: number, bucket: string, max: number) {
if (transitRateLimiter.check(bucket, String(userId), max, TRANSIT_RATE_WINDOW, Date.now())) return null;
return {
content: [{ type: 'text' as const, text: 'Too many transit requests. Please try again later.' }],
isError: true,
};
}
export function registerTransitTools(server: McpServer, userId: number, scopes: string[] | null): void {
if (canRead(scopes, 'geo')) {
server.registerTool(
'search_transit_stops',
{
description:
'Search real public-transit stops and stations via Transitous. Use the returned coordinates with search_transit_routes.',
inputSchema: {
query: z.string().min(2).max(200),
language: z.string().min(2).max(5).optional(),
near: z
.object(transitCoordinatesSchema.shape)
.optional()
.describe('Optional coordinates used to bias nearby results'),
},
annotations: TOOL_ANNOTATIONS_OPEN_WORLD_READONLY,
},
async ({ query, language, near }) => {
const limited = rateLimit(userId, 'mcp_transit_geocode', 300);
if (limited) return limited;
try {
return ok(await geocode(query, language, near ? `${near.lat},${near.lng}` : undefined));
} catch (err) {
return errorResult(err, 'Transit stop search failed.');
}
},
);
server.registerTool(
'search_transit_routes',
{
description:
'Search scheduled public-transit routes via Transitous between two coordinates. Returns itineraries that can be passed unchanged to create_transit_journey. `dropped` counts provider itineraries that failed validation and are therefore absent from the results — a non-zero value means the provider offered routes this tool could not represent.',
inputSchema: {
from: transitPlaceSchema,
to: transitPlaceSchema,
time: z
.string()
.datetime({ offset: true })
.optional()
.describe('ISO 8601 departure or arrival time with timezone offset'),
arriveBy: z.boolean().optional().default(false),
modes: z.array(transitModes).max(14).optional(),
maxTransfers: z.number().int().min(0).max(10).optional(),
},
annotations: TOOL_ANNOTATIONS_OPEN_WORLD_READONLY,
},
async ({ from, to, time, arriveBy, modes, maxTransfers }) => {
const limited = rateLimit(userId, 'mcp_transit_plan', 60);
if (limited) return limited;
try {
const result = await plan({
from: `${from.lat},${from.lng}`,
to: `${to.lat},${to.lng}`,
time,
arriveBy,
modes: modes?.join(','),
maxTransfers,
});
const itineraries = result.itineraries.flatMap((itinerary) => {
const parsed = transitItinerarySchema.safeParse(cleanTransitItineraryNames(itinerary, from.name, to.name));
if (!parsed.success) return [];
const firstStop = parsed.data.legs[0].from;
const lastStop = parsed.data.legs[parsed.data.legs.length - 1].to;
return transitCoordinatesMatch(from, firstStop) && transitCoordinatesMatch(to, lastStop)
? [parsed.data]
: [];
});
// A rejected itinerary is provider data we could not vouch for, but dropping it
// silently is indistinguishable from "no routes exist" — report the count so the
// caller knows the difference.
return ok({ itineraries, dropped: result.itineraries.length - itineraries.length });
} catch (err) {
return errorResult(err, 'Transit route search failed.');
}
},
);
}
if (!canWrite(scopes, 'reservations')) return;
server.registerTool(
'create_transit_journey',
{
description:
'Add one itinerary returned by search_transit_routes to a trip day as a first-class automated public-transit journey.',
inputSchema: {
tripId: z.number().int().positive(),
dayId: z.number().int().positive().describe('Trip day on which the journey departs'),
from: transitPlaceSchema,
to: transitPlaceSchema,
itinerary: transitItinerarySchema,
notes: z.string().max(1000).optional(),
},
annotations: TOOL_ANNOTATIONS_OPEN_WORLD_NON_IDEMPOTENT,
},
async ({ tripId, dayId, from, to, itinerary, notes }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied();
const day = getDay(dayId, tripId);
if (!day) {
return { content: [{ type: 'text' as const, text: 'dayId does not belong to this trip.' }], isError: true };
}
const cleaned = cleanTransitItineraryNames(itinerary, from.name, to.name);
const firstStop = cleaned.legs[0].from;
const lastStop = cleaned.legs[cleaned.legs.length - 1].to;
if (!transitCoordinatesMatch(from, firstStop) || !transitCoordinatesMatch(to, lastStop)) {
return {
content: [
{ type: 'text' as const, text: 'The itinerary does not match the requested origin and destination.' },
],
isError: true,
};
}
let reservationParts: ReturnType<typeof buildTransitReservationParts>;
try {
reservationParts = buildTransitReservationParts(from, to, cleaned);
} catch (err) {
return errorResult(err, 'Unable to resolve the transit journey timezones.');
}
const { endpoints, metadata } = reservationParts;
const departure = endpoints[0];
const arrival = endpoints[endpoints.length - 1];
if (!day.date) {
return {
content: [{ type: 'text' as const, text: 'Automated transit requires a dated trip day.' }],
isError: true,
};
}
if (departure.local_date !== day.date) {
return {
content: [
{
type: 'text' as const,
text: `The journey departs on ${departure.local_date}, but dayId is ${day.date}.`,
},
],
isError: true,
};
}
const endDay = listDays(tripId).days.find((day) => day.date === arrival.local_date);
if (!endDay) {
return {
content: [{ type: 'text' as const, text: `No trip day exists for the arrival date ${arrival.local_date}.` }],
isError: true,
};
}
const { reservation } = createReservation(tripId, {
title: `${from.name} → ${to.name}`,
type: 'transit',
status: 'confirmed',
day_id: dayId,
end_day_id: endDay.id,
reservation_time: `${departure.local_date}T${departure.local_time}`,
reservation_end_time: `${arrival.local_date}T${arrival.local_time}`,
notes,
metadata,
endpoints,
needs_review: false,
});
safeBroadcast(tripId, 'reservation:created', { reservation });
notifyBookingChange(tripId, userId, reservation.title, reservation.type || '');
return ok({ reservation });
},
);
}
-229
View File
@@ -1,229 +0,0 @@
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { z } from 'zod';
import { canAccessTrip } from '../../db/database';
import { isDemoUser } from '../../services/authService';
import {
createReservation, deleteReservation, getReservation, updateReservation,
type EndpointInput,
} from '../../services/reservationService';
import { linkBudgetItemToReservation } from '../../services/budgetService';
import { getDay } from '../../services/dayService';
import { findByIata } from '../../services/airportService';
import {
safeBroadcast, TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
TOOL_ANNOTATIONS_WRITE, demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
} from './_shared';
import { canWrite } from '../scopes';
const TRANSPORT_TYPES = ['flight', 'train', 'car', 'cruise'] as const;
const endpointObjectSchema = z.object({
role: z.enum(['from', 'to', 'stop']).describe('Endpoint role: "from" (origin), "to" (destination), or "stop" (intermediate)'),
sequence: z.number().int().min(0).describe('Order within the route (0-based)'),
name: z.string().min(1).describe('Location name (e.g. "Paris Gare de Lyon", "ZRH Terminal 2")'),
code: z.string().optional().describe('IATA airport code for flights (e.g. "ZRH"). Leave empty for other transport types.'),
lat: z.number().optional().describe('Latitude. For flights, leave empty and set code instead — coordinates are filled from the airport.'),
lng: z.number().optional().describe('Longitude. For flights, leave empty and set code instead — coordinates are filled from the airport.'),
timezone: z.string().optional().describe('IANA timezone (e.g. "Europe/Zurich"). Use airport tz for flights.'),
local_time: z.string().optional().describe('Local departure/arrival time at this endpoint, e.g. "14:35"'),
local_date: z.string().optional().describe('Local date at this endpoint, YYYY-MM-DD'),
});
const endpointSchema = z.array(endpointObjectSchema).optional();
type Endpoint = z.infer<typeof endpointObjectSchema>;
/**
* Endpoint coordinates are stored NOT NULL. Callers may supply a flight endpoint
* with only an IATA `code` (the tool description encourages this), so fill missing
* lat/lng/timezone from the airport database. Returns an error string for the first
* endpoint that can't be resolved rather than letting the NOT NULL bind throw.
*
* Normalizes to the service's EndpointInput shape (nullable fields coerced from the
* schema's optionals), so lat/lng are guaranteed present before the insert.
*/
function resolveEndpointCoords(endpoints: Endpoint[] | undefined): { endpoints: EndpointInput[] } | { error: string } {
if (!endpoints) return { endpoints: [] };
const out: EndpointInput[] = [];
for (const e of endpoints) {
const base = {
role: e.role,
sequence: e.sequence,
name: e.name,
code: e.code ?? null,
timezone: e.timezone ?? null,
local_time: e.local_time ?? null,
local_date: e.local_date ?? null,
};
if (e.lat != null && e.lng != null) { out.push({ ...base, lat: e.lat, lng: e.lng }); continue; }
if (e.code) {
const airport = findByIata(e.code);
if (airport) {
out.push({ ...base, lat: airport.lat, lng: airport.lng, timezone: e.timezone ?? airport.tz });
continue;
}
return { error: `Could not resolve airport code "${e.code}". Use search_airports to find a valid IATA code, or supply lat/lng directly.` };
}
return { error: `Endpoint "${e.name}" is missing coordinates. For flights set "code" to the IATA airport code; for other transport types supply lat/lng.` };
}
return { endpoints: out };
}
export function registerTransportTools(server: McpServer, userId: number, scopes: string[] | null): void {
if (!canWrite(scopes, 'reservations')) return;
server.registerTool(
'create_transport',
{
description: 'Create a transport booking (flight, train, car, or cruise) for a trip. Use endpoints[] to record origin/destination and intermediate stops — for flights, set code to the IATA airport code (use search_airports first). Created as pending — confirm with update_transport. Set price to record the cost; it will appear on the booking and in the Budget tab.',
inputSchema: {
tripId: z.number().int().positive(),
type: z.enum(['flight', 'train', 'car', 'cruise']),
title: z.string().min(1).max(200),
status: z.enum(['pending', 'confirmed', 'cancelled']).optional().default('pending'),
start_day_id: z.number().int().positive().optional().describe('Departure day'),
end_day_id: z.number().int().positive().optional().describe('Arrival day (if different from departure)'),
reservation_time: z.string().optional().describe('ISO 8601 datetime or time string for departure'),
reservation_end_time: z.string().optional().describe('ISO 8601 datetime or time string for arrival'),
confirmation_number: z.string().max(100).optional(),
notes: z.string().max(1000).optional(),
metadata: z.record(z.string(), z.string()).optional().describe('Type-specific metadata: flights → { airline, flight_number, departure_airport, arrival_airport }; trains → { train_number, platform, seat }'),
endpoints: endpointSchema,
needs_review: z.boolean().optional(),
price: z.number().nonnegative().optional().describe('Transport cost — shown on the booking and linked in the Budget tab'),
budget_category: z.string().max(100).optional().describe('Budget category for the price entry (defaults to transport type)'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, type, title, status, start_day_id, end_day_id, reservation_time, reservation_end_time, confirmation_number, notes, metadata, endpoints, needs_review, price, budget_category }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied();
if (start_day_id && !getDay(start_day_id, tripId))
return { content: [{ type: 'text' as const, text: 'start_day_id does not belong to this trip.' }], isError: true };
if (end_day_id && !getDay(end_day_id, tripId))
return { content: [{ type: 'text' as const, text: 'end_day_id does not belong to this trip.' }], isError: true };
const resolved = resolveEndpointCoords(endpoints);
if ('error' in resolved) return { content: [{ type: 'text' as const, text: resolved.error }], isError: true };
const meta: Record<string, string> = { ...(metadata ?? {}) };
if (price != null) meta.price = String(price);
const { reservation } = createReservation(tripId, {
title,
type,
reservation_time,
reservation_end_time,
location: undefined,
confirmation_number,
notes,
day_id: start_day_id,
end_day_id: end_day_id ?? start_day_id,
status: status ?? 'pending',
metadata: Object.keys(meta).length > 0 ? meta : undefined,
endpoints: resolved.endpoints,
needs_review,
});
if (price != null && price > 0) {
const item = linkBudgetItemToReservation(tripId, reservation.id, {
name: title,
category: budget_category || type,
total_price: price,
});
safeBroadcast(tripId, 'budget:created', { item });
}
safeBroadcast(tripId, 'reservation:created', { reservation });
return ok({ reservation });
}
);
server.registerTool(
'update_transport',
{
description: 'Update an existing transport booking. Pass endpoints[] to replace the full list of stops (origin, destination, intermediates). Use status "confirmed" to confirm.',
inputSchema: {
tripId: z.number().int().positive(),
reservationId: z.number().int().positive(),
type: z.enum(['flight', 'train', 'car', 'cruise']).optional(),
title: z.string().min(1).max(200).optional(),
status: z.enum(['pending', 'confirmed', 'cancelled']).optional(),
start_day_id: z.number().int().positive().optional().describe('Departure day'),
end_day_id: z.number().int().positive().optional().describe('Arrival day (if different from departure)'),
reservation_time: z.string().optional().describe('ISO 8601 datetime or time string for departure'),
reservation_end_time: z.string().optional().describe('ISO 8601 datetime or time string for arrival'),
confirmation_number: z.string().max(100).optional(),
notes: z.string().max(1000).optional(),
metadata: z.record(z.string(), z.string()).optional().describe('Type-specific metadata: flights → { airline, flight_number, departure_airport, arrival_airport }; trains → { train_number, platform, seat }'),
endpoints: endpointSchema,
needs_review: z.boolean().optional(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, reservationId, type, title, status, start_day_id, end_day_id, reservation_time, reservation_end_time, confirmation_number, notes, metadata, endpoints, needs_review }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied();
const existing = getReservation(reservationId, tripId);
if (!existing) return { content: [{ type: 'text' as const, text: 'Transport not found.' }], isError: true };
const resolvedType = type ?? existing.type;
if (!(TRANSPORT_TYPES as readonly string[]).includes(resolvedType))
return { content: [{ type: 'text' as const, text: 'Reservation is not a transport type. Use update_reservation instead.' }], isError: true };
if (start_day_id && !getDay(start_day_id, tripId))
return { content: [{ type: 'text' as const, text: 'start_day_id does not belong to this trip.' }], isError: true };
if (end_day_id && !getDay(end_day_id, tripId))
return { content: [{ type: 'text' as const, text: 'end_day_id does not belong to this trip.' }], isError: true };
// Only resolve when endpoints are explicitly provided; undefined leaves them untouched.
let resolvedEndpoints: EndpointInput[] | undefined;
if (endpoints !== undefined) {
const resolved = resolveEndpointCoords(endpoints);
if ('error' in resolved) return { content: [{ type: 'text' as const, text: resolved.error }], isError: true };
resolvedEndpoints = resolved.endpoints;
}
const { reservation } = updateReservation(reservationId, tripId, {
title,
type,
reservation_time,
reservation_end_time,
confirmation_number,
notes,
day_id: start_day_id,
end_day_id,
status,
metadata,
endpoints: resolvedEndpoints,
needs_review,
}, existing);
safeBroadcast(tripId, 'reservation:updated', { reservation });
return ok({ reservation });
}
);
server.registerTool(
'delete_transport',
{
description: 'Delete a transport booking from a trip.',
inputSchema: {
tripId: z.number().int().positive(),
reservationId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ tripId, reservationId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied();
const { deleted } = deleteReservation(reservationId, tripId);
if (!deleted) return { content: [{ type: 'text' as const, text: 'Transport not found.' }], isError: true };
safeBroadcast(tripId, 'reservation:deleted', { reservationId });
return ok({ success: true });
}
);
}
-398
View File
@@ -1,398 +0,0 @@
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { z } from 'zod';
import { canAccessTrip } from '../../db/database';
import { isDemoUser } from '../../services/authService';
import {
listTrips, createTrip, updateTrip, deleteTrip, getTripSummary,
isOwner, verifyTripAccess,
listMembers as listTripMembers, getTripOwner, addMember as addTripMember,
removeMember as removeTripMember,
copyTripById, exportICS, NotFoundError, ValidationError,
} from '../../services/tripService';
import {
createOrUpdateShareLink, getShareLink, deleteShareLink,
} from '../../services/shareService';
import { isAddonEnabled, getCollabFeatures } from '../../services/adminService';
import { ADDON_IDS } from '../../addons';
import { countMessages, listPolls } from '../../services/collabService';
import {
listItems as listTodoItems,
} from '../../services/todoService';
import { rebaseTripCurrency } from '../../services/budgetService';
import {
safeBroadcast, MAX_MCP_TRIP_DAYS,
TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
} from './_shared';
import { canRead, canReadTrips, canWrite, canDeleteTrips, canShareTrips } from '../scopes';
export function registerTripTools(server: McpServer, userId: number, scopes: string[] | null, getDeprecationNotice: () => string | null = () => null): void {
const R = canReadTrips(scopes);
const W = canWrite(scopes, 'trips');
const D = canDeleteTrips(scopes);
const S = canShareTrips(scopes);
// --- TRIPS ---
if (W) server.registerTool(
'create_trip',
{
description: 'Create a new trip. Returns the created trip with its generated days.',
inputSchema: {
title: z.string().min(1).max(200).describe('Trip title'),
description: z.string().max(2000).optional().describe('Trip description'),
start_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Start date (YYYY-MM-DD)'),
end_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('End date (YYYY-MM-DD)'),
currency: z.string().length(3).optional().describe('Currency code (e.g. EUR, USD)'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ title, description, start_date, end_date, currency }) => {
if (isDemoUser(userId)) return demoDenied();
if (start_date) {
const d = new Date(start_date + 'T00:00:00Z');
if (isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== start_date)
return { content: [{ type: 'text' as const, text: 'start_date is not a valid calendar date.' }], isError: true };
}
if (end_date) {
const d = new Date(end_date + 'T00:00:00Z');
if (isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== end_date)
return { content: [{ type: 'text' as const, text: 'end_date is not a valid calendar date.' }], isError: true };
}
if (start_date && end_date && new Date(end_date) < new Date(start_date)) {
return { content: [{ type: 'text' as const, text: 'End date must be after start date.' }], isError: true };
}
const { trip } = createTrip(userId, { title, description, start_date, end_date, currency }, MAX_MCP_TRIP_DAYS);
return ok({ trip });
}
);
if (W) server.registerTool(
'update_trip',
{
description: 'Update an existing trip\'s details.',
inputSchema: {
tripId: z.number().int().positive(),
title: z.string().min(1).max(200).optional(),
description: z.string().max(2000).optional(),
start_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
end_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
currency: z.string().length(3).optional(),
is_archived: z.boolean().optional().describe('Archive (true) or unarchive (false) the trip'),
cover_image: z.string().optional().describe('Cover image path, e.g. /uploads/covers/abc.jpg'),
date_shift_mode: z.enum(['keep_bookings', 'shift_all']).optional().describe(
'When changing dates: keep_bookings (default) keeps dated reservations/accommodations on their dates while day plans move; shift_all moves the whole itinerary, bookings included'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, title, description, start_date, end_date, currency, is_archived, cover_image, date_shift_mode }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('trip_edit', tripId, userId)) return permissionDenied();
if (start_date) {
const d = new Date(start_date + 'T00:00:00Z');
if (isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== start_date)
return { content: [{ type: 'text' as const, text: 'start_date is not a valid calendar date.' }], isError: true };
}
if (end_date) {
const d = new Date(end_date + 'T00:00:00Z');
if (isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== end_date)
return { content: [{ type: 'text' as const, text: 'end_date is not a valid calendar date.' }], isError: true };
}
// Re-anchor the budget before the trip row moves off the old currency (#1543).
await rebaseTripCurrency(tripId, currency);
const { updatedTrip } = updateTrip(tripId, userId, { title, description, start_date, end_date, currency, is_archived, cover_image, date_shift_mode }, 'user');
safeBroadcast(tripId, 'trip:updated', { trip: updatedTrip });
return ok({ trip: updatedTrip });
}
);
if (D) server.registerTool(
'delete_trip',
{
description: 'Delete a trip. Only the trip owner can delete it.',
inputSchema: {
tripId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ tripId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!isOwner(tripId, userId)) return noAccess();
deleteTrip(tripId, userId, 'user');
return ok({ success: true, tripId });
}
);
// list_trips and get_trip_summary are always registered regardless of OAuth scopes —
// they are navigation tools that any MCP client needs to discover trip IDs.
server.registerTool(
'list_trips',
{
description: 'List all trips the current user owns or is a member of. Use this for trip discovery before calling get_trip_summary.',
inputSchema: {
include_archived: z.boolean().optional().describe('Include archived trips (default false)'),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ include_archived }) => {
const notice = getDeprecationNotice();
const trips = listTrips(userId, include_archived ? null : 0);
if (notice) return {
isError: true as const,
content: [
{ type: 'text' as const, text: notice },
{ type: 'text' as const, text: JSON.stringify({ trips }, null, 2) },
],
};
return ok({ trips });
}
);
// --- TRIP SUMMARY ---
server.registerTool(
'get_trip_summary',
{
description: 'Get a full denormalized summary of a trip in a single call: metadata, members, days with assignments and notes, accommodations, budget line items (when enabled), packing list (when enabled), reservations, collab notes and poll/message counts (when enabled), and to-do items (when enabled). Use this as a context loader before planning or modifying a trip.',
inputSchema: {
tripId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ tripId }) => {
if (!canAccessTrip(tripId, userId)) return noAccess();
const summary = getTripSummary(tripId, userId);
if (!summary) return noAccess();
// Addon availability gates
const packingEnabled = isAddonEnabled(ADDON_IDS.PACKING);
const budgetEnabled = isAddonEnabled(ADDON_IDS.BUDGET);
const collabEnabled = isAddonEnabled(ADDON_IDS.COLLAB);
const collabFeatures = collabEnabled ? getCollabFeatures() : null;
// Scope gates — sections not covered by the client's OAuth scopes are omitted.
// Core trip data (metadata, days, members, accommodations) is always included
// because this tool is always registered and needed for navigation.
const canReadBudget = budgetEnabled && canRead(scopes, 'budget');
const canReadPacking = packingEnabled && canRead(scopes, 'packing');
const canReadCollab = collabEnabled && canRead(scopes, 'collab');
const canReadTodos = packingEnabled && canRead(scopes, 'todos');
const canReadRes = canRead(scopes, 'reservations');
const todos = canReadTodos ? listTodoItems(tripId) : [];
let pollCount = 0;
let messageCount = 0;
if (canReadCollab) {
if (collabFeatures?.polls) pollCount = listPolls(tripId).length;
if (collabFeatures?.chat) messageCount = countMessages(tripId);
}
const notice = getDeprecationNotice();
// The core bucket (trip metadata, members WITH email, days with place
// coordinates, accommodations) carries confidential PII and itinerary data,
// so it is gated on trips:read just like the sub-sections below. Without a
// read scope the tool still resolves trip id + title so it stays usable for
// navigation (list_trips already covers discovery). trek_ PATs (null scopes)
// and any trips:read holder keep the full payload — no behaviour change.
const summaryData = {
trip: R ? summary.trip : { id: summary.trip.id, title: summary.trip.title },
members: R ? summary.members : undefined,
days: R ? summary.days : undefined,
// Accommodations are "accommodation details" under reservations:read too
// (see SCOPE_INFO) and pair with reservations in the share payload, so a
// reservations-scoped token keeps them — gate on either read scope.
accommodations: (R || canReadRes) ? summary.accommodations : undefined,
reservations: canReadRes ? summary.reservations : undefined,
packing: canReadPacking ? summary.packing : undefined,
budget: canReadBudget ? summary.budget : undefined,
collab_notes: canReadCollab && collabFeatures?.notes ? summary.collab_notes : [],
todos,
pollCount,
messageCount,
};
if (notice) return {
isError: true as const,
content: [
{ type: 'text' as const, text: notice },
{ type: 'text' as const, text: JSON.stringify(summaryData, null, 2) },
],
};
return ok(summaryData);
}
);
// --- TRIP MEMBERS, COPY, ICS, SHARE ---
if (R) server.registerTool(
'list_trip_members',
{
description: 'List all members of a trip (owner + collaborators).',
inputSchema: {
tripId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ tripId }) => {
if (!canAccessTrip(tripId, userId)) return noAccess();
const ownerRow = getTripOwner(tripId);
if (!ownerRow) return noAccess();
const { owner, members } = listTripMembers(tripId, ownerRow.user_id);
return ok({ owner, members });
}
);
if (W) server.registerTool(
'add_trip_member',
{
description: 'Add a user to a trip by their username or email address. Only the trip owner can do this.',
inputSchema: {
tripId: z.number().int().positive(),
identifier: z.string().min(1).describe('Username or email of the user to add'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, identifier }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
const ownerRow = getTripOwner(tripId);
if (!ownerRow || ownerRow.user_id !== userId)
return { content: [{ type: 'text' as const, text: 'Only the trip owner can add members.' }], isError: true };
try {
const result = addTripMember(tripId, identifier, ownerRow.user_id, userId);
safeBroadcast(tripId, 'member:added', { member: result.member });
return ok({ member: result.member });
} catch (err) {
const msg = err instanceof ValidationError || err instanceof NotFoundError ? err.message : 'Failed to add member.';
return { content: [{ type: 'text' as const, text: msg }], isError: true };
}
}
);
if (W) server.registerTool(
'remove_trip_member',
{
description: 'Remove a member from a trip. Only the trip owner can do this.',
inputSchema: {
tripId: z.number().int().positive(),
memberId: z.number().int().positive().describe('User ID of the member to remove'),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ tripId, memberId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
const ownerRow = getTripOwner(tripId);
if (!ownerRow || ownerRow.user_id !== userId)
return { content: [{ type: 'text' as const, text: 'Only the trip owner can remove members.' }], isError: true };
removeTripMember(tripId, memberId);
safeBroadcast(tripId, 'member:removed', { userId: memberId });
return ok({ success: true });
}
);
if (W) server.registerTool(
'copy_trip',
{
description: 'Duplicate a trip (all days, places, itinerary, packing, budget, reservations, day notes). Packing items are reset to unchecked. Returns the new trip.',
inputSchema: {
tripId: z.number().int().positive().describe('Source trip ID to duplicate'),
title: z.string().min(1).max(200).optional().describe('Title for the new trip (defaults to source title)'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, title }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
try {
const newTripId = copyTripById(tripId, userId, title);
const newTrip = canAccessTrip(newTripId, userId);
return ok({ trip: { id: newTripId, ...newTrip } });
} catch {
return { content: [{ type: 'text' as const, text: 'Failed to copy trip.' }], isError: true };
}
}
);
if (R) server.registerTool(
'export_trip_ics',
{
description: 'Export a trip\'s itinerary and reservations as iCalendar (.ics) format text. Useful for importing into calendar apps.',
inputSchema: {
tripId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ tripId }) => {
if (!canAccessTrip(tripId, userId)) return noAccess();
try {
const { ics, filename } = exportICS(tripId);
return ok({ ics, filename });
} catch {
return { content: [{ type: 'text' as const, text: 'Trip not found.' }], isError: true };
}
}
);
if (S) server.registerTool(
'get_share_link',
{
description: 'Get the current public share link for a trip, including its permission flags. Returns null if no share link exists.',
inputSchema: {
tripId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ tripId }) => {
// Read parity with the REST route GET /api/trips/:tripId/share-link, which
// only requires trip membership (share_manage gates create/delete, not read).
if (!canAccessTrip(tripId, userId)) return noAccess();
const link = getShareLink(String(tripId));
return ok({ link });
}
);
if (S) server.registerTool(
'create_share_link',
{
description: 'Create or update the public share link for a trip. Set permission flags to control what is visible to guests.',
inputSchema: {
tripId: z.number().int().positive(),
share_map: z.boolean().optional().default(true).describe('Share the map and places'),
share_bookings: z.boolean().optional().default(true).describe('Share reservations'),
share_packing: z.boolean().optional().default(false).describe('Share packing list'),
share_budget: z.boolean().optional().default(false).describe('Share budget'),
share_collab: z.boolean().optional().default(false).describe('Share collab messages'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, share_map, share_bookings, share_packing, share_budget, share_collab }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('share_manage', tripId, userId)) return permissionDenied();
const { token, created } = createOrUpdateShareLink(String(tripId), userId, {
share_map: share_map ?? true,
share_bookings: share_bookings ?? true,
share_packing: share_packing ?? false,
share_budget: share_budget ?? false,
share_collab: share_collab ?? false,
});
return ok({ token, created });
}
);
if (S) server.registerTool(
'delete_share_link',
{
description: 'Revoke the public share link for a trip. Guests will no longer be able to access the shared view.',
inputSchema: {
tripId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ tripId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('share_manage', tripId, userId)) return permissionDenied();
deleteShareLink(String(tripId));
return ok({ success: true });
}
);
}
-401
View File
@@ -1,401 +0,0 @@
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { z } from 'zod';
import { isDemoUser, getCurrentUser } from '../../services/authService';
import {
getOwnPlan, getActivePlan, getActivePlanId, getPlanData,
updatePlan, setUserColor,
sendInvite as sendVacayInvite, acceptInvite, declineInvite, cancelInvite, dissolvePlan,
getAvailableUsers,
listYears, addYear, deleteYear,
getEntries as getVacayEntries, toggleEntry, toggleCompanyHoliday,
getStats as getVacayStats, updateStats as updateVacayStats,
addHolidayCalendar, updateHolidayCalendar, deleteHolidayCalendar,
getCountries as getHolidayCountries, getHolidays,
} from '../../services/vacayService';
import { isAddonEnabled } from '../../services/adminService';
import { ADDON_IDS } from '../../addons';
import {
TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
demoDenied, ok,
} from './_shared';
import { canRead, canWrite } from '../scopes';
export function registerVacayTools(server: McpServer, userId: number, scopes: string[] | null): void {
const R = canRead(scopes, 'vacay');
const W = canWrite(scopes, 'vacay');
if (isAddonEnabled(ADDON_IDS.VACAY)) {
if (R) server.registerTool(
'get_vacay_plan',
{
description: "Get the current user's active vacation plan (own or joined).",
inputSchema: {},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async () => {
const plan = getPlanData(userId);
return ok({ plan });
}
);
if (W) server.registerTool(
'update_vacay_plan',
{
description: 'Update vacation plan settings (weekends blocking, holidays, carry-over).',
inputSchema: {
block_weekends: z.boolean().optional(),
holidays_enabled: z.boolean().optional(),
holidays_region: z.string().nullable().optional(),
company_holidays_enabled: z.boolean().optional(),
carry_over_enabled: z.boolean().optional(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ block_weekends, holidays_enabled, holidays_region, company_holidays_enabled, carry_over_enabled }) => {
if (isDemoUser(userId)) return demoDenied();
const planId = getActivePlanId(userId);
// updatePlan already returns the fully-hydrated { plan }; surface it so the
// AI consumer sees the updated plan, matching get_vacay_plan.
const result = await updatePlan(planId, { block_weekends, holidays_enabled, holidays_region, company_holidays_enabled, carry_over_enabled }, undefined);
return ok(result);
}
);
if (W) server.registerTool(
'set_vacay_color',
{
description: "Set the current user's color in the vacation plan calendar.",
inputSchema: {
color: z.string().describe('Hex color e.g. #6366f1'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ color }) => {
if (isDemoUser(userId)) return demoDenied();
const planId = getActivePlanId(userId);
setUserColor(userId, planId, color, undefined);
// Echo the persisted color (mirrors the service default) so the AI consumer sees what was set.
return ok({ success: true, color: color || '#6366f1' });
}
);
if (R) server.registerTool(
'get_available_vacay_users',
{
description: 'List users who can be invited to the current vacation plan.',
inputSchema: {},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async () => {
const planId = getActivePlanId(userId);
const users = getAvailableUsers(userId, planId);
return ok({ users });
}
);
if (W) server.registerTool(
'send_vacay_invite',
{
description: 'Invite a user to join the vacation plan by their user ID.',
inputSchema: {
targetUserId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ targetUserId }) => {
if (isDemoUser(userId)) return demoDenied();
const planId = getActivePlanId(userId);
const me = getCurrentUser(userId);
if (!me) return { content: [{ type: 'text' as const, text: 'User not found.' }], isError: true };
const result = sendVacayInvite(planId, userId, me.username, me.email, targetUserId);
if (result.error) return { content: [{ type: 'text' as const, text: result.error }], isError: true };
return ok({ success: true });
}
);
if (W) server.registerTool(
'accept_vacay_invite',
{
description: 'Accept a pending invitation to join another user\'s vacation plan.',
inputSchema: {
planId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ planId }) => {
if (isDemoUser(userId)) return demoDenied();
const result = acceptInvite(userId, planId, undefined);
if (result.error) return { content: [{ type: 'text' as const, text: result.error }], isError: true };
return ok({ success: true });
}
);
if (W) server.registerTool(
'decline_vacay_invite',
{
description: 'Decline a pending vacation plan invitation.',
inputSchema: {
planId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ planId }) => {
declineInvite(userId, planId, undefined);
return ok({ success: true });
}
);
if (W) server.registerTool(
'cancel_vacay_invite',
{
description: 'Cancel an outgoing invitation (owner cancels invite they sent).',
inputSchema: {
targetUserId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ targetUserId }) => {
if (isDemoUser(userId)) return demoDenied();
const planId = getActivePlanId(userId);
cancelInvite(planId, targetUserId);
return ok({ success: true });
}
);
if (W) server.registerTool(
'dissolve_vacay_plan',
{
description: 'Dissolve the shared plan — all members are removed and everyone returns to their own individual plan.',
inputSchema: {},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async () => {
if (isDemoUser(userId)) return demoDenied();
dissolvePlan(userId, undefined);
return ok({ success: true });
}
);
if (R) server.registerTool(
'list_vacay_years',
{
description: 'List calendar years tracked in the current vacation plan.',
inputSchema: {},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async () => {
const planId = getActivePlanId(userId);
const years = listYears(planId);
return ok({ years });
}
);
if (W) server.registerTool(
'add_vacay_year',
{
description: 'Add a calendar year to the vacation plan.',
inputSchema: {
year: z.number().int().min(2000).max(2100),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ year }) => {
if (isDemoUser(userId)) return demoDenied();
const planId = getActivePlanId(userId);
const years = addYear(planId, year, undefined);
return ok({ years });
}
);
if (W) server.registerTool(
'delete_vacay_year',
{
description: 'Remove a calendar year from the vacation plan.',
inputSchema: {
year: z.number().int(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ year }) => {
if (isDemoUser(userId)) return demoDenied();
const planId = getActivePlanId(userId);
const years = deleteYear(planId, year, undefined);
return ok({ years });
}
);
if (R) server.registerTool(
'get_vacay_entries',
{
description: 'Get all vacation day entries for a plan and year.',
inputSchema: {
year: z.number().int(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ year }) => {
const planId = getActivePlanId(userId);
const entries = getVacayEntries(planId, String(year));
return ok({ entries });
}
);
if (W) server.registerTool(
'toggle_vacay_entry',
{
description: 'Toggle a day on or off as a vacation day for the current user.',
inputSchema: {
date: z.string().describe('ISO date YYYY-MM-DD'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ date }) => {
if (isDemoUser(userId)) return demoDenied();
const planId = getActivePlanId(userId);
const result = toggleEntry(userId, planId, date, undefined);
return ok(result);
}
);
if (W) server.registerTool(
'toggle_company_holiday',
{
description: 'Toggle a date as a company holiday for the whole plan.',
inputSchema: {
date: z.string(),
note: z.string().optional(),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ date, note }) => {
if (isDemoUser(userId)) return demoDenied();
const planId = getActivePlanId(userId);
const result = toggleCompanyHoliday(planId, date, note, undefined);
return ok(result);
}
);
if (R) server.registerTool(
'get_vacay_stats',
{
description: 'Get vacation statistics for a specific year (days used, remaining, carried over).',
inputSchema: {
year: z.number().int(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ year }) => {
const planId = getActivePlanId(userId);
const stats = getVacayStats(planId, year);
return ok({ stats });
}
);
if (W) server.registerTool(
'update_vacay_stats',
{
description: 'Update the vacation day allowance for a specific user and year.',
inputSchema: {
year: z.number().int(),
vacationDays: z.number().int().min(0),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ year, vacationDays }) => {
if (isDemoUser(userId)) return demoDenied();
const planId = getActivePlanId(userId);
updateVacayStats(userId, planId, year, vacationDays, undefined);
return ok({ success: true });
}
);
if (W) server.registerTool(
'add_holiday_calendar',
{
description: 'Add a public holiday calendar (by region code) to the vacation plan.',
inputSchema: {
region: z.string().describe('Country/region code e.g. US, GB, DE'),
label: z.string().nullable().optional(),
color: z.string().optional(),
sortOrder: z.number().int().optional(),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ region, label, color, sortOrder }) => {
if (isDemoUser(userId)) return demoDenied();
const planId = getActivePlanId(userId);
const calendar = addHolidayCalendar(planId, region, label ?? null, color, sortOrder, undefined);
return ok({ calendar });
}
);
if (W) server.registerTool(
'update_holiday_calendar',
{
description: 'Update label or color for a holiday calendar.',
inputSchema: {
calendarId: z.number().int().positive(),
label: z.string().nullable().optional(),
color: z.string().optional(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ calendarId, label, color }) => {
if (isDemoUser(userId)) return demoDenied();
const planId = getActivePlanId(userId);
const cal = updateHolidayCalendar(calendarId, planId, { label, color }, undefined);
if (!cal) return { content: [{ type: 'text' as const, text: 'Holiday calendar not found.' }], isError: true };
return ok({ calendar: cal });
}
);
if (W) server.registerTool(
'delete_holiday_calendar',
{
description: 'Remove a holiday calendar from the vacation plan.',
inputSchema: {
calendarId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ calendarId }) => {
if (isDemoUser(userId)) return demoDenied();
const planId = getActivePlanId(userId);
deleteHolidayCalendar(calendarId, planId, undefined);
return ok({ success: true });
}
);
if (R) server.registerTool(
'list_holiday_countries',
{
description: 'List countries available for public holiday calendars.',
inputSchema: {},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async () => {
const result = await getHolidayCountries();
if (result.error) return { content: [{ type: 'text' as const, text: result.error }], isError: true };
return ok({ countries: result.data });
}
);
if (R) server.registerTool(
'list_holidays',
{
description: 'List public holidays for a country and year.',
inputSchema: {
country: z.string().describe('ISO 3166-1 alpha-2 code'),
year: z.number().int(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ country, year }) => {
const result = await getHolidays(String(year), country);
if (result.error) return { content: [{ type: 'text' as const, text: result.error }], isError: true };
return ok({ holidays: result.data });
}
);
}
}
-119
View File
@@ -1,119 +0,0 @@
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import { db } from '../db/database';
import { JWT_SECRET } from '../config';
import { AuthRequest, OptionalAuthRequest, User } from '../types';
import { applyIdempotency } from './idempotency';
import { isDemoEmail } from '../services/demo';
export function extractToken(req: Request): string | null {
// Prefer httpOnly cookie; fall back to Authorization: Bearer (MCP, API clients)
const cookieToken = (req as any).cookies?.trek_session;
if (cookieToken) return cookieToken;
const authHeader = req.headers['authorization'];
return (authHeader && authHeader.split(' ')[1]) || null;
}
/**
* Verify a JWT and load its user, enforcing the password_version gate.
*
* Exported so every auth surface in the codebase (MCP bearer tokens,
* file download query tokens, the photo-serving route) goes through the
* same check. A password reset bumps `users.password_version`, which
* invalidates every JWT that embedded the prior value — but only if
* every verify path actually compares the claim. Previously several
* paths called `jwt.verify` directly and skipped the DB lookup, so a
* stolen token kept working after the victim reset.
*/
export function verifyJwtAndLoadUser(token: string): User | null {
try {
const decoded = jwt.verify(token, JWT_SECRET, { algorithms: ['HS256'] }) as { id: number; pv?: number; purpose?: string };
// Purpose-scoped tokens (e.g. the short-lived mfa_login token) share this
// secret but are not full session tokens — only their dedicated endpoint
// may accept them, so reject any token carrying a purpose claim here.
if (decoded.purpose) return null;
const row = db.prepare(
'SELECT id, username, email, role, password_version FROM users WHERE id = ?'
).get(decoded.id) as (User & { password_version?: number }) | undefined;
if (!row) return null;
// Session invalidation: any token whose embedded password_version
// predates the user's current one is rejected. Tokens issued before
// the `pv` claim existed (decoded.pv === undefined) are treated as
// version 0 so legacy sessions keep working until the user resets.
const tokenPv = typeof decoded.pv === 'number' ? decoded.pv : 0;
const currentPv = typeof row.password_version === 'number' ? row.password_version : 0;
if (tokenPv !== currentPv) return null;
// Don't leak password_version beyond the middleware.
const { password_version: _pv, ...user } = row;
return user as User;
} catch {
return null;
}
}
const authenticate = (req: Request, res: Response, next: NextFunction): void => {
const token = extractToken(req);
if (!token) {
res.status(401).json({ error: 'Access token required', code: 'AUTH_REQUIRED' });
return;
}
const user = verifyJwtAndLoadUser(token);
if (!user) {
res.status(401).json({ error: 'Invalid or expired token', code: 'AUTH_REQUIRED' });
return;
}
(req as AuthRequest).user = user;
applyIdempotency(req, res, next, user.id);
};
/** Like `authenticate` but rejects requests that don't carry an httpOnly session cookie.
* Used on state-mutating OAuth endpoints (consent POST, client CRUD, session revoke)
* to prevent Bearer JWT tokens obtained by other means from managing OAuth clients. */
const requireCookieAuth = (req: Request, res: Response, next: NextFunction): void => {
const cookieToken = (req as any).cookies?.trek_session;
if (!cookieToken) {
res.status(401).json({ error: 'Cookie session required for this endpoint', code: 'COOKIE_AUTH_REQUIRED' });
return;
}
const user = verifyJwtAndLoadUser(cookieToken);
if (!user) {
res.status(401).json({ error: 'Invalid or expired session', code: 'AUTH_REQUIRED' });
return;
}
(req as AuthRequest).user = user;
next();
};
const optionalAuth = (req: Request, res: Response, next: NextFunction): void => {
const token = extractToken(req);
if (!token) {
(req as OptionalAuthRequest).user = null;
return next();
}
(req as OptionalAuthRequest).user = verifyJwtAndLoadUser(token) || null;
next();
};
const adminOnly = (req: Request, res: Response, next: NextFunction): void => {
const authReq = req as AuthRequest;
if (!authReq.user || authReq.user.role !== 'admin') {
res.status(403).json({ error: 'Admin access required' });
return;
}
next();
};
const demoUploadBlock = (req: Request, res: Response, next: NextFunction): void => {
const authReq = req as AuthRequest;
if (process.env.DEMO_MODE?.toLowerCase() === 'true' && isDemoEmail(authReq.user?.email)) {
res.status(403).json({ error: 'Uploads are disabled in demo mode. Self-host TREK for full functionality.' });
return;
}
next();
};
export { authenticate, requireCookieAuth, optionalAuth, adminOnly, demoUploadBlock };
+106 -34
View File
@@ -3,8 +3,61 @@ import compression from 'compression';
import cors from 'cors';
import helmet from 'helmet';
import cookieParser from 'cookie-parser';
import { logDebug, logWarn, logError } from '../services/auditLog';
import { enforceGlobalMfaPolicy } from './mfaPolicy';
import { readEnv, type AppEnv } from '../app-config';
import { logDebug, logWarn, logError } from '../nest/audit/audit-log.logger';
/**
* Field names redacted from request-log query/body dumps (case-insensitive —
* lookup lowercases the key first). `secretaccesskey` covers the S3 storage
* backend's secret field (storage-admin PUT bodies land in the same debug
* log line as any other request body).
*
* Exported (module-level, not per-request) so it can be unit-tested directly
* without threading LOG_LEVEL through the real logger pipeline.
*/
export const SENSITIVE_KEYS = new Set([
'password',
'new_password',
'current_password',
'token',
'jwt',
'authorization',
'cookie',
'client_secret',
'mfa_token',
'code',
'smtp_pass',
'secretaccesskey',
]);
/**
* Suffixes that make a field sensitive whatever its prefix. Matched on the end of
* the key, not anywhere in it: `accessKeyId` is an identifier and stays readable,
* while `refresh_token`, `code_verifier`, `mapbox_access_token` and the whole
* `*_api_key` family are secrets nobody needs in a debug log.
*/
const SENSITIVE_SUFFIXES = ['_token', '_key', '_secret', '_password', '_pass', '_verifier'];
function isSensitiveName(name: string): boolean {
const lower = name.toLowerCase();
return SENSITIVE_KEYS.has(lower) || SENSITIVE_SUFFIXES.some((suffix) => lower.endsWith(suffix));
}
/** Deep-redacts every key in `SENSITIVE_KEYS` (case-insensitive) from a request-log value. */
export function redact(value: unknown): unknown {
if (!value || typeof value !== 'object') return value;
if (Array.isArray(value)) return (value as unknown[]).map(redact);
const entries = value as Record<string, unknown>;
// PUT /api/settings names the setting instead of using it as the field:
// {key: 'carto_api_key', value: '<secret>'}. Neither field name is sensitive
// on its own, so without this the secret goes into the debug log in cleartext.
const namedSecret = typeof entries.key === 'string' && isSensitiveName(entries.key);
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(entries)) {
out[k] = isSensitiveName(k) || (namedSecret && k === 'value') ? '[REDACTED]' : redact(v);
}
return out;
}
/**
* The global request pipeline shared by the legacy Express app and the NestJS
@@ -15,18 +68,24 @@ import { enforceGlobalMfaPolicy } from './mfaPolicy';
* behaviourally transparent — and is the prerequisite for retiring Express,
* since the Nest instance must carry the whole shell on its own.
*
* `bodyParser` is opt-out: the Nest instance does its own body parsing, so it
* passes `false` to avoid parsing the request twice.
* Body parsing is NOT here: the Nest instance does it, with the limit pinned in
* bootstrap.ts. The flag that used to switch a second parser on had exactly one
* caller, which passed false.
*/
export function applyGlobalMiddleware(
app: express.Application,
opts: { bodyParser?: boolean } = {},
opts: { http?: AppEnv['http'] } = {},
): void {
const { bodyParser = true } = opts;
// The whole pipeline is configured at APPLY time (the per-request closures
// capture these values), so a snapshot is the correct semantic. bootstrap
// threads in the DI-loaded httpConfig; direct callers fall back to an
// apply-time readEnv() — same values, same freeze point.
const { http = readEnv().http } = opts;
const { nodeEnv, isProduction } = readEnv().app;
// Trust first proxy (nginx/Docker) for correct req.ip
if (process.env.NODE_ENV?.toLowerCase() === 'production' || process.env.TRUST_PROXY) {
app.set('trust proxy', Number.parseInt(process.env.TRUST_PROXY) || 1);
if (isProduction || http.trustProxyRaw) {
app.set('trust proxy', http.trustProxy);
}
// Compress responses (gzip via Accept-Encoding). The Atlas admin-0 country
@@ -44,9 +103,7 @@ export function applyGlobalMiddleware(
}),
);
const allowedOrigins = process.env.ALLOWED_ORIGINS
? process.env.ALLOWED_ORIGINS.split(',').map(o => o.trim()).filter(Boolean)
: null;
const allowedOrigins = http.corsOrigins;
let corsOrigin: cors.CorsOptions['origin'];
if (allowedOrigins) {
@@ -54,13 +111,13 @@ export function applyGlobalMiddleware(
if (!origin || allowedOrigins.includes(origin)) callback(null, true);
else callback(new Error('Not allowed by CORS'));
};
} else if (process.env.NODE_ENV?.toLowerCase() === 'production') {
} else if (isProduction) {
corsOrigin = false;
} else {
corsOrigin = true;
}
const shouldForceHttps = process.env.FORCE_HTTPS?.toLowerCase() === 'true';
const shouldForceHttps = http.forceHttps;
// HSTS is worth enabling any time we're serving production traffic,
// not only when FORCE_HTTPS is set. Self-hosters behind Traefik /
// Caddy / Cloudflare Tunnel typically leave FORCE_HTTPS unset (the
@@ -72,8 +129,10 @@ export function applyGlobalMiddleware(
// sibling subdomain the same operator may still be running over plain
// HTTP. Operators who want the stricter policy opt in with
// `HSTS_INCLUDE_SUBDOMAINS=true`.
const hstsActive = shouldForceHttps || process.env.NODE_ENV === 'production';
const hstsIncludeSubdomains = process.env.HSTS_INCLUDE_SUBDOMAINS === 'true';
// nodeEnv compared case-sensitively here on purpose (legacy parity — the
// trust-proxy/CORS checks above are the case-insensitive ones).
const hstsActive = shouldForceHttps || nodeEnv === 'production';
const hstsIncludeSubdomains = http.hstsIncludeSubdomains;
// RFC 8414 / RFC 9728 / RFC 7591: discovery docs and DCR are world-readable/writable.
// /mcp needs open CORS so external MCP clients (ChatGPT, Claude.ai, Inspector) can call it
@@ -114,6 +173,14 @@ export function applyGlobalMiddleware(
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
// 'unsafe-eval' is load-bearing, not leftover: heic-to's libheif build
// initialises embind through new Function(), and that is what converts
// an iPhone .heic the moment somebody picks one. 'wasm-unsafe-eval'
// alone was tried first and was not enough (93b51a0b). The package
// ships a CSP-safe entry point at heic-to/csp; dropping this directive
// means switching client/src/utils/convertHeic.ts over to it and
// verifying a real .heic upload in a browser, not just deleting the
// string here.
scriptSrc: ["'self'", "'wasm-unsafe-eval'", "'unsafe-eval'"],
styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com", "https://unpkg.com"],
imgSrc: ["'self'", "data:", "blob:", "https:"],
@@ -122,7 +189,15 @@ export function applyGlobalMiddleware(
"https://nominatim.openstreetmap.org", "https://overpass-api.de",
"https://places.googleapis.com", "https://api.openweathermap.org",
"https://en.wikipedia.org", "https://commons.wikimedia.org",
"https://*.basemaps.cartocdn.com", "https://*.tile.openstreetmap.org",
// Both forms here too: CARTO documents the apex host on its key page,
// so that is the template users paste in, and the {s} sharded form is
// what TREK ships (#2054).
"https://basemaps.cartocdn.com", "https://*.basemaps.cartocdn.com",
// Both forms: a CSP wildcard host never matches the apex, and OSM
// serves everything from the bare tile.openstreetmap.org since it
// retired the a/b/c/d shards (#1733). The sharded hosts stay listed
// for tile templates users saved before that.
"https://tile.openstreetmap.org", "https://*.tile.openstreetmap.org",
"https://unpkg.com", "https://open-meteo.com", "https://api.open-meteo.com",
"https://geocoding-api.open-meteo.com", "https://api.frankfurter.dev",
"https://router.project-osrm.org/route/v1/", "https://routing.openstreetmap.de/",
@@ -151,33 +226,30 @@ export function applyGlobalMiddleware(
referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
}));
// The instance's own hostname, when the operator configured one. The redirect
// below is a 301, so echoing a client-supplied Host header would let a stranger
// park a foreign origin in a visitor's cache. Falls back to the request Host for
// instances that never set APP_URL, which is what it always did.
const configuredHost = (() => {
const url = readEnv().app.appUrl;
try {
return url ? new URL(url).host : null;
} catch {
return null;
}
})();
if (shouldForceHttps) {
app.use((req: Request, res: Response, next: NextFunction) => {
if (req.path === '/api/health') return next();
if (req.secure || req.headers['x-forwarded-proto'] === 'https') return next();
res.redirect(301, 'https://' + req.headers.host + req.url);
res.redirect(301, 'https://' + (configuredHost ?? req.headers.host) + req.url);
});
}
if (bodyParser) {
app.use(express.json({ limit: '100kb' }));
app.use(express.urlencoded({ extended: true }));
}
app.use(cookieParser());
app.use(enforceGlobalMfaPolicy);
// Request logging with sensitive field redaction
const SENSITIVE_KEYS = new Set(['password', 'new_password', 'current_password', 'token', 'jwt', 'authorization', 'cookie', 'client_secret', 'mfa_token', 'code', 'smtp_pass']);
const redact = (value: unknown): unknown => {
if (!value || typeof value !== 'object') return value;
if (Array.isArray(value)) return (value as unknown[]).map(redact);
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
out[k] = SENSITIVE_KEYS.has(k.toLowerCase()) ? '[REDACTED]' : redact(v);
}
return out;
};
// Request logging with sensitive field redaction (SENSITIVE_KEYS/redact above)
app.use((req: Request, res: Response, next: NextFunction) => {
if (req.path === '/api/health') return next();
const startedAt = Date.now();
-80
View File
@@ -1,80 +0,0 @@
import { Request, Response, NextFunction } from 'express';
import { db } from '../db/database';
const MUTATING_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
// Reject pathological client-supplied keys outright instead of hashing
// everything — 128 chars is plenty for any realistic UUID / ULID / nonce.
const MAX_KEY_LENGTH = 128;
// Responses larger than this are not worth caching — a backup-restore
// endpoint could otherwise store a megabyte-sized JSON body per request
// key and, with mass key creation, blow up idempotency_keys.
const MAX_CACHED_BODY_BYTES = 256 * 1024;
interface IdempotencyRow {
status_code: number;
response_body: string;
}
/**
* Called from within `authenticate` after req.user is set.
*
* For mutating requests carrying X-Idempotency-Key:
* - If (key, userId, method, path) already stored: replays the cached response.
* - Otherwise: wraps res.json to capture and store a successful response.
*
* The lookup is scoped by method + path as well as user so the same key
* replayed against a different endpoint doesn't return the cached body
* of an unrelated request. Key length is capped and the cached body is
* skipped when it exceeds `MAX_CACHED_BODY_BYTES`.
*
* Storing happens in idempotency_keys (24h TTL, cleaned by scheduler).
*/
export function applyIdempotency(req: Request, res: Response, next: NextFunction, userId: number): void {
if (!MUTATING_METHODS.has(req.method)) {
next();
return;
}
const key = req.headers['x-idempotency-key'] as string | undefined;
if (!key) {
next();
return;
}
if (key.length > MAX_KEY_LENGTH) {
res.status(400).json({ error: 'X-Idempotency-Key exceeds maximum length of 128 characters' });
return;
}
// Return cached response only if the same key was seen for the same
// user AND the same method+path — avoids a POST's cached body leaking
// into an unrelated PATCH that reused the idempotency-key string.
const existing = db.prepare(
'SELECT status_code, response_body FROM idempotency_keys WHERE key = ? AND user_id = ? AND method = ? AND path = ?'
).get(key, userId, req.method, req.path) as IdempotencyRow | undefined;
if (existing) {
res.status(existing.status_code).json(JSON.parse(existing.response_body));
return;
}
// Wrap res.json to capture the response on first successful execution
const originalJson = res.json.bind(res);
res.json = function (body: unknown): Response {
if (res.statusCode >= 200 && res.statusCode < 300) {
try {
const serialized = JSON.stringify(body);
if (serialized.length <= MAX_CACHED_BODY_BYTES) {
db.prepare(
`INSERT OR IGNORE INTO idempotency_keys (key, user_id, method, path, status_code, response_body, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?)`
).run(key, userId, req.method, req.path, res.statusCode, serialized, Math.floor(Date.now() / 1000));
}
} catch {
// Non-fatal: if storage fails, the request still succeeds
}
}
return originalJson(body);
};
next();
}
-111
View File
@@ -1,111 +0,0 @@
import { Request, Response, NextFunction } from 'express';
import { db } from '../db/database';
import { extractToken, verifyJwtAndLoadUser } from './auth';
import { DEMO_EMAILS } from '../services/demo';
/** Paths that never require MFA (public or pre-auth). */
export function isPublicApiPath(method: string, pathNoQuery: string): boolean {
if (method === 'GET' && pathNoQuery === '/api/health') return true;
if (method === 'GET' && pathNoQuery === '/api/auth/app-config') return true;
if (method === 'POST' && pathNoQuery === '/api/auth/login') return true;
if (method === 'POST' && pathNoQuery === '/api/auth/register') return true;
if (method === 'POST' && pathNoQuery === '/api/auth/demo-login') return true;
if (method === 'GET' && pathNoQuery.startsWith('/api/auth/invite/')) return true;
if (method === 'POST' && pathNoQuery === '/api/auth/mfa/verify-login') return true;
// Unauthenticated passkey (primary) login ceremony.
if (method === 'POST' && pathNoQuery === '/api/auth/passkey/login/options') return true;
if (method === 'POST' && pathNoQuery === '/api/auth/passkey/login/verify') return true;
if (pathNoQuery.startsWith('/api/auth/oidc/')) return true;
return false;
}
/** Authenticated paths allowed while MFA is not yet enabled (setup + lockout recovery). */
export function isMfaSetupExemptPath(method: string, pathNoQuery: string): boolean {
if (method === 'GET' && pathNoQuery === '/api/auth/me') return true;
if (method === 'POST' && pathNoQuery === '/api/auth/mfa/setup') return true;
if (method === 'POST' && pathNoQuery === '/api/auth/mfa/enable') return true;
// Allow enrolling a passkey as the second factor (a user-verified passkey
// satisfies require_mfa), so a fresh user under the policy isn't stuck.
if (method === 'POST' && pathNoQuery === '/api/auth/passkey/register/options') return true;
if (method === 'POST' && pathNoQuery === '/api/auth/passkey/register/verify') return true;
if (method === 'GET' && pathNoQuery === '/api/auth/passkey/credentials') return true;
if ((method === 'GET' || method === 'PUT') && pathNoQuery === '/api/auth/app-settings') return true;
return false;
}
/**
* When app_settings.require_mfa is true, block API access for users without MFA enabled,
* except for public routes and MFA setup endpoints.
*/
export function enforceGlobalMfaPolicy(req: Request, res: Response, next: NextFunction): void {
const pathNoQuery = (req.originalUrl || req.url || '').split('?')[0];
if (!pathNoQuery.startsWith('/api')) {
next();
return;
}
if (isPublicApiPath(req.method, pathNoQuery)) {
next();
return;
}
// Accept both the httpOnly session cookie (regular SPA users) and the
// Authorization header (MCP / API clients). Previously this only looked
// at the header so every normal cookie-authenticated session sailed
// past `require_mfa` unchecked.
const token = extractToken(req);
if (!token) {
next();
return;
}
// Use the shared verify helper so the `password_version` gate applies
// here too — a JWT stolen before a password reset would otherwise
// continue to satisfy this middleware until its natural 24h expiry.
const verified = verifyJwtAndLoadUser(token);
if (!verified) {
next();
return;
}
const userId = verified.id;
const requireRow = db.prepare("SELECT value FROM app_settings WHERE key = 'require_mfa'").get() as { value: string } | undefined;
if (requireRow?.value !== 'true') {
next();
return;
}
if (process.env.DEMO_MODE?.toLowerCase() === 'true' && verified.email && DEMO_EMAILS.has(verified.email)) {
next();
return;
}
const row = db.prepare('SELECT mfa_enabled FROM users WHERE id = ?').get(userId) as
| { mfa_enabled: number | boolean }
| undefined;
if (!row) {
next();
return;
}
// A user-verified passkey is phishing-resistant and inherently two-factor, so
// owning at least one satisfies the require_mfa policy exactly like TOTP does.
// (All stored passkeys were registered with userVerification required.)
const mfaOk = row.mfa_enabled === 1 || row.mfa_enabled === true;
const passkeyOk = !!db.prepare('SELECT 1 FROM webauthn_credentials WHERE user_id = ? LIMIT 1').get(userId);
if (mfaOk || passkeyOk) {
next();
return;
}
if (isMfaSetupExemptPath(req.method, pathNoQuery)) {
next();
return;
}
res.status(403).json({
error: 'Two-factor authentication is required. Complete setup in Settings.',
code: 'MFA_REQUIRED',
});
}
-37
View File
@@ -1,37 +0,0 @@
import { Request, Response, NextFunction } from 'express';
import { canAccessTrip, isOwner } from '../db/database';
import { AuthRequest } from '../types';
/** Middleware: verifies the authenticated user is an owner or member of the trip, then attaches trip to req. */
function requireTripAccess(req: Request, res: Response, next: NextFunction): void {
const authReq = req as AuthRequest;
const tripId = req.params.tripId || req.params.id;
if (!tripId) {
res.status(400).json({ error: 'Trip ID required' });
return;
}
const trip = canAccessTrip(Number(tripId), authReq.user.id);
if (!trip) {
res.status(404).json({ error: 'Trip not found' });
return;
}
authReq.trip = trip;
next();
}
/** Middleware: verifies the authenticated user is the trip owner (not just a member). */
function requireTripOwner(req: Request, res: Response, next: NextFunction): void {
const authReq = req as AuthRequest;
const tripId = req.params.tripId || req.params.id;
if (!tripId) {
res.status(400).json({ error: 'Trip ID required' });
return;
}
if (!isOwner(Number(tripId), authReq.user.id)) {
res.status(403).json({ error: 'Only the trip owner can do this' });
return;
}
next();
}
export { requireTripAccess, requireTripOwner };
-26
View File
@@ -1,26 +0,0 @@
import { Request, Response, NextFunction } from 'express';
function maxLength(field: string, max: number) {
return (req: Request, res: Response, next: NextFunction): void => {
if (req.body[field] && typeof req.body[field] === 'string' && req.body[field].length > max) {
res.status(400).json({ error: `${field} must be ${max} characters or less` });
return;
}
next();
};
}
function validateStringLengths(maxLengths: Record<string, number>) {
return (req: Request, res: Response, next: NextFunction): void => {
for (const [field, max] of Object.entries(maxLengths)) {
const value = req.body[field];
if (value && typeof value === 'string' && value.length > max) {
res.status(400).json({ error: `${field} must be ${max} characters or less` });
return;
}
}
next();
};
}
export { maxLength, validateStringLengths };
+123
View File
@@ -0,0 +1,123 @@
# nest-mcp
Decorator-driven MCP registration for NestJS. Domains declare MCP tools, resources and prompts as decorated methods on ordinary Nest providers; a discovery-backed registry collects them at boot and attaches them — filtered by the access policy — onto each per-session `McpServer`.
Formerly the standalone `@trek/nest-mcp` workspace package; folded into the server 2026-08-22. Two invariants survive the fold:
- **Self-contained**: this directory imports nothing from the rest of `server/` except the type-only `../mcp/scopes` import in `types.ts` (which types `access.group`/`mode` against the real scope unions). Keep it that way — new TREK semantics belong in the host layer, not here.
- **No scope semantics of its own**: access *meaning* comes entirely from the `accessPolicy`/`validateAccess` given at `McpModule.forRoot(...)` — TREK's live in `src/mcp/nest-mcp-policy.ts`.
Tests live in `server/tests/unit/nest-mcp/` and run with the normal server suite; coverage is gated at ≥80% in `server/vitest.config.ts`.
## API
### Decorators
```ts
import { McpController, Tool, Resource, ResourceTemplate, Prompt } from '../../nest-mcp';
import { z } from 'zod';
@McpController() // implies @Injectable(); register the class in a module's providers: []
export class ThingsMcp {
constructor(private readonly things: ThingsService) {}
@Tool({
name: 'list_things',
description: 'List all things.',
inputSchema: {}, // ZodRawShape, passed straight to the SDK
annotations: { readOnlyHint: true },
access: { group: 'things', mode: 'read' }, // resolved by the accessPolicy
})
async listThings(_args: Record<string, never>, ctx: McpContext) {
return { content: [{ type: 'text', text: JSON.stringify(this.things.list(ctx.userId)) }] };
}
}
```
- `@Tool(options)` — mirrors `server.registerTool` (`name`, `title`, `description`, `inputSchema`, `outputSchema`, `annotations`, `_meta`). Handler: `(args, ctx)`; `args` is `{}` when no `inputSchema` was declared.
- `@Resource(options)` — fixed URI (`uri`, `mimeType`, …). Handler: `(uri: URL, ctx)`.
- `@ResourceTemplate(options)` — `uriTemplate` (RFC 6570). Handler: `(uri: URL, variables, ctx)`. (No `list`/`complete` template callbacks yet — extend when a domain needs them.)
- `@Prompt(options)` — mirrors `registerPrompt` (`argsSchema` entries must be string-valued Zod schemas). Handler: `(args, ctx)`.
`ctx` always takes the SDK `extra` slot — the last handler argument.
### Access control
Every decorator accepts `access` and `when`:
- **Declarative** — `access: { group: 'things', mode: 'read' | 'write' }`, resolved by the `accessPolicy` given once at `McpModule.forRoot(...)`. `group` and `mode` are typed against the scope-derived unions in `types.ts`, so a typo'd group is a compile error in `.mcp.ts` files.
- **Predicate** — `access: (ctx) => boolean`, bypasses the policy.
- **Availability gate** — `when: (ctx, self) => boolean`, evaluated *before* `access` (both must pass). Use it for feature/addon toggles so scope markers stay declarative: `when: (_ctx, self: PackingMcp) => self.addons.isAddonEnabled(...)`, `access: { group: 'packing', mode: 'read' }`. `self` is the `@McpController()` instance, handed in at attach time — the options object is built when the class is defined, so without it a gate can only reach a module-level singleton, and hosts end up constructing a second copy of a service outside their own container to answer a toggle.
- **Omitted `access`** — the entry is always registered (subject to `when`).
### Result helpers & annotation presets
Handler-side conveniences, exported from the barrel so decorated domains need nothing from the legacy MCP layer:
```ts
import { ok, errorResult, demoDenied, TOOL_ANNOTATIONS_READONLY } from '../../nest-mcp';
ok({ tags }) // { content: [{ type: 'text', text: <pretty JSON> }] }
errorResult('Tag not found.') // { content: [...], isError: true } — message verbatim
demoDenied() // canned demo-mode write refusal
```
Six `TOOL_ANNOTATIONS_*` presets cover the read/write/delete/idempotency matrix (plus `OPEN_WORLD` variants). TREK-specific canned errors (permission wording, RBAC lookups) belong in the host layer, built on `errorResult` — see `server/src/mcp/tools/_shared.ts`, which re-exports the generic helpers from here.
### Fail-fast validation
`McpRegistryService` runs `registry.validate()` at boot (`onModuleInit`), and `createTestRegistry` runs it on construction, so misconfiguration breaks startup instead of MCP session creation:
- duplicate names per kind (fixed resources: duplicate URIs);
- declarative `access` without a configured `accessPolicy`;
- declarative `access` rejected by the optional `validateAccess` hook.
All problems are aggregated into one `Invalid MCP registry: ...` error, so a single boot failure reports every misconfiguration.
`validateAccess?: (access, entry) => string | null | undefined` (on both `McpModule.forRoot(...)` and `createTestRegistry(...)` options) is called once per entry with declarative access — predicates are opaque and skipped. Return a problem description to fail boot, null/undefined to accept:
```ts
McpModule.forRoot({
accessPolicy,
validateAccess: ({ group, mode }) =>
hostKnowsGroupMode(group, mode) ? null : `no '${group}:${mode}' scope`,
})
```
### Context and access typing
`McpContext` (the per-session context handed to every handler, predicate and the policy) and the `McpAccessGroupRegistry`/`McpAccessModeRegistry` interfaces that type `access.group`/`mode` are defined directly in `types.ts`. Before the fold they were empty interfaces the host augmented via `declare module '@trek/nest-mcp'`; the TREK shapes are now baked in, with the lockstep asserts in `src/mcp/nest-mcp-policy.ts` pinning the registries to `scopes.ts` at compile time.
### Wiring
```ts
// AppModule
McpModule.forRoot({ accessPolicy: (access, ctx) => /* scope semantics */ })
// wherever per-session servers are built (may be outside Nest — hand the
// registry over after app.init()):
const registry = app.get(McpRegistryService);
registry.attach(server, { userId, scopes, isStaticToken });
registry.list(); // introspection
```
### Testing without Nest
```ts
import { createTestRegistry } from '../../../src/nest-mcp';
const registry = createTestRegistry([new ThingsMcp(new ThingsService(db))], { accessPolicy });
registry.attach(server, ctx);
```
## Migrating a TREK MCP domain (recipe)
1. Create `server/src/nest/<domain>/<domain>.mcp.ts`: an `@McpController()` class injecting the domain's Nest service. Port each `server.registerTool(...)` from `server/src/mcp/tools/<domain>.ts` to a `@Tool()` method **byte-identically** (names, descriptions, schemas, annotations, error strings, `ok()` payloads).
2. Replace the registrar's `canRead/canWrite` registration-time gates with `access: { group, mode }` (TREK's policy in `server/src/mcp/nest-mcp-policy.ts` implements the `scopes.ts` semantics). Addon gates become `when: (_ctx, self: XMcp) => self.addons.isAddonEnabled(ADDON_IDS.X)` alongside the declarative `access`.
3. Add the class to the domain module's `providers: []`.
4. Delete the legacy registrar file and its call in `server/src/mcp/tools.ts`.
5. Add one line constructing the instance in `server/tests/helpers/mcp-test-controllers.ts` and keep the domain's existing unit tests green — behavior must be indistinguishable to a client.
## Notes
The MCP SDK's exports map uses extension-less wildcards that TypeScript cannot resolve; `server/tsconfig.json` `paths` and `server/vitest.config.ts` aliases point at the CJS dist files. `registry.ts` is the only file here importing the SDK.
+42
View File
@@ -0,0 +1,42 @@
import { addEntry, markController, type ClassRef } from './metadata';
import type { PromptOptions, ResourceOptions, ResourceTemplateOptions, ToolOptions } from './types';
import { Injectable } from '@nestjs/common';
/**
* Marks a class as an MCP controller. Implies `@Injectable()` — register the
* class in a module's `providers: []` and inject domain services through the
* constructor as usual. Discovery scans ONLY marked classes (explicit opt-in,
* deterministic registry).
*/
export function McpController(): ClassDecorator {
return (target) => {
Injectable()(target);
markController(target as unknown as ClassRef);
};
}
function mcpMethodDecorator(entry: (methodName: string) => Parameters<typeof addEntry>[1]): MethodDecorator {
return (target, propertyKey) => {
addEntry((target as { constructor: unknown }).constructor as ClassRef, entry(String(propertyKey)));
};
}
/** Registers the method as an MCP tool. Handler signature: `(args, ctx)`. */
export function Tool(options: ToolOptions): MethodDecorator {
return mcpMethodDecorator((methodName) => ({ kind: 'tool', methodName, options }));
}
/** Registers the method as a fixed-URI MCP resource. Handler signature: `(uri: URL, ctx)`. */
export function Resource(options: ResourceOptions): MethodDecorator {
return mcpMethodDecorator((methodName) => ({ kind: 'resource', methodName, options }));
}
/** Registers the method as an MCP resource template. Handler signature: `(uri: URL, variables, ctx)`. */
export function ResourceTemplate(options: ResourceTemplateOptions): MethodDecorator {
return mcpMethodDecorator((methodName) => ({ kind: 'resourceTemplate', methodName, options }));
}
/** Registers the method as an MCP prompt. Handler signature: `(args, ctx)`. */
export function Prompt(options: PromptOptions): MethodDecorator {
return mcpMethodDecorator((methodName) => ({ kind: 'prompt', methodName, options }));
}
+64
View File
@@ -0,0 +1,64 @@
/**
* Result-shape helpers and tool-annotation presets shared by MCP handlers.
* App-agnostic on purpose — host-specific canned errors (permission wording,
* RBAC lookups, broadcasts) belong in the host, built on `errorResult`.
*/
/** The text-content result shape MCP tool handlers return. */
export interface McpTextResult {
content: { type: 'text'; text: string }[];
isError?: boolean;
}
/** Success result: `data` pretty-printed as a single JSON text block. */
export function ok(data: unknown): McpTextResult {
return { content: [{ type: 'text' as const, text: JSON.stringify(data, null, 2) }] };
}
/** Error result with a verbatim message (no formatting, no prefix). */
export function errorResult(text: string): McpTextResult {
return { content: [{ type: 'text' as const, text }], isError: true };
}
/** Canned refusal for write tools when the acting user is a demo account. */
export function demoDenied(): McpTextResult {
return errorResult('Write operations are disabled in demo mode.');
}
export const TOOL_ANNOTATIONS_READONLY = {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
} as const;
export const TOOL_ANNOTATIONS_OPEN_WORLD_READONLY = {
...TOOL_ANNOTATIONS_READONLY,
openWorldHint: true,
} as const;
export const TOOL_ANNOTATIONS_WRITE = {
readOnlyHint: false,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
} as const;
export const TOOL_ANNOTATIONS_DELETE = {
readOnlyHint: false,
destructiveHint: true,
idempotentHint: true,
openWorldHint: false,
} as const;
export const TOOL_ANNOTATIONS_NON_IDEMPOTENT = {
readOnlyHint: false,
destructiveHint: false,
idempotentHint: false,
openWorldHint: false,
} as const;
export const TOOL_ANNOTATIONS_OPEN_WORLD_NON_IDEMPOTENT = {
...TOOL_ANNOTATIONS_NON_IDEMPOTENT,
openWorldHint: true,
} as const;
+39
View File
@@ -0,0 +1,39 @@
export { McpController, Prompt, Resource, ResourceTemplate, Tool } from './decorators';
export {
demoDenied,
errorResult,
ok,
TOOL_ANNOTATIONS_DELETE,
TOOL_ANNOTATIONS_NON_IDEMPOTENT,
TOOL_ANNOTATIONS_OPEN_WORLD_NON_IDEMPOTENT,
TOOL_ANNOTATIONS_OPEN_WORLD_READONLY,
TOOL_ANNOTATIONS_READONLY,
TOOL_ANNOTATIONS_WRITE,
type McpTextResult,
} from './helpers';
export { McpRegistryService } from './mcp-registry.service';
export { McpModule } from './mcp.module';
export { McpRegistry, type McpRegistryOptions } from './registry';
export { createTestRegistry } from './testing';
export {
MCP_MODULE_OPTIONS,
type McpAccess,
type McpAccessGroup,
type McpAccessGroupRegistry,
type McpAccessMode,
type McpAccessModeRegistry,
type McpAccessPolicy,
type McpAccessPredicate,
type McpAccessValidator,
type McpAttachOptions,
type McpContext,
type McpDeclarativeAccess,
type McpEntry,
type McpEntryKind,
type McpModuleOptions,
type McpRegistryListing,
type PromptOptions,
type ResourceOptions,
type ResourceTemplateOptions,
type ToolOptions,
} from './types';
@@ -0,0 +1,37 @@
import { isMcpController } from './metadata';
import { McpRegistry } from './registry';
import { MCP_MODULE_OPTIONS, type McpModuleOptions } from './types';
import { Inject, Injectable, type OnModuleInit } from '@nestjs/common';
import { DiscoveryService, MetadataScanner } from '@nestjs/core';
/**
* DI-discovered registry: at boot, scans every provider marked with
* `@McpController()` and records its decorated methods. Attach it to a
* per-session `McpServer` with `attach(server, ctx)`.
*/
@Injectable()
export class McpRegistryService extends McpRegistry implements OnModuleInit {
constructor(
private readonly discovery: DiscoveryService,
private readonly scanner: MetadataScanner,
@Inject(MCP_MODULE_OPTIONS) options: McpModuleOptions,
) {
super(options);
}
onModuleInit(): void {
// A provider can be wrapped once per module that lists it — dedupe by
// instance so an entry is never recorded (and later registered) twice.
const seen = new Set<object>();
for (const wrapper of this.discovery.getProviders()) {
const { instance, metatype } = wrapper;
if (!instance || typeof instance !== 'object' || seen.has(instance)) continue;
if (!isMcpController(metatype)) continue;
seen.add(instance);
this.register(instance, this.scanner.getAllMethodNames(Object.getPrototypeOf(instance)));
}
// Fail app boot on duplicate names / policy-less declarative access
// instead of failing per-session at attach().
this.validate();
}
}
+22
View File
@@ -0,0 +1,22 @@
import { McpRegistryService } from './mcp-registry.service';
import { MCP_MODULE_OPTIONS, type McpModuleOptions } from './types';
import { Module, type DynamicModule } from '@nestjs/common';
import { DiscoveryModule } from '@nestjs/core';
@Module({})
export class McpModule {
/**
* Registers the discovery-backed `McpRegistryService` globally. The
* `accessPolicy` resolves every declarative `access: { group, mode }`
* marker — the package itself defines no scope semantics.
*/
static forRoot(options: McpModuleOptions = {}): DynamicModule {
return {
module: McpModule,
global: true,
imports: [DiscoveryModule],
providers: [{ provide: MCP_MODULE_OPTIONS, useValue: options }, McpRegistryService],
exports: [McpRegistryService],
};
}
}
+47
View File
@@ -0,0 +1,47 @@
import type { McpEntry } from './types';
/**
* Metadata store. A package-private WeakMap/WeakSet keyed by class
* constructor instead of reflect-metadata: it has zero runtime
* prerequisites (no polyfill import order to get right), works in bare
* vitest workers and in `createTestRegistry` without a Nest app, and is
* trivially extraction-clean.
*/
/** A class constructor, without using the banned bare `Function` type. */
export type ClassRef = abstract new (...args: never[]) => unknown;
const controllers = new WeakSet<ClassRef>();
const entries = new WeakMap<ClassRef, Map<string, McpEntry>>();
export function markController(ctor: ClassRef): void {
controllers.add(ctor);
}
export function isMcpController(ctor: unknown): ctor is ClassRef {
return typeof ctor === 'function' && controllers.has(ctor as ClassRef);
}
export function addEntry(ctor: ClassRef, entry: McpEntry): void {
let map = entries.get(ctor);
if (!map) {
map = new Map();
entries.set(ctor, map);
}
map.set(entry.methodName, entry);
}
/**
* Look up the entry recorded for `methodName`, walking the constructor
* prototype chain so inherited decorated methods are found on subclasses.
*/
export function getEntry(ctor: ClassRef, methodName: string): McpEntry | undefined {
let current: ClassRef | null = ctor;
while (current) {
const found = entries.get(current)?.get(methodName);
if (found) return found;
const parent: unknown = Object.getPrototypeOf(current);
current = typeof parent === 'function' ? (parent as ClassRef) : null;
}
return undefined;
}
+307
View File
@@ -0,0 +1,307 @@
import { getEntry, isMcpController, type ClassRef } from './metadata';
import type {
McpAccessPolicy,
McpAccessValidator,
McpAttachOptions,
McpContext,
McpEntry,
McpRegistryListing,
PromptOptions,
ResourceOptions,
ResourceTemplateOptions,
ToolOptions,
} from './types';
import { ResourceTemplate as SdkResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import type { ZodRawShape } from 'zod';
interface BoundEntry {
entry: McpEntry;
instance: object;
}
export interface McpRegistryOptions {
accessPolicy?: McpAccessPolicy;
validateAccess?: McpAccessValidator;
}
type AnyHandler = (this: unknown, ...handlerArgs: unknown[]) => unknown;
/**
* Structural view of the SDK registration surface. The SDK's real signatures
* are generic over the Zod shapes; the registry passes schemas straight
* through and binds `ctx` where the SDK would pass `extra`, so it needs (and
* exposes) none of that type-level machinery.
*/
interface LooseRegistrar {
registerTool(name: string, config: Record<string, unknown>, cb: (...cbArgs: unknown[]) => unknown): unknown;
registerResource(
name: string,
uriOrTemplate: string | SdkResourceTemplate,
config: Record<string, unknown>,
cb: (...cbArgs: unknown[]) => unknown,
): unknown;
registerPrompt(name: string, config: Record<string, unknown>, cb: (...cbArgs: unknown[]) => unknown): unknown;
}
function describeBound({ entry, instance }: BoundEntry): string {
return `${(instance as { constructor: { name: string } }).constructor.name}.${entry.methodName}`;
}
/** Own + inherited method names, excluding constructor and Object.prototype. */
function enumerateMethodNames(instance: object): string[] {
const names = new Set<string>();
let proto: object | null = Object.getPrototypeOf(instance);
while (proto && proto !== Object.prototype) {
for (const name of Object.getOwnPropertyNames(proto)) {
if (name === 'constructor') continue;
const descriptor = Object.getOwnPropertyDescriptor(proto, name);
if (typeof descriptor?.value === 'function') names.add(name);
}
proto = Object.getPrototypeOf(proto);
}
return [...names];
}
/**
* Holds every decorated MCP entry bound to its provider instance and attaches
* them, filtered by access, onto a per-session `McpServer`. Plain class with
* no DI so `createTestRegistry` can build one without a Nest app;
* `McpRegistryService` is the DI-discovered subclass.
*/
export class McpRegistry {
private readonly bound: BoundEntry[] = [];
private readonly accessPolicy?: McpAccessPolicy;
private readonly validateAccess?: McpAccessValidator;
constructor(options: McpRegistryOptions = {}) {
this.accessPolicy = options.accessPolicy;
this.validateAccess = options.validateAccess;
}
/**
* Records every decorated method of `instance`. `methodNames` (e.g. from
* Nest's MetadataScanner) narrows the scan; omitted, the instance's
* prototype chain is enumerated directly.
*/
register(instance: object, methodNames?: readonly string[]): void {
const ctor = (instance as { constructor: unknown }).constructor;
if (!isMcpController(ctor)) {
throw new Error(`${(ctor as ClassRef).name} is not decorated with @McpController()`);
}
const names = methodNames ?? enumerateMethodNames(instance);
for (const name of new Set(names)) {
const entry = getEntry(ctor, name);
if (entry) this.bound.push({ entry, instance });
}
}
/**
* Registers every entry passing its access check onto `server`, binding
* `ctx` as the handler's last argument (in the SDK `extra` slot). `opts`
* carries per-session hooks — see `McpAttachOptions`.
*/
attach(server: McpServer, ctx: McpContext, opts?: McpAttachOptions): void {
const registrar = server as unknown as LooseRegistrar;
for (const { entry, instance } of this.bound) {
if (!this.allowed(entry, ctx, instance)) continue;
const handler = (instance as unknown as Record<string, AnyHandler>)[entry.methodName];
switch (entry.kind) {
case 'tool':
this.attachTool(registrar, entry.options, instance, handler, ctx, opts);
break;
case 'resource':
this.attachResource(registrar, entry.options, instance, handler, ctx, opts);
break;
case 'resourceTemplate':
this.attachResourceTemplate(registrar, entry.options, instance, handler, ctx, opts);
break;
case 'prompt':
this.attachPrompt(registrar, entry.options, instance, handler, ctx, opts);
break;
}
}
}
/**
* Fail-fast configuration check — call once after all instances are
* registered (McpRegistryService runs it at boot, createTestRegistry on
* construction) so misconfiguration breaks app startup instead of MCP
* session creation:
* - duplicate names per kind (fixed resources: duplicate URIs), which the
* SDK would otherwise reject per-session at attach();
* - declarative access without a configured accessPolicy;
* - declarative access the host-supplied `validateAccess` hook rejects
* (predicates are opaque to the host and never passed to it).
* All problems are aggregated into one error so a single boot failure
* reports every misconfiguration.
*/
validate(): void {
const seen = new Map<string, BoundEntry>();
const duplicates: string[] = [];
const unresolvable: string[] = [];
const invalidAccess: string[] = [];
for (const bound of this.bound) {
const { entry } = bound;
const key =
entry.kind === 'resource' ? `resource uri "${entry.options.uri}"` : `${entry.kind} "${entry.options.name}"`;
const prior = seen.get(key);
if (prior) duplicates.push(`${key} (${describeBound(prior)} and ${describeBound(bound)})`);
else seen.set(key, bound);
const access = entry.options.access;
if (access === undefined || typeof access === 'function') continue;
if (!this.accessPolicy) unresolvable.push(`${key} (${describeBound(bound)})`);
const problem = this.validateAccess?.(access, this.toListing(bound));
if (problem) invalidAccess.push(`${key} (${describeBound(bound)}): ${problem}`);
}
const problems: string[] = [];
if (duplicates.length) problems.push(`duplicate MCP registrations: ${duplicates.join(', ')}`);
if (unresolvable.length) {
problems.push(
`entries declare declarative access but no accessPolicy was configured ` +
`(McpModule.forRoot({ accessPolicy })): ${unresolvable.join(', ')}`,
);
}
if (invalidAccess.length) problems.push(`invalid access declarations: ${invalidAccess.join(', ')}`);
if (problems.length) throw new Error(`Invalid MCP registry: ${problems.join('; ')}`);
}
/** Introspection: every recorded entry, regardless of access. */
list(): McpRegistryListing[] {
return this.bound.map((bound) => this.toListing(bound));
}
private toListing({ entry, instance }: BoundEntry): McpRegistryListing {
return {
kind: entry.kind,
name: entry.options.name,
className: (instance as { constructor: { name: string } }).constructor.name,
methodName: entry.methodName,
access: entry.options.access,
};
}
private allowed(entry: McpEntry, ctx: McpContext, instance: object): boolean {
// The declaring instance goes in so the gate can read an injected
// collaborator. It is resolved here, at attach, rather than captured when
// the options object was built — the class body runs long before the
// container exists.
if (entry.options.when && !entry.options.when(ctx, instance)) return false;
const access = entry.options.access;
if (access === undefined) return true;
if (typeof access === 'function') return access(ctx);
if (!this.accessPolicy) {
// Fail loud: silently registering would leak a gated entry, silently
// skipping would be undebuggable.
throw new Error(
`MCP ${entry.kind} "${entry.options.name}" declares declarative access ` +
`but no accessPolicy was configured (McpModule.forRoot({ accessPolicy }))`,
);
}
return this.accessPolicy(access, ctx);
}
private attachTool(
registrar: LooseRegistrar,
options: ToolOptions,
instance: object,
handler: AnyHandler,
ctx: McpContext,
opts?: McpAttachOptions,
): void {
const config: Record<string, unknown> = {
title: options.title,
description: options.description,
inputSchema: options.inputSchema as ZodRawShape | undefined,
outputSchema: options.outputSchema,
annotations: options.annotations,
_meta: options._meta,
};
// The SDK invokes the callback as (args, extra) when inputSchema is
// present (even an empty shape) and as (extra) otherwise — normalize so
// the decorated method always receives (args, ctx).
const cb =
options.inputSchema !== undefined
? (args: unknown, _extra: unknown) => {
opts?.onInvoke?.({ kind: 'tool', name: options.name });
return handler.call(instance, args, ctx);
}
: (_extra: unknown) => {
opts?.onInvoke?.({ kind: 'tool', name: options.name });
return handler.call(instance, {}, ctx);
};
registrar.registerTool(options.name, config, cb);
}
private attachResource(
registrar: LooseRegistrar,
options: ResourceOptions,
instance: object,
handler: AnyHandler,
ctx: McpContext,
opts?: McpAttachOptions,
): void {
const metadata: Record<string, unknown> = {
title: options.title,
description: options.description,
mimeType: options.mimeType,
_meta: options._meta,
};
registrar.registerResource(options.name, options.uri, metadata, (uri: unknown, _extra: unknown) => {
opts?.onInvoke?.({ kind: 'resource', name: options.name });
return handler.call(instance, uri, ctx);
});
}
private attachResourceTemplate(
registrar: LooseRegistrar,
options: ResourceTemplateOptions,
instance: object,
handler: AnyHandler,
ctx: McpContext,
opts?: McpAttachOptions,
): void {
const metadata: Record<string, unknown> = {
title: options.title,
description: options.description,
mimeType: options.mimeType,
_meta: options._meta,
};
registrar.registerResource(
options.name,
new SdkResourceTemplate(options.uriTemplate, { list: undefined }),
metadata,
(uri: unknown, variables: unknown, _extra: unknown) => {
opts?.onInvoke?.({ kind: 'resourceTemplate', name: options.name });
return handler.call(instance, uri, variables, ctx);
},
);
}
private attachPrompt(
registrar: LooseRegistrar,
options: PromptOptions,
instance: object,
handler: AnyHandler,
ctx: McpContext,
opts?: McpAttachOptions,
): void {
const config: Record<string, unknown> = {
title: options.title,
description: options.description,
argsSchema: options.argsSchema,
};
const cb =
options.argsSchema !== undefined
? (args: unknown, _extra: unknown) => {
opts?.onInvoke?.({ kind: 'prompt', name: options.name });
return handler.call(instance, args, ctx);
}
: (_extra: unknown) => {
opts?.onInvoke?.({ kind: 'prompt', name: options.name });
return handler.call(instance, {}, ctx);
};
registrar.registerPrompt(options.name, config, cb);
}
}
+14
View File
@@ -0,0 +1,14 @@
import { McpRegistry, type McpRegistryOptions } from './registry';
/**
* Builds a registry from hand-constructed `@McpController()` instances —
* no Nest app required. For test harnesses that assemble a bare `McpServer`
* (e.g. over an in-memory transport).
*/
export function createTestRegistry(instances: readonly object[], options: McpRegistryOptions = {}): McpRegistry {
const registry = new McpRegistry(options);
for (const instance of instances) registry.register(instance);
// Same fail-fast contract as McpRegistryService.onModuleInit.
registry.validate();
return registry;
}
+186
View File
@@ -0,0 +1,186 @@
import type { Scope, ScopeGroup } from '../mcp/scopes';
import type { ZodRawShape } from 'zod';
/**
* The mode half of every scope: 'read' | 'write' | 'delete' | 'share'.
* Mirrors `ScopeMode` in `src/mcp/nest-mcp-policy.ts`, which stays the
* exported one (its only consumer is that file's own lockstep assert).
*/
type ScopeMode = Scope extends `${string}:${infer M}` ? M : never;
/**
* The per-session context handed to `McpRegistry.attach(server, ctx)` and
* forwarded to every handler (last argument) and access predicate/policy —
* mirrors what registerTools() receives per session.
*
* Historically this was an empty interface augmented by the host (nest-mcp
* was a separate extraction-clean workspace); since the fold into the server
* the TREK shape lives here directly. The type-only `../mcp/scopes` import
* above is the one deliberate coupling to the rest of the server.
*/
export interface McpContext {
userId: number;
scopes: string[] | null;
isStaticToken: boolean;
/**
* Fire-once static-token deprecation notice closure (built per session in
* src/nest/mcp-transport/mcp-transport.service.ts and threaded through
* registerTools → registry.attach).
* Optional so direct createTestRegistry ctxs without it keep working —
* consumers (list_trips / get_trip_summary) treat absence as "no notice".
*/
getDeprecationNotice?: () => string | null;
}
/**
* Registry of valid `access.group` values, keyed by the scope-derived union
* so a typo'd group is a compile error in `.mcp.ts` files. The semantics of
* a group come from the access policy in `src/mcp/nest-mcp-policy.ts`, not
* from here.
*/
// A plain alias, not an empty interface: the empty single-extends form only
// existed so an external host could augment the union, and since the fold into
// the server there is no such host. `keyof` resolves the same either way.
export type McpAccessGroupRegistry = Record<ScopeGroup, true>;
export type McpAccessGroup = keyof McpAccessGroupRegistry extends never
? string
: keyof McpAccessGroupRegistry & string;
/**
* Same registry pattern for the access *mode* half. Without the full mode
* union `mode` would be 'read' | 'write' only, and journey's share tools
* could only be expressed as opaque predicates, which the boot gate in
* `src/mcp/nest-mcp-policy.ts` cannot check.
*/
export type McpAccessModeRegistry = Record<ScopeMode, true>;
export type McpAccessMode = keyof McpAccessModeRegistry extends never
? 'read' | 'write'
: keyof McpAccessModeRegistry & string;
/**
* Declarative access marker resolved by the host-supplied `accessPolicy`.
* The package attaches no semantics to `group`/`mode` — the policy does.
*/
export interface McpDeclarativeAccess {
group: McpAccessGroup;
mode: McpAccessMode;
}
/** Predicate escape hatch — bypasses the policy entirely. */
export type McpAccessPredicate = (ctx: McpContext) => boolean;
export type McpAccess = McpDeclarativeAccess | McpAccessPredicate;
/**
* Host-supplied resolver for declarative access, given once at
* `McpModule.forRoot({ accessPolicy })`. Return true to register the entry
* on the session's server.
*/
export type McpAccessPolicy = (access: McpDeclarativeAccess, ctx: McpContext) => boolean;
interface McpEntryOptionsBase {
name: string;
title?: string;
description?: string;
/**
* Availability gate evaluated BEFORE `access` (short-circuits it) — for
* "is this feature on at all" checks like addon toggles. Keeps `access`
* purely about permissions, so declarative scope markers still compose
* with runtime feature gates instead of being replaced by predicates.
*
* `self` is the `@McpController()` instance the entry was declared on,
* handed in at attach time. Without it the gate could only reach a
* module-level singleton, because the options object is built when the class
* is defined and there is no `this` yet — which is how a host ends up
* constructing a second copy of a service outside its own container just to
* answer "is this addon on". With it, the predicate reads an injected
* collaborator and the dependency is visible in the module graph.
*
* Declared with method syntax on purpose: that makes the parameter bivariant,
* so a predicate written against its own controller class stays assignable
* here. The registry always passes the instance that declared the entry.
*/
when?(ctx: McpContext, self: object): boolean;
/** Omitted ⇒ the entry is always registered (subject to `when`). */
access?: McpAccess;
}
/**
* Mirrors the SDK's `registerTool` config. `inputSchema` is a ZodRawShape
* passed straight through — the SDK does the parsing/validation.
* `annotations`/`_meta` are kept structural so the package's public d.ts
* never imports deep SDK subpaths.
*/
export interface ToolOptions extends McpEntryOptionsBase {
inputSchema?: ZodRawShape;
outputSchema?: ZodRawShape;
annotations?: Record<string, unknown>;
_meta?: Record<string, unknown>;
}
/** Mirrors `registerResource(name, uri, metadata, cb)` for a fixed URI. */
export interface ResourceOptions extends McpEntryOptionsBase {
uri: string;
mimeType?: string;
_meta?: Record<string, unknown>;
}
/** Mirrors `registerResource(name, new ResourceTemplate(uriTemplate), metadata, cb)`. */
export interface ResourceTemplateOptions extends McpEntryOptionsBase {
uriTemplate: string;
mimeType?: string;
_meta?: Record<string, unknown>;
}
/** Mirrors the SDK's `registerPrompt` config (argsSchema entries must be string-valued Zod schemas). */
export interface PromptOptions extends McpEntryOptionsBase {
argsSchema?: ZodRawShape;
}
export type McpEntryKind = 'tool' | 'resource' | 'resourceTemplate' | 'prompt';
/** Per-session options for `McpRegistry.attach()`. */
export interface McpAttachOptions {
/**
* Called immediately before every attached handler runs, with the entry's
* kind and registered name. This is the host's observability seam (e.g. a
* tool-call audit trail) — nest-mcp itself attaches no semantics to it.
* Contract: the hook MUST NOT throw; nest-mcp does not catch, so a throwing
* hook fails the very invocation it is observing. Hosts wrap their own
* failure handling.
*/
onInvoke?: (info: { kind: McpEntryKind; name: string }) => void;
}
export type McpEntry =
| { kind: 'tool'; methodName: string; options: ToolOptions }
| { kind: 'resource'; methodName: string; options: ResourceOptions }
| { kind: 'resourceTemplate'; methodName: string; options: ResourceTemplateOptions }
| { kind: 'prompt'; methodName: string; options: PromptOptions };
/** Introspection view of one recorded entry (see `McpRegistry.list()`). */
export interface McpRegistryListing {
kind: McpEntryKind;
name: string;
className: string;
methodName: string;
access?: McpAccess;
}
/**
* Host-supplied per-entry check run by `validate()`. Return a problem
* description to fail boot, null/undefined to accept. Only called for
* entries with DECLARATIVE access (predicates are opaque to the host).
*/
export type McpAccessValidator = (access: McpDeclarativeAccess, entry: McpRegistryListing) => string | null | undefined;
export interface McpModuleOptions {
accessPolicy?: McpAccessPolicy;
validateAccess?: McpAccessValidator;
}
/** Injection token for the options object given to `McpModule.forRoot()`. */
export const MCP_MODULE_OPTIONS = Symbol('MCP_MODULE_OPTIONS');
+904 -20
View File
@@ -15,24 +15,362 @@ server/src/nest/<domain>/<domain>.controller.ts # same routes/verbs/params/s
server/src/nest/<domain>/<domain>.module.ts # registered in app.module.ts
```
Add the prefix to `DEFAULT_NEST_PREFIXES` in `strangler.ts` to route it to Nest
(operators can override at runtime via the `NEST_PREFIXES` env var — instant
rollback, no redeploy). Trip-scoped mounts use a pattern prefix with a `:param`
segment (e.g. `/api/trips/:tripId/packing`); the matcher routes only that nested
mount to Nest and leaves the sibling trip routes (days, places, ...) on Express.
Register the module in `app.module.ts` and it is live. There is no routing gate to
flip any more: **every request goes through Nest**. The `strangler.ts` matcher and
its `DEFAULT_NEST_PREFIXES` / `NEST_PREFIXES` escape hatch are gone — Express only
remains as the platform underneath `@nestjs/platform-express`.
## Migrated so far
- **Phase 1 (leaf):** weather, airports, config (public), system-notices, maps,
categories, tags, notifications, atlas.
- **Phase 2 (trip sub-domains):** vacay (addon), packing, todo.
- **DI-native services (legacy `src/services/*` deleted):** tags, categories,
todo, packing, day-notes, trip-invite, assignments, share, settings, files,
collab, vacay, reservations, day, permissions, audit, budget, trip, maps,
transit, place, transit-itinerary, collections, atlas, auth, oidc, passkey,
notifications, admin, webauthn-config, user-cleanup, oauth, wiki, mailer,
notification transports, notification preferences, memories (immich, synology,
unified, photo-resolver, thumbnails, trek-photo cache), journey, journeyShare
— see the migration recipe below.
- **Foundation (BE-Phase 1, complete):** the eight stateless helpers moved to
`common/`; every trip-access check routes through `DatabaseService`
(`services/tripAccess.ts` and the dead `middleware/tripAccess.ts` are gone);
`queryHelpers` and `tripMembership` are providers; every cron is a domain
`*.job.ts` provider on `scheduling/CronRegistrarService` (`src/scheduler.ts`
is deleted).
- **Plugin RPC surface (BE-7, complete):** all 113 wire methods are
`@PluginMethod` / `@PluginOpenMethod` handlers on `@PluginController()` providers
in their own domains (`<domain>/<domain>.rpc.ts`; the three that belong to no
domain live in `plugins/host/rpc/`), and all 18 host-to-plugin hook contracts are
`@PluginHook` declarations on `PluginHooks`. `PluginRpcHost` no longer holds a
handler: it builds the granted subset of the dispatch map from the registry,
dispatches, audits and maps errors. `PluginHostDepsFactory` — the 26-argument
wiring sheet named throughout the log below — is now
`PluginRpcHostFactory` and injects two things. See
`plugins/host/rpc-kit/README.md`.
- **Plugin module split (complete):** `PluginsModule` was 21 controllers, 24 domain
imports and 10 providers in one class, so `AdminModule` importing it for one
cascade-disable call inherited the whole graph. It is now `PluginsRuntimeModule`
(supervisor, capability router, hook contracts — the half with the domain imports),
`PluginContributionsModule` (the 14 read-only hook controllers, in
`plugins/contributions/`), `PluginOAuthModule` (`plugins/oauth/`) and a composition
root holding the install and delivery controllers. `AdminModule` imports the runtime
alone. Note the invariant the boot-time coverage check now depends on: importing
`PluginsRuntimeModule` must pull in EVERY domain that owns part of the wire surface,
which is why `WeatherModule` sits in its import list.
- **Guards (BE-Phase 2, done):** the JWT verify lives in `auth/`, and
`middleware/auth.ts`, `validate.ts`, `idempotency.ts` and `mfaPolicy.ts` are
deleted; the three addon guards are one `AddonGuard` + `@RequireAddon`; the
demo-mode block is one condition. `TripAccessGuard` and `TripOwnerGuard` cover
the trip-scoped and owner-only routes.
**Authentication is default-deny.** `GlobalAuthGuard` is an `APP_GUARD`: a route
is authenticated unless it carries `@Public(reason)` or `@OptionalAuth(reason)`,
or declares its own `@UseGuards` chain. A controller that declares a chain keeps
it — global guards run before route guards, so an addon-gated controller has to
stay in charge of answering 404 before anything answers 401, or the response
leaks which addons are installed. The global guard still *resolves* the user in
that case, without refusing, because `MfaPolicyGuard` runs behind it and reads
`req.user`.
Adding a `@Public()` route is not a local decision: `validateRouteGuards` runs in
`buildApp()` and refuses to boot unless the route is also in
`PUBLIC_ROUTE_ALLOW_LIST` in `common/validate-route-guards.ts`. That list is the
whole anonymous surface of the server, in one reviewable place. Stale entries
fail too.
**`src/services/` is gone.** It was the legacy layer this whole migration existed
to empty, and the last of it — `airtrail/`, 1305 lines of plain functions over the
better-sqlite3 singleton — folded into `integrations/`. An ESLint
`no-restricted-imports` rule now refuses any import of a `services/` path, because
the directory disappearing is not what keeps it gone: it grew one reasonable file
at a time. Backup made the same trip earlier: `services/backupService.ts` is
`nest/backup/backup.impl.ts`, imported only by its own domain, and it stays a
module of free functions rather than becoming methods because the restore path
closes and reinitializes the core DB handle — rewriting that shape in the same
step as the move would make a regression there impossible to bisect.
Note that the trip-access and `canEdit` methods on the domain services are **not**
dead weight waiting for a guard: their callers are overwhelmingly the `*.mcp.ts`
tools, which never pass through an HTTP guard. In the five domains piloted for
`TripAccessGuard`, 40 of the 46 callers are MCP; only 6 sit in controllers.
## Cross-cutting Foundation pieces
- `common/idempotency.interceptor.ts` — global `APP_INTERCEPTOR` replaying the
client's `X-Idempotency-Key` on mutations, mirroring the legacy
`applyIdempotency` middleware so retried writes don't double-apply.
- `strangler.ts` — supports both static prefixes and `:param` pattern prefixes.
client's `X-Idempotency-Key` on mutations. It replaced the `applyIdempotency`
middleware, which is deleted; this is the only implementation.
- `common/` — the stateless helpers (`avatarUrl`, `conflictResult`, `demo`,
`passwordPolicy`, `timezoneService`, `cookie`, `rowShape`, `geo`, `crypto/`).
Free functions, not providers: `db/migrations.ts` imports them from outside the
container and could not inject one. `geo.ts` holds the two haversines; there
were three implementations of the metre variant, differing by one clamp, and
the clamped form is the one kept — `asin` of a value a hair over 1 is NaN, and
a NaN distance silently fails every comparison it feeds instead of throwing.
`maps.helpers.ts` re-exports `haversineMetres` rather than defining it, because
callers and a test import it from there.
- `auth/jwt-verify.ts` — `extractToken` + `verifyJwtAndLoadUser`, the canonical
session check behind the four guards, the MCP bearer path and the file-download
query token. Free functions for the same reason.
`JWT_SECRET` stays a live binding from `src/config` and must NOT move to
`app-config`: the admin panel rotates it at runtime, and a `registerAs` token
would freeze the boot value.
- `query-helpers/` — the batch loaders that keep list endpoints off N+1 queries.
- `trip-membership/` — `joinTripAsMember`. Its own module rather than folded into
auth or trip-invite, because both call it (as do oidc and the plugin host) and
either home would put `AuthModule` and `TripInviteModule` in a cycle.
- `addons/addon.guard.ts` + `@RequireAddon(addonId, label)` — the addon route
gate. Declare `AddonGuard` **before** `JwtAuthGuard`: a disabled addon has to
answer 404 to anonymous callers, so the addon check must beat the 401.
- `common/demo-write.ts` — `isDemoWriteBlocked`, the demo-mode upload block. A
function and not a guard on purpose; see the gotcha below.
- `storage/` — the storage abstraction and its admin surface. `storage.types.ts`
defines the driver contract (opaque keys, no rename/append — S3 constraints
baked in) plus the `ServedCategory` seam: `STORAGE_CATEGORIES` (shared, 8,
configurable) + the legacy `photos` directory that is served and backed up
but not configurable. `drivers/` (local, s3, mirror) all pass one contract
suite (`tests/unit/nest/storage/storage-driver.contract.ts`).
`storage-registry.service.ts` merges built-ins ← env (`place-photos-local`)
← `app_settings` rows, validates semantics (references, no mirror nesting),
falls back to last-good/defaults at boot but NEVER on admin writes
(`preview()` runs the real build first), seeds once from
`data/storage-config.json`, and hot-swaps on `reload()`.
`storage.service.ts` is the facade every byte-path uses.
`storage-admin.{controller,service}.ts` (+ `storage-secrets.ts`,
`storage-probe.ts`) carry `api/admin/storage`: masked GET of the effective
world, full-document PUT (unmask → preview → encrypt → one transaction →
reload → audit), and per-target test probes with ephemeral drivers. Secrets
live `enc:v1:`-encrypted inside the `storage.backends` JSON (the implicit
key covers installs without an explicit `ENCRYPTION_KEY`). The client
presents mirrors as replicas-on-primary; the wire keeps explicit mirror
backends. `storage-jobs.service.ts` runs backfill and category-migration
jobs (one at a time, TTL'd statuses).
- `memories/photo-provider.ts` + `providers/` — the PhotoProvider seam (#584).
Dispatch to a photo backend was a `switch (photo.provider)` in three places
(`photo-resolver.service.ts` twice, `journey-public.controller.ts` once, where
anything that was not Immich got handed to Synology). It is
`PhotoProviderRegistry.get(id)` now, over adapters registered under the
`PHOTO_PROVIDERS` multi-provider token in `memories.module.ts` — adding a
backend is one registration.
- Adapters, not `implements` on the services: ImmichService and
SynologyService are also the album/browse surfaces, with their own argument
orders and return shapes. The mapping lives in the adapter.
- `PhotoAssetRef` exists because the two services took the same three values
in different orders — `(userId, assetId, ownerId)` against
`(userId, targetUserId, photoId)`. A transposition compiled cleanly and
served another user's photo.
- `local` is deliberately NOT a provider. It is storage on this disk, it has
no row in `photo_providers`, and its "asset info" comes from the DB row
rather than from a backend. Both dispatch sites branch on it explicitly.
- The rename `memories/` → `media/` was considered and dropped: it is 275
files of import churn, and `scripts/coverage-thresholds.mjs` buckets on one
path segment, so merging `photos/` into it would collapse two ratchet
entries into one and drop the stricter of the two.
- `realtime/` — the /ws transport, as a Nest gateway.
- `realtime.gateway.ts` owns the connection lifecycle and the handshake, with
`DatabaseService` and `EphemeralTokenService` injected instead of imported.
It replaced `setupWebSocket(server)`, which index.ts kicked off with a
dynamic import after listen().
- `ws-state.ts` holds the socket registry, and that is **module state on
purpose**. The no-Nest test harnesses build `new RealtimeService()`
outside the container and 115 test files `vi.mock` the `src/websocket`
stub; rooms on a provider instance would leave their broadcasts going to
an empty map, with no error and no log. Same reasoning as the geo
throttle cursor.
- `trek-ws.adapter.ts` exists because the stock `WsAdapter` dispatches on
`{ event, data }` and every deployed client sends `{ type, tripId }`. It
also builds the ws server itself rather than delegating: the base's port-0
branch uses `noServer: true` and performs the upgrade from its own registry,
which never consults `verifyClient`, so delegating would silently drop the
origin check. The per-socket `error` listener is attached FIRST, because an
unhandled one kills the process (#1576), and the flood guard counts every
inbound frame before parsing, because malformed frames are the ones worth
limiting.
- The socket id stays a **monotonic integer**. The client echoes it as
`X-Socket-Id` and `broadcast` excludes the originator with
`Number(excludeSid)`; a uuid is `NaN`, `NaN === NaN` is false, and every
client would receive its own writes back. It shows up as drag-and-drop that
jumps, not as an error.
- `RealtimeGatewayModule` is imported by AppModule alone. RealtimeModule is
@Global, so a gateway there follows into every hand-assembled TestingModule,
and Nest's SocketModule then loads an adapter none of them set: it reaches
for `@nestjs/platform-socket.io` and calls `process.exit(1)` when it is
absent.
- `buildApp()` creates the http server and binds the adapter to it BEFORE
`app.init()`, and callers take it from `getHttpServer()`. Nest binds gateways
during init, so an adapter registered later binds nothing, and one given the
app instead of the server binds to Nest's internal server, which this process
never listens on. Either way the boot is green and no browser can connect.
- `src/websocket.ts` survives as a re-export. 115 test files `vi.mock` that
path to assert on broadcasts; repointing them all would be a large diff that
proves nothing.
- `geo/` — the ONE Nominatim client (#576). There used to be two: atlas
throttled to the published 1.1s and cached its answers, maps did neither, so
five interactive routes fired straight at the service while the atlas loops
politely waited and OSM saw a single instance ignoring its rate limit. Both
domains now go through `nominatimFetch`.
- The throttle cursor and the cache are **module state, not provider state**,
for the permissions-cache reason: the no-Nest test harnesses build their
collaborators with `new`, outside the container, and a second copy of the
cursor is the very bug the fold removes. `GeoModule` is registered straight in AppModule and neither
`MapsModule` nor `AtlasModule` imports it — an import would claim an
injection edge that does not exist.
- `GeocodingService` owns exactly one thing: the cache-cleanup timer's
lifecycle, via `OnModuleInit`/`OnModuleDestroy`. Atlas used to start that
interval as an import-time side effect, documented as a parity exception. It
is not one any more.
- Two lanes over one cursor. Interactive calls (`/api/maps/search`,
`/autocomplete`, `/details`, `/reverse`, `/resolve-url`) take the next slot;
background calls (the atlas enrichment loops, which walk every uncached
place) yield to anything queued on a request path.
- The cache key carries the **query shape**, not coordinates alone. Atlas asks
at zoom 3 and zoom 8, maps at zoom 18; a coordinate-only key answered a
street lookup with a country.
- `AbortSignal.timeout` is built **after** the throttle wait. Built up front,
the 1.1s spent queueing would eat nearly half of the identity lookup's 2.5s
budget before the socket opens.
- `setGeoThrottleInterval(ms)` is a test seam, and `tests/setup.ts` zeroes it.
Nineteen maps cases drive these paths back to back with real timers; at the
real interval they slept nineteen seconds and covered nothing extra. A
function rather than a `NODE_ENV` check, for the reason app-config exists.
### Reaching the container from outside it
Two shapes, and the choice is settled:
**Prefer handing the dependency in.** `bootstrap.ts` hands the `/mcp` handler
its registry via `setMcpRegistry(app.get(...))` after `buildApp()` — the
outside code names the capability it needs, structurally, never the provider
class, so no module cycle can close through it. (The retired `src/scheduler.ts`
was the fullest example — a structural `SchedulerDeps` interface filled by
`index.ts` — until every cron became an in-container `*.job.ts` provider and
the seam disappeared entirely, which is the real endgame for this shape.)
**`<domain>.bridge.ts` is a retired shape** — zero bridge files remain since
the MCP/OAuth mount moved behind the container (2026-08-11). It served code
that ran before `app.init()` and so could not inject; its cost was real: a
bridge rebuilt its services with `new`, so adding one constructor parameter to
a service meant hand-editing every bridge that constructed it — five of them in
one PR, at the worst. If a pre-init consumer ever reappears, prefer the
`bootstrap.ts` pattern instead: resolve the container singleton with
`app.get(...)` before init (the `httpConfig.KEY` / discovery-metadata
precedent) rather than minting a second instance.
**Express middleware with DI has two honest mounts** (first used by the mount
migration): `consumer.apply(...).forRoutes('<concrete path>')` in a module's
`configure()` — an Express prefix mount, exactly the legacy `app.use('/path')`
semantics, which is how `OauthModule` mounts the MCP SDK's authorize/register
routers and `PlatformModule` the consent-COOP override — and, for middleware
that must see the ORIGINAL `req.url` (a wildcard `forRoutes()` is a pattern
mount that strips the matched prefix), a pathless `app.use` in `bootstrap.ts`
over a container-resolved factory provider (`MCP_METADATA_MIDDLEWARE`).
`nest/mcp-transport/` (the /mcp controller + service over injected services)
and `nest/mcp-shared/` (`McpToolGuardsService` for the `*.mcp.ts` classes) are
the module shapes that replaced the last bridges.
**A bridge imported from INSIDE the container hides an edge from the module
graph**, which is a different problem from serving a genuine outside consumer.
Nine `*.mcp.ts` files did that with `addons.bridge` for one boolean each, and
not by preference: a decorator's options object is built while the class is
being defined, so the `when:` closure had no `this` to reach an injected service
through. `src/nest-mcp/` hands the gate its declaring instance now, and
`addons/addon-gate.ts` turns that into `addonGate(ADDON_IDS.X)` over an injected
`AddonsService`. `reservations.mcp.ts` (assignments) and `atlas.mcp.ts` /
`journey.mcp.ts` (auth) went the same way.
No in-container bridge uses are left. The last four folded 2026-08-11, and
their folds are the playbook for any edge that reappears — plain injection
would have closed a real cycle in every case, so each cut the knot with a
finer-grained module instead:
- `budget.mcp.ts` / `packing.mcp.ts` / `costs.rpc.ts` → `trips.bridge`:
everything that owns the hydrated trip reads (TripsService,
TripReadModelService, TripMembersService) lives in modules importing the
budget/packing domains, so the consumers moved instead — the id-level
membership reads went to the dependency-free `TripMembershipModule`
(`getOwnerId` / `listMemberUserIds` / `listAccessibleTripIds`) and the two
cross-domain prompts moved above the read model onto
`trips/trip-prompts.mcp.ts`. `trips.bridge` (102 lines, ~25 hand-built
services) is deleted.
- `places.mcp.ts` → `assignments.bridge`: the cycle `DaysModule →
PlacesModule → AssignmentsModule → DaysModule` is real, but only
AssignmentsMcp needs DaysService — the service itself does not, so it moved
to a leaf `AssignmentsDomainModule` (the journey-domain split) that
PlacesModule imports. `assignments.bridge` is deleted.
- `reservations.controller.ts` → `airtrail.bridge`: the pull genuinely needs
ReservationsService, so `AirtrailModule` keeps it — but the write-back push
only needs the hydrated reservation READ. That read became
`ReservationsReadRepository` (leaf, the trek_photos pattern), the link
lifecycle + push became `AirtrailLinkService` in `AirtrailCoreModule`, and
the controller injects it. `airtrail.bridge` is deleted, and
`notifications.instance.ts` — whose last consumer it was — died with it.
Two more were on this list and folded 2026-08-11:
- `auth/user-cleanup.service.ts` → `budget.bridge` died when `BudgetModule`
dropped its `AuthModule` import (BudgetMcp's demo guard reads
`RuntimeEnvService` + the users table via `isDemoUserId`, not
`AuthService`), which let `AuthModule` import `BudgetModule` and
`UserCleanupService` inject `BudgetService`. `budget.bridge` is deleted.
- `backup/backup.impl.ts` → `permissions.bridge`: the restore path is free
functions, not a provider, so there is nothing for an injected service to
hang off — but the thing it needs is the cache, not the service. The cache
moved to `permissions/permissions-cache.ts` (the `oauth.pending-codes.ts`
precedent) and `backup.impl` imports the plain `invalidatePermissionsCache`
from there.
`files.bridge` used to be on the list and is gone, resolved 2026-08-10 exactly
as predicted: `MulterModule.registerAsync` over an `AllowedFileTypesService`
leaf, and `files.controller.ts` / `journey.controller.ts` build their multer
options from that. `systemNotices/conditions.ts` similarly stopped importing
`addons.bridge`: the enablement check is threaded in through
`ConditionContext.addonEnabled` by the DI-native `SystemNoticesService`.
`days`, `packing`, `photos` and `reservations` had no production consumer left
and are deleted. Each still built a service outside the container at module load
for nobody, and three domain docblocks were still sending readers to them. The
cases that exercised them kept their assertions and point at the service.
`journey.bridge` died 2026-08-11 with `src/mcp/resources.ts`, when the last
four legacy resources became `@Resource`/`@ResourceTemplate` methods on
`journey.mcp.ts`.
Five bridges remain, all pinned by the one pre-`app.init()` MCP/OAuth mount
(`addons`, `audit`, `auth`, `oauth`, `permissions` — shrunk to the exports that
seam consumes) and all dying together if that mount ever moves behind the
container. When one loses its last outside-container consumer, delete it in
the same change rather than leaving it as a courtesy: an unused bridge reads
as a supported entry point.
The nine fire-and-forget notification senders inject too. They were lazy
`import('../notifications/notifications.bridge').then(({ send }) => …)` calls
working around a cycle that no longer exists, and the laziness hid the edge
while handing each send a NotificationsService built outside the container.
That sweep needed a method, because `tests/` sits outside `tsconfig`'s `include`:
a missed constructor argument does not fail to compile, it arrives as
`undefined`. Adding `tests` to a throwaway `tsconfig` and diffing the errors
before and after named all **46** hand-wired `new` sites exactly; a grep would
have been a guess. Worth repeating for any change that widens a service
constructor — and worth knowing that such a config reports **288 pre-existing
errors** in the suites, almost all deliberate partial constructions in the
harnesses (`new AuthService(db, permissions, atlas)` where the class takes six).
That is why `tests/` is not in the build's `include`, and cleaning it up is its
own piece of work.
`notifications.instance.ts` held the out-of-container `NotificationsService`
for the cycle-dodge bridges and died 2026-08-11 with the last of them
(`airtrail.bridge`) — every production consumer injects the container
singleton now. The module-scoped channel registry it leaned on stays (the
no-Nest test harnesses still construct instances; CHOVR-015 pins the
sharing).
- `app-config/` — the `@nestjs/config` binding (`AppConfigModule`, global). Never
read `process.env` in a module (ESLint enforces this): inject a boot-stable
namespace via its `registerAs` token (`@Inject(mcpConfig.KEY) … ConfigType<…>`)
or read runtime-toggled values live through `RuntimeEnvService` / `readEnv()`
from `src/app-config`. The classification and invariants live in
`src/app-config/README.md`.
## Parity gotchas worth remembering
@@ -44,6 +382,40 @@ mount to Nest and leaves the sibling trip routes (days, places, ...) on Express.
returns `{ error: 'Admin only' }`, not the AdminGuard's `Admin access required`.
- Trip-scoped routes verify trip access (404) and the relevant permission (403)
per handler and forward `X-Socket-Id` to the WebSocket broadcast.
- **Never gate a multipart upload with a guard.** Guards run before the parser,
so throwing from one leaves the request body unread and Node resets the
connection — the client sees `ECONNRESET`, not your 403. Check inside the
handler, after the interceptor has drained the upload. `PROFILE-015` is the
regression test.
- **`@Global()` only applies to modules that are in the graph.** An e2e
`TestingModule` built around one domain module does not get `AppConfigModule`
for free just because it is global: a provider injecting `RuntimeEnvService`
fails to resolve and takes every suite importing that module down with it.
Import it explicitly, the way `PermissionsModule` is handled.
- **A module-scoped registry that outside code writes into must stay a module,
not a provider.** The notification channel registry is the live example:
`PluginRuntimeService` pushes its channel getter in at `onModuleInit`, and
`notifications.instance.ts` builds its own `NotificationsService` for the
surviving cycle-dodge bridges. As a provider that instance would get a second,
empty registry and every plugin channel would go quiet — with no error
anywhere. `CHOVR-015` is the regression test. Same reasoning as
`oauth/oauth.pending-codes.ts`.
- **Self-registration by side-effect import is a trap.** The built-in channels
used to register because `notificationPreferencesService` happened to `import
'./notifications/builtins'`. Dropping that one line would have silenced email,
webhook and ntfy without a failure. They are built from injected transports and
registered in `NotificationsService`'s constructor now, so every path that can
dispatch has them.
- **The coverage gate reads `src/nest/**` and nothing else.** Moving code in from
`src/mcp/` or `src/services/` does not just relocate it — it starts being
measured. PR #1844 landed `airports.mcp.ts` at 0% branches because
`search_airports`/`get_airport` had never had a test in either world, and the
aggregate fell to 79.86% with every suite green. Before pushing anything that
moves files into this tree, run `npm run test:coverage`, not just `npm test`.
- A guard with a constructor dependency has to be a registered provider
everywhere it is used. The three auth guards are dependency-free on purpose —
38 directories apply them and 21 do not import `AuthModule`, so giving them a
dependency is its own migration, not a side effect of another change.
## Parity is law
@@ -53,23 +425,75 @@ strings. Where the legacy route returns a hand-written error (e.g. weather's
`{ error: 'Latitude and longitude are required' }`), reproduce that exact body in
the controller rather than relying on the generic `ZodValidationPipe` envelope.
## TripAccessGuard and TripOwnerGuard, and where they do not fit
`permissions/trip-access.guard.ts` resolves `:tripId` once per request, answers 404
"Trip not found" for anything the user cannot reach (never 403 — that would confirm the
id exists), and hands the row to the handler through `@Trip()`. `@RequirePermission`
carries the same action string the domain services pass to `checkPermission`.
Two limits are worth knowing before rolling it onto another controller, because both
were found the expensive way:
- **A guard runs before the body pipe.** Any route whose DTO validation is expected to
answer 400 *ahead of* the trip 404 cannot use it. `places` is exactly that case — its
e2e suite documents the pipe-first ordering as a deliberate parity shift — so its
create/update/import routes keep their in-handler `requireTrip`, and that is not an
oversight. Its five body-free routes (list, get, unrate, image, delete) do carry
the guard; the split runs along "does this handler take a DTO-typed body", not
along the domain.
- **A guard also runs before interceptors.** On a multipart upload route, a 404 sent
while the client is still streaming destroys the socket, so the caller sees
ECONNRESET instead of the 404. The three upload routes (files, collab note files,
places) keep their own check for that reason; their controllers apply the guard per
handler instead of on the class.
`permissions/trip-owner.guard.ts` is the stricter sibling: `@RequireTripOwner(message)`
demands that the caller *owns* the trip, not merely that they may edit it. Handing a
trip over and creating or deleting guests are the two things a collaborator must never
do however generous the trip's permission settings are.
It deliberately does **not** inject `PermissionsService`. `checkPermission` returns true
for every admin, and the trip actions are admin-lowerable, so routing ownership through
it would quietly hand any admin the ability to transfer other people's trips. The check
is the literal one the routes did by hand: `trip.user_id === user.id`. The message
travels in the metadata because the two call sites answer with different strings and
both are asserted.
The services keep `verifyTripAccess`/`canEdit` regardless: most of their callers are
`*.mcp.ts` tools, which never pass through an HTTP guard.
## Coverage is gated per domain, as a ratchet
`server/vitest.config.ts` carries one threshold entry per `src/nest/<domain>/`, set at
that domain's measured coverage minus one point. The single repo-wide 80% it replaced
let a well-covered domain subsidise a thin one — `booking-import` sits at 50% and
`integrations` at 20%, and the aggregate still cleared the bar, so either could have
lost another ten points with the build staying green.
Regenerate the block with `node scripts/coverage-thresholds.mjs` after a run that
RAISED coverage. Raise an entry when you improve a domain; never lower one to make a
build pass. The script reads `coverage/coverage-summary.json` rather than the text
reporter on purpose: the text reporter prints one row per DIRECTORY, so a domain with
subdirectories reads several points higher there than it actually is.
## How to write the tests
Every module ships three kinds of tests; the coverage gate (`vitest.config.ts`,
scoped to `src/nest/**`) requires ≥80%.
Every module ships two kinds of tests. The coverage gate (`vitest.config.ts`)
requires ≥80% over `src/nest/**` — note that it is an **average across the whole
tree**, not a per-file floor, so a large untested module can hide behind the
well-covered small ones.
1. **Service / controller unit spec** — `tests/unit/nest/<domain>.controller.test.ts`.
Instantiate the controller with a mocked service; assert status codes, the exact
`{ error }` bodies, and that inputs are forwarded correctly (defaults, coercion).
See `weather.controller.test.ts`.
2. **Parity test** — `tests/parity/<domain>.parity.test.ts`. Mock the shared service
identically for both apps, then fire the same request at the Express route and the
Nest controller with the `expectParity()` harness (`tests/parity/parity.ts`) and
assert identical status + body. This is the gate before flipping the toggle.
See `weather.parity.test.ts`.
Parity against the behaviour being replaced belongs here too — assert the exact
status codes and bodies the old path produced. There is no separate
`tests/parity/` directory; it was removed along with the routing toggle.
3. **e2e** — `tests/e2e/<domain>.e2e.test.ts`. Boot the Nest module against a temp
2. **e2e** — `tests/e2e/<domain>.e2e.test.ts`. Boot the Nest module against a temp
in-memory SQLite db via the shared harness (`tests/e2e/harness.ts`:
`createTempDb`/`seedUser`/`sessionCookie`), exercising the **real** `JwtAuthGuard`
end-to-end (401 without cookie, 200 with a signed session). Mock external I/O
@@ -78,7 +502,467 @@ scoped to `src/nest/**`) requires ≥80%.
## Definition of Done (per module)
Contract in `@trek/shared` → service ported 1:1 → controller with identical routes →
validation/error parity → unit + parity + e2e tests over the gate → prefix toggled to
Nest → parity verified on the demo DB → **then** decommission the old Express
route/service (separate step, after the toggle is confirmed in prod) → frontend points
at the typed contract (Frontend Track).
validation/error parity → unit + e2e tests, with the old behaviour asserted in the
unit test → module registered in `app.module.ts` → **then** decommission the legacy
service (separate step) → frontend points at the typed contract (Frontend Track).
## Migrating a legacy `src/services/*` service into its Nest module (recipe)
Pilot: **tags** (`services/tagService.ts` → `nest/tags/tags.service.ts` +
`nest/tags/tags.bridge.ts`); categories followed the same shape (and piloted the
first `@Resource` in `categories.mcp.ts`); todo followed too (and piloted the
first `@ResourceTemplate` plus the `when` addon gate in `todo.mcp.ts`, and the
first in-container consumer wiring: `TripsService` injects `TodoService` via
`exports: [TodoService]` instead of using the bridge); packing followed (the
largest port so far: a 17-tool + 2-resource `packing.mcp.ts` with inline admin
gates, and the first `PluginHostDepsFactory` swap done as part of a service
migration — no bridge entry for the plugin host); day-notes followed (the first
migration needing **no bridge at all**: after its three tools + resource moved
to `day-notes.mcp.ts` and the plugin host injection, nothing outside the
container consumed it); trip-invite followed (the smallest port: no MCP
surface, no plugin-host import and no bridge — the SQL folded straight into
`trip-invite.service.ts`); assignments followed (a 7-tool `assignments.mcp.ts`,
the plugin-host swap, and a bridge kept only for the two legacy registrars —
places and reservations — that borrow its existence checks; the batch loaders
stay in `services/queryHelpers.ts`, shared with the unmigrated place
service); share followed (never imported by the plugin host, and its three MCP
tools stay in the legacy trips registrar — their `trips:share` scope gate has
no declarative `access: { group, mode }` equivalent — so the port is the SQL
fold plus a 3-export `share.bridge.ts` for `mcp/tools/trips.ts`); settings
followed (no MCP surface, no bridge, and the first migration that converted an
in-container plain-function consumer into a provider instead of bridging it:
`llm-parse/llm-config.resolver.ts` became the injectable `LlmConfigResolver`,
injected by `LlmParseService` and `PluginHostDepsFactory`); files followed (no
MCP surface and no addon gate; the load-time constants + pure helpers consumed
by three controllers' module-scope multer configs moved to
`files.constants.ts`, and `files.bridge.ts` survives with a single export —
the request-time `getAllowedExtensions` app_settings read those configs need
outside DI — while every function consumer, including the plugin host and
`TripsService`, injects `FilesService`); collab followed (a 12-tool +
3-resource `collab.mcp.ts` that piloted **composite `when` gates** — the collab
addon AND the per-sub-feature `getCollabFeatures()` flags (notes/polls/chat)
that the legacy registrar and resources checked at registration time — plus
the plugin-host swap and a 3-export `collab.bridge.ts` for the two remaining
legacy consumers, `tripService`'s trip summary and `mcp/tools/trips.ts`);
vacay followed (the largest MCP port yet — a 26-tool + 3-resource
`vacay.mcp.ts`, including the first fixed-URI `@Resource` behind a `when`
addon gate — plus the plugin-host swap and a 1-export `vacay.bridge.ts` for
`tripService`'s trip-window entry shift; the DTO ratchet for its 13
grandfathered body contracts landed as a sibling commit); reservations
followed (the residue fold: the wrapper `ReservationsService` was already
DI-native at the edge, so the 626-line legacy module folded into it — a 5-tool
+ 1-resource `reservations.mcp.ts`, the plugin host's last plain-function
reservation import (`notifyBookingChange`) swapped for the injected service,
`TripsService` and `BookingImportService` converted from function imports to
injection, and a 9-export + 3-type `reservations.bridge.ts` for the legacy
`tripService`, the airtrail import/sync pair and the still-legacy transports
registrar (the transit registrar has since migrated to `transit.mcp.ts`); the
DTO ratchet for its 4 grandfathered body contracts
landed as a sibling commit, which also loosened the shared positions schema to
the real wire contract — `day_plan_position` optional, pinned by RESV-006);
day followed (the 592-line legacy `dayService` folded into the existing
wrapper `DaysService` — including the accommodation SQL that
`nest/reservations/accommodations.service.ts` now reaches via an injected
`DaysService` — with the hand-rolled `BEGIN`/`COMMIT` blocks in
reorder/insert converted to `db.transaction()`; a 7-tool + 2-resource
`days.mcp.ts`, the plugin host's 11-symbol import swapped for the injected
service, `TripsService` + the assignments/reservations MCP controllers
converted to injection, and a 6-export `days.bridge.ts` for the legacy
`tripService` and the still-legacy transports registrar (transit has since
migrated); the DTO
ratchet for its 4 day + 2 accommodation grandfathered body contracts landed
as a sibling commit);
permissions followed (the first Wave-2 **cross-cutting** migration and the
first greenfield module in the series — no prior wrapper, controller, MCP
surface or DTO of its own: a new `nest/permissions/` whose
`PermissionsService` is injected by 16 domain services, the airtrail-import
controller and `PluginHostDepsFactory` (its 16th constructor dep) in one move,
plus a 5-function `permissions.bridge.ts` for `mcp/tools/_shared.ts` — one
repoint covering every `hasTripPermission` call site — and the four legacy
consumers adminService/authService/backupService/collectionsService; the
permissions **cache stays module-scoped** in `permissions.service.ts` on
purpose, so the bridge instance and the container singleton share one cache
and backup-restore's bridge-side `invalidatePermissionsCache()` flushes what
request handlers serve; the domain e2e suites swapped their path mocks for a
`vi.spyOn(app.get(PermissionsService), 'checkPermission')` instance spy);
auditLog followed (the other Wave-2 half, split into five files: the
injectable `AuditService` (`writeAudit` over `DatabaseService`), the pure
`client-ip.ts` (files.constants precedent — the four getClientIp-only
controllers stay plain imports), the deliberately side-effectful plain
`audit-log.logger.ts` — frozen-at-import `LOG_LEVEL` and the import-time
`data/logs` mkdir are a documented parity exception to the no-side-effects
rule because `index.ts` lazy-requires it pre-container and tests/setup.ts
sets the level pre-import — plus `audit.module.ts` and a full-surface
`audit.bridge.ts` for `mcp/index.ts`, `mcp/oauthProvider.ts` and the legacy
airtrail/immich/oauth services, while log*-only consumers (index.ts's lazy
require strings, scheduler, globalMiddleware, notifications) point at the
logger directly; 8 controllers + `PluginRuntimeService` inject `AuditService`,
and the domain e2e suites dropped the audit mock entirely — writeAudit runs
for real against an `audit_log` table in their temp DBs).
The exchangeRateService fold followed (the pure-infra FX helper — Frankfurter
fetch + module-scoped 6h cache, no SQL, no controller, no MCP registrar of its
own — folded into `nest/budget/` as a dep-free `ExchangeRatesService`, injected
by `BudgetService` and `PluginHostDepsFactory` (its 17th constructor dep); the
rate **cache stays module-scoped** like the permissions cache, so any
out-of-container instance and the container singleton share one cached
upstream feed).
budgetService followed (the 755-line Wave-4 money core folded into the wrapper
`BudgetService`: items/members/payers CRUD, the FX freeze + rebase paths and
the settlement maths with `splitEqualShares` gone private; the freeze-then-write
composites kept their wrapper names while the raw settlement writes became
`insertSettlement`/`applySettlementUpdate` so the MCP paths keep skipping the
freeze; the 11-tool `mcp/tools/budget.ts` registrar + 3 `resources.ts` budget
resources moved to `budget.mcp.ts`; TripsService, ReservationsService (+ its
MCP class) and BookingImportService inject `BudgetService`; a 4-export
`budget.bridge.ts` served the legacy tripService/userCleanupService and the
trips/transports registrars (deleted 2026-08-11: BudgetMcp's demo guard moved
off AuthService onto `isDemoUserId`, BudgetModule dropped AuthModule, and
`UserCleanupService` injects `BudgetService` now);
`exchange-rates.bridge.ts` was deleted with its
last consumers, and the controller adopted `budget.dto.ts` — all nine
allow-list entries removed).
tripService followed (the 1121-line Wave-4 hub — the biggest fold — moved into
the wrapper `TripsService`: TRIP_SELECT + list/create/get, the
`generateDays` two-phase renumber engine, the updateTrip date-shift
transaction, the member/guest lifecycle (#973/#1362), the ICS export with its
module-scoped tz-validity cache, `copyTripById` and `getTripSummary`; its six
bridge imports became injected services (CollabService + VacayService joined
the constructor); the 10-tool trips registrar + 3 `resources.ts` trip
resources + the trip-summary prompt moved to `trips.mcp.ts` — the first
`@Prompt` use, with the fire-once static-token deprecation notice now riding
the `registry.attach` ctx — and the 3 share-link tools it carried moved to
`share.mcp.ts` on the `canShareTrips` predicate (delete_trip and the
canReadTrips reads are predicates too — the broadened legacy gates have no
declarative equivalent); FeedsService and the plugin host inject
`TripsService` (its 20th constructor dep); a 4-export `trips.bridge.ts`
serves budget.mcp.ts / packing.mcp.ts / costs.rpc.ts (verified-permanent
2026-08-11: the trip read-model/members modules import the budget and packing
domains, so injecting any backing service there closes a real cycle; the
prompts registrar it also served is long migrated);
`todo.bridge.ts`, `share.bridge.ts`, `collab.bridge.ts` and `vacay.bridge.ts`
were deleted with their last consumers and the unused days/budget bridge
exports pruned; the controller adopted `trips.dto.ts` — all seven allow-list
entries removed).
mapsService followed (the 1429-line geo core — Google Places, Nominatim,
Overpass mirror racing, Wikimedia photos, Maps-URL resolution — folded into the
wrapper `MapsService`; the pure parser/UA/POI-category helpers moved to
`maps.helpers.ts` as plain exports (files.constants/client-ip precedent —
the DI-native TransitService's User-Agent imports from there, not a bridge), the module-scoped
POI cache / photo-fetch semaphore / frozen Overpass mirrors stayed module-scoped
on purpose (permissions-cache precedent: any out-of-container instance and the
DI singleton share them); the 3 geo tools left the mixed `mcp/tools/mapsWeather.ts`
registrar for the decorator-driven `maps.mcp.ts` (the registrar file survives —
its weather + airport tools await their own migrations); BookingImportService
injects `MapsService` for its Nominatim geocoding, and a 3-export
`maps.bridge.ts` served the legacy placeEnrichment helper and the places
registrar — both absorbed by the 2026-07 place fold, which deleted the bridge).
transitService followed (the first fully SQL-free domain fold — the 333-line
Transitous/MOTIS proxy became a dep-free `TransitService` (no
`DatabaseService`; the ExchangeRatesService precedent), its response cache,
frozen-at-import `TRANSIT_API_BASE` and lazy User-Agent memo staying
module-scoped on purpose; the pure `deriveTransitStats` + mode whitelist +
itinerary types moved to `transit.helpers.ts` (maps.helpers precedent) so the
downstream legacy `transitItineraryService` needed no bridge (since relocated
into the domain as `transit-itinerary.helpers.ts`); the whole 3-tool
`mcp/tools/transit.ts` registrar moved to `transit.mcp.ts` — the two geo
search tools on `access: { group: 'geo', mode: 'read' }` and
`create_transit_journey` on `reservations:write`, with its days/reservations
bridge imports becoming injected `DaysService`/`ReservationsService` (+
`DatabaseService` for `canAccessTrip`) — leaving **zero bridge files** and the
transports registrar as `days.bridge.ts`'s last consumer).
placeService followed (the step-4 tail: the 1029-line place core — the
CRUD + ratings SQL, the GPX/KML/KMZ importers and the Google/Naver list
importers — folded into the wrapper `PlacesService`, with the pure pieces
(frozen XML parsers, the KMZ unpacker, the dedup predicates, the Google
hex-id parsers, `reclaimPhotoCache`) moving to `places.helpers.ts` on the
maps.helpers precedent; the 10-tool `mcp/tools/places.ts` registrar + the
`trek://trips/{tripId}/places` resource moved to `places.mcp.ts` —
`search_place` came along because its gate is `places:read`, not the geo
group, and now injects `MapsService`; TripsService, DaysMcp,
BookingImportService and the plugin host (its 21st constructor dep) inject
`PlacesService`, leaving **zero bridge files** for the domain; the two
`assignments.bridge` imports stay in `places.mcp.ts` on purpose —
AssignmentsModule imports DaysModule and DaysModule now imports
PlacesModule, so injecting would close a
DaysModule → PlacesModule → AssignmentsModule → DaysModule cycle
(reservations.mcp.ts uses the same seam for the same reason). The sibling
`placeEnrichment` fold went further than the recipe's minimum: the 168-line
helper's DB/websocket/Maps half became `PlacesService` methods over the
injected `DatabaseService`/`RealtimeService`/`MapsService` and its pure
match selector joined `places.helpers.ts`, which retired **`maps.bridge.ts`**
with its last consumer. The DTO ratchet for its 7 grandfathered body
contracts landed as a third commit, which also loosened
`placeBulkUpdateRequestSchema.ids` (`.min(1)` dropped) so the endpoint's
empty-list short-circuit stays reachable, and retired three bespoke 400
strings — 'Place name is required', 'ids must be an array of numbers' and
'URL is required' — in favour of the pipe envelope, accepting that a
malformed body now 400s ahead of the trip-access 404 (the todo/trips trade).
transitItineraryService followed (the first pure-helpers relocation with no
service fold at all — the 287-line module is 100% pure, so the recipe's SQL /
bridge / DTO / plugin-host steps were all no-ops: the Zod itinerary schemas +
endpoint/metadata builders moved byte-identical to
`transit-itinerary.helpers.ts`, next to `transit.helpers.ts`; the schemas
**must** stay module-level plain exports because `transit.mcp.ts` consumes
them inside `@Tool({ inputSchema })` decorators, which evaluate at module load
before any container exists; the sole consumer — the in-container
`transit.mcp.ts` — was a one-import repoint, closing step 4 of the
dependency-honest order; the legacy module had no direct suite, so a new
21-case `TRANSIT-ITIN-*` characterization suite now pins all 12 superRefine
error strings, the `??` time fallbacks, the coordinate tolerances and the
reservation endpoint/metadata builder).
collectionsService followed (the biggest single fold yet — 1024 lines / 28
exports into `CollectionsService` over DatabaseService + PermissionsService +
RealtimeService, with the `deleteOldCollectionCover` path re-anchored one
directory deeper and the `sendInvite` lazy notificationService `import()`
kept, collab precedent; the 25-tool legacy registrar `mcp/tools/collections.ts`
moved to `collections.mcp.ts` — at relocation time deliberately with NO
`when:` addon gate, since the legacy registrar registered unconditionally
while REST/plugin-host gate on the addon; the trailing `fix(server)` quirk
commit then gated all 25 tools (the addon ships disabled by default, so the
ungated surface was live on fresh installs) alongside wrapping every
multi-statement write in `db.transaction()`, making the bulk ops
all-or-nothing, and forwarding `X-Socket-Id` on the from-trip saves — each
pinned by a new 23-case `tools-collections` characterization suite plus the
`COLLECTIONS-SVC-090…092` band (the legacy registrar had no tool-level tests
at all);
the plugin host swapped its 7 collections imports for the injected service —
its 22nd constructor dep — and NO bridge was needed anywhere; the dead
`buildDedupSet` module helper was dropped in the move, the only line that
didn't relocate verbatim).
atlasService followed (1612 lines split two ways, places precedent: the DB
half — stats aggregation, visited countries/regions with the #1490
tombstone/cascade logic, bucket-list CRUD — folded into `AtlasService` over
DatabaseService alone, while the ~750-line pure-geo half — the bundled
admin0/admin1 stores and their #1576 OOM-shaped streaming builders, the
point-in-polygon indexes, Nominatim geocoding with its shared ≥1.1s throttle,
the 50k geocode cache with its import-time unref'd cleanup interval, and the
`geocodingInFlight` dedup set — moved to the plain module `atlas-geo.ts` so
those caches stay process-global across the container instance, the bridge
instance and test helpers; `assetPath` re-anchored one directory deeper, the
only non-verbatim line. The 10-tool legacy registrar `mcp/tools/atlas.ts`
plus all four atlas resources in `mcp/resources.ts` (`trek://bucket-list`,
`trek://visited-countries`, `trek://atlas/stats`, `trek://atlas/regions`)
moved to `atlas.mcp.ts` — here the `when:` atlas-addon gate IS parity, since
the legacy registrar and resources both gated on the addon while the REST
controller deliberately does not; the mark_region_visited /
get_country_atlas_places no-uppercase divergence from REST relocated
untouched. The plugin host swapped its 9 atlas imports for the injected
service — its 23rd constructor dep — and a minimal 2-export `atlas.bridge.ts`
existed solely for the legacy `authService.getTravelStats` edge
(`getCountryFromCoords` re-exported straight from atlas-geo,
`getHiddenCountries` over the bridge instance); it died with the auth fold, as
predicted. resources.test.ts retired with its last two cases — every resource
it covered now lives in the domain suites. The trailing `fix(server)` quirk
commit then wrapped the four multi-statement mark/unmark writes in
`db.transaction()` (the region cascade nests as a savepoint), made the
trip-less `countryPlaces` early return honour `manually_marked`, fixed the
`|| null` bindings that dropped `lat: 0`/`lng: 0`/`notes: ''` on bucket
update, user-scoped the mutating bucket SQL, and uppercased the MCP
region/country-places codes to match REST — each pinned by
`ATLAS-SVC-031…036` plus two MCP casing cases; see migration-graph.md's
"Quirks fixed after the atlas fold".)
authService followed (1497 lines, the biggest fold and the head of the
auth → admin → oauth chain: the pure crypto half — backup-code
hash/match/generate, `stripUserForClient`, key masking, the import-time
`DUMMY_PASSWORD_HASH` timing equaliser and the `avatarDir` mkdir (both
documented parity exceptions) — moved to the plain module `auth.helpers.ts`,
while the DB half — toggles/app-config, register/login with the CWE-208
dummy-hash path, MFA setup/enable/disable/verify, the password-reset
throttle+token flows with their two `db.transaction()` revocation blocks,
API keys/settings, travel stats, MCP/ws/resource tokens, `isDemoUser` and
the two token verifiers — folded into `AuthService` over DatabaseService +
injected PermissionsService (ex `permissions.bridge`) and AtlasService (ex
`atlas.bridge`, which died on schedule). The `mfaSetupPending` and
per-email reset-throttle maps stay module-scoped (with the unref'd cleanup
interval) so the bridge instance and the container singleton share them; the
otplib `window: 1` mutation runs at module top; `require('../../../package.json')`
and `avatarDir` re-anchored one directory deeper — the only non-verbatim
lines besides the two injection swaps. No MCP registrar existed and the
plugin host never imported authService, so neither surface changed; the 15
in-container `*.mcp.ts` demo guards now inject AuthService (their modules
import AuthModule) — except `atlas.mcp.ts`, which keeps a bridge import
because AuthService injects AtlasService and the reverse module edge would
close a cycle (places.mcp precedent). The 8-export `auth.bridge.ts` serves
`mcp/index.ts` token verification, the three legacy tool registrars'
`isDemoUser`, and the un-migrated adminService.
Tests moved with IDs preserved: authService.test.ts → auth.helpers.test.ts,
authServiceDb.test.ts → auth.service.test.ts (+ AUTH-BR-001…007 bridge
delegation); auth.e2e converted DI-native — the 30-method whole-module mock
died, login now runs real bcrypt and real audit rows; oidc.e2e switched its
dead path-mock for a `vi.spyOn(app.get(AuthService), …)` instance stub.)
oidcService followed (the frontier cash-in the auth fold predicted: a pure
fold of the 508-line module into the existing wrapper `OidcService` over
DatabaseService + injected AuthService — the `resolveAuthToggles`
`auth.bridge` import became the injection, the first repoint-consumer of that
bridge to migrate. No MCP registrar, no plugin-host import, and **no bridge
at all**: nothing outside the container consumes the domain (day-notes/
trip-invite class), so the `pendingStates`/`authCodes` maps, their two sweep
`setInterval`s, the single-slot discovery cache and the JWKS cache became
**instance state** — the module-scope precedent (permissions/atlas-geo/auth
maps) applies only where a bridge instance must share state, and none exists
here; the sweepers start in the constructor and are cleared in
`onModuleDestroy`, the one wire-invisible deviation. The `uuid`/`bcryptjs`
lazy requires, the `invite_exhausted` reference-sentinel transaction (reshaped
one line for `DatabaseService.transaction`) and every SQL string relocated
verbatim; controller and its unit suite needed zero edits. Tests moved with
IDs preserved: oidcService.test.ts → oidc.service.test.ts (OIDC-SVC-001…045,
superseding the 18-case delegation-shim suite; 046–048 carry its wrapper
cases); oidc.e2e swapped its whole-module path mock for
`vi.spyOn(app.get(OidcService), …)` instance spies; the integration suite
spies the four HTTP methods on the container instance while driving the real
state maps on that same instance.)
passkeyService followed (the last frontier member of the auth stack: the
364-line WebAuthn module folded into a new `nest/auth/passkey.service.ts`
`PasskeyService` over DatabaseService + injected AuthService — its three
`auth.bridge` imports resolved to `this.auth.generateToken` plus plain
`stripUserForClient`/`avatarUrl` helper imports, and `resolveWebauthnConfig`
stayed a plain `services/webauthnConfig` import at the time (it has since
become the injected `WebauthnConfigService`, which also feeds auth.service's
`passkey_configured`). No MCP registrar, no plugin-host
import, and **no bridge at all** — both consumers were already in-container:
`PasskeyController` swapped its `import *` shim for the injection, and
`AdminService` swapped its `adminResetPasskeys` function import for the
injected service (`AuthModule` now exports PasskeyService and `AdminModule`
imports AuthModule — the todo→TripsService in-container precedent). No
module-level mutable state existed to preserve: the challenge store is
DB-backed (`webauthn_challenges`, single-use `DELETE … RETURNING` claim,
5-min TTL), so the fold is a plain stateless injectable — every SQL string,
error string and the counter/login-bookkeeping transaction relocated
verbatim. Tests: the legacy module had **no service-level suite**, so
PASSKEY-SVC-001…030 were written fresh with the fold (characterization over a
real `:memory:` DB, `@simplewebauthn/server` mocked at the ceremony-verdict
boundary — the repo's first such mock); auth-guard.test.ts's PasskeyController
block swapped its path mock for a constructor stub.)
notificationService followed (the notifications fan-in, step 3 of the
dependency-honest order: the `send()` dispatcher **and** the
`inAppNotifications.ts` store folded together into the existing
`NotificationsService` over DatabaseService + RealtimeService — the wrapper's
in-app delegation became the real SQL, while the prefs matrix, the smtp/
webhook/ntfy transports, the channel registry and `inAppNotificationActions`
stay plain-module imports (graph-classified infra helpers, complete with
their registry⇄prefs cycle). A one-export `notifications.bridge.ts` (`send`)
covered the outside-container consumers — scheduler's two cron `require`s,
legacy adminService and memories/{unified,synology} (that bridge died
2026-08-10 with the scheduler migration; `notifications.instance.ts` carries
the surviving cycle-dodge bridges) — **and** the six
deliberately-lazy fire-and-forget `import().then(({ send }) => …)` sends in
migrated Nest services (collab/collections/packing/reservations/trips/vacay,
path-only repoints; kept lazy so a send can never block or cycle a domain
module). In-container static consumers inject instead: `AdminController`'s
dev test send (AdminModule → NotificationsModule) and the plugin host
(`NotificationsService` = `PluginHostDepsFactory`'s 24th dep). The 5-tool
legacy registrar + the `notifications-in-app` resource moved 1:1 to
`notifications.mcp.ts` (no `when:` — the domain is core, not addon-gated).
Tests moved with IDs preserved: notificationService.test.ts →
notifications.service.test.ts (NSVC-001…019/NTFY-SVCB-*/NSVC-PLUG-001…007,
plus the NSVC-020 bridge pin), inAppNotificationPrefs.test.ts →
notifications.inapp-prefs.test.ts (INOTIF-*); ~18 suites repointed their
path mocks/warm-ups to the bridge; admin.controller.test and the plugin-host
suite converted theirs to constructor stubs; the module e2e went DI-native
(real notifications DDL, prefs/transports still path-mocked).)
adminService followed (the last Wave-5 god file and the first fold where recipe
steps 2-4 were all no-ops or near-no-ops: **no `src/mcp/tools/admin.ts` has ever
existed** — the "11 MCP consumers" figure carried in `migrate.md` /
`migration-graph.md` predated the Phase-0 addons extraction, so no registrar
moved, `mcp/tools.ts` / `mcp/resources.ts` / `mcp-test-controllers.ts` were
untouched — and `plugin-host-deps.factory.ts` never imported the domain either
(its addon reads already went through the DI-native `AddonsService`). The
851-line module folded into the wrapper `AdminService` over `DatabaseService`
plus injected Settings/Addons/Passkey/Packing/Auth/Permissions/Notifications
services: the `auth.bridge` (`resolveAuthToggles`), `notifications.bridge`
(`send`) and `permissions.bridge` (`getAllPermissions`/`savePermissions`)
imports all became injections, while `PERMISSION_ACTIONS` stayed a plain const
import and the `mcp/sessionManager` deep import kept its anti-cycle comment.
The pure + module-scoped half moved to `admin.helpers.ts` — `compareVersions`,
`utcSuffix`, `BCRYPT_COST`, the import-time `isDocker` probe (a documented
parity exception, auth.helpers precedent) and the 5-minute version cache, which
stays module-scoped so the bridge instance and the container singleton share it.
Ahead of the fold the 11 packing-template functions relocated to
`PackingService`, which already owned all three template tables
(`saveAsTemplate` writes every one of them) — that also resolved the `admin-2`
residual without a bridge, since `packing.mcp.ts` already injects the service;
`AdminModule` gained PackingModule and PermissionsModule, both cycle-free.
A 1-export `admin.bridge.ts` (`checkAndNotifyVersion`) served the only
out-of-container consumer, `scheduler.ts`'s daily cron (both died 2026-08-10
with the scheduler migration — `VersionCheckJob` injects `AdminService`).
Four lines are
non-verbatim, all path re-anchoring one directory deeper for `nest/admin/`
(`rotateJwtSecret`'s data dir, the `package.json` version require, the
websocket/demo-reset lazy requires) — both resolved paths verified against the
emitted `dist/` layout. Tests moved with IDs preserved (adminService.test.ts →
`nest/admin.service.test.ts`, ADMIN-SVC-001…069 incl. the pre-existing 029/030
gap and duplicated 069, + ADMIN-BR-001 pinning the bridge and the shared version
cache; versionNotification.test.ts → `nest/admin.version-notification.test.ts`,
VNOTIF-001…007; the template cases rode along to `packing.service.test.ts`), and
the module e2e went DI-native — its 3-method whole-module mock died, 6 cases
became 15 over real SQL. A sibling DTO ratchet cleared all twenty
`AdminController` allow-list entries — the largest single block — trading the
three `'enabled must be a boolean'` checks plus `'permissions object required'`
and `'Object body required'` for the pipe envelope; the schemas are
deliberately permissive wherever the service owns a bespoke 400 of its own.)
Repeat these steps per
service (next up: **backupService** / **airtrail** —
per the dependency-honest order in
`migration-graph.md`). This is a
**pure relocation** — byte-identical
SQL, statuses, bodies, and error strings. The plugin RPC host is **no longer a
bridge consumer**: since Option A of `src/nest/plugins/DI-MIGRATION.md` it
injects domain services via `PluginHostDepsFactory`, so a migrated domain adds
`exports: [XService]` + a `PluginsModule` import instead of a bridge entry.
Only the pre-`app.init()` MCP/OAuth mount still needs bridges — the module-
cycle seams are folded, nothing on the websocket path imports one, and the
crons all inject now (`*.job.ts` providers on `scheduling/CronRegistrarService`).
1. **Move the SQL** into `<domain>.service.ts` as methods over an injected
`DatabaseService` (`this.db.all<T>/get<T>/run/prepare/transaction`; strict
constructor injection, no `@Optional()`). Preserve every quirk: falsy-coercion
defaults (`x || fallback`, never `??`), post-insert/post-update re-selects (no
RETURNING), `COALESCE` semantics. If a controller already wraps the legacy
functions, do not change the service's method surface. The module needs no
`imports: [DatabaseModule]` — it's `@Global`.
2. **Add `<domain>.bridge.ts`** next to the service **only if non-Nest consumers
exist** (legacy MCP tool registrars, websocket — the plugin RPC host and the
crons now inject instead, see above). It builds a module-level instance over
the shared connection Proxy — `new XService(new DatabaseService(db))`,
reinitialize-proof, same pattern as `nest/todo/todo.bridge.ts` — and exports
the legacy function names 1:1.
Container code injects the service; only outside-container code imports the
bridge. When porting an MCP registrar, note the `access: { group, mode }`
markers are typed against the scope-derived `ScopeGroup` union and
boot-validated by `trekMcpValidateAccess` (`src/mcp/nest-mcp-policy.ts`) —
an unknown group, or `mode: 'write'` on a read-only group (`geo`,
`weather`), fails app boot. **`mode` is typed the same way**: it is the mode
half of `Scope` (`read | write | delete | share`), fed into
`src/nest-mcp/types.ts` through `McpAccessModeRegistry` exactly like the
group registry. A scope that is neither read nor write — `journey:share` is the
one today — gets a real marker, *not* a `(ctx) => canX(ctx.scopes)`
predicate: predicates bypass the policy entirely and are invisible to the
boot gate, so a scope typo in one would ship as a silent full-access tool.
Reach for a predicate only when the gate genuinely is not a scope. *(Design decision, settled with the tags pilot:
MCP tools stay outside the container and use the bridge. The alternative — handing the Nest app to the
MCP layer via `app.get(XService)` — was rejected: it would thread the container
through `mcpHandler` + every tool registrar and force a Nest bootstrap into the
container-less `tests/helpers/mcp-harness.ts` used by ~25 MCP suites.)*
3. **Repoint non-Nest consumers** — import-path-only diffs from
`services/<x>Service` to `nest/<domain>/<domain>.bridge`; call sites unchanged.
4. **Delete the legacy service** once `grep -rn "services/<x>Service" src tests`
only hits the tests you're rewriting.
5. **Tests:**
- Move `tests/unit/services/<x>Service.test.ts` →
`tests/unit/nest/<domain>.service.test.ts`, preserving case IDs. Construct the
service directly — `new XService(new DatabaseService(testDb))` — no
TestingModule, no `overrideProvider` (repo convention). Add one delegation
case per bridge export: the bridge sits under `src/nest/**`, inside the ≥80%
coverage gate, and these cases pin it deterministically.
- Convert the module e2e to the DI-native pattern (exemplar
`tests/e2e/trips.e2e.test.ts`): temp-db DDL for the domain's tables,
`imports: [DatabaseModule, <Domain>Module]`, real SQL assertions. Keep only
the `vi.mock('../../src/db/database', …)` — the auth guard still reads users
through the singleton, and `DatabaseModule`'s factory picks up the same
mocked db. Drop the legacy-service mock entirely.
- Suites that mocked the legacy module mock the bridge path instead — same
factory shape, path-only change. (For the plugin host suite,
`plugin-host-deps.factory.test.ts`, the domain becomes a constructor stub
instead of a path mock.)
6. **Verify** (from `server/`): `npm run typecheck`, `test:unit`,
`test:integration`, `test:e2e`, `lint:check`, `test:coverage`.
@@ -12,8 +12,10 @@ import {
} from '@nestjs/common';
import type { User } from '../../types';
import { AccommodationsService } from './accommodations.service';
import { AccommodationCreateDto, AccommodationUpdateDto } from './accommodations.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';
type AccommodationBody = {
place_id?: number;
@@ -37,39 +39,29 @@ type AccommodationBody = {
* reservation/budget deletions) with the forwarded X-Socket-Id.
*/
@Controller('api/trips/:tripId/accommodations')
@UseGuards(JwtAuthGuard)
// TripAccessGuard resolves :tripId and 404s a trip the user cannot reach; mutations
// add @RequirePermission('day_edit'), the same action string the service's canEdit
// passes, so the HTTP and MCP paths cannot demand different rights.
@UseGuards(JwtAuthGuard, TripAccessGuard)
export class AccommodationsController {
constructor(private readonly accommodations: AccommodationsService) {}
private requireTrip(tripId: string, user: User) {
const trip = this.accommodations.verifyTripAccess(tripId, user.id);
if (!trip) {
throw new HttpException({ error: 'Trip not found' }, 404);
}
return trip;
}
private requireEdit(trip: NonNullable<ReturnType<AccommodationsService['verifyTripAccess']>>, user: User): void {
if (!this.accommodations.canEdit(trip, user)) {
throw new HttpException({ error: 'No permission' }, 403);
}
}
@Get()
list(@CurrentUser() user: User, @Param('tripId') tripId: string) {
this.requireTrip(tripId, user);
return { accommodations: this.accommodations.list(tripId) };
}
@RequirePermission('day_edit')
@Post()
create(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Body() body: AccommodationBody,
@Body() rawBody: AccommodationCreateDto,
@Headers('x-socket-id') socketId?: string,
) {
const trip = this.requireTrip(tripId, user);
this.requireEdit(trip, user);
const body = rawBody as AccommodationBody;
const { place_id, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, notes } = body;
if (!place_id || !start_day_id || !end_day_id) {
throw new HttpException({ error: 'place_id, start_day_id, and end_day_id are required' }, 400);
@@ -84,16 +76,16 @@ export class AccommodationsController {
return { accommodation };
}
@RequirePermission('day_edit')
@Put(':id')
update(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Param('id') id: string,
@Body() body: AccommodationBody,
@Body() rawBody: AccommodationUpdateDto,
@Headers('x-socket-id') socketId?: string,
) {
const trip = this.requireTrip(tripId, user);
this.requireEdit(trip, user);
const body = rawBody as AccommodationBody;
const existing = this.accommodations.get(id, tripId);
if (!existing) {
throw new HttpException({ error: 'Accommodation not found' }, 404);
@@ -108,6 +100,7 @@ export class AccommodationsController {
return { accommodation };
}
@RequirePermission('day_edit')
@Delete(':id')
remove(
@CurrentUser() user: User,
@@ -115,17 +108,15 @@ export class AccommodationsController {
@Param('id') id: string,
@Headers('x-socket-id') socketId?: string,
) {
const trip = this.requireTrip(tripId, user);
this.requireEdit(trip, user);
if (!this.accommodations.get(id, tripId)) {
throw new HttpException({ error: 'Accommodation not found' }, 404);
}
const { linkedReservationId, deletedBudgetItemId } = this.accommodations.remove(id);
if (linkedReservationId) {
this.accommodations.broadcast(tripId, 'reservation:deleted', { reservationId: linkedReservationId }, socketId);
const { linkedReservationIds, deletedBudgetItemIds } = this.accommodations.remove(id);
for (const reservationId of linkedReservationIds) {
this.accommodations.broadcast(tripId, 'reservation:deleted', { reservationId }, socketId);
}
if (deletedBudgetItemId) {
this.accommodations.broadcast(tripId, 'budget:deleted', { itemId: deletedBudgetItemId }, socketId);
for (const itemId of deletedBudgetItemIds) {
this.accommodations.broadcast(tripId, 'budget:deleted', { itemId }, socketId);
}
this.accommodations.broadcast(tripId, 'accommodation:deleted', { accommodationId: Number(id) }, socketId);
return { success: true };
@@ -0,0 +1,5 @@
import { createZodDto } from 'nestjs-zod';
import { accommodationCreateBodySchema, accommodationUpdateRequestSchema } from '@trek/shared';
export class AccommodationCreateDto extends createZodDto(accommodationCreateBodySchema) {}
export class AccommodationUpdateDto extends createZodDto(accommodationUpdateRequestSchema) {}
@@ -0,0 +1,216 @@
import {
McpController, Tool, ResourceTemplate, type McpContext,
TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
demoDenied, ok,
} from '../../nest-mcp';
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
import { z } from 'zod';
import { AuthService } from '../auth/auth.service';
import { PlacesService } from '../places/places.service';
import { noAccess, permissionDenied } from '../../mcp/tools/_shared';
import { DatabaseService } from '../database/database.service';
import { AccommodationsService } from './accommodations.service';
function parseId(value: string | string[]): number | null {
const n = Number(Array.isArray(value) ? value[0] : value);
return Number.isInteger(n) && n > 0 ? n : null;
}
/**
* Accommodation MCP surface. The four tools and the
* trek://trips/{tripId}/accommodations resource moved here verbatim from
* DaysMcp when accommodations became their own domain; names, descriptions,
* schemas, annotations, error shapes and broadcasts are unchanged.
*
* It keeps DatabaseService and PlacesService because create_place_accommodation
* creates the place and the stay in one transaction. That is also what let
* DaysMcp drop both of them, and DaysModule its PlacesModule import.
*/
@McpController()
export class AccommodationsMcp {
constructor(
private readonly accommodations: AccommodationsService,
private readonly db: DatabaseService,
private readonly places: PlacesService,
private readonly auth: AuthService,
private readonly guards: McpToolGuardsService,
) {}
@Tool({
name: 'create_accommodation',
description: 'Add an accommodation (hotel, Airbnb, etc.) to a trip, linked to a place and a date range.',
inputSchema: {
tripId: z.number().int().positive(),
place_id: z.number().int().positive().describe('The place to use as the accommodation'),
start_day_id: z.number().int().positive().describe('Check-in day ID'),
end_day_id: z.number().int().positive().describe('Check-out day ID'),
check_in: z.string().max(10).optional().describe('Check-in time e.g. "15:00"'),
check_in_end: z.string().max(10).optional().describe('Check-in window end time e.g. "20:00"'),
check_out: z.string().max(10).optional().describe('Check-out time e.g. "11:00"'),
confirmation: z.string().max(100).optional(),
notes: z.string().max(1000).optional(),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
access: { group: 'trips', mode: 'write' },
})
async createAccommodation(
{ tripId, place_id, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, notes }: {
tripId: number; place_id: number; start_day_id: number; end_day_id: number;
check_in?: string; check_in_end?: string; check_out?: string; confirmation?: string; notes?: string;
},
ctx: McpContext,
) {
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.accommodations.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!this.guards.hasTripPermission('day_edit', tripId, ctx.userId)) return permissionDenied();
const errors = this.accommodations.validateAccommodationRefs(tripId, place_id, start_day_id, end_day_id);
if (errors.length > 0) return { content: [{ type: 'text' as const, text: errors.map(e => e.message).join(', ') }], isError: true };
const accommodation = this.accommodations.createAccommodation(tripId, { place_id, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, notes });
this.guards.safeBroadcast(tripId, 'accommodation:created', { accommodation });
return ok({ accommodation });
}
@Tool({
name: 'create_place_accommodation',
description: 'Create a new place and immediately set it as an accommodation for a date range in one atomic operation. Use place details from search_place results. Only use when the place does not yet exist — if it already exists, use create_accommodation directly. Set price + currency to record the accommodation cost so it shows on the item.',
inputSchema: {
tripId: z.number().int().positive(),
name: z.string().min(1).max(200),
description: z.string().max(2000).optional(),
lat: z.number().optional(),
lng: z.number().optional(),
address: z.string().max(500).optional(),
category_id: z.number().int().positive().optional().describe('Category ID — use list_categories to see available options'),
google_place_id: z.string().optional().describe('Google Place ID from search_place — enables opening hours display'),
google_ftid: z.string().optional().describe('Google Maps feature ID from search_place — enables direct Google Maps links'),
osm_id: z.string().optional().describe('OpenStreetMap ID from search_place (e.g. "way:12345")'),
place_notes: z.string().max(2000).optional().describe('Notes for the place'),
website: z.string().max(500).optional(),
phone: z.string().max(50).optional(),
start_day_id: z.number().int().positive().describe('Check-in day ID'),
end_day_id: z.number().int().positive().describe('Check-out day ID'),
check_in: z.string().max(10).optional().describe('Check-in time e.g. "15:00"'),
check_in_end: z.string().max(10).optional().describe('Check-in window end time e.g. "20:00"'),
check_out: z.string().max(10).optional().describe('Check-out time e.g. "11:00"'),
confirmation: z.string().max(100).optional(),
accommodation_notes: z.string().max(1000).optional().describe('Notes for the accommodation'),
price: z.number().nonnegative().optional().describe('Total accommodation cost (shown on the item)'),
currency: z.string().length(3).optional().describe('ISO 4217 currency code (e.g. "EUR", "USD")'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
access: { group: 'trips', mode: 'write' },
})
async createPlaceAccommodation(
{ tripId, name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, place_notes, website, phone, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, accommodation_notes, price, currency }: {
tripId: number; name: string; description?: string; lat?: number; lng?: number; address?: string;
category_id?: number; google_place_id?: string; google_ftid?: string; osm_id?: string;
place_notes?: string; website?: string; phone?: string; start_day_id: number; end_day_id: number;
check_in?: string; check_in_end?: string; check_out?: string; confirmation?: string;
accommodation_notes?: string; price?: number; currency?: string;
},
ctx: McpContext,
) {
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.accommodations.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!this.guards.hasTripPermission('day_edit', tripId, ctx.userId)) return permissionDenied();
const dayErrors = this.accommodations.validateAccommodationRefs(tripId, undefined, start_day_id, end_day_id);
if (dayErrors.length > 0) return { content: [{ type: 'text' as const, text: dayErrors.map(e => e.message).join(', ') }], isError: true };
try {
const result = this.db.transaction(() => {
const place = this.places.create(String(tripId), { name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, notes: place_notes, website, phone, price, currency });
const accommodation = this.accommodations.createAccommodation(tripId, { place_id: place.id, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, notes: accommodation_notes });
return { place, accommodation };
});
this.guards.safeBroadcast(tripId, 'place:created', { place: result.place });
this.guards.safeBroadcast(tripId, 'accommodation:created', { accommodation: result.accommodation });
return ok(result);
} catch {
return { content: [{ type: 'text' as const, text: 'Failed to create place and accommodation.' }], isError: true };
}
}
@Tool({
name: 'update_accommodation',
description: 'Update fields on an existing accommodation.',
inputSchema: {
tripId: z.number().int().positive(),
accommodationId: z.number().int().positive(),
place_id: z.number().int().positive().optional(),
start_day_id: z.number().int().positive().optional(),
end_day_id: z.number().int().positive().optional(),
check_in: z.string().max(10).optional(),
check_in_end: z.string().max(10).optional().describe('Check-in window end time e.g. "20:00"'),
check_out: z.string().max(10).optional(),
confirmation: z.string().max(100).optional(),
notes: z.string().max(1000).optional(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
access: { group: 'trips', mode: 'write' },
})
async updateAccommodation(
{ tripId, accommodationId, place_id, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, notes }: {
tripId: number; accommodationId: number; place_id?: number; start_day_id?: number; end_day_id?: number;
check_in?: string; check_in_end?: string; check_out?: string; confirmation?: string; notes?: string;
},
ctx: McpContext,
) {
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.accommodations.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!this.guards.hasTripPermission('day_edit', tripId, ctx.userId)) return permissionDenied();
const existing = this.accommodations.getAccommodation(accommodationId, tripId);
if (!existing) return { content: [{ type: 'text' as const, text: 'Accommodation not found.' }], isError: true };
const accommodation = this.accommodations.updateAccommodation(accommodationId, existing, { place_id, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, notes });
this.guards.safeBroadcast(tripId, 'accommodation:updated', { accommodation });
return ok({ accommodation });
}
@Tool({
name: 'delete_accommodation',
description: 'Delete an accommodation from a trip.',
inputSchema: {
tripId: z.number().int().positive(),
accommodationId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
access: { group: 'trips', mode: 'write' },
})
async deleteAccommodation({ tripId, accommodationId }: { tripId: number; accommodationId: number }, ctx: McpContext) {
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.accommodations.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!this.guards.hasTripPermission('day_edit', tripId, ctx.userId)) return permissionDenied();
if (!this.accommodations.getAccommodation(accommodationId, tripId)) return { content: [{ type: 'text' as const, text: 'Accommodation not found.' }], isError: true };
// linkedReservationId stays the first one so the tool's answer keeps its shape;
// linkedReservationIds carries the rest for a block that had more than one booking.
const { linkedReservationId, linkedReservationIds } = this.accommodations.deleteAccommodation(accommodationId);
this.guards.safeBroadcast(tripId, 'accommodation:deleted', { id: accommodationId, linkedReservationId, linkedReservationIds });
return ok({ success: true, linkedReservationId, linkedReservationIds });
}
@ResourceTemplate({
name: 'trip-accommodations',
uriTemplate: 'trek://trips/{tripId}/accommodations',
description: 'Accommodations (hotels, rentals) for a trip with check-in/out details',
mimeType: 'application/json',
access: { group: 'trips', mode: 'read' },
})
async tripAccommodationsResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) {
const id = parseId(tripId);
if (id === null || !this.accommodations.verifyTripAccess(id, ctx.userId)) {
return {
contents: [{
uri: uri.href,
mimeType: 'application/json',
text: JSON.stringify({ error: 'Trip not found or access denied' }),
}],
};
}
const accommodations = this.accommodations.listAccommodations(id);
return {
contents: [{
uri: uri.href,
mimeType: 'application/json',
text: JSON.stringify(accommodations, null, 2),
}],
};
}
}
@@ -0,0 +1,30 @@
import { Module } from '@nestjs/common';
import { AccommodationsController } from './accommodations.controller';
import { AccommodationsService } from './accommodations.service';
import { AccommodationsRpc } from './accommodations.rpc';
import { AccommodationsMcp } from './accommodations.mcp';
import { PlacesModule } from '../places/places.module';
import { AuthModule } from '../auth/auth.module';
import { DatabaseModule } from '../database/database.module';
import { PermissionsModule } from '../permissions/permissions.module';
import { RealtimeModule } from '../realtime/realtime.module';
import { PluginGuardsModule } from '../plugins/host/plugin-guards.module';
import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
/**
* Accommodations. One fachlichkeit, one module: the routes used to sit in
* reservations/ while the SQL sat on DaysService, so neither module owned the
* thing outright and every call crossed a domain boundary to reach its own data.
*
* It imports neither days nor reservations. The stay rows reference days by id,
* which is a foreign key, not a module edge. PlacesModule is here only because
* create_place_accommodation writes a place and a stay in one transaction --
* the same reason DaysMcp could drop it.
*/
@Module({
imports: [McpSharedModule, PermissionsModule, RealtimeModule, PluginGuardsModule, DatabaseModule, PlacesModule, AuthModule],
controllers: [AccommodationsController],
providers: [AccommodationsService, AccommodationsRpc, AccommodationsMcp],
exports: [AccommodationsService],
})
export class AccommodationsModule {}
@@ -0,0 +1,108 @@
import { accommodationCreateRequestSchema, accommodationUpdateRequestSchema } from '@trek/shared';
import { PluginController, PluginMethod } from '../plugins/host/rpc-kit/decorators';
import { PluginGuards } from '../plugins/host/plugin-guards.service';
import { BadParams, ForbiddenResource } from '../plugins/host/rpc-errors';
import { num, schemaMessage } from '../plugins/host/rpc-params';
import type { PluginRpcContext } from '../plugins/host/rpc-kit/types';
import { RealtimeService } from '../realtime/realtime.service';
import { AccommodationsService } from './accommodations.service';
/**
* Accommodations hold db:write:accommodations but are gated on 'day_edit', NOT on
* reservation_edit. The blocks live in the accommodation service and the REST path guards them
* the same way; the decorator makes the mismatch visible instead of burying it.
*/
const ACCOMMODATION_EDIT_ACTION = 'day_edit';
type AccommodationInput = {
place_id?: number | string;
start_day_id?: number | string;
end_day_id?: number | string;
check_in?: string | null;
check_in_end?: string | null;
check_out?: string | null;
confirmation?: string | null;
notes?: string | null;
};
/**
* The lodging-block surface a plugin may reach (#plugins).
*
* Everything delegates to AccommodationsService, so the auto-created partner hotel reservation,
* the metadata sync on update and the delete cascade behave exactly like the
* accommodations REST controller, cascade broadcasts included.
*/
@PluginController()
export class AccommodationsRpc {
constructor(
private readonly days: AccommodationsService,
private readonly realtime: RealtimeService,
private readonly guards: PluginGuards,
) {}
@PluginMethod('accommodations.create', { permission: 'db:write:accommodations' })
create(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
const tripId = num(params.tripId, 'tripId');
const actor = this.guards.requireActor(ctx, 'accommodation');
const parsed = accommodationCreateRequestSchema.safeParse(params.input);
if (!parsed.success) throw new BadParams(`invalid accommodation: ${schemaMessage(parsed.error)}`);
this.guards.requireTripEdit(tripId, actor, ACCOMMODATION_EDIT_ACTION);
const input = parsed.data as AccommodationInput;
const placeId = Math.trunc(Number(input.place_id));
const startDayId = Math.trunc(Number(input.start_day_id));
const endDayId = Math.trunc(Number(input.end_day_id));
if (!placeId || !startDayId || !endDayId) throw new BadParams('place_id, start_day_id, and end_day_id are required');
// Verifies the place and both days belong to this trip.
const errors = this.days.validateAccommodationRefs(tripId, placeId, startDayId, endDayId);
if (errors.length > 0) throw new ForbiddenResource(errors[0].message);
const accommodation = this.days.createAccommodation(tripId, {
place_id: placeId,
start_day_id: startDayId,
end_day_id: endDayId,
check_in: input.check_in ?? undefined,
check_in_end: input.check_in_end ?? undefined,
check_out: input.check_out ?? undefined,
confirmation: input.confirmation ?? undefined,
notes: input.notes ?? undefined,
});
this.realtime.broadcast(tripId, 'accommodation:created', { accommodation });
// The block creates a partner hotel reservation, so the bookings view refreshes too.
this.realtime.broadcast(tripId, 'reservation:created', {});
return accommodation;
}
@PluginMethod('accommodations.update', { permission: 'db:write:accommodations' })
update(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
const tripId = num(params.tripId, 'tripId');
const accommodationId = num(params.accommodationId, 'accommodationId');
const actor = this.guards.requireActor(ctx, 'accommodation');
const parsed = accommodationUpdateRequestSchema.safeParse(params.input);
if (!parsed.success) throw new BadParams(`invalid accommodation: ${schemaMessage(parsed.error)}`);
this.guards.requireTripEdit(tripId, actor, ACCOMMODATION_EDIT_ACTION);
const existing = this.days.getAccommodation(accommodationId, tripId);
if (!existing) throw new ForbiddenResource(`no accommodation ${accommodationId} on trip ${tripId}`);
const input = parsed.data as { place_id?: number; start_day_id?: number; end_day_id?: number; check_in?: string; check_in_end?: string; check_out?: string; confirmation?: string; notes?: string };
const errors = this.days.validateAccommodationRefs(tripId, input.place_id, input.start_day_id, input.end_day_id);
if (errors.length > 0) throw new ForbiddenResource(errors[0].message);
const accommodation = this.days.updateAccommodation(accommodationId, existing, input);
this.realtime.broadcast(tripId, 'accommodation:updated', { accommodation });
return accommodation;
}
@PluginMethod('accommodations.delete', { permission: 'db:write:accommodations' })
delete(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
const tripId = num(params.tripId, 'tripId');
const accommodationId = num(params.accommodationId, 'accommodationId');
const actor = this.guards.requireActor(ctx, 'accommodation');
this.guards.requireTripEdit(tripId, actor, ACCOMMODATION_EDIT_ACTION);
if (!this.days.getAccommodation(accommodationId, tripId)) {
throw new ForbiddenResource(`no accommodation ${accommodationId} on trip ${tripId}`);
}
// Deleting a block can take its partner reservation and budget item with it.
const { linkedReservationIds, deletedBudgetItemIds } = this.days.deleteAccommodation(accommodationId);
for (const reservationId of linkedReservationIds) this.realtime.broadcast(tripId, 'reservation:deleted', { reservationId });
for (const itemId of deletedBudgetItemIds) this.realtime.broadcast(tripId, 'budget:deleted', { itemId });
this.realtime.broadcast(tripId, 'accommodation:deleted', { accommodationId });
return { deleted: true };
}
}
@@ -0,0 +1,256 @@
import { Injectable } from '@nestjs/common';
import type { TrekWsPayload, TrekWsTripEventName } from '@trek/shared';
import { RealtimeService } from '../realtime/realtime.service';
import { DatabaseService, type TripAccess } from '../database/database.service';
import { PermissionsService } from '../permissions/permissions.service';
import type { User } from '../../types';
type Trip = TripAccess;
export interface DayAccommodation {
id: number;
trip_id: number;
place_id: number | null;
start_day_id: number;
end_day_id: number;
check_in: string | null;
check_in_end: string | null;
check_out: string | null;
confirmation: string | null;
notes: string | null;
}
export interface CreateAccommodationData {
place_id: number;
start_day_id: number;
end_day_id: number;
check_in?: string;
check_in_end?: string;
check_out?: string;
confirmation?: string;
notes?: string;
}
/**
* Accommodations: the stay rows in day_accommodations plus the hotel reservation
* and budget item that hang off them.
*
* The SQL used to live on DaysService while this class owned the routes and
* delegated every call into it — one fachlichkeit split across two modules.
* The statements moved here unchanged. What deliberately stayed in days/ is the
* reorder side: assertNoInvertedAccommodation and resyncAccommodationDays are
* about re-dating day rows, and the accommodation is the thing being carried,
* not the thing doing the carrying.
*
* Still gated by 'day_edit', the same permission as days.
*/
@Injectable()
export class AccommodationsService {
constructor(
private readonly dbs: DatabaseService,
private readonly permissions: PermissionsService,
private readonly realtime: RealtimeService,
) {}
private get db() {
return this.dbs;
}
/** Owner or member, returning the trip. Takes a number too: the MCP tools pass
* the parsed id, the REST path the raw param. */
verifyTripAccess(tripId: string | number, userId: number) {
return this.dbs.canAccessTrip(Number(tripId), userId);
}
canEdit(trip: Trip, user: User): boolean {
return this.permissions.checkPermission('day_edit', user.role, trip.user_id, user.id, trip.user_id !== user.id);
}
broadcast<E extends TrekWsTripEventName>(tripId: string, event: E, payload: TrekWsPayload<E>, socketId: string | undefined): void {
this.realtime.broadcast(tripId, event, payload, socketId);
}
// -------------------------------------------------------------------------
// The route-facing names the controller has always used.
// -------------------------------------------------------------------------
list(tripId: string | number) {
return this.listAccommodations(tripId);
}
validateRefs(tripId: string | number, placeId?: number, startDayId?: number, endDayId?: number) {
return this.validateAccommodationRefs(tripId, placeId, startDayId, endDayId);
}
get(id: string | number, tripId: string | number) {
return this.getAccommodation(id, tripId);
}
create(tripId: string | number, data: CreateAccommodationData) {
return this.createAccommodation(tripId, data);
}
update(id: string | number, existing: DayAccommodation, fields: Parameters<AccommodationsService['updateAccommodation']>[2]) {
return this.updateAccommodation(id, existing, fields);
}
remove(id: string | number) {
return this.deleteAccommodation(id);
}
// -------------------------------------------------------------------------
// Accommodation CRUD
// -------------------------------------------------------------------------
private getAccommodationWithPlace(id: number | bigint) {
return this.db.get(`
SELECT a.*, p.name as place_name, p.address as place_address, p.image_url as place_image, p.lat as place_lat, p.lng as place_lng
FROM day_accommodations a
LEFT JOIN places p ON a.place_id = p.id
WHERE a.id = ?
`, id);
}
listAccommodations(tripId: string | number) {
return this.db.all(`
SELECT a.*, p.name as place_name, p.address as place_address, p.image_url as place_image, p.lat as place_lat, p.lng as place_lng,
r.title as reservation_title
FROM day_accommodations a
LEFT JOIN places p ON a.place_id = p.id
LEFT JOIN reservations r ON r.accommodation_id = a.id
WHERE a.trip_id = ?
ORDER BY a.created_at ASC
`, tripId);
}
validateAccommodationRefs(tripId: string | number, placeId?: number, startDayId?: number, endDayId?: number) {
const errors: { field: string; message: string }[] = [];
if (placeId !== undefined) {
const place = this.db.get('SELECT id FROM places WHERE id = ? AND trip_id = ?', placeId, tripId);
if (!place) errors.push({ field: 'place_id', message: 'Place not found' });
}
if (startDayId !== undefined) {
const startDay = this.db.get('SELECT id FROM days WHERE id = ? AND trip_id = ?', startDayId, tripId);
if (!startDay) errors.push({ field: 'start_day_id', message: 'Start day not found' });
}
if (endDayId !== undefined) {
const endDay = this.db.get('SELECT id FROM days WHERE id = ? AND trip_id = ?', endDayId, tripId);
if (!endDay) errors.push({ field: 'end_day_id', message: 'End day not found' });
}
return errors;
}
createAccommodation(tripId: string | number, data: CreateAccommodationData) {
const { place_id, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, notes } = data;
// The stay and its partner hotel reservation are one logical write —
// atomic, so a failed reservation insert can't leave an orphan stay.
const accommodationId = this.db.transaction(() => {
const result = this.db.run(
'INSERT INTO day_accommodations (trip_id, place_id, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
tripId, place_id, start_day_id, end_day_id, check_in || null, check_in_end || null, check_out || null, confirmation || null, notes || null
);
const newId = result.lastInsertRowid;
// Auto-create linked reservation for this accommodation
const placeName = this.db.get<{ name: string }>('SELECT name FROM places WHERE id = ?', place_id)?.name || 'Hotel';
const startDayDate = this.db.get<{ date: string }>('SELECT date FROM days WHERE id = ?', start_day_id)?.date || null;
const meta: Record<string, string> = {};
if (check_in) meta.check_in_time = check_in;
if (check_in_end) meta.check_in_end_time = check_in_end;
if (check_out) meta.check_out_time = check_out;
this.db.run(`
INSERT INTO reservations (trip_id, day_id, title, reservation_time, location, confirmation_number, notes, status, type, accommodation_id, metadata)
VALUES (?, ?, ?, ?, ?, ?, ?, 'confirmed', 'hotel', ?, ?)
`,
tripId, start_day_id, placeName, startDayDate || null, null,
confirmation || null, notes || null, newId,
Object.keys(meta).length > 0 ? JSON.stringify(meta) : null
);
return newId;
});
return this.getAccommodationWithPlace(accommodationId);
}
getAccommodation(id: string | number, tripId: string | number) {
return this.db.get<DayAccommodation>('SELECT * FROM day_accommodations WHERE id = ? AND trip_id = ?', id, tripId);
}
updateAccommodation(id: string | number, existing: DayAccommodation, fields: {
place_id?: number; start_day_id?: number; end_day_id?: number;
check_in?: string; check_in_end?: string; check_out?: string; confirmation?: string; notes?: string;
}) {
const newPlaceId = fields.place_id !== undefined ? fields.place_id : existing.place_id;
const newStartDayId = fields.start_day_id !== undefined ? fields.start_day_id : existing.start_day_id;
const newEndDayId = fields.end_day_id !== undefined ? fields.end_day_id : existing.end_day_id;
const newCheckIn = fields.check_in !== undefined ? fields.check_in : existing.check_in;
const newCheckInEnd = fields.check_in_end !== undefined ? fields.check_in_end : existing.check_in_end;
const newCheckOut = fields.check_out !== undefined ? fields.check_out : existing.check_out;
const newConfirmation = fields.confirmation !== undefined ? fields.confirmation : existing.confirmation;
const newNotes = fields.notes !== undefined ? fields.notes : existing.notes;
this.db.run(
'UPDATE day_accommodations SET place_id = ?, start_day_id = ?, end_day_id = ?, check_in = ?, check_in_end = ?, check_out = ?, confirmation = ?, notes = ? WHERE id = ?',
newPlaceId, newStartDayId, newEndDayId, newCheckIn, newCheckInEnd, newCheckOut, newConfirmation, newNotes, id
);
// Sync check-in/out/confirmation to every linked reservation. The booking form
// lets more than one hotel booking point at the same block and there is no
// unique constraint on reservations.accommodation_id, so a single .get() would
// silently leave the others on the old times.
const linkedRes = this.db.all<{ id: number; metadata: string | null }>('SELECT id, metadata FROM reservations WHERE accommodation_id = ?', Number(id));
for (const res of linkedRes) {
const meta = res.metadata ? JSON.parse(res.metadata) : {};
if (newCheckIn) meta.check_in_time = newCheckIn;
if (newCheckInEnd) meta.check_in_end_time = newCheckInEnd;
if (newCheckOut) meta.check_out_time = newCheckOut;
this.db.run('UPDATE reservations SET metadata = ?, confirmation_number = COALESCE(?, confirmation_number) WHERE id = ?',
JSON.stringify(meta), newConfirmation || null, res.id);
}
return this.getAccommodationWithPlace(Number(id));
}
/**
* Delete accommodation and its linked reservations (and any linked budget items),
* atomically.
*
* Takes ALL linked reservations, not just the first: reservations.accommodation_id
* carries no foreign key and no unique constraint, so a second booking pointed at
* the same block used to survive the delete as a row referencing an accommodation
* that no longer exists. `linkedReservationId` / `deletedBudgetItemId` stay on the
* result as the first of each, because the RPC, MCP and REST callers read them.
*/
deleteAccommodation(id: string | number): {
linkedReservationId: number | null;
deletedBudgetItemId: number | null;
linkedReservationIds: number[];
deletedBudgetItemIds: number[];
} {
return this.db.transaction(() => {
const linkedRes = this.db.all<{ id: number }>('SELECT id FROM reservations WHERE accommodation_id = ?', Number(id));
const deletedBudgetItemIds: number[] = [];
for (const res of linkedRes) {
const linkedBudget = this.db.get<{ id: number }>('SELECT id FROM budget_items WHERE reservation_id = ?', res.id);
if (linkedBudget) {
this.db.run('DELETE FROM budget_items WHERE id = ?', linkedBudget.id);
deletedBudgetItemIds.push(linkedBudget.id);
}
this.db.run('DELETE FROM reservations WHERE id = ?', res.id);
}
this.db.run('DELETE FROM day_accommodations WHERE id = ?', id);
const linkedReservationIds = linkedRes.map(r => r.id);
return {
linkedReservationId: linkedReservationIds[0] ?? null,
deletedBudgetItemId: deletedBudgetItemIds[0] ?? null,
linkedReservationIds,
deletedBudgetItemIds,
};
});
}
}
+40
View File
@@ -0,0 +1,40 @@
import type { McpContext } from '../../nest-mcp';
import type { AddonsService } from './addons.service';
import { ADDON_IDS } from '../../addons';
/**
* The `when:` gates for addon-scoped MCP surfaces.
*
* They used to close over `addons.bridge`, which builds its own AddonsService
* outside the container. That was never a preference — a decorator's options
* object is built while the class is being defined, so the closure had no
* `this` to reach an injected service through, and nine domains hid an edge to
* the addons domain from the module graph to answer one boolean.
*
* `src/nest-mcp` now hands the gate the declaring controller instance, so the
* only thing a domain has to do is expose the service it already injects:
*
* constructor(private readonly vacay: VacayService, readonly addons: AddonsService) {}
* const vacayAddonOn = addonGate(ADDON_IDS.VACAY);
*
* `addons` is public rather than private because the gate is a module-level
* function in the same file, not a method — TypeScript's `private` is scoped to
* the class body.
*/
export interface HasAddons {
readonly addons: AddonsService;
}
/** Gate an MCP entry on an addon being enabled. */
export function addonGate(addonId: string) {
return (_ctx: McpContext, self: HasAddons): boolean => self.addons.isAddonEnabled(addonId);
}
/**
* Gate on one of collab's sub-feature flags. Every collab entry rides both the
* addon toggle and its own flag — notes, polls or chat.
*/
export function collabFeatureGate(feature: 'chat' | 'notes' | 'polls') {
return (_ctx: McpContext, self: HasAddons): boolean =>
self.addons.isAddonEnabled(ADDON_IDS.COLLAB) && self.addons.getCollabFeatures()[feature];
}
+33
View File
@@ -0,0 +1,33 @@
import { CanActivate, ExecutionContext, HttpException, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AddonsService } from './addons.service';
import { REQUIRE_ADDON, type RequireAddonMeta } from './require-addon.decorator';
/**
* Enforces @RequireAddon. Replaces the three hand-written addon guards
* (collections, airtrail, journey), which differed only in which addon id they
* read and which word led the 404 body.
*
* A handler-level @RequireAddon overrides the controller's, so a route group
* can carry one addon and a single endpoint another. Without the decorator the
* guard is a no-op — it never gates a route that did not ask for it.
*/
@Injectable()
export class AddonGuard implements CanActivate {
constructor(
private readonly addons: AddonsService,
private readonly reflector: Reflector,
) {}
canActivate(context: ExecutionContext): boolean {
const meta = this.reflector.getAllAndOverride<RequireAddonMeta | undefined>(REQUIRE_ADDON, [
context.getHandler(),
context.getClass(),
]);
if (!meta) return true;
if (!this.addons.isAddonEnabled(meta.addonId)) {
throw new HttpException({ error: `${meta.label} addon is not enabled` }, 404);
}
return true;
}
}
+9 -1
View File
@@ -1,14 +1,22 @@
import { Module } from '@nestjs/common';
import { AddonsController } from './addons.controller';
import { AddonsService } from './addons.service';
import { AddonGuard } from './addon.guard';
/**
* GET /api/addons — enabled add-ons + photo providers (was an inline handler in
* server/src/app.ts). The addon sub-features (atlas, vacay) keep their own
* modules; this only serves the EXACT /api/addons listing.
*
* Exports AddonsService — the owner of addon/feature-flag enablement reads
* (isAddonEnabled + bag-tracking/collab-features flags, extracted from
* adminService per finding `admin-1`) — for the in-container consumers.
* Deliberately NOT @Global (permissions precedent): e2e TestingModules resolve
* it transitively through each consumer's explicit import.
*/
@Module({
controllers: [AddonsController],
providers: [AddonsService],
providers: [AddonsService, AddonGuard],
exports: [AddonsService, AddonGuard],
})
export class AddonsModule {}
+124 -8
View File
@@ -1,22 +1,91 @@
import { Injectable } from '@nestjs/common';
import { db } from '../../db/database';
import { DatabaseService } from '../database/database.service';
import type { Addon } from '../../types';
import { getBagTracking, getCollabFeatures } from '../../services/adminService';
import { getPhotoProviderConfig } from '../../services/memories/helpersService';
import { getPhotoProviderConfig } from '../memories/memories.helpers';
/**
* Thin wrapper around the enabled-addons + photo-provider read that the legacy
* inline `GET /api/addons` handler performed (server/src/app.ts). The SQL,
* ordering, boolean coercions and the merged photo-provider entries are
* reproduced 1:1 so the body is byte-identical for the client.
*
* Also the single owner of addon/feature-flag enablement state (moved verbatim
* from services/adminService.ts, finding `admin-1`): isAddonEnabled plus the
* bag-tracking and collab-features flags. The boolean polarities differ on
* purpose — bag tracking is opt-in (`=== 'true'`, default OFF), the collab
* sub-features are opt-out (`!== 'false'`, default ON). Reads are uncached
* per-call queries so admin toggles stay immediately visible.
*/
@Injectable()
export class AddonsService {
constructor(private readonly dbs: DatabaseService) {}
private get db() {
return this.dbs.connection;
}
isAddonEnabled(addonId: string): boolean {
const addon = this.db.prepare('SELECT enabled FROM addons WHERE id = ?').get(addonId) as
| { enabled: number }
| undefined;
return !!addon?.enabled;
}
getBagTracking() {
const row = this.db.prepare("SELECT value FROM app_settings WHERE key = 'bag_tracking_enabled'").get() as
| { value: string }
| undefined;
return { enabled: row?.value === 'true' };
}
updateBagTracking(enabled: boolean) {
this.db.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('bag_tracking_enabled', ?)").run(
enabled ? 'true' : 'false',
);
return { enabled: !!enabled };
}
getCollabFeatures() {
const rows = this.db
.prepare(
"SELECT key, value FROM app_settings WHERE key IN ('collab_chat_enabled', 'collab_notes_enabled', 'collab_polls_enabled', 'collab_whatsnext_enabled')",
)
.all() as { key: string; value: string }[];
const map: Record<string, string> = {};
for (const r of rows) map[r.key] = r.value;
return {
chat: map['collab_chat_enabled'] !== 'false',
notes: map['collab_notes_enabled'] !== 'false',
polls: map['collab_polls_enabled'] !== 'false',
whatsnext: map['collab_whatsnext_enabled'] !== 'false',
};
}
updateCollabFeatures(features: { chat?: boolean; notes?: boolean; polls?: boolean; whatsnext?: boolean }) {
const mapping: Record<string, string> = {
chat: 'collab_chat_enabled',
notes: 'collab_notes_enabled',
polls: 'collab_polls_enabled',
whatsnext: 'collab_whatsnext_enabled',
};
const before = this.getCollabFeatures();
const stmt = this.db.prepare('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)');
for (const [feat, key] of Object.entries(mapping)) {
if (features[feat] !== undefined) stmt.run(key, features[feat] ? 'true' : 'false');
}
const after = this.getCollabFeatures();
// Collab flags gate MCP tool/resource registration, so callers must know
// whether anything actually flipped — a no-op save must not tear down every
// live MCP session (#1414).
const changed = (Object.keys(after) as Array<keyof typeof after>).some((k) => after[k] !== before[k]);
return { features: after, changed };
}
list() {
const addons = db
const addons = this.db
.prepare('SELECT id, name, type, icon, enabled FROM addons WHERE enabled = 1 ORDER BY sort_order')
.all() as Pick<Addon, 'id' | 'name' | 'type' | 'icon' | 'enabled'>[];
const providers = db
const providers = this.db
.prepare(
`SELECT id, name, icon, enabled, sort_order
FROM photo_providers
@@ -24,7 +93,7 @@ export class AddonsService {
ORDER BY sort_order, id`,
)
.all() as Array<{ id: string; name: string; icon: string; enabled: number; sort_order: number }>;
const fields = db
const fields = this.db
.prepare(
`SELECT provider_id, field_key, label, input_type, placeholder, hint, required, secret, settings_key, payload_key, sort_order
FROM photo_provider_fields
@@ -52,8 +121,8 @@ export class AddonsService {
}
return {
collabFeatures: getCollabFeatures(),
bagTracking: getBagTracking().enabled,
collabFeatures: this.getCollabFeatures(),
bagTracking: this.getBagTracking().enabled,
addons: [
...addons.map((a) => ({ ...a, enabled: !!a.enabled })),
...providers.map((p) => ({
@@ -79,4 +148,51 @@ export class AddonsService {
],
};
}
// ── Places provider flags ──────────────────────────────────────────────────
// These three sat as raw app_settings SQL on AdminService, next to the
// bag-tracking and collab flags it already delegated here. They read
// `=== 'true'` — fail-closed, matching getBagTracking(). They read
// `!== 'false'` (fail-open) before the 2026-08 quirk fix; a migration
// backfills 'true' for installs that never touched the switches, so nobody
// loses a feature on upgrade.
private readFlag(key: string) {
const row = this.db.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as { value: string } | undefined;
return { enabled: row?.value === 'true' };
}
private writeFlag(key: string, enabled: boolean) {
this.db.prepare('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)').run(key, enabled ? 'true' : 'false');
return { enabled: !!enabled };
}
getPlacesPhotos() { return this.readFlag('places_photos_enabled'); }
updatePlacesPhotos(enabled: boolean) { return this.writeFlag('places_photos_enabled', enabled); }
getPlacesAutocomplete() { return this.readFlag('places_autocomplete_enabled'); }
updatePlacesAutocomplete(enabled: boolean) { return this.writeFlag('places_autocomplete_enabled', enabled); }
getPlacesDetails() { return this.readFlag('places_details_enabled'); }
updatePlacesDetails(enabled: boolean) { return this.writeFlag('places_details_enabled', enabled); }
/**
* Enrichment reads fail-OPEN, unlike the three switches above.
*
* Those needed migration 185 to backfill 'true' precisely because they read
* `=== 'true'`: without a row, an install that had been happily using the
* feature would have lost it on upgrade. This switch is new, so there is no
* row to backfill anywhere and no migration worth writing for one boolean —
* reading it the other way round gets the same outcome for free.
*
* It has to agree with PlaceEnrichmentService.enrichDisabled(), which reads
* the same key the same way. If these two ever disagree the admin panel shows
* "off" while the feature runs, which is worse than either default.
*/
getPlacesEnrich() {
const row = this.db.prepare("SELECT value FROM app_settings WHERE key = 'places_enrich_enabled'").get() as
| { value: string }
| undefined;
return { enabled: row?.value !== 'false' };
}
updatePlacesEnrich(enabled: boolean) { return this.writeFlag('places_enrich_enabled', enabled); }
}
+19
View File
@@ -0,0 +1,19 @@
import type { RequestHandler } from 'express';
import { AddonsService } from './addons.service';
import { ADDON_IDS } from '../../addons';
/**
* Gate: 404 (empty body) when the MCP addon is disabled (M2 — prevents feature
* fingerprinting). A factory over the injected AddonsService rather than a
* middleware class: consumers build it inside their module's configure() and
* hand the bare RequestHandler to consumer.apply() ahead of the SDK routers.
*/
export function createMcpAddonGate(addons: AddonsService): RequestHandler {
return (_req, res, next) => {
if (!addons.isAddonEnabled(ADDON_IDS.MCP)) {
res.status(404).end();
return;
}
next();
};
}
@@ -0,0 +1,24 @@
import { SetMetadata } from '@nestjs/common';
export const REQUIRE_ADDON = 'trek:require-addon';
export interface RequireAddonMeta {
addonId: string;
/** Leads the 404 body: `${label} addon is not enabled`. */
label: string;
}
/**
* Gate a controller (or a single handler) on a global addon toggle. When the
* admin has the addon off, the route answers 404 as if it did not exist.
*
* Pair it with AddonGuard, and list that guard BEFORE JwtAuthGuard:
*
* @UseGuards(AddonGuard, JwtAuthGuard)
* @RequireAddon(ADDON_IDS.JOURNEY, 'Journey')
*
* The order is the contract, not a preference — a disabled addon has to answer
* 404 to anonymous callers too, so the addon check has to run before the 401.
*/
export const RequireAddon = (addonId: string, label: string) =>
SetMetadata<string, RequireAddonMeta>(REQUIRE_ADDON, { addonId, label });
+113 -154
View File
@@ -1,13 +1,35 @@
import { Body, Controller, Delete, Get, HttpCode, HttpException, NotFoundException, Param, Post, Put, Query, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { readEnv } from '../../app-config';
import { AdminService } from './admin.service';
import { TokenService } from '../tokens/token.service';
import { RegistrationInvitesService } from '../auth/registration-invites.service';
import { OauthService } from '../oauth/oauth.service';
import {
AdminUserCreateDto,
AdminUserUpdateDto,
AdminPermissionsDto,
AdminInviteCreateDto,
AdminFeatureToggleDto,
AdminTemplateNameDto,
AdminOidcUpdateDto,
AdminAddonUpdateDto,
AdminCollabFeaturesDto,
AdminNotificationPreferencesDto,
AdminDefaultUserSettingsDto,
AdminTestNotificationDto,
} from './admin.dto';
import { PluginRuntimeService } from '../plugins/plugin-runtime.service';
import { AddonsService } from '../addons/addons.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { AdminGuard } from '../auth/admin.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { writeAudit, getClientIp, logInfo } from '../../services/auditLog';
import { send as sendNotification } from '../../services/notificationService';
import { getClientIp } from '../audit/client-ip';
import { logInfo } from '../audit/audit-log.logger';
import { AuditService } from '../audit/audit.service';
import { NotificationsService } from '../notifications/notifications.service';
import type { User } from '../../types';
import { ManagedForbidden } from '../common/managed';
/** Throw the legacy {error,status} envelope when a service call reports failure. */
function ok<T>(result: T): Exclude<T, { error: string }> {
@@ -27,13 +49,25 @@ function ok<T>(result: T): Exclude<T, { error: string }> {
* admin-gated, the {error,status} envelopes, the audit-log writes, the MCP
* session invalidation on addon/collab changes, create-201 vs the rest 200, and
* the dev-only test-notification endpoint (404 outside development).
*
* Bodies validate via admin.dto.ts (@trek/shared schemas through the global
* ZodValidationPipe) — malformed bodies now get the pipe's standard
* { error: 'field: message; …' } envelope instead of the old inline typeof
* checks (the sanctioned ratchet behavior); valid bodies behave identically,
* and every bespoke service-level 400 is untouched.
*/
@Controller('api/admin')
@UseGuards(JwtAuthGuard, AdminGuard)
export class AdminController {
constructor(
private readonly admin: AdminService,
private readonly addons: AddonsService,
private readonly pluginRuntime: PluginRuntimeService,
private readonly audit: AuditService,
private readonly notifications: NotificationsService,
private readonly tokens: TokenService,
private readonly invites: RegistrationInvitesService,
private readonly oauth: OauthService,
) {}
// ── Users ──
@@ -42,16 +76,16 @@ export class AdminController {
@Post('users')
@HttpCode(201)
createUser(@CurrentUser() user: User, @Body() body: unknown, @Req() req: Request) {
const result = ok(this.admin.createUser(body));
writeAudit({ userId: user.id, action: 'admin.user_create', resource: String(result.insertedId), ip: getClientIp(req), details: result.auditDetails });
createUser(@CurrentUser() user: User, @Body() body: AdminUserCreateDto, @Req() req: Request) {
const result = ok(this.admin.createUser(body as Parameters<AdminService['createUser']>[0]));
this.audit.writeAudit({ userId: user.id, action: 'admin.user_create', resource: String(result.insertedId), ip: getClientIp(req), details: result.auditDetails });
return { user: result.user };
}
@Put('users/:id')
updateUser(@CurrentUser() user: User, @Param('id') id: string, @Body() body: unknown, @Req() req: Request) {
updateUser(@CurrentUser() user: User, @Param('id') id: string, @Body() body: AdminUserUpdateDto, @Req() req: Request) {
const result = ok(this.admin.updateUser(id, body));
writeAudit({ userId: user.id, action: 'admin.user_update', resource: String(id), ip: getClientIp(req), details: { targetUser: result.previousEmail, fields: result.changed } });
this.audit.writeAudit({ userId: user.id, action: 'admin.user_update', resource: String(id), ip: getClientIp(req), details: { targetUser: result.previousEmail, fields: result.changed } });
logInfo(`Admin ${user.email} edited user ${result.previousEmail} (fields: ${result.changed.join(', ')})`);
return { user: result.user };
}
@@ -59,7 +93,7 @@ export class AdminController {
@Delete('users/:id')
deleteUser(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) {
const result = ok(this.admin.deleteUser(id, user.id));
writeAudit({ userId: user.id, action: 'admin.user_delete', resource: String(id), ip: getClientIp(req), details: { targetUser: result.email } });
this.audit.writeAudit({ userId: user.id, action: 'admin.user_delete', resource: String(id), ip: getClientIp(req), details: { targetUser: result.email } });
logInfo(`Admin ${user.email} deleted user ${result.email}`);
return { success: true };
}
@@ -67,10 +101,17 @@ export class AdminController {
@Delete('users/:id/passkeys')
resetUserPasskeys(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) {
const result = ok(this.admin.resetUserPasskeys(id));
writeAudit({ userId: user.id, action: 'admin.user_passkeys_reset', resource: String(id), ip: getClientIp(req), details: { targetUser: result.email, deleted: result.deleted } });
this.audit.writeAudit({ userId: user.id, action: 'admin.user_passkeys_reset', resource: String(id), ip: getClientIp(req), details: { targetUser: result.email, deleted: result.deleted } });
return { success: true, deleted: result.deleted };
}
@Delete('users/:id/mfa')
resetUserMfa(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) {
const result = ok(this.admin.resetUserMfa(id, user.id));
this.audit.writeAudit({ userId: user.id, action: 'admin.user_mfa_reset', resource: String(id), ip: getClientIp(req), details: { targetUser: result.email } });
return { success: true };
}
// ── Stats / permissions / audit ──
@Get('stats')
stats() { return this.admin.getStats(); }
@@ -79,32 +120,15 @@ export class AdminController {
permissions() { return this.admin.getPermissions(); }
@Put('permissions')
savePermissions(@CurrentUser() user: User, @Body() body: { permissions?: unknown }, @Req() req: Request) {
if (!body.permissions || typeof body.permissions !== 'object') {
throw new HttpException({ error: 'permissions object required' }, 400);
}
savePermissions(@CurrentUser() user: User, @Body() body: AdminPermissionsDto, @Req() req: Request) {
const result = this.admin.savePermissions(body.permissions as unknown as Parameters<AdminService['savePermissions']>[0]);
writeAudit({ userId: user.id, action: 'admin.permissions_update', resource: 'permissions', ip: getClientIp(req), details: body.permissions as Record<string, unknown> });
this.audit.writeAudit({ userId: user.id, action: 'admin.permissions_update', resource: 'permissions', ip: getClientIp(req), details: body.permissions as Record<string, unknown> });
return { success: true, permissions: result.permissions, ...(result.skipped.length ? { skipped: result.skipped } : {}) };
}
@Get('audit-log')
auditLog(@Query() query: { limit?: string; offset?: string }) { return this.admin.getAuditLog(query); }
// ── OIDC ──
@Get('oidc')
getOidc() { return this.admin.getOidcSettings(); }
@Put('oidc')
updateOidc(@CurrentUser() user: User, @Body() body: { issuer?: string } & Record<string, unknown>, @Req() req: Request) {
const result = this.admin.updateOidcSettings(body);
if (result.error) {
throw new HttpException({ error: result.error }, result.status || 400);
}
writeAudit({ userId: user.id, action: 'admin.oidc_update', ip: getClientIp(req), details: { issuer_set: !!body.issuer } });
return { success: true };
}
@Post('save-demo-baseline')
@HttpCode(200)
saveDemoBaseline(@CurrentUser() user: User, @Req() req: Request) {
@@ -112,7 +136,7 @@ export class AdminController {
if (result.error) {
throw new HttpException({ error: result.error }, result.status!);
}
writeAudit({ userId: user.id, action: 'admin.demo_baseline_save', ip: getClientIp(req) });
this.audit.writeAudit({ userId: user.id, action: 'admin.demo_baseline_save', ip: getClientIp(req) });
return { success: true, message: result.message };
}
@@ -125,159 +149,109 @@ export class AdminController {
@Get('version-check')
async versionCheck() { return this.admin.checkVersion(); }
// ── Admin notification preferences ──
@Get('notification-preferences')
getNotificationPrefs(@CurrentUser() user: User) { return this.admin.getPreferencesMatrix(user.id, user.role); }
@Put('notification-preferences')
setNotificationPrefs(@CurrentUser() user: User, @Body() body: unknown) {
this.admin.setAdminPreferences(user.id, body);
return this.admin.getPreferencesMatrix(user.id, user.role);
}
// ── Invites ──
@Get('invites')
listInvites() { return { invites: this.admin.listInvites() }; }
listInvites() { return { invites: this.invites.listInvites() }; }
// Trips an admin can optionally bind a registration invite to (#1402).
@Get('invites/trips')
listInviteTrips() { return { trips: this.admin.listTripsForInvite() }; }
listInviteTrips() { return { trips: this.invites.listTripsForInvite() }; }
@Post('invites')
@HttpCode(201)
createInvite(@CurrentUser() user: User, @Body() body: unknown, @Req() req: Request) {
const result = this.admin.createInvite(user.id, body);
writeAudit({ userId: user.id, action: 'admin.invite_create', resource: String(result.inviteId), ip: getClientIp(req), details: { max_uses: result.uses, expires_in_days: result.expiresInDays, trip_id: result.tripId } });
createInvite(@CurrentUser() user: User, @Body() body: AdminInviteCreateDto, @Req() req: Request) {
const result = this.invites.createInvite(user.id, body);
this.audit.writeAudit({ userId: user.id, action: 'admin.invite_create', resource: String(result.inviteId), ip: getClientIp(req), details: { max_uses: result.uses, expires_in_days: result.expiresInDays, trip_id: result.tripId } });
return { invite: result.invite };
}
@Delete('invites/:id')
deleteInvite(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) {
ok(this.admin.deleteInvite(id));
writeAudit({ userId: user.id, action: 'admin.invite_delete', resource: String(id), ip: getClientIp(req) });
ok(this.invites.deleteInvite(id));
this.audit.writeAudit({ userId: user.id, action: 'admin.invite_delete', resource: String(id), ip: getClientIp(req) });
return { success: true };
}
// ── Feature toggles ──
// Straight to AddonsService, which owns every one of these flags. They used to go
// through eleven-plus pass-through methods on AdminService, and the three places
// flags were raw app_settings SQL there even though the other flags lived in the
// addons domain. The routes stay HERE rather than moving next to the service: an
// admin-gated controller in AddonsModule would make that module import AuthModule,
// and PluginGuardsModule imports AddonsModule precisely because it is a leaf — the
// edge would close a cycle.
@Get('bag-tracking')
getBagTracking() { return this.admin.getBagTracking(); }
getBagTracking() { return this.addons.getBagTracking(); }
@Put('bag-tracking')
updateBagTracking(@CurrentUser() user: User, @Body() body: { enabled?: unknown }, @Req() req: Request) {
const result = this.admin.updateBagTracking(body.enabled);
writeAudit({ userId: user.id, action: 'admin.bag_tracking', ip: getClientIp(req), details: { enabled: result.enabled } });
updateBagTracking(@CurrentUser() user: User, @Body() body: AdminFeatureToggleDto, @Req() req: Request) {
const result = this.addons.updateBagTracking(body.enabled);
this.audit.writeAudit({ userId: user.id, action: 'admin.bag_tracking', ip: getClientIp(req), details: { enabled: result.enabled } });
return result;
}
@Get('places-photos')
getPlacesPhotos() { return this.admin.getPlacesPhotos(); }
getPlacesPhotos() { return this.addons.getPlacesPhotos(); }
@Put('places-photos')
updatePlacesPhotos(@CurrentUser() user: User, @Body() body: { enabled?: unknown }, @Req() req: Request) {
if (typeof body.enabled !== 'boolean') throw new HttpException({ error: 'enabled must be a boolean' }, 400);
const result = this.admin.updatePlacesPhotos(body.enabled);
writeAudit({ userId: user.id, action: 'admin.places_photos', ip: getClientIp(req), details: { enabled: result.enabled } });
updatePlacesPhotos(@CurrentUser() user: User, @Body() body: AdminFeatureToggleDto, @Req() req: Request) {
const result = this.addons.updatePlacesPhotos(body.enabled);
this.audit.writeAudit({ userId: user.id, action: 'admin.places_photos', ip: getClientIp(req), details: { enabled: result.enabled } });
return result;
}
@Get('places-autocomplete')
getPlacesAutocomplete() { return this.admin.getPlacesAutocomplete(); }
getPlacesAutocomplete() { return this.addons.getPlacesAutocomplete(); }
@Put('places-autocomplete')
updatePlacesAutocomplete(@CurrentUser() user: User, @Body() body: { enabled?: unknown }, @Req() req: Request) {
if (typeof body.enabled !== 'boolean') throw new HttpException({ error: 'enabled must be a boolean' }, 400);
const result = this.admin.updatePlacesAutocomplete(body.enabled);
writeAudit({ userId: user.id, action: 'admin.places_autocomplete', ip: getClientIp(req), details: { enabled: result.enabled } });
updatePlacesAutocomplete(@CurrentUser() user: User, @Body() body: AdminFeatureToggleDto, @Req() req: Request) {
const result = this.addons.updatePlacesAutocomplete(body.enabled);
this.audit.writeAudit({ userId: user.id, action: 'admin.places_autocomplete', ip: getClientIp(req), details: { enabled: result.enabled } });
return result;
}
@Get('places-details')
getPlacesDetails() { return this.admin.getPlacesDetails(); }
getPlacesDetails() { return this.addons.getPlacesDetails(); }
@Put('places-details')
updatePlacesDetails(@CurrentUser() user: User, @Body() body: { enabled?: unknown }, @Req() req: Request) {
if (typeof body.enabled !== 'boolean') throw new HttpException({ error: 'enabled must be a boolean' }, 400);
const result = this.admin.updatePlacesDetails(body.enabled);
writeAudit({ userId: user.id, action: 'admin.places_details', ip: getClientIp(req), details: { enabled: result.enabled } });
updatePlacesDetails(@CurrentUser() user: User, @Body() body: AdminFeatureToggleDto, @Req() req: Request) {
const result = this.addons.updatePlacesDetails(body.enabled);
this.audit.writeAudit({ userId: user.id, action: 'admin.places_details', ip: getClientIp(req), details: { enabled: result.enabled } });
return result;
}
@Get('places-enrich')
getPlacesEnrich() { return this.addons.getPlacesEnrich(); }
@Put('places-enrich')
updatePlacesEnrich(@CurrentUser() user: User, @Body() body: AdminFeatureToggleDto, @Req() req: Request) {
const result = this.addons.updatePlacesEnrich(body.enabled);
this.audit.writeAudit({ userId: user.id, action: 'admin.places_enrich', ip: getClientIp(req), details: { enabled: result.enabled } });
return result;
}
@Get('collab-features')
getCollabFeatures() { return this.admin.getCollabFeatures(); }
getCollabFeatures() { return this.addons.getCollabFeatures(); }
@Put('collab-features')
updateCollabFeatures(@CurrentUser() user: User, @Body() body: unknown, @Req() req: Request) {
const { features, changed } = this.admin.updateCollabFeatures(body);
updateCollabFeatures(@CurrentUser() user: User, @Body() body: AdminCollabFeaturesDto, @Req() req: Request) {
const { features, changed } = this.addons.updateCollabFeatures(body);
// Collab flags gate MCP registration, but a no-op save must not tear down
// every live MCP session (#1414).
if (changed) this.admin.invalidateMcpSessions();
writeAudit({ userId: user.id, action: 'admin.collab_features', ip: getClientIp(req), details: features });
this.audit.writeAudit({ userId: user.id, action: 'admin.collab_features', ip: getClientIp(req), details: features });
return features;
}
// ── Packing templates ──
@Get('packing-templates')
listPackingTemplates() { return { templates: this.admin.listPackingTemplates() }; }
@Get('packing-templates/:id')
getPackingTemplate(@Param('id') id: string) { return ok(this.admin.getPackingTemplate(id)); }
@Post('packing-templates')
@HttpCode(201)
createPackingTemplate(@CurrentUser() user: User, @Body() body: { name?: unknown }) {
return ok(this.admin.createPackingTemplate(body.name, user.id));
}
@Put('packing-templates/:id')
updatePackingTemplate(@Param('id') id: string, @Body() body: unknown) { return ok(this.admin.updatePackingTemplate(id, body)); }
@Delete('packing-templates/:id')
deletePackingTemplate(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) {
const result = ok(this.admin.deletePackingTemplate(id));
writeAudit({ userId: user.id, action: 'admin.packing_template_delete', resource: String(id), ip: getClientIp(req), details: { name: result.name } });
return { success: true };
}
@Post('packing-templates/:id/categories')
@HttpCode(201)
createTemplateCategory(@Param('id') id: string, @Body() body: { name?: unknown }) {
return ok(this.admin.createTemplateCategory(id, body.name));
}
@Put('packing-templates/:templateId/categories/:catId')
updateTemplateCategory(@Param('templateId') templateId: string, @Param('catId') catId: string, @Body() body: unknown) {
return ok(this.admin.updateTemplateCategory(templateId, catId, body));
}
@Delete('packing-templates/:templateId/categories/:catId')
deleteTemplateCategory(@Param('templateId') templateId: string, @Param('catId') catId: string) {
ok(this.admin.deleteTemplateCategory(templateId, catId));
return { success: true };
}
@Post('packing-templates/:templateId/categories/:catId/items')
@HttpCode(201)
createTemplateItem(@Param('templateId') templateId: string, @Param('catId') catId: string, @Body() body: { name?: unknown }) {
return ok(this.admin.createTemplateItem(templateId, catId, body.name));
}
@Put('packing-templates/:templateId/items/:itemId')
updateTemplateItem(@Param('itemId') itemId: string, @Body() body: unknown) { return ok(this.admin.updateTemplateItem(itemId, body)); }
@Delete('packing-templates/:templateId/items/:itemId')
deleteTemplateItem(@Param('itemId') itemId: string) {
ok(this.admin.deleteTemplateItem(itemId));
return { success: true };
}
// ── Addons ──
@Get('addons')
listAddons() { return { addons: this.admin.listAddons() }; }
@Put('addons/:id')
async updateAddon(@CurrentUser() user: User, @Param('id') id: string, @Body() body: unknown, @Req() req: Request) {
async updateAddon(@CurrentUser() user: User, @Param('id') id: string, @Body() body: AdminAddonUpdateDto, @Req() req: Request) {
const result = ok(this.admin.updateAddon(id, body));
writeAudit({ userId: user.id, action: 'admin.addon_update', resource: String(id), ip: getClientIp(req), details: result.auditDetails });
this.audit.writeAudit({ userId: user.id, action: 'admin.addon_update', resource: String(id), ip: getClientIp(req), details: result.auditDetails });
// Sessions only need re-creating when the registered MCP surface can
// actually change — an enabled-flip of an MCP-relevant addon. Config-only
// saves and photo-provider toggles used to kill every session (#1414).
@@ -293,25 +267,27 @@ export class AdminController {
// ── MCP tokens / OAuth sessions ──
@Get('mcp-tokens')
listMcpTokens() { return { tokens: this.admin.listMcpTokens() }; }
listMcpTokens() { return { tokens: this.tokens.listAllMcpTokens() }; }
@Delete('mcp-tokens/:id')
deleteMcpToken(@Param('id') id: string) {
ok(this.admin.deleteMcpToken(id));
deleteMcpToken(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) {
ok(this.tokens.adminDeleteMcpToken(id));
this.audit.writeAudit({ userId: user.id, action: 'admin.mcp_token_delete', resource: String(id), ip: getClientIp(req) });
return { success: true };
}
@Get('oauth-sessions')
listOAuthSessions() { return { sessions: this.admin.listOAuthSessions() }; }
listOAuthSessions() { return { sessions: this.oauth.listAllOAuthSessions() }; }
@Delete('oauth-sessions/:id')
revokeOAuthSession(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) {
ok(this.admin.revokeOAuthSession(id));
writeAudit({ userId: user.id, action: 'admin.oauth_session.revoke', resource: String(id), ip: getClientIp(req) });
ok(this.oauth.adminRevokeOAuthSession(id));
this.audit.writeAudit({ userId: user.id, action: 'admin.oauth_session_revoke', resource: String(id), ip: getClientIp(req) });
return { success: true };
}
// ── JWT rotation ──
@ManagedForbidden('rotating the secret signs every user out and fixes nothing the admin can reach')
@Post('rotate-jwt-secret')
@HttpCode(200)
rotateJwtSecret(@CurrentUser() user: User, @Req() req: Request) {
@@ -319,44 +295,27 @@ export class AdminController {
if (result.error) {
throw new HttpException({ error: result.error }, result.status!);
}
writeAudit({ userId: user.id, action: 'admin.rotate_jwt_secret', ip: getClientIp(req) });
this.audit.writeAudit({ userId: user.id, action: 'admin.rotate_jwt_secret', ip: getClientIp(req) });
return { success: true };
}
// ── Default user settings ──
@Get('default-user-settings')
getDefaultUserSettings() { return this.admin.getAdminUserDefaults(); }
@Put('default-user-settings')
setDefaultUserSettings(@CurrentUser() user: User, @Body() body: unknown, @Req() req: Request) {
if (!body || typeof body !== 'object' || Array.isArray(body)) {
throw new HttpException({ error: 'Object body required' }, 400);
}
try {
this.admin.setAdminUserDefaults(body as unknown as Record<string, unknown>);
writeAudit({ userId: user.id, action: 'admin.default_user_settings_update', ip: getClientIp(req), details: body as Record<string, unknown> });
return this.admin.getAdminUserDefaults();
} catch (err) {
throw new HttpException({ error: err instanceof Error ? err.message : String(err) }, 400);
}
}
// ── Dev-only: test notification (404 outside development, mirroring the conditional mount) ──
@Post('dev/test-notification')
@HttpCode(200)
async devTestNotification(@CurrentUser() user: User, @Body() body: { event?: string; scope?: string; targetId?: number; params?: Record<string, unknown>; inApp?: boolean }) {
if (process.env.NODE_ENV?.toLowerCase() !== 'development') {
async devTestNotification(@CurrentUser() user: User, @Body() body: AdminTestNotificationDto) {
if (!readEnv().app.isDevelopment) {
throw new NotFoundException();
}
try {
await sendNotification({
await this.notifications.send({
event: body.event ?? 'trip_reminder',
actorId: user.id,
scope: body.scope ?? 'user',
targetId: body.targetId ?? user.id,
params: { actor: user.email, ...(body.params ?? {}) },
inApp: body.inApp,
} as unknown as Parameters<typeof sendNotification>[0]);
} as unknown as Parameters<NotificationsService['send']>[0]);
return { success: true };
} catch (err) {
throw new HttpException({ error: err instanceof Error ? err.message : String(err) }, 400);
+38
View File
@@ -0,0 +1,38 @@
import { createZodDto } from 'nestjs-zod';
import {
adminUserCreateRequestSchema,
adminUserUpdateRequestSchema,
adminPermissionsRequestSchema,
adminInviteCreateRequestSchema,
adminFeatureToggleRequestSchema,
adminTemplateNameRequestSchema,
adminOidcUpdateRequestSchema,
adminAddonUpdateRequestSchema,
adminCollabFeaturesRequestSchema,
adminNotificationPreferencesRequestSchema,
adminDefaultUserSettingsRequestSchema,
adminTestNotificationRequestSchema,
} from '@trek/shared';
/**
* Server-side createZodDto wrappers over the @trek/shared admin contracts. The
* global ZodValidationPipe (APP_PIPE in app.module.ts) validates any @Body()
* parameter typed with one of these classes by metatype — the Zod schemas in
* shared/ remain the single source of truth for the wire contract.
*
* Twelve classes cover the twenty grandfathered AdminController body contracts:
* the four feature toggles share AdminFeatureToggleDto and the six
* packing-template create/update routes share AdminTemplateNameDto.
*/
export class AdminUserCreateDto extends createZodDto(adminUserCreateRequestSchema) {}
export class AdminUserUpdateDto extends createZodDto(adminUserUpdateRequestSchema) {}
export class AdminPermissionsDto extends createZodDto(adminPermissionsRequestSchema) {}
export class AdminInviteCreateDto extends createZodDto(adminInviteCreateRequestSchema) {}
export class AdminFeatureToggleDto extends createZodDto(adminFeatureToggleRequestSchema) {}
export class AdminTemplateNameDto extends createZodDto(adminTemplateNameRequestSchema) {}
export class AdminOidcUpdateDto extends createZodDto(adminOidcUpdateRequestSchema) {}
export class AdminAddonUpdateDto extends createZodDto(adminAddonUpdateRequestSchema) {}
export class AdminCollabFeaturesDto extends createZodDto(adminCollabFeaturesRequestSchema) {}
export class AdminNotificationPreferencesDto extends createZodDto(adminNotificationPreferencesRequestSchema) {}
export class AdminDefaultUserSettingsDto extends createZodDto(adminDefaultUserSettingsRequestSchema) {}
export class AdminTestNotificationDto extends createZodDto(adminTestNotificationRequestSchema) {}
+97
View File
@@ -0,0 +1,97 @@
import fs from 'fs';
/**
* Pure + module-scoped half of the admin domain, relocated verbatim from
* services/adminService.ts with the 2026-08 fold (auth.helpers / maps.helpers /
* atlas-geo precedent).
*
* The version cache is module-scoped **on purpose** (the permissions-cache
* precedent, permissions.bridge.ts): the daily version-check cron
* (VersionCheckJob) and GET /api/admin/version-check both run on the container
* singleton now, but the module scope keeps the one-5-minute-cache guarantee
* independent of how many AdminService instances exist (the legacy module and
* the retired admin bridge relied on exactly that). Instance state would double
* the GitHub traffic and let the cron notify on a version the UI has not seen
* yet.
*/
/** bcrypt cost factor for user passwords — kept in sync with authService. */
export const BCRYPT_COST = 12;
export function utcSuffix(ts: string | null | undefined): string | null {
if (!ts) return null;
return ts.endsWith('Z') ? ts : ts.replace(' ', 'T') + 'Z';
}
export function compareVersions(a: string, b: string): number {
const parse = (v: string) => {
const [base, pre] = v.split('-pre.');
const parts = base.split('.').map(Number);
const n = pre !== undefined ? Number.parseInt(pre, 10) : null;
const preN = n !== null && Number.isFinite(n) ? n : null;
return { parts, preN };
};
const pa = parse(a),
pb = parse(b);
for (let i = 0; i < Math.max(pa.parts.length, pb.parts.length); i++) {
const na = pa.parts[i] || 0,
nb = pb.parts[i] || 0;
if (na > nb) return 1;
if (na < nb) return -1;
}
// Equal base: stable > prerelease; higher preN wins among prereleases
if (pa.preN === null && pb.preN !== null) return 1;
if (pa.preN !== null && pb.preN === null) return -1;
if (pa.preN !== null && pb.preN !== null) {
if (pa.preN > pb.preN) return 1;
if (pa.preN < pb.preN) return -1;
}
return 0;
}
/**
* Documented parity exception to the "modules must be importable without side
* effects" rule (auth.helpers.ts's import-time DUMMY_PASSWORD_HASH precedent):
* this probes the filesystem at module evaluation, exactly as the legacy module
* did. Making it lazy would change *when* `fs` is consulted relative to a
* suite's vi.mock setup, and so could shift `is_docker` in checkVersion
* payloads.
*/
export const isDocker = (() => {
try {
return (
fs.existsSync('/.dockerenv') ||
(fs.existsSync('/proc/1/cgroup') && fs.readFileSync('/proc/1/cgroup', 'utf8').includes('docker'))
);
} catch {
return false;
}
})();
export interface VersionInfo {
current: string;
latest: string;
update_available: boolean;
release_url?: string;
is_docker: boolean;
is_prerelease: boolean;
}
const VERSION_CACHE_TTL = 5 * 60 * 1000; // 5 minutes
let _versionCache: { data: VersionInfo; expiresAt: number } | null = null;
/** Cached payload while inside the TTL, otherwise null. */
export function readVersionCache(): VersionInfo | null {
if (_versionCache && Date.now() < _versionCache.expiresAt) return _versionCache.data;
return null;
}
/** `ttl` overrides the 5-minute default — failed checks cache on a shorter one. */
export function writeVersionCache(data: VersionInfo, ttl: number = VERSION_CACHE_TTL): void {
_versionCache = { data, expiresAt: Date.now() + ttl };
}
/** Test-only: clear the in-memory version cache. */
export function __clearVersionCacheForTests(): void {
_versionCache = null;
}
+23 -3
View File
@@ -1,11 +1,31 @@
import { Module } from '@nestjs/common';
import { TokensModule } from '../tokens/tokens.module';
import { OauthModule } from '../oauth/oauth.module';
import { AdminController } from './admin.controller';
import { AdminService } from './admin.service';
import { PluginsModule } from '../plugins/plugins.module';
import { VersionCheckJob } from './version-check.job';
import { DemoResetJob } from './demo-reset.job';
import { SchedulingModule } from '../scheduling/scheduling.module';
import { PluginsRuntimeModule } from '../plugins/plugins-runtime.module';
import { SettingsModule } from '../settings/settings.module';
import { AuditModule } from '../audit/audit.module';
import { AddonsModule } from '../addons/addons.module';
// AuthModule exports PasskeyService for the admin passkey-reset endpoint.
import { AuthModule } from '../auth/auth.module';
// NotificationsModule exports NotificationsService for the dev test-notification send.
import { NotificationsModule } from '../notifications/notifications.module';
// PackingModule exports PackingService, which owns the packing-template tables
// backing the admin /packing-templates routes. Cycle-free: PackingModule imports
// only PermissionsModule + AuthModule, neither of which reaches AdminModule.
import { PackingModule } from '../packing/packing.module';
// PermissionsModule exports PermissionsService for the permission matrix — it is
// not @Global, so the import must be explicit.
import { PermissionsModule } from '../permissions/permissions.module';
import { AppConfigModule } from '../app-config/app-config.module';
@Module({
imports: [PluginsModule],
imports: [AppConfigModule, PluginsRuntimeModule, SettingsModule, AuditModule, AddonsModule, AuthModule, NotificationsModule, PackingModule, PermissionsModule, TokensModule, OauthModule, SchedulingModule],
controllers: [AdminController],
providers: [AdminService],
providers: [AdminService, VersionCheckJob, DemoResetJob],
})
export class AdminModule {}
+717 -64
View File
@@ -1,82 +1,735 @@
import { Injectable } from '@nestjs/common';
import * as svc from '../../services/adminService';
import { getAdminUserDefaults, setAdminUserDefaults } from '../../services/settingsService';
import bcrypt from 'bcryptjs';
import crypto from 'crypto';
import fs from 'fs';
import path from 'path';
import { ADDON_IDS } from '../../addons';
import { readEnv } from '../../app-config';
import { updateJwtSecret } from '../../config';
// Import from sessionManager directly, NOT the ../../mcp barrel — the direct
// path keeps this module's graph minimal, and the split predates the barrel's
// shrink to process-wide state. The invalidateMcpSessions barrel import below
// is deliberately separate: it is only reached from the controller, never from
// the cron path.
import { revokeUserSessions, revokeUserSessionsForClient } from '../../mcp/sessionManager';
import { invalidateMcpSessions } from '../../mcp';
import { getPreferencesMatrix, setAdminPreferences } from '../../services/notificationPreferencesService';
import { adminResetPasskeys } from '../../services/passkeyService';
import { emitUserDeleted } from '../../plugin-user-lifecycle';
import type { User, Addon } from '../../types';
import { maybe_encrypt_api_key, decrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { avatarUrl } from '../common/avatarUrl';
import { prepareLlmAddonConfigForWrite, maskLlmAddonConfig } from '../llm-parse/llm-config';
import { getPhotoProviderConfig } from '../memories/memories.helpers';
import { validatePassword } from '../common/passwordPolicy';
import { UserCleanupService } from '../auth/user-cleanup.service';
import { DatabaseService } from '../database/database.service';
import { AddonsService } from '../addons/addons.service';
import { RealtimeService } from '../realtime/realtime.service';
import { PasskeyService } from '../auth/passkey.service';
import { AuthService } from '../auth/auth.service';
import { PermissionsService } from '../permissions/permissions.service';
import { PERMISSION_ACTIONS } from '../permissions/permissions.service';
import { NotificationsService } from '../notifications/notifications.service';
import {
BCRYPT_COST,
compareVersions,
isDocker,
readVersionCache,
utcSuffix,
writeVersionCache,
type VersionInfo,
} from './admin.helpers';
import { MANAGED_FORBIDDEN_ERROR } from '../common/managed';
/** Outbound GitHub calls: hard timeout and response-size cap (server/CLAUDE.md). */
const GITHUB_TIMEOUT_MS = 10_000;
const GITHUB_MAX_BYTES = 2_000_000;
/** Failed version checks cache briefly so an outage isn't refetched per page load. */
const VERSION_FAILURE_TTL = 60_000;
/**
* Thin Nest wrapper around the existing admin service (+ the settings,
* MCP-session and notification-preference helpers the legacy route used). All
* business logic, audit-relevant return shapes and the addon/MCP invalidation
* reuse the legacy code unchanged.
* Admin domain service — owns the admin SQL (folded from the legacy
* services/adminService.ts with the 2026-08 migration): user CRUD, instance
* stats, the permission matrix, the audit-log read side, OIDC settings, the
* demo baseline, GitHub release/version checks, invite tokens, the three
* places feature toggles, addons + photo providers, MCP tokens, OAuth sessions
* and JWT rotation.
*
* Every quirk relocated byte-for-byte: the `||` falsy defaults (never `??`),
* post-insert/post-update re-selects instead of RETURNING, the COALESCE partial
* update, the #1362 guest exclusions and the exact error strings. The legacy
* `{ error, status }` envelope is the return contract — the controller's `ok()`
* helper turns it into an HttpException, so nothing here throws.
*
* The bag-tracking/collab-feature toggles, user defaults, passkey reset and
* packing templates delegate to the services that own those tables. The pure
* and module-scoped pieces (compareVersions, isDocker, the version cache) live
* in admin.helpers.ts.
*/
@Injectable()
export class AdminService {
// Users
listUsers() { return svc.listUsers(); }
createUser(body: unknown) { return svc.createUser(body as Parameters<typeof svc.createUser>[0]); }
updateUser(id: string, body: unknown) { return svc.updateUser(id, body as Parameters<typeof svc.updateUser>[1]); }
deleteUser(id: string, actingUserId: number) { return svc.deleteUser(id, actingUserId); }
resetUserPasskeys(id: string) { return adminResetPasskeys(Number(id)); }
constructor(
private readonly db: DatabaseService,
private readonly addons: AddonsService,
private readonly passkeys: PasskeyService,
private readonly auth: AuthService,
private readonly permissions: PermissionsService,
private readonly notifications: NotificationsService,
private readonly userCleanup: UserCleanupService,
private readonly realtime: RealtimeService,
) {}
getStats() { return svc.getStats(); }
getPermissions() { return svc.getPermissions(); }
savePermissions(permissions: Parameters<typeof svc.savePermissions>[0]) { return svc.savePermissions(permissions); }
getAuditLog(query: { limit?: string; offset?: string }) { return svc.getAuditLog(query); }
// ── User CRUD ──────────────────────────────────────────────────────────────
getOidcSettings() { return svc.getOidcSettings(); }
updateOidcSettings(body: unknown) { return svc.updateOidcSettings(body as Parameters<typeof svc.updateOidcSettings>[0]); }
saveDemoBaseline() { return svc.saveDemoBaseline(); }
listUsers() {
// Guests (#1362) are accountless trip participants, not real users — keep them out
// of admin user management entirely.
const users = this.db.all<
Pick<User, 'id' | 'username' | 'email' | 'role' | 'created_at' | 'updated_at' | 'last_login'> & {
avatar?: string | null;
}
>(
'SELECT id, username, email, role, avatar, created_at, updated_at, last_login FROM users WHERE COALESCE(is_guest, 0) = 0 ORDER BY created_at DESC',
);
let onlineUserIds = new Set<number>();
try {
// The catch stays here rather than in the facade: an admin list that shows
// everyone as offline is a better answer than a 500, and that judgement
// belongs to this caller, not to every future one.
onlineUserIds = this.realtime.getOnlineUserIds();
} catch {
/* */
}
return users.map((u) => ({
...u,
avatar_url: avatarUrl(u),
created_at: utcSuffix(u.created_at),
updated_at: utcSuffix(u.updated_at as string),
last_login: utcSuffix(u.last_login),
online: onlineUserIds.has(u.id),
}));
}
getGithubReleases(perPage: string, page: string) { return svc.getGithubReleases(perPage, page); }
checkVersion() { return svc.checkVersion(); }
createUser(data: { username: string; email: string; password: string; role?: string }) {
const username = data.username?.trim();
const email = data.email?.trim();
const password = data.password?.trim();
// Invites
listInvites() { return svc.listInvites(); }
listTripsForInvite() { return svc.listTripsForInvite(); }
createInvite(userId: number, body: unknown) { return svc.createInvite(userId, body as Parameters<typeof svc.createInvite>[1]); }
deleteInvite(id: string) { return svc.deleteInvite(id); }
if (!username || !email || !password) {
return { error: 'Username, email and password are required', status: 400 };
}
// Feature toggles
getBagTracking() { return svc.getBagTracking(); }
updateBagTracking(enabled: unknown) { return svc.updateBagTracking(enabled as boolean); }
getPlacesPhotos() { return svc.getPlacesPhotos(); }
updatePlacesPhotos(enabled: boolean) { return svc.updatePlacesPhotos(enabled); }
getPlacesAutocomplete() { return svc.getPlacesAutocomplete(); }
updatePlacesAutocomplete(enabled: boolean) { return svc.updatePlacesAutocomplete(enabled); }
getPlacesDetails() { return svc.getPlacesDetails(); }
updatePlacesDetails(enabled: boolean) { return svc.updatePlacesDetails(enabled); }
getCollabFeatures() { return svc.getCollabFeatures(); }
updateCollabFeatures(body: unknown) { return svc.updateCollabFeatures(body as Parameters<typeof svc.updateCollabFeatures>[0]); }
const pwCheck = validatePassword(password);
if (!pwCheck.ok) return { error: pwCheck.reason, status: 400 };
// Packing templates
listPackingTemplates() { return svc.listPackingTemplates(); }
getPackingTemplate(id: string) { return svc.getPackingTemplate(id); }
createPackingTemplate(name: unknown, userId: number) { return svc.createPackingTemplate(name as string, userId); }
updatePackingTemplate(id: string, body: unknown) { return svc.updatePackingTemplate(id, body as Parameters<typeof svc.updatePackingTemplate>[1]); }
deletePackingTemplate(id: string) { return svc.deletePackingTemplate(id); }
createTemplateCategory(templateId: string, name: unknown) { return svc.createTemplateCategory(templateId, name as string); }
updateTemplateCategory(templateId: string, catId: string, body: unknown) { return svc.updateTemplateCategory(templateId, catId, body as Parameters<typeof svc.updateTemplateCategory>[2]); }
deleteTemplateCategory(templateId: string, catId: string) { return svc.deleteTemplateCategory(templateId, catId); }
createTemplateItem(templateId: string, catId: string, name: unknown) { return svc.createTemplateItem(templateId, catId, name as string); }
updateTemplateItem(itemId: string, body: unknown) { return svc.updateTemplateItem(itemId, body as Parameters<typeof svc.updateTemplateItem>[1]); }
deleteTemplateItem(itemId: string) { return svc.deleteTemplateItem(itemId); }
if (data.role && !['user', 'admin'].includes(data.role)) {
return { error: 'Invalid role', status: 400 };
}
// Addons + tokens + sessions
listAddons() { return svc.listAddons(); }
updateAddon(id: string, body: unknown) { return svc.updateAddon(id, body as Parameters<typeof svc.updateAddon>[1]); }
listMcpTokens() { return svc.listMcpTokens(); }
deleteMcpToken(id: string) { return svc.deleteMcpToken(id); }
listOAuthSessions() { return svc.listOAuthSessions(); }
revokeOAuthSession(id: string) { return svc.revokeOAuthSession(id); }
rotateJwtSecret() { return svc.rotateJwtSecret(); }
// Guests (#1362) live in a reserved synthetic namespace; never let one block a real account.
const existingUsername = this.db.get('SELECT id FROM users WHERE username = ? AND COALESCE(is_guest, 0) = 0', username);
if (existingUsername) return { error: 'Username already taken', status: 409 };
const existingEmail = this.db.get('SELECT id FROM users WHERE email = ? AND COALESCE(is_guest, 0) = 0', email);
if (existingEmail) return { error: 'Email already taken', status: 409 };
const passwordHash = bcrypt.hashSync(password, BCRYPT_COST);
const result = this.db.run(
'INSERT INTO users (username, email, password_hash, role) VALUES (?, ?, ?, ?)',
username, email, passwordHash, data.role || 'user',
);
const user = this.db.get(
'SELECT id, username, email, role, created_at, updated_at FROM users WHERE id = ?',
result.lastInsertRowid,
);
return {
user,
insertedId: Number(result.lastInsertRowid),
auditDetails: { username, email, role: data.role || 'user' },
};
}
updateUser(id: string, data: { username?: string; email?: string; role?: string; password?: string }) {
const username = typeof data.username === 'string' ? data.username.trim() : data.username;
const email = typeof data.email === 'string' ? data.email.trim() : data.email;
const { role, password } = data;
const user = this.db.get<User>('SELECT * FROM users WHERE id = ?', id);
if (!user) return { error: 'User not found', status: 404 };
if (role && !['user', 'admin'].includes(role)) {
return { error: 'Invalid role', status: 400 };
}
// An empty string used to fall through `username || null` into COALESCE and
// silently mean "leave unchanged". Say so instead of pretending it worked.
if (username === '') return { error: 'Username cannot be empty', status: 400 };
if (email === '') return { error: 'Email cannot be empty', status: 400 };
if (username && username !== user.username) {
const conflict = this.db.get('SELECT id FROM users WHERE username = ? AND id != ? AND COALESCE(is_guest, 0) = 0', username, id);
if (conflict) return { error: 'Username already taken', status: 409 };
}
if (email && email !== user.email) {
const conflict = this.db.get('SELECT id FROM users WHERE email = ? AND id != ? AND COALESCE(is_guest, 0) = 0', email, id);
if (conflict) return { error: 'Email already taken', status: 409 };
}
if (password) {
const pwCheck = validatePassword(password);
if (!pwCheck.ok) return { error: pwCheck.reason, status: 400 };
}
const passwordHash = password ? bcrypt.hashSync(password, BCRYPT_COST) : null;
// Don't let the admin UI demote the last remaining admin — that would leave the
// instance with no one able to manage it (and on OIDC-only setups, no recovery). #1274
if (role && role !== 'admin') {
const current = this.db.get<{ role?: string }>('SELECT role FROM users WHERE id = ?', id);
if (current?.role === 'admin') {
const adminCount = this.db.get<{ count: number }>("SELECT COUNT(*) as count FROM users WHERE role = 'admin'")!.count;
if (adminCount <= 1) return { error: 'Cannot remove the last admin', status: 400 };
}
}
// An admin sets a password for exactly one reason: the account is believed
// compromised. Without bumping password_version, verifyJwtAndLoadUser keeps
// accepting every cookie the intruder already holds, so the one action taken
// to lock them out was the one action that did not. Both self-service paths
// (changePassword, resetPassword) have always done this; this one had not.
const newPv = password ? ((user as User & { password_version?: number }).password_version ?? 0) + 1 : null;
this.db.transaction(() => {
this.db.run(
`
UPDATE users SET
username = COALESCE(?, username),
email = COALESCE(?, email),
role = COALESCE(?, role),
password_hash = COALESCE(?, password_hash),
password_version = COALESCE(?, password_version),
updated_at = CURRENT_TIMESTAMP
WHERE id = ?
`,
username || null, email || null, role || null, passwordHash, newPv, id,
);
if (password) {
// The version bump only invalidates JWT cookies. These two stores carry
// their own credentials and are revoked separately, exactly as the
// self-service paths do it.
this.db.run('DELETE FROM mcp_tokens WHERE user_id = ?', id);
try {
this.db.run(
'UPDATE oauth_tokens SET revoked_at = CURRENT_TIMESTAMP WHERE user_id = ? AND revoked_at IS NULL',
id,
);
} catch { /* very old installs predate oauth_tokens */ }
}
});
if (password) {
try { revokeUserSessions(Number(id)); } catch { /* best-effort, same as elsewhere */ }
}
const updated = this.db.get('SELECT id, username, email, role, created_at, updated_at FROM users WHERE id = ?', id);
const changed: string[] = [];
if (username) changed.push('username');
if (email) changed.push('email');
if (role) changed.push('role');
if (password) changed.push('password');
return {
user: updated,
previousEmail: user.email,
changed,
};
}
deleteUser(id: string, currentUserId: number) {
if (Number.parseInt(id) === currentUserId) {
return { error: 'Cannot delete own account', status: 400 };
}
const userToDel = this.db.get<{ id: number; email: string }>('SELECT id, email FROM users WHERE id = ?', id);
if (!userToDel) return { error: 'User not found', status: 404 };
this.userCleanup.deleteUserCompletely(userToDel.id);
emitUserDeleted(userToDel.id); // let plugins erase their own per-user data
return { email: userToDel.email };
}
resetUserPasskeys(id: string) { return this.passkeys.adminResetPasskeys(Number(id)); }
/**
* Clear another account's TOTP so its owner can enrol again.
*
* The passkey half of this has existed since passkeys landed; the TOTP half
* never did, which left one ordinary event with no answer: somebody on a trip
* loses their phone. Without this the only ways out are an operator reaching
* into the database or the account being deleted and rebuilt.
*
* Never for the caller themselves. An admin who wants their own MFA gone
* disables it through Settings, where the current password is required —
* making that reachable from here would turn a stolen admin session into a
* way to strip the second factor off the very account it came from.
*/
resetUserMfa(id: string, actingUserId: number): { error?: string; status?: number; success?: boolean; email?: string } {
const targetId = Number(id);
if (targetId === actingUserId) {
return { error: 'Use Settings to change your own two-factor setup', status: 400 };
}
const target = this.db.get<{ id: number; email: string; mfa_enabled: number | boolean }>(
'SELECT id, email, mfa_enabled FROM users WHERE id = ?',
targetId,
);
if (!target) return { error: 'User not found', status: 404 };
// Same three columns disableMfa clears, so an admin reset and a self-service
// disable leave the account in exactly one state rather than two.
this.db.run(
'UPDATE users SET mfa_enabled = 0, mfa_secret = NULL, mfa_backup_codes = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
targetId,
);
return { success: true, email: target.email };
}
// ── Stats ──────────────────────────────────────────────────────────────────
getStats() {
const totalUsers = this.db.get<{ count: number }>('SELECT COUNT(*) as count FROM users WHERE COALESCE(is_guest, 0) = 0')!.count;
const totalTrips = this.db.get<{ count: number }>('SELECT COUNT(*) as count FROM trips')!.count;
const totalPlaces = this.db.get<{ count: number }>('SELECT COUNT(*) as count FROM places')!.count;
const totalFiles = this.db.get<{ count: number }>('SELECT COUNT(*) as count FROM trip_files')!.count;
return { totalUsers, totalTrips, totalPlaces, totalFiles };
}
// ── Permissions ────────────────────────────────────────────────────────────
getPermissions() {
const current = this.permissions.getAllPermissions();
const actions = PERMISSION_ACTIONS.map((a) => ({
key: a.key,
level: current[a.key],
defaultLevel: a.defaultLevel,
allowedLevels: a.allowedLevels,
}));
return { permissions: actions };
}
savePermissions(permissions: Record<string, string>) {
const { skipped } = this.permissions.savePermissions(permissions);
return { permissions: this.permissions.getAllPermissions(), skipped };
}
// ── Audit Log ──────────────────────────────────────────────────────────────
getAuditLog(query: { limit?: string; offset?: string }) {
const limitRaw = Number.parseInt(String(query.limit || '100'), 10);
const offsetRaw = Number.parseInt(String(query.offset || '0'), 10);
const limit = Math.min(Math.max(Number.isFinite(limitRaw) ? limitRaw : 100, 1), 500);
const offset = Math.max(Number.isFinite(offsetRaw) ? offsetRaw : 0, 0);
type Row = {
id: number;
created_at: string;
user_id: number | null;
username: string | null;
user_email: string | null;
action: string;
resource: string | null;
details: string | null;
ip: string | null;
};
const rows = this.db.all<Row>(
`
SELECT a.id, a.created_at, a.user_id, u.username, u.email as user_email, a.action, a.resource, a.details, a.ip
FROM audit_log a
LEFT JOIN users u ON u.id = a.user_id
ORDER BY a.id DESC
LIMIT ? OFFSET ?
`,
limit, offset,
);
const total = this.db.get<{ c: number }>('SELECT COUNT(*) as c FROM audit_log')!.c;
const entries = rows.map((r) => {
// Unparseable details fall back to the raw string rather than the old
// { _parse_error: true } sentinel, which the admin UI rendered literally.
let details: Record<string, unknown> | string | null = null;
if (r.details) {
try {
details = JSON.parse(r.details) as Record<string, unknown>;
} catch {
details = r.details;
}
}
const created_at =
r.created_at && !r.created_at.endsWith('Z') ? r.created_at.replace(' ', 'T') + 'Z' : r.created_at;
return { ...r, created_at, details };
});
return { entries, total, limit, offset };
}
// ── Demo Baseline ──────────────────────────────────────────────────────────
saveDemoBaseline(): { error?: string; status?: number; message?: string } {
if (!readEnv().demo.enabled) {
return { error: 'Not found', status: 404 };
}
try {
// Lazy require: demo-reset is a demo-only module.
const { saveBaseline } = require('../../demo/demo-reset');
saveBaseline();
return { message: 'Demo baseline saved. Hourly resets will restore to this state.' };
} catch (err: unknown) {
console.error(err);
return { error: 'Failed to save baseline', status: 500 };
}
}
// ── GitHub Integration ─────────────────────────────────────────────────────
/**
* GitHub fetch with the timeout + size cap the outbound-fetch rule requires
* (server/CLAUDE.md). Returns null on any failure; callers decide the fallback.
*/
private async fetchGithub(url: string): Promise<unknown | null> {
try {
const resp = await fetch(url, {
headers: { Accept: 'application/vnd.github.v3+json', 'User-Agent': 'TREK-Server' },
signal: AbortSignal.timeout(GITHUB_TIMEOUT_MS),
});
if (!resp.ok) return null;
const text = await resp.text();
if (text.length > GITHUB_MAX_BYTES) {
console.error(`[admin] GitHub response exceeded ${GITHUB_MAX_BYTES} bytes, ignoring`);
return null;
}
return JSON.parse(text);
} catch (err: unknown) {
console.error(`[admin] GitHub request failed: ${err instanceof Error ? err.message : String(err)}`);
return null;
}
}
async getGithubReleases(perPage: string = '10', page: string = '1') {
// The query arrives as raw strings from the admin UI; clamp to what the
// GitHub API accepts instead of interpolating them into the URL as given.
const per = Math.min(Math.max(Number.parseInt(perPage, 10) || 10, 1), 100);
const pg = Math.max(Number.parseInt(page, 10) || 1, 1);
const qs = new URLSearchParams({ per_page: String(per), page: String(pg) });
const data = await this.fetchGithub(`https://api.github.com/repos/liketrek/TREK/releases?${qs}`);
return Array.isArray(data) ? data : [];
}
async checkVersion(): Promise<VersionInfo> {
// Lazy require, re-anchored for nest/admin/ (was ../../package.json in services/).
const currentVersion: string = readEnv().app.appVersion || require('../../../package.json').version;
const isPrerelease = currentVersion.includes('-pre.');
// Answered rather than refused on a centrally administered install: the admin
// page calls this on open, and a 403 there would be an error message where a
// quiet surface belongs. The operator decides when to upgrade, so from inside
// the instance there is nothing available.
if (readEnv().managed.enabled) {
return {
current: currentVersion,
latest: currentVersion,
update_available: false,
is_docker: isDocker,
is_prerelease: isPrerelease,
};
}
const cached = readVersionCache();
if (cached) return cached;
const fallback: VersionInfo = {
current: currentVersion,
latest: currentVersion,
update_available: false,
is_docker: isDocker,
is_prerelease: isPrerelease,
};
// Failures cache too (on a shorter TTL), so a GitHub outage doesn't mean a
// live fetch on every admin page load — the legacy code only cached success.
const fail = () => {
writeVersionCache(fallback, VERSION_FAILURE_TTL);
return fallback;
};
let result: VersionInfo;
if (isPrerelease) {
// Fetch release list and find the newest prerelease
const data = await this.fetchGithub('https://api.github.com/repos/liketrek/TREK/releases?per_page=100') as
| Array<{ tag_name?: string; html_url?: string; prerelease?: boolean }>
| null;
if (!data) return fail();
const prereleases = Array.isArray(data) ? data.filter((r) => r.prerelease) : [];
if (!prereleases.length) return fail();
// Pre-compute stripped versions, then sort descending
const tagged = prereleases.map((r) => ({ r, v: (r.tag_name || '').replace(/^v/, '') }));
tagged.sort((a, b) => compareVersions(b.v, a.v));
const latest = tagged[0].v;
const update_available = !!latest && latest !== currentVersion && compareVersions(latest, currentVersion) > 0;
result = {
current: currentVersion,
latest,
update_available,
release_url: tagged[0].r.html_url || '',
is_docker: isDocker,
is_prerelease: true,
};
} else {
const data = await this.fetchGithub('https://api.github.com/repos/liketrek/TREK/releases/latest') as
| { tag_name?: string; html_url?: string }
| null;
if (!data) return fail();
const latest = (data.tag_name || '').replace(/^v/, '');
const update_available = !!latest && latest !== currentVersion && compareVersions(latest, currentVersion) > 0;
result = {
current: currentVersion,
latest,
update_available,
release_url: data.html_url || '',
is_docker: isDocker,
is_prerelease: false,
};
}
writeVersionCache(result);
return result;
}
async checkAndNotifyVersion(): Promise<void> {
try {
const result = await this.checkVersion();
if (!result.update_available) return;
const lastNotified = this.db.get<{ value: string }>(
'SELECT value FROM app_settings WHERE key = ?', 'last_notified_version',
)?.value;
if (lastNotified === result.latest) return;
this.db.run(
'INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)',
'last_notified_version', result.latest,
);
await this.notifications.send({
event: 'version_available',
actorId: null,
scope: 'admin',
targetId: 0,
params: { version: result.latest },
});
} catch {
// Silently ignore — version check is non-critical
}
}
// ── Addons ─────────────────────────────────────────────────────────────────
listAddons() {
const addons = this.db
.all<Addon>('SELECT * FROM addons ORDER BY sort_order, id')
// Hidden rather than shown-and-refused, because a toggle that answers 403
// is worse than no toggle.
//
// AI parsing: the endpoint, the model and what a document costs all belong
// to the operator, so there is no instance decision left to make — not even
// whether it runs.
//
// AirTrail: the addon exists to reach a server the admin runs themselves,
// and a managed instance has no route to one.
.filter(
(a) =>
!(
readEnv().managed.enabled &&
(a.id === ADDON_IDS.LLM_PARSING || a.id === ADDON_IDS.AIRTRAIL)
),
);
const providers = this.db.all<{
id: string;
name: string;
description?: string | null;
icon: string;
enabled: number;
sort_order: number;
}>(`
SELECT id, name, description, icon, enabled, sort_order
FROM photo_providers
ORDER BY sort_order, id
`)
// Immich and Synology Photos are servers the admin runs at home. A managed
// instance cannot reach one (its egress does not go there, and it should
// not), so offering the connection would only produce a timeout.
.filter(() => !readEnv().managed.enabled);
const fields = this.db.all<{
provider_id: string;
field_key: string;
label: string;
input_type: string;
placeholder?: string | null;
required: number;
secret: number;
settings_key?: string | null;
payload_key?: string | null;
sort_order: number;
}>(`
SELECT provider_id, field_key, label, input_type, placeholder, required, secret, settings_key, payload_key, sort_order
FROM photo_provider_fields
ORDER BY sort_order, id
`);
const fieldsByProvider = new Map<string, typeof fields>();
for (const field of fields) {
const arr = fieldsByProvider.get(field.provider_id) || [];
arr.push(field);
fieldsByProvider.set(field.provider_id, arr);
}
return [
...addons.map((a) => ({
...a,
enabled: !!a.enabled,
config:
a.id === ADDON_IDS.LLM_PARSING
? maskLlmAddonConfig(JSON.parse(a.config || '{}'))
: JSON.parse(a.config || '{}'),
})),
...providers.map((p) => ({
id: p.id,
name: p.name,
description: p.description,
type: 'photo_provider',
icon: p.icon,
enabled: !!p.enabled,
config: getPhotoProviderConfig(p.id),
fields: (fieldsByProvider.get(p.id) || []).map((f) => ({
key: f.field_key,
label: f.label,
input_type: f.input_type,
placeholder: f.placeholder || '',
required: !!f.required,
secret: !!f.secret,
settings_key: f.settings_key || null,
payload_key: f.payload_key || null,
sort_order: f.sort_order,
})),
sort_order: p.sort_order,
})),
];
}
updateAddon(id: string, data: { enabled?: boolean; config?: Record<string, unknown> }) {
type ProviderRow = { id: string; name: string; description?: string | null; icon: string; enabled: number; sort_order: number };
const addon = this.db.get<Addon>('SELECT * FROM addons WHERE id = ?', id);
const provider = this.db.get<ProviderRow>('SELECT * FROM photo_providers WHERE id = ?', id);
if (!addon && !provider) return { error: 'Addon not found', status: 404 };
// The whole addon, not just its config: on a centrally administered install
// the operator owns the endpoint, the model and the per-document cost, so
// there is nothing here for an instance admin to set — including whether it
// runs at all. listAddons hides the row; this closes the route behind it.
if (readEnv().managed.enabled && id === ADDON_IDS.LLM_PARSING) {
return { error: MANAGED_FORBIDDEN_ERROR.error, status: 403 };
}
this.db.transaction(() => {
if (addon) {
if (data.enabled !== undefined)
this.db.run('UPDATE addons SET enabled = ? WHERE id = ?', data.enabled ? 1 : 0, id);
if (data.config !== undefined) {
// The AI-parsing addon holds an API key — encrypt it at rest and preserve
// the stored key when the client echoes the mask sentinel (see llmConfig.ts).
const configToStore =
id === ADDON_IDS.LLM_PARSING
? prepareLlmAddonConfigForWrite(data.config, JSON.parse(addon.config || '{}'))
: data.config;
this.db.run('UPDATE addons SET config = ? WHERE id = ?', JSON.stringify(configToStore), id);
}
} else {
if (data.enabled !== undefined)
this.db.run('UPDATE photo_providers SET enabled = ? WHERE id = ?', data.enabled ? 1 : 0, id);
}
});
const updatedAddon = this.db.get<Addon>('SELECT * FROM addons WHERE id = ?', id);
const updatedProvider = this.db.get<ProviderRow>('SELECT * FROM photo_providers WHERE id = ?', id);
const updated = updatedAddon
? {
...updatedAddon,
enabled: !!updatedAddon.enabled,
config:
updatedAddon.id === ADDON_IDS.LLM_PARSING
? maskLlmAddonConfig(JSON.parse(updatedAddon.config || '{}'))
: JSON.parse(updatedAddon.config || '{}'),
}
: updatedProvider
? {
id: updatedProvider.id,
name: updatedProvider.name,
description: updatedProvider.description,
type: 'photo_provider',
icon: updatedProvider.icon,
enabled: !!updatedProvider.enabled,
config: getPhotoProviderConfig(updatedProvider.id),
sort_order: updatedProvider.sort_order,
}
: null;
// Only these addons gate MCP tool/resource/prompt registration (see
// registerTools/registerResources) — and only a real enabled-flip changes
// what a session would register. Config-only saves, photo providers and
// MCP-irrelevant addons must not tear down every live session (#1414).
const MCP_RELEVANT_ADDONS = new Set<string>([
ADDON_IDS.MCP,
ADDON_IDS.PACKING,
ADDON_IDS.BUDGET,
ADDON_IDS.COLLAB,
ADDON_IDS.ATLAS,
ADDON_IDS.VACAY,
ADDON_IDS.JOURNEY,
]);
const enabledChanged = !!addon && data.enabled !== undefined && (data.enabled ? 1 : 0) !== addon.enabled;
return {
addon: updated,
mcpAffected: enabledChanged && MCP_RELEVANT_ADDONS.has(id),
auditDetails: {
enabled: data.enabled !== undefined ? !!data.enabled : undefined,
config_changed: data.config !== undefined,
},
};
}
// ── JWT Rotation ───────────────────────────────────────────────────────────
rotateJwtSecret(): { error?: string; status?: number } {
const newSecret = crypto.randomBytes(32).toString('hex');
// Re-anchored one directory deeper for nest/admin/ (was '../../data' in services/).
const dataDir = path.resolve(__dirname, '../../../data');
const secretFile = path.join(dataDir, '.jwt_secret');
try {
if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true });
fs.writeFileSync(secretFile, newSecret, { mode: 0o600 });
} catch {
return { error: 'Failed to persist new JWT secret to disk', status: 500 };
}
updateJwtSecret(newSecret);
return {};
}
invalidateMcpSessions() { invalidateMcpSessions(); }
// Settings + notification preference helpers (non-admin-service modules)
getAdminUserDefaults() { return getAdminUserDefaults(); }
setAdminUserDefaults(body: Record<string, unknown>) { return setAdminUserDefaults(body); }
getPreferencesMatrix(userId: number, role: string) { return getPreferencesMatrix(userId, role, 'admin'); }
setAdminPreferences(userId: number, body: unknown) { return setAdminPreferences(userId, body as Parameters<typeof setAdminPreferences>[1]); }
// ── Settings + notification preference helpers (non-admin-service modules) ──
}
+35
View File
@@ -0,0 +1,35 @@
import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
import { logInfo, logError } from '../audit/audit-log.logger';
import { RuntimeEnvService } from '../app-config/runtime-env.service';
import { CronRegistrarService } from '../scheduling/cron-registrar.service';
import { resetDemoUser } from '../../demo/demo-reset';
/**
* Demo mode: hourly reset of demo user data (moved from src/scheduler.ts).
* Gated on DEMO_MODE at bootstrap — parity: toggling it always required a
* restart — and scheduled in the server-local zone (the old cron.schedule call
* passed no timezone). demo-reset is a static import: its module top is
* side-effect-free, and the dangerous closeDb/reinitialize sequence stays
* inside resetDemoUser, called at tick time.
*/
@Injectable()
export class DemoResetJob implements OnApplicationBootstrap {
constructor(
private readonly runtimeEnv: RuntimeEnvService,
private readonly registrar: CronRegistrarService,
) {}
onApplicationBootstrap(): void {
if (!this.registrar.isEnabled() || !this.runtimeEnv.isDemoMode()) return;
this.registrar.register('demo-reset', '0 * * * *', () => this.tick(), { timezone: 'none' });
logInfo('Demo hourly reset scheduled');
}
tick(): void {
try {
resetDemoUser();
} catch (err: unknown) {
logError(`Demo reset: ${err instanceof Error ? err.message : err}`);
}
}
}
@@ -0,0 +1,38 @@
import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
import { logError } from '../audit/audit-log.logger';
import { AdminService } from './admin.service';
import { CronRegistrarService } from '../scheduling/cron-registrar.service';
import { RuntimeEnvService } from '../app-config/runtime-env.service';
/**
* Daily version check (moved from src/scheduler.ts — it was the only consumer
* of the old admin bridge, which died with the move). checkAndNotifyVersion
* shares the module-scoped 5-minute cache in admin.helpers.ts with
* GET /api/admin/version-check, so the cron and the route hit GitHub once
* between them. No boot log — parity with the old starter.
*/
@Injectable()
export class VersionCheckJob implements OnApplicationBootstrap {
constructor(
private readonly admin: AdminService,
private readonly registrar: CronRegistrarService,
private readonly env: RuntimeEnvService,
) {}
onApplicationBootstrap(): void {
if (!this.registrar.isEnabled()) return;
// A centrally administered install never registers it. The upgrade schedule
// is the operator's, so the daily call to github.com would only ever produce
// a notification telling the admin to do something they cannot do.
if (this.env.isManaged()) return;
this.registrar.register('version-check', '0 9 * * *', () => this.tick());
}
async tick(): Promise<void> {
try {
await this.admin.checkAndNotifyVersion();
} catch (err: unknown) {
logError(`Version check: ${err instanceof Error ? err.message : err}`);
}
}
}
+71
View File
@@ -0,0 +1,71 @@
import fs from 'node:fs';
import path from 'node:path';
/**
* The bundled airport dataset — a JSON file read once and kept in memory.
*
* Free functions rather than a provider: nothing here touches the database, and
* the two MCP registrars (mcp/tools/mapsWeather.ts, mcp/tools/transports.ts)
* call them from outside the container. AirportsService is the in-container
* face; the DB-touching backfill lives there.
*/
export interface Airport {
iata: string;
icao: string | null;
name: string;
city: string;
country: string;
lat: number;
lng: number;
tz: string;
}
let cache: Airport[] | null = null;
let byIata: Map<string, Airport> | null = null;
export function load(): Airport[] {
if (cache) return cache;
const file = path.join(__dirname, '..', '..', '..', 'assets', 'airports.json');
if (!fs.existsSync(file)) {
console.warn('[airports] airports.json missing — run `node scripts/build-airports.mjs`');
cache = [];
byIata = new Map();
return cache;
}
const raw = fs.readFileSync(file, 'utf8');
cache = JSON.parse(raw) as Airport[];
byIata = new Map(cache.map(a => [a.iata, a]));
return cache;
}
export function findByIata(code: string): Airport | null {
load();
return byIata!.get(code.toUpperCase()) ?? null;
}
export function searchAirports(query: string, limit = 12): Airport[] {
const all = load();
const q = query.trim().toLowerCase();
if (!q) return [];
const upper = q.toUpperCase();
if (q.length === 3) {
const exact = byIata!.get(upper);
if (exact) return [exact];
}
const matches: Array<{ a: Airport; score: number }> = [];
for (const a of all) {
let score = 0;
if (a.iata === upper) score = 100;
else if (a.icao === upper) score = 90;
else if (a.iata.startsWith(upper)) score = 70;
else if (a.city.toLowerCase().startsWith(q)) score = 60;
else if (a.name.toLowerCase().startsWith(q)) score = 50;
else if (a.city.toLowerCase().includes(q)) score = 30;
else if (a.name.toLowerCase().includes(q)) score = 20;
if (score > 0) matches.push({ a, score });
}
matches.sort((x, y) => y.score - x.score || x.a.iata.localeCompare(y.a.iata));
return matches.slice(0, limit).map(m => m.a);
}
+46
View File
@@ -0,0 +1,46 @@
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, ok, type McpContext } from '../../nest-mcp';
import { z } from 'zod';
import { findByIata, searchAirports } from './airports.data';
/**
* Airport lookup MCP tools, moved 1:1 from the legacy registrar in
* src/mcp/tools/mapsWeather.ts. Same names, descriptions, input schemas and
* result shapes; the registration-time `canRead(scopes, 'geo')` gate became the
* declarative `access` marker, matching maps.mcp.ts.
*
* No injected service: the airport table is a static dataset loaded once by
* airports.data.ts. AirportsService owns the flight-endpoint backfill against
* the database, which these two tools never touch.
*/
@McpController()
export class AirportsMcp {
@Tool({
name: 'search_airports',
description: 'Search for airports by name, city, or IATA code. Returns matching airports with IATA code, name, city, country, coordinates, and timezone. Use before create_transport (flight) to get the correct IATA code and timezone for endpoints.',
inputSchema: {
query: z.string().min(1).max(200).describe('Airport name, city, or IATA code (e.g. "zurich", "ZRH", "charles de gaulle")'),
limit: z.number().int().min(1).max(50).optional().default(10),
},
annotations: TOOL_ANNOTATIONS_READONLY,
access: { group: 'geo', mode: 'read' },
})
searchAirports({ query, limit }: { query: string; limit?: number }, _ctx: McpContext) {
const airports = searchAirports(query, limit ?? 10);
return ok({ airports });
}
@Tool({
name: 'get_airport',
description: 'Get a single airport by its IATA code. Returns name, city, country, coordinates, and timezone.',
inputSchema: {
iata: z.string().length(3).toUpperCase().describe('IATA airport code (e.g. "ZRH", "AMS", "CDG")'),
},
annotations: TOOL_ANNOTATIONS_READONLY,
access: { group: 'geo', mode: 'read' },
})
getAirport({ iata }: { iata: string }, _ctx: McpContext) {
const airport = findByIata(iata);
if (!airport) return { content: [{ type: 'text' as const, text: 'Airport not found.' }], isError: true };
return ok({ airport });
}
}
+8 -2
View File
@@ -1,10 +1,16 @@
import { Module } from '@nestjs/common';
import { AirportsController } from './airports.controller';
import { AirportsService } from './airports.service';
import { DatabaseModule } from '../database/database.module';
import { AirportsMcp } from './airports.mcp';
/** Airports domain (L2 leaf module). Registered in AppModule. */
/** Airports domain (L2 leaf module). Registered in AppModule.
* DatabaseModule is imported explicitly: the flight-endpoint backfill needs the
* connection, and @Global only reaches modules that are in the graph — which
* the airports e2e TestingModule is not. */
@Module({
imports: [DatabaseModule],
controllers: [AirportsController],
providers: [AirportsService],
providers: [AirportsService, AirportsMcp],
})
export class AirportsModule {}
+66 -6
View File
@@ -1,14 +1,29 @@
import { Injectable } from '@nestjs/common';
import { Injectable, OnApplicationBootstrap } from '@nestjs/common';
import type { Airport } from '@trek/shared';
import { searchAirports, findByIata } from '../../services/airportService';
import { searchAirports, findByIata, load } from './airports.data';
import { DatabaseService } from '../database/database.service';
/**
* Thin Nest wrapper around the existing airport service. It delegates to the
* same `searchAirports` / `findByIata` functions the legacy route uses, so the
* in-memory dataset and lookup behaviour stay identical and unduplicated.
* The in-container face of the airport dataset, plus the flight-endpoint
* backfill that needs the database.
*
* The backfill used to run from db/database.ts at module load, through a
* require() back into services/ — a cycle that only held because `db` happened
* to be initialised by then. It runs on application bootstrap now: it repairs
* rows, nothing boots on it, and the container is fully built by that point.
*/
@Injectable()
export class AirportsService {
export class AirportsService implements OnApplicationBootstrap {
constructor(private readonly db: DatabaseService) {}
onApplicationBootstrap(): void {
try {
this.backfillFlightEndpoints();
} catch (err) {
console.error('[DB] Flight endpoint backfill failed:', err);
}
}
search(query: string): Airport[] {
return searchAirports(query) as Airport[];
}
@@ -16,4 +31,49 @@ export class AirportsService {
findByIata(code: string): Airport | null {
return findByIata(code) as Airport | null;
}
backfillFlightEndpoints(): void {
const pending = this.db.prepare(`
SELECT r.id, r.metadata, r.reservation_time, r.reservation_end_time
FROM reservations r
WHERE r.type = 'flight'
AND NOT EXISTS (SELECT 1 FROM reservation_endpoints e WHERE e.reservation_id = r.id)
`).all() as { id: number; metadata: string | null; reservation_time: string | null; reservation_end_time: string | null }[];
if (pending.length === 0) return;
load();
const insert = this.db.prepare(`
INSERT INTO reservation_endpoints (reservation_id, role, sequence, name, code, lat, lng, timezone, local_time, local_date)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
const markReview = this.db.prepare('UPDATE reservations SET needs_review = 1 WHERE id = ?');
let filled = 0;
let flagged = 0;
for (const r of pending) {
if (!r.metadata) { markReview.run(r.id); flagged++; continue; }
let meta: any;
try { meta = JSON.parse(r.metadata); } catch { markReview.run(r.id); flagged++; continue; }
const dep = meta.departure_airport ? findByIata(String(meta.departure_airport).slice(0, 3)) : null;
const arr = meta.arrival_airport ? findByIata(String(meta.arrival_airport).slice(0, 3)) : null;
if (!dep || !arr) { markReview.run(r.id); flagged++; continue; }
const split = (iso: string | null) => {
if (!iso) return { date: null as string | null, time: null as string | null };
const [date, time] = iso.split('T');
return { date: date || null, time: time ? time.slice(0, 5) : null };
};
const depParts = split(r.reservation_time);
const arrParts = split(r.reservation_end_time);
insert.run(r.id, 'from', 0, dep.city ? `${dep.city} (${dep.iata})` : dep.name, dep.iata, dep.lat, dep.lng, dep.tz, depParts.time, depParts.date);
insert.run(r.id, 'to', 1, arr.city ? `${arr.city} (${arr.iata})` : arr.name, arr.iata, arr.lat, arr.lng, arr.tz, arrParts.time, arrParts.date);
filled++;
}
console.log(`[airports] Backfill: ${filled} filled, ${flagged} flagged for review`);
}
}
@@ -0,0 +1,38 @@
/**
* Global binding of @nestjs/config onto TREK's app-config layer.
*
* INVARIANTS — breaking either silently breaks ~60 env-mutating tests:
* - `cache: false`, always. `cache: true` would freeze ConfigService lookups
* for the whole app lifetime; the runtime-toggled vars (DEMO_MODE, NODE_ENV,
* OIDC_*, …) must stay live via RuntimeEnvService/readEnv().
* - No `validate`/`validationSchema` here. Fail-fast validation runs exactly
* once, from the production entrypoint (src/app-config/boot-validate.ts) —
* buildApp() is invoked dozens of times per test run and must stay
* side-effect-free.
* - `ignoreEnvFile: true`, always. dotenv is loaded ONCE in index.ts; tests
* deliberately never load .env, and reading it here would leak a
* developer's local server/.env into every integration test.
*
* The framework's ConfigModule is aliased ONLY inside this file: app.module.ts
* already imports a local `ConfigModule` (the /api/config endpoint module), so
* the alias keeps the two from colliding anywhere else.
*/
import { Global, Module } from '@nestjs/common';
import { ConfigModule as NestConfigModule } from '@nestjs/config';
import { BOOT_STABLE_TOKENS } from './tokens';
import { RuntimeEnvService } from './runtime-env.service';
@Global()
@Module({
imports: [
NestConfigModule.forRoot({
isGlobal: true,
ignoreEnvFile: true,
cache: false,
load: BOOT_STABLE_TOKENS,
}),
],
providers: [RuntimeEnvService],
exports: [RuntimeEnvService],
})
export class AppConfigModule {}
+13
View File
@@ -0,0 +1,13 @@
export { AppConfigModule } from './app-config.module';
export { RuntimeEnvService } from './runtime-env.service';
export {
httpConfig,
sessionConfig,
mcpConfig,
integrationsConfig,
backupConfig,
dbConfig,
pathsConfig,
netConfig,
BOOT_STABLE_TOKENS,
} from './tokens';
@@ -0,0 +1,58 @@
import { Injectable } from '@nestjs/common';
import { readEnv, type AppEnv } from '../../app-config';
/**
* DI-friendly access to the RUNTIME-TOGGLED env values (DEMO_MODE, NODE_ENV,
* APP_VERSION, OIDC_*, …). Every method delegates to readEnv() at call time —
* never snapshot a namespace into a field or the constructor, or the ~60 tests
* that mutate process.env mid-lifetime break.
*
* Boot-stable values are NOT accessed through this service; inject their
* registerAs token instead (see tokens.ts).
*/
@Injectable()
export class RuntimeEnvService {
/** The full live-derived env — prefer the convenience getters where one exists. */
env(): AppEnv {
return readEnv();
}
isDemoMode(): boolean {
return readEnv().demo.enabled;
}
/**
* True when somebody other than this instance's admin owns its configuration.
* Runtime-toggled like DEMO_MODE, so never cache the result in a field.
*/
isManaged(): boolean {
return readEnv().managed.enabled;
}
/** True only under exactly NODE_ENV='test' (case-sensitive, like the :memory: DB pick). */
isTest(): boolean {
return readEnv().app.isTest;
}
nodeEnv(): string | undefined {
return readEnv().app.nodeEnv;
}
isProduction(): boolean {
return readEnv().app.isProduction;
}
isDevelopment(): boolean {
return readEnv().app.isDevelopment;
}
/** Raw APP_VERSION — call sites keep their own fallback ('0.0.0' vs package.json vs semver). */
appVersion(): string | undefined {
return readEnv().app.appVersion;
}
/** Raw APP_URL — call sites keep their own trailing-slash handling. */
appUrl(): string | undefined {
return readEnv().app.appUrl;
}
}
+57
View File
@@ -0,0 +1,57 @@
/**
* registerAs tokens over the app-config derive functions, for the BOOT-STABLE
* namespaces only (see src/app-config/README.md for the classification).
*
* A token's factory runs during NestFactory.create(), so the injected object is
* a SNAPSHOT per built app — integration tests that mutate env and then rebuild
* buildApp() get fresh values automatically. Runtime-toggled values (DEMO_MODE,
* NODE_ENV, OIDC_*, …) must NOT get tokens here; they go through
* RuntimeEnvService / readEnv() so mid-lifetime env mutations stay visible.
*
* Consumption pattern:
* constructor(@Inject(httpConfig.KEY) private readonly http: ConfigType<typeof httpConfig>) {}
*
* NOTE: today only httpConfig has a DI consumer (bootstrap.ts threads it into
* the pre-init middleware); the migrated call sites otherwise read through
* readEnv() because they live in classes whose unit tests instantiate them
* directly. The full token set is provisioned deliberately — it is the
* sanctioned pattern for NEW Nest consumers of boot-stable config, not dead
* scaffolding to prune.
*/
import { registerAs } from '@nestjs/config';
import {
deriveBackup,
deriveDb,
deriveHttp,
deriveIntegrations,
deriveMcp,
deriveNet,
derivePaths,
deriveSession,
} from '../../app-config';
/**
* http is snapshot-consumed only by the pre-init Express layer (bootstrap
* threads it into applyGlobalMiddleware) — apply-time freeze per built app.
* Request-time reads of the same vars (cookie.ts FORCE_HTTPS checks) stay live
* via readEnv().
*/
export const httpConfig = registerAs('http', () => deriveHttp(process.env));
export const sessionConfig = registerAs('session', () => deriveSession(process.env));
export const mcpConfig = registerAs('mcp', () => deriveMcp(process.env));
export const integrationsConfig = registerAs('integrations', () => deriveIntegrations(process.env));
export const backupConfig = registerAs('backup', () => deriveBackup(process.env));
export const dbConfig = registerAs('db', () => deriveDb(process.env));
export const pathsConfig = registerAs('paths', () => derivePaths(process.env));
export const netConfig = registerAs('net', () => deriveNet(process.env));
export const BOOT_STABLE_TOKENS = [
httpConfig,
sessionConfig,
mcpConfig,
integrationsConfig,
backupConfig,
dbConfig,
pathsConfig,
netConfig,
];
+52 -8
View File
@@ -1,14 +1,24 @@
import { Module } from '@nestjs/common';
import { APP_FILTER, APP_INTERCEPTOR } from '@nestjs/core';
import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
import { ZodValidationPipe } from './common/zod-validation.pipe';
import { AppConfigModule } from './app-config/app-config.module';
import { DatabaseModule } from './database/database.module';
import { HealthController } from './health/health.controller';
import { HealthService } from './health/health.service';
import { RealtimeModule } from './realtime/realtime.module';
import { HealthModule } from './health/health.module';
import { PlatformModule } from './platform/platform.module';
import { McpTransportModule } from './mcp-transport/mcp-transport.module';
import { GlobalAuthGuard } from './auth/global-auth.guard';
import { MfaPolicyGuard } from './auth/mfa-policy.guard';
import { ManagedGuard } from './common/managed.guard';
import { WeatherModule } from './weather/weather.module';
import { HelpModule } from './help/help.module';
import { AirportsModule } from './airports/airports.module';
import { ConfigModule } from './config/config.module';
import { SystemNoticesModule } from './system-notices/system-notices.module';
import { ManagedExtModule } from './managed/managed-ext.module';
import { MapsModule } from './maps/maps.module';
import { GeoModule } from './geo/geo.module';
import { PlaceEnrichmentModule } from './place-enrichment/place-enrichment.module';
import { CategoriesModule } from './categories/categories.module';
import { TagsModule } from './tags/tags.module';
import { NotificationsModule } from './notifications/notifications.module';
@@ -18,6 +28,8 @@ import { PackingModule } from './packing/packing.module';
import { BudgetModule } from './budget/budget.module';
import { ReservationsModule } from './reservations/reservations.module';
import { DaysModule } from './days/days.module';
import { DayNotesModule } from './day-notes/day-notes.module';
import { AccommodationsModule } from './accommodations/accommodations.module';
import { AssignmentsModule } from './assignments/assignments.module';
import { PlacesModule } from './places/places.module';
import { TripsModule } from './trips/trips.module';
@@ -34,17 +46,28 @@ import { TripInviteModule } from './trip-invite/trip-invite.module';
import { TransitModule } from './transit/transit.module';
import { FeedsModule } from './feeds/feeds.module';
import { SettingsModule } from './settings/settings.module';
import { StorageModule } from './storage/storage.module';
import { BackupModule } from './backup/backup.module';
import { BookingImportModule } from './booking-import/booking-import.module';
import { ReservationImportModule } from './reservation-import/reservation-import.module';
import { LlmParseModule } from './llm-parse/llm-parse.module';
import { AuthModule } from './auth/auth.module';
import { OidcModule } from './oidc/oidc.module';
import { OauthModule } from './oauth/oauth.module';
import { AdminModule } from './admin/admin.module';
import { AddonsModule } from './addons/addons.module';
import { AuditModule } from './audit/audit.module';
import { PermissionsModule } from './permissions/permissions.module';
import { PluginsModule } from './plugins/plugins.module';
import { SchedulingModule } from './scheduling/scheduling.module';
import { McpModule } from '../nest-mcp';
import { trekMcpAccessPolicy, trekMcpValidateAccess } from '../mcp/nest-mcp-policy';
import { TrekExceptionFilter } from './common/trek-exception.filter';
import { SpaFallbackFilter } from './platform/spa-fallback.filter';
import { IdempotencyInterceptor } from './common/idempotency.interceptor';
import { SessionRenewalInterceptor } from './auth/session-renewal.interceptor';
import { IdempotencyCleanupJob } from './common/idempotency-cleanup.job';
import { RealtimeGatewayModule } from './realtime/realtime-gateway.module';
/**
* Root NestJS module for the incremental migration. Domain modules
@@ -52,10 +75,20 @@ import { IdempotencyInterceptor } from './common/idempotency.interceptor';
* migrated.
*/
@Module({
imports: [DatabaseModule, WeatherModule, HelpModule, AirportsModule, ConfigModule, SystemNoticesModule, MapsModule, CategoriesModule, TagsModule, NotificationsModule, AtlasModule, VacayModule, PackingModule, TodoModule, BudgetModule, ReservationsModule, DaysModule, AssignmentsModule, PlacesModule, TripsModule, CollabModule, FilesModule, PhotosModule, MemoriesModule, AirtrailModule, JourneyModule, CollectionsModule, ShareModule, TripInviteModule, TransitModule, FeedsModule, SettingsModule, BackupModule, AuthModule, OidcModule, OauthModule, AdminModule, AddonsModule, PluginsModule, BookingImportModule],
controllers: [HealthController],
imports: [AppConfigModule, DatabaseModule, RealtimeModule, RealtimeGatewayModule, SchedulingModule, McpModule.forRoot({ accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess }), HealthModule, PlatformModule, McpTransportModule, WeatherModule, HelpModule, AirportsModule, ConfigModule, SystemNoticesModule, GeoModule, MapsModule, PlaceEnrichmentModule, CategoriesModule, TagsModule, NotificationsModule, AtlasModule, VacayModule, PackingModule, TodoModule, BudgetModule, ReservationsModule, DaysModule, DayNotesModule, AccommodationsModule, AssignmentsModule, PlacesModule, TripsModule, CollabModule, FilesModule, PhotosModule, MemoriesModule, AirtrailModule, JourneyModule, CollectionsModule, ShareModule, TripInviteModule, TransitModule, FeedsModule, SettingsModule, StorageModule, BackupModule, AuthModule, OidcModule, OauthModule, AdminModule, AddonsModule, AuditModule, PermissionsModule, PluginsModule, BookingImportModule, ReservationImportModule, LlmParseModule, ManagedExtModule],
providers: [
HealthService,
// Default-deny: a route is authenticated unless it carries @Public() or
// @OptionalAuth(), or declares its own @UseGuards chain. Protection used to
// be opt-in, which made a forgotten guard a silent bypass instead of an error.
{ provide: APP_GUARD, useClass: GlobalAuthGuard },
// Second, and only second: it reads the user the guard above resolved
// instead of verifying the token a second time, which is what the Express
// middleware it replaces did on every /api request.
{ provide: APP_GUARD, useClass: MfaPolicyGuard },
// Third, and only third: a stranger gets the 401 the two above would have
// given them rather than a 403 that confirms the route exists. Inert unless
// the instance is centrally administered AND the route carries the marker.
{ provide: APP_GUARD, useClass: ManagedGuard },
// Global error-envelope normaliser (DI-registered so it also catches
// framework-level exceptions like the not-found handler).
{ provide: APP_FILTER, useClass: TrekExceptionFilter },
@@ -63,9 +96,20 @@ import { IdempotencyInterceptor } from './common/idempotency.interceptor';
// equivalent of the legacy Express app.get('*') catch-all). @Catch(NotFoundException)
// is more specific than TrekExceptionFilter, so Nest routes 404s here.
{ provide: APP_FILTER, useClass: SpaFallbackFilter },
// Replays the X-Idempotency-Key the client sends on every write, matching
// the legacy applyIdempotency middleware so retried mutations don't double-apply.
// Replays the X-Idempotency-Key the client sends on every write, so retried
// mutations don't double-apply.
{ provide: APP_INTERCEPTOR, useClass: IdempotencyInterceptor },
// Sliding session renewal: re-issues the trek_session cookie once a
// cookie-authenticated token is past half its lifetime (#1927).
{ provide: APP_INTERCEPTOR, useClass: SessionRenewalInterceptor },
// Its nightly TTL purge — a provider here because common/ has no module.
IdempotencyCleanupJob,
// Global Zod validation: any parameter typed with a createZodDto class
// (the <domain>.dto.ts wrappers over @trek/shared schemas) is validated;
// everything else passes through untouched. Paired with the boot gate in
// common/validate-body-contracts.ts so unvalidated mutation bodies refuse
// to boot instead of shipping silently.
{ provide: APP_PIPE, useClass: ZodValidationPipe },
],
})
export class AppModule {}

Some files were not shown because too many files have changed in this diff Show More