Leon4gr45 commited on
Commit
57a889c
·
verified ·
1 Parent(s): 2515b86

Upload folder using huggingface_hub (part 5)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. server/node_modules/supports-color/package.json +53 -0
  2. server/node_modules/supports-color/readme.md +76 -0
  3. server/package.json +107 -0
  4. server/public/.gitkeep +0 -0
  5. server/reset-admin.js +21 -0
  6. server/scripts/build-airports.mjs +108 -0
  7. server/scripts/build-atlas-geo.mjs +225 -0
  8. server/scripts/build.mjs +9 -0
  9. server/scripts/dev.mjs +32 -0
  10. server/scripts/migrate-encryption.ts +329 -0
  11. server/src/addons.ts +13 -0
  12. server/src/bootstrap.ts +55 -0
  13. server/src/config.ts +156 -0
  14. server/src/db/database.ts +153 -0
  15. server/src/db/migrations.ts +0 -0
  16. server/src/db/schema.ts +508 -0
  17. server/src/db/seeds.ts +152 -0
  18. server/src/demo/demo-reset.ts +85 -0
  19. server/src/demo/demo-seed.ts +279 -0
  20. server/src/index.ts +133 -0
  21. server/src/mcp/index.ts +351 -0
  22. server/src/mcp/oauthProvider.ts +221 -0
  23. server/src/mcp/resources.ts +442 -0
  24. server/src/mcp/scopes.ts +119 -0
  25. server/src/mcp/sessionManager.ts +41 -0
  26. server/src/mcp/tools.ts +54 -0
  27. server/src/mcp/tools/_shared.ts +71 -0
  28. server/src/mcp/tools/assignments.ts +189 -0
  29. server/src/mcp/tools/atlas.ts +197 -0
  30. server/src/mcp/tools/budget.ts +180 -0
  31. server/src/mcp/tools/collab.ts +285 -0
  32. server/src/mcp/tools/days.ts +294 -0
  33. server/src/mcp/tools/journey.ts +422 -0
  34. server/src/mcp/tools/mapsWeather.ts +148 -0
  35. server/src/mcp/tools/notifications.ts +99 -0
  36. server/src/mcp/tools/packing.ts +347 -0
  37. server/src/mcp/tools/places.ts +269 -0
  38. server/src/mcp/tools/prompts.ts +138 -0
  39. server/src/mcp/tools/reservations.ts +227 -0
  40. server/src/mcp/tools/tags.ts +84 -0
  41. server/src/mcp/tools/todos.ts +199 -0
  42. server/src/mcp/tools/transports.ts +177 -0
  43. server/src/mcp/tools/trips.ts +381 -0
  44. server/src/mcp/tools/vacay.ts +398 -0
  45. server/src/middleware/auth.ts +119 -0
  46. server/src/middleware/globalMiddleware.ts +165 -0
  47. server/src/middleware/idempotency.ts +80 -0
  48. server/src/middleware/mfaPolicy.ts +111 -0
  49. server/src/middleware/tripAccess.ts +37 -0
  50. server/src/middleware/validate.ts +26 -0
server/node_modules/supports-color/package.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "supports-color",
3
+ "version": "7.2.0",
4
+ "description": "Detect whether a terminal supports color",
5
+ "license": "MIT",
6
+ "repository": "chalk/supports-color",
7
+ "author": {
8
+ "name": "Sindre Sorhus",
9
+ "email": "sindresorhus@gmail.com",
10
+ "url": "sindresorhus.com"
11
+ },
12
+ "engines": {
13
+ "node": ">=8"
14
+ },
15
+ "scripts": {
16
+ "test": "xo && ava"
17
+ },
18
+ "files": [
19
+ "index.js",
20
+ "browser.js"
21
+ ],
22
+ "keywords": [
23
+ "color",
24
+ "colour",
25
+ "colors",
26
+ "terminal",
27
+ "console",
28
+ "cli",
29
+ "ansi",
30
+ "styles",
31
+ "tty",
32
+ "rgb",
33
+ "256",
34
+ "shell",
35
+ "xterm",
36
+ "command-line",
37
+ "support",
38
+ "supports",
39
+ "capability",
40
+ "detect",
41
+ "truecolor",
42
+ "16m"
43
+ ],
44
+ "dependencies": {
45
+ "has-flag": "^4.0.0"
46
+ },
47
+ "devDependencies": {
48
+ "ava": "^1.4.1",
49
+ "import-fresh": "^3.0.0",
50
+ "xo": "^0.24.0"
51
+ },
52
+ "browser": "browser.js"
53
+ }
server/node_modules/supports-color/readme.md ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # supports-color [![Build Status](https://travis-ci.org/chalk/supports-color.svg?branch=master)](https://travis-ci.org/chalk/supports-color)
2
+
3
+ > Detect whether a terminal supports color
4
+
5
+
6
+ ## Install
7
+
8
+ ```
9
+ $ npm install supports-color
10
+ ```
11
+
12
+
13
+ ## Usage
14
+
15
+ ```js
16
+ const supportsColor = require('supports-color');
17
+
18
+ if (supportsColor.stdout) {
19
+ console.log('Terminal stdout supports color');
20
+ }
21
+
22
+ if (supportsColor.stdout.has256) {
23
+ console.log('Terminal stdout supports 256 colors');
24
+ }
25
+
26
+ if (supportsColor.stderr.has16m) {
27
+ console.log('Terminal stderr supports 16 million colors (truecolor)');
28
+ }
29
+ ```
30
+
31
+
32
+ ## API
33
+
34
+ Returns an `Object` with a `stdout` and `stderr` property for testing either streams. Each property is an `Object`, or `false` if color is not supported.
35
+
36
+ The `stdout`/`stderr` objects specifies a level of support for color through a `.level` property and a corresponding flag:
37
+
38
+ - `.level = 1` and `.hasBasic = true`: Basic color support (16 colors)
39
+ - `.level = 2` and `.has256 = true`: 256 color support
40
+ - `.level = 3` and `.has16m = true`: Truecolor support (16 million colors)
41
+
42
+
43
+ ## Info
44
+
45
+ It obeys the `--color` and `--no-color` CLI flags.
46
+
47
+ For situations where using `--color` is not possible, use the environment variable `FORCE_COLOR=1` (level 1), `FORCE_COLOR=2` (level 2), or `FORCE_COLOR=3` (level 3) to forcefully enable color, or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks.
48
+
49
+ Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively.
50
+
51
+
52
+ ## Related
53
+
54
+ - [supports-color-cli](https://github.com/chalk/supports-color-cli) - CLI for this module
55
+ - [chalk](https://github.com/chalk/chalk) - Terminal string styling done right
56
+
57
+
58
+ ## Maintainers
59
+
60
+ - [Sindre Sorhus](https://github.com/sindresorhus)
61
+ - [Josh Junon](https://github.com/qix-)
62
+
63
+
64
+ ---
65
+
66
+ <div align="center">
67
+ <b>
68
+ <a href="https://tidelift.com/subscription/pkg/npm-supports-color?utm_source=npm-supports-color&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
69
+ </b>
70
+ <br>
71
+ <sub>
72
+ Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
73
+ </sub>
74
+ </div>
75
+
76
+ ---
server/package.json ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "@trek/server",
3
+ "version": "3.1.0",
4
+ "main": "src/index.ts",
5
+ "scripts": {
6
+ "start": "node --require tsconfig-paths/register dist/index.js",
7
+ "dev": "node scripts/dev.mjs",
8
+ "build": "node scripts/build.mjs",
9
+ "start:prod": "node --require tsconfig-paths/register dist/index.js",
10
+ "typecheck": "tsc --noEmit",
11
+ "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
12
+ "format:check": "prettier --check \"src/**/*.ts\" \"test/**/*.ts\"",
13
+ "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
14
+ "lint:check": "eslint .",
15
+ "test": "vitest run",
16
+ "test:watch": "vitest",
17
+ "test:unit": "vitest run tests/unit",
18
+ "test:integration": "vitest run tests/integration",
19
+ "test:ws": "vitest run tests/websocket",
20
+ "test:e2e": "vitest run tests/e2e",
21
+ "test:coverage": "vitest run --coverage"
22
+ },
23
+ "dependencies": {
24
+ "@modelcontextprotocol/sdk": "^1.28.0",
25
+ "@nestjs/common": "^11.1.24",
26
+ "@nestjs/core": "^11.1.24",
27
+ "@nestjs/platform-express": "^11.1.24",
28
+ "@nestjs/swagger": "^11.4.5",
29
+ "@simplewebauthn/server": "^13.1.2",
30
+ "@trek/shared": "*",
31
+ "archiver": "^6.0.1",
32
+ "bcryptjs": "^2.4.3",
33
+ "better-sqlite3": "^12.8.0",
34
+ "cookie-parser": "^1.4.7",
35
+ "cors": "^2.8.5",
36
+ "dotenv": "^16.4.1",
37
+ "express": "^4.18.3",
38
+ "fast-xml-parser": "^5.5.10",
39
+ "helmet": "^8.1.0",
40
+ "jimp": "^1.6.1",
41
+ "jsonwebtoken": "^9.0.2",
42
+ "multer": "^2.1.1",
43
+ "node-cron": "^4.2.1",
44
+ "nodemailer": "^8.0.5",
45
+ "otplib": "^12.0.1",
46
+ "qrcode": "^1.5.4",
47
+ "reflect-metadata": "^0.2.2",
48
+ "rxjs": "^7.8.2",
49
+ "semver": "^7.7.4",
50
+ "swagger-ui-express": "^5.0.1",
51
+ "tsconfig-paths": "^4.2.0",
52
+ "tsx": "^4.21.0",
53
+ "typescript": "^6.0.2",
54
+ "undici": "^7.0.0",
55
+ "unzipper": "^0.12.3",
56
+ "uuid": "^14.0.0",
57
+ "ws": "^8.21.0",
58
+ "zod": "^4.3.6"
59
+ },
60
+ "overrides": {
61
+ "hono": "^4.12.16",
62
+ "@hono/node-server": "^1.19.13",
63
+ "picomatch": "^4.0.4",
64
+ "ip-address": "^10.1.1",
65
+ "multer": "^2.1.1",
66
+ "ws": "^8.21.0",
67
+ "qs": "^6.15.2",
68
+ "file-type": "^21.3.4"
69
+ },
70
+ "devDependencies": {
71
+ "@eslint/js": "^10.0.1",
72
+ "@nestjs/testing": "^11.1.24",
73
+ "@swc/core": "^1.15.40",
74
+ "@trivago/prettier-plugin-sort-imports": "^6.0.2",
75
+ "@types/archiver": "^7.0.0",
76
+ "@types/bcryptjs": "^2.4.6",
77
+ "@types/better-sqlite3": "^7.6.13",
78
+ "@types/cookie-parser": "^1.4.10",
79
+ "@types/cors": "^2.8.19",
80
+ "@types/express": "^4.17.25",
81
+ "@types/jsonwebtoken": "^9.0.10",
82
+ "@types/multer": "^2.1.0",
83
+ "@types/node": "^25.5.0",
84
+ "@types/node-cron": "^3.0.11",
85
+ "@types/nodemailer": "^7.0.11",
86
+ "@types/qrcode": "^1.5.5",
87
+ "@types/semver": "^7.7.1",
88
+ "@types/supertest": "^6.0.3",
89
+ "@types/unzipper": "^0.10.11",
90
+ "@types/uuid": "^10.0.0",
91
+ "@types/ws": "^8.18.1",
92
+ "@vitest/coverage-istanbul": "^4.1.9",
93
+ "@vitest/coverage-v8": "^4.1.9",
94
+ "eslint": "^9.18.0",
95
+ "eslint-config-flat-gitignore": "^2.3.0",
96
+ "eslint-config-prettier": "^10.0.1",
97
+ "eslint-plugin-prettier": "^5.2.2",
98
+ "nodemon": "^3.1.0",
99
+ "prettier": "^3.8.3",
100
+ "prettier-plugin-organize-imports": "^4.3.0",
101
+ "supertest": "^7.2.2",
102
+ "typescript-eslint": "^8.58.2",
103
+ "tz-lookup": "^6.1.25",
104
+ "unplugin-swc": "^1.5.9",
105
+ "vitest": "^4.1.9"
106
+ }
107
+ }
server/public/.gitkeep ADDED
File without changes
server/reset-admin.js ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const path = require('path');
2
+ const Database = require('better-sqlite3');
3
+ const bcrypt = require('bcryptjs');
4
+
5
+ const dbPath = path.join(__dirname, 'data/travel.db');
6
+ const db = new Database(dbPath);
7
+
8
+ const hash = bcrypt.hashSync('admin123', 10);
9
+ const existing = db.prepare('SELECT id FROM users WHERE email = ?').get('admin@admin.com');
10
+
11
+ if (existing) {
12
+ db.prepare('UPDATE users SET password_hash = ?, role = ? WHERE email = ?')
13
+ .run(hash, 'admin', 'admin@admin.com');
14
+ console.log('✓ Admin-Passwort zurückgesetzt: admin@admin.com / admin123');
15
+ } else {
16
+ db.prepare('INSERT INTO users (username, email, password_hash, role) VALUES (?, ?, ?, ?)')
17
+ .run('admin', 'admin@admin.com', hash, 'admin');
18
+ console.log('✓ Admin-User erstellt: admin@admin.com / admin123');
19
+ }
20
+
21
+ db.close();
server/scripts/build-airports.mjs ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env node
2
+ // Build server/assets/airports.json from OurAirports (davidmegginson.github.io/ourairports-data).
3
+ // License: Public Domain. Keeps large/medium airports with an IATA code; timezone derived from coords via tz-lookup.
4
+
5
+ import fs from 'node:fs'
6
+ import path from 'node:path'
7
+ import https from 'node:https'
8
+ import { fileURLToPath } from 'node:url'
9
+ import tzLookup from 'tz-lookup'
10
+
11
+ const __dirname = path.dirname(fileURLToPath(import.meta.url))
12
+ const OUT = path.join(__dirname, '..', 'assets', 'airports.json')
13
+ const SRC = 'https://davidmegginson.github.io/ourairports-data/airports.csv'
14
+
15
+ function fetchText(url) {
16
+ return new Promise((resolve, reject) => {
17
+ https.get(url, (res) => {
18
+ if (res.statusCode !== 200) return reject(new Error(`HTTP ${res.statusCode}`))
19
+ let data = ''
20
+ res.setEncoding('utf8')
21
+ res.on('data', chunk => { data += chunk })
22
+ res.on('end', () => resolve(data))
23
+ }).on('error', reject)
24
+ })
25
+ }
26
+
27
+ function parseCsv(text) {
28
+ const rows = []
29
+ let row = []
30
+ let cur = ''
31
+ let inQuotes = false
32
+ for (let i = 0; i < text.length; i++) {
33
+ const ch = text[i]
34
+ if (inQuotes) {
35
+ if (ch === '"') {
36
+ if (text[i + 1] === '"') { cur += '"'; i++ } else { inQuotes = false }
37
+ } else {
38
+ cur += ch
39
+ }
40
+ } else {
41
+ if (ch === '"') inQuotes = true
42
+ else if (ch === ',') { row.push(cur); cur = '' }
43
+ else if (ch === '\n') { row.push(cur); rows.push(row); row = []; cur = '' }
44
+ else if (ch === '\r') { /* skip */ }
45
+ else cur += ch
46
+ }
47
+ }
48
+ if (cur.length > 0 || row.length > 0) { row.push(cur); rows.push(row) }
49
+ return rows
50
+ }
51
+
52
+ const raw = await fetchText(SRC)
53
+ const rows = parseCsv(raw)
54
+ const header = rows[0]
55
+ const idx = (name) => header.indexOf(name)
56
+ const TYPE = idx('type')
57
+ const NAME = idx('name')
58
+ const LAT = idx('latitude_deg')
59
+ const LNG = idx('longitude_deg')
60
+ const COUNTRY = idx('iso_country')
61
+ const MUNICIPALITY = idx('municipality')
62
+ const SERVICE = idx('scheduled_service')
63
+ const ICAO = idx('icao_code')
64
+ const IATA = idx('iata_code')
65
+
66
+ const KEEP = new Set(['large_airport', 'medium_airport'])
67
+ const airports = []
68
+ let skippedNoTz = 0
69
+
70
+ for (let i = 1; i < rows.length; i++) {
71
+ const r = rows[i]
72
+ if (!r || r.length < header.length) continue
73
+ if (!KEEP.has(r[TYPE])) continue
74
+ const iata = r[IATA]?.trim().toUpperCase()
75
+ if (!iata || iata.length !== 3) continue
76
+ if (r[SERVICE] !== 'yes') continue
77
+ const lat = Number(r[LAT])
78
+ const lng = Number(r[LNG])
79
+ if (!Number.isFinite(lat) || !Number.isFinite(lng)) continue
80
+
81
+ let tz = null
82
+ try { tz = tzLookup(lat, lng) } catch { skippedNoTz++; continue }
83
+ if (!tz) { skippedNoTz++; continue }
84
+
85
+ airports.push({
86
+ iata,
87
+ icao: r[ICAO]?.trim().toUpperCase() || null,
88
+ name: r[NAME],
89
+ city: r[MUNICIPALITY] || '',
90
+ country: r[COUNTRY] || '',
91
+ lat: Math.round(lat * 1e6) / 1e6,
92
+ lng: Math.round(lng * 1e6) / 1e6,
93
+ tz,
94
+ })
95
+ }
96
+
97
+ const seen = new Map()
98
+ for (const a of airports) {
99
+ const existing = seen.get(a.iata)
100
+ if (!existing) { seen.set(a.iata, a); continue }
101
+ if (existing.icao && !a.icao) continue
102
+ if (!existing.icao && a.icao) seen.set(a.iata, a)
103
+ }
104
+ const unique = Array.from(seen.values()).sort((a, b) => a.iata.localeCompare(b.iata))
105
+
106
+ fs.writeFileSync(OUT, JSON.stringify(unique))
107
+ const size = fs.statSync(OUT).size
108
+ console.log(`Wrote ${unique.length} airports to ${OUT} (${(size / 1024).toFixed(1)} KB); skipped ${skippedNoTz} without timezone`)
server/scripts/build-atlas-geo.mjs ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env node
2
+ // Build server/assets/atlas/{admin0,admin1}.geojson.gz from geoBoundaries (gbOpen).
3
+ //
4
+ // Why: Atlas previously fetched country + sub-national boundaries from Natural Earth's
5
+ // GitHub `master` at runtime. Natural Earth is stale (e.g. it still shows Norway's
6
+ // pre-2020 counties) and depicts some contested territory in ways the project does not
7
+ // want (see nvkelso/natural-earth-vector#391). geoBoundaries (CC BY 4.0) is current,
8
+ // redistributable, and carries ISO 3166-2 codes on its per-country ADM1 files.
9
+ //
10
+ // This downloads the *simplified* per-country gbOpen ADM0 (countries) and ADM1
11
+ // (regions) layers from a pinned geoBoundaries revision, normalizes each feature to
12
+ // the property names the Atlas client/server already read, and writes two gzipped
13
+ // FeatureCollections that the server serves at runtime (no network at boot).
14
+ //
15
+ // geoBoundaries: CC BY 4.0 — https://www.geoboundaries.org/ (attribution required).
16
+
17
+ import fs from 'node:fs'
18
+ import path from 'node:path'
19
+ import zlib from 'node:zlib'
20
+ import { fileURLToPath } from 'node:url'
21
+
22
+ const __dirname = path.dirname(fileURLToPath(import.meta.url))
23
+ const OUT_DIR = path.join(__dirname, '..', 'assets', 'atlas')
24
+
25
+ // Pinned geoBoundaries revision (override with GB_REF=<sha|branch|tag>). The LFS media
26
+ // endpoint resolves a commit SHA, branch, or tag in the <ref> path segment.
27
+ const GB_REF = process.env.GB_REF || '5c25134028196d43ce97b5071934fd0cfc92f09f'
28
+ const MEDIA = (a3, level) =>
29
+ `https://media.githubusercontent.com/media/wmgeolab/geoBoundaries/${GB_REF}` +
30
+ `/releaseData/gbOpen/${a3}/${level}/geoBoundaries-${a3}-${level}_simplified.geojson`
31
+
32
+ // Country borders come from CGAZ (the Comprehensive Global Administrative Zones composite)
33
+ // rather than per-country gbOpen ADM0: CGAZ is gap-filled, so it includes territories
34
+ // that gbOpen omits or folds away — notably Svalbard (inside Norway's geometry) and
35
+ // Greenland. The country layer only needs A3/A2/name, so CGAZ's lack of `shapeISO` is
36
+ // irrelevant. (gbOpen ADM0 maxes Norway at 71°N and has no Svalbard at all.)
37
+ const CGAZ_ADM0 =
38
+ `https://media.githubusercontent.com/media/wmgeolab/geoBoundaries/${GB_REF}` +
39
+ `/releaseData/CGAZ/geoBoundariesCGAZ_ADM0.geojson`
40
+
41
+ const CONCURRENCY = 8
42
+ const RETRIES = 3
43
+
44
+ // Complete ISO-3166-1 alpha-3 → alpha-2 map (source: lukes/ISO-3166-Countries-with-
45
+ // Regional-Codes). Drives ADM1 enumeration (one gbOpen request per code; missing ones
46
+ // 404 and are skipped) and stamps `iso_a2`/`ISO_A2` (geoBoundaries keys by alpha-3
47
+ // `shapeGroup`). A complete map — not the client's curated ~180 — is what restores the
48
+ // dropped territories (Greenland, Falklands, French Guiana, …).
49
+ 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", "YEM":"YE", "ZAF":"ZA", "ZMB":"ZM", "ZWE":"ZW"}
50
+
51
+ const COUNTRIES = Object.keys(A3_TO_A2) // every ISO alpha-3 code (ADM1 fetch list)
52
+
53
+ // Cache raw downloads so re-runs (e.g. to tune simplification) don't re-fetch ~360 files.
54
+ const CACHE_DIR = path.join(__dirname, '..', '.atlas-geo-cache', GB_REF)
55
+
56
+ async function fetchGeo(url) {
57
+ const cacheFile = path.join(CACHE_DIR, url.split('/').slice(-1)[0])
58
+ if (fs.existsSync(cacheFile)) {
59
+ const cached = fs.readFileSync(cacheFile, 'utf8')
60
+ return cached === '' ? null : JSON.parse(cached)
61
+ }
62
+ for (let attempt = 1; attempt <= RETRIES; attempt++) {
63
+ try {
64
+ const res = await fetch(url, { headers: { 'User-Agent': 'TREK atlas builder' } })
65
+ if (res.status === 404) { fs.writeFileSync(cacheFile, ''); return null } // no file — skip
66
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
67
+ const text = await res.text()
68
+ if (text.startsWith('version https://git-lfs')) throw new Error('got LFS pointer, not content')
69
+ const parsed = JSON.parse(text)
70
+ fs.writeFileSync(cacheFile, text)
71
+ return parsed
72
+ } catch (err) {
73
+ if (attempt === RETRIES) {
74
+ console.warn(` ! ${url.split('/').slice(-1)[0]}: ${err.message}`)
75
+ return null
76
+ }
77
+ await new Promise(r => setTimeout(r, 500 * attempt))
78
+ }
79
+ }
80
+ return null
81
+ }
82
+
83
+ // Run async tasks with a fixed concurrency cap.
84
+ async function pool(items, worker) {
85
+ const results = []
86
+ let i = 0
87
+ const runners = Array.from({ length: CONCURRENCY }, async () => {
88
+ while (i < items.length) {
89
+ const idx = i++
90
+ results[idx] = await worker(items[idx], idx)
91
+ }
92
+ })
93
+ await Promise.all(runners)
94
+ return results
95
+ }
96
+
97
+ // Geometry size control. geoBoundaries' "_simplified" files still carry ~12-decimal
98
+ // coordinates, which dominate the JSON size. Quantizing to a fixed grid (rounding
99
+ // preserves topology — identical input coords map to identical output) and dropping
100
+ // the now-redundant consecutive duplicate points shrinks the bundles ~5-8x with no
101
+ // visible effect at the atlas' zoom range (3-10). ADM0 fills are viewed zoomed out, so
102
+ // they tolerate a coarser grid than ADM1 region borders.
103
+ const ADM0_DECIMALS = 2 // ~1.1 km
104
+ const ADM1_DECIMALS = 3 // ~110 m
105
+
106
+ function quantizeRing(ring, decimals) {
107
+ const m = 10 ** decimals
108
+ const out = []
109
+ let prevX, prevY
110
+ for (const pt of ring) {
111
+ const x = Math.round(pt[0] * m) / m
112
+ const y = Math.round(pt[1] * m) / m
113
+ if (x === prevX && y === prevY) continue
114
+ out.push([x, y])
115
+ prevX = x; prevY = y
116
+ }
117
+ return out
118
+ }
119
+
120
+ // Quantize a (Multi)Polygon, dropping rings that collapse below a valid ring (<4 pts).
121
+ function quantizeGeometry(geom, decimals) {
122
+ if (!geom) return null
123
+ if (geom.type === 'Polygon') {
124
+ const rings = geom.coordinates.map(r => quantizeRing(r, decimals)).filter(r => r.length >= 4)
125
+ return rings.length ? { type: 'Polygon', coordinates: rings } : null
126
+ }
127
+ if (geom.type === 'MultiPolygon') {
128
+ const polys = geom.coordinates
129
+ .map(poly => poly.map(r => quantizeRing(r, decimals)).filter(r => r.length >= 4))
130
+ .filter(poly => poly.length)
131
+ return polys.length ? { type: 'MultiPolygon', coordinates: polys } : null
132
+ }
133
+ return geom
134
+ }
135
+
136
+ // Normalize one CGAZ ADM0 feature (keyed by alpha-3 `shapeGroup`) to the property names
137
+ // the client country layer reads (ISO_A2/ADM0_A3/NAME/ADMIN). Returns null for the CRS
138
+ // pseudo-entry or anything without a group/geometry.
139
+ function normalizeAdm0Feature(f) {
140
+ const a3 = f.properties?.shapeGroup
141
+ if (!a3) return null
142
+ const name = f.properties?.shapeName || a3
143
+ const geometry = quantizeGeometry(f.geometry, ADM0_DECIMALS)
144
+ if (!geometry) return null
145
+ return {
146
+ type: 'Feature',
147
+ properties: { ISO_A2: A3_TO_A2[a3] || null, ADM0_A3: a3, NAME: name, ADMIN: name },
148
+ geometry,
149
+ }
150
+ }
151
+
152
+ function normalizeAdm1(geo, a3, countryName) {
153
+ if (!geo?.features) return []
154
+ return geo.features.map(f => {
155
+ const name = f.properties?.shapeName || ''
156
+ const geometry = quantizeGeometry(f.geometry, ADM1_DECIMALS)
157
+ if (!geometry) return null
158
+ const a2 = A3_TO_A2[a3] || null
159
+ // shapeISO is a real ISO 3166-2 code for ~90% of features; geoBoundaries leaves the
160
+ // rest blank or uses an `XX_YYY` placeholder. Keep real/placeholder codes as-is
161
+ // (stable per polygon → manual mark/unmark works, real ones match Nominatim). For
162
+ // blank codes, synthesize a stable id mirroring the server's geocode fallback so
163
+ // every region is still markable.
164
+ let code = f.properties?.shapeISO || ''
165
+ if (!code && a2) code = `${a2}-${name.replace(/[^A-Za-z0-9]/g, '').substring(0, 3).toUpperCase()}`
166
+ return {
167
+ type: 'Feature',
168
+ // Property names the Atlas region layer + server getRegionGeo already read.
169
+ properties: {
170
+ iso_a2: a2,
171
+ iso_3166_2: code,
172
+ name,
173
+ name_en: name,
174
+ admin: countryName,
175
+ },
176
+ geometry,
177
+ }
178
+ }).filter(Boolean)
179
+ }
180
+
181
+ async function main() {
182
+ console.log(`[atlas-geo] geoBoundaries ref ${GB_REF}; ${COUNTRIES.length} countries`)
183
+ fs.mkdirSync(OUT_DIR, { recursive: true })
184
+ fs.mkdirSync(CACHE_DIR, { recursive: true })
185
+
186
+ // ADM0 (countries) — one comprehensive CGAZ file (large; cached). Also yields the
187
+ // English country name (shapeGroup → shapeName) used for the ADM1 `admin` field.
188
+ console.log('[atlas-geo] downloading CGAZ ADM0 (countries)…')
189
+ const cgaz = await fetchGeo(CGAZ_ADM0)
190
+ const adm0Features = []
191
+ const a3ToName = {}
192
+ for (const f of cgaz?.features || []) {
193
+ const nf = normalizeAdm0Feature(f)
194
+ if (nf) { a3ToName[nf.properties.ADM0_A3] = nf.properties.NAME; adm0Features.push(nf) }
195
+ }
196
+
197
+ // ADM1 (sub-national regions) — per-country gbOpen (carries ISO 3166-2 `shapeISO`).
198
+ console.log('[atlas-geo] downloading ADM1 (regions)…')
199
+ const adm1Raw = await pool(COUNTRIES, a3 => fetchGeo(MEDIA(a3, 'ADM1')))
200
+ const adm1Features = []
201
+ let withCodes = 0
202
+ COUNTRIES.forEach((a3, idx) => {
203
+ const feats = normalizeAdm1(adm1Raw[idx], a3, a3ToName[a3] || a3)
204
+ for (const f of feats) if (f.properties.iso_3166_2) withCodes++
205
+ adm1Features.push(...feats)
206
+ })
207
+
208
+ const write = (name, features) => {
209
+ const fc = { type: 'FeatureCollection', features }
210
+ const gz = zlib.gzipSync(Buffer.from(JSON.stringify(fc)), { level: 9 })
211
+ const file = path.join(OUT_DIR, `${name}.geojson.gz`)
212
+ fs.writeFileSync(file, gz)
213
+ console.log(`[atlas-geo] wrote ${path.relative(path.join(__dirname, '..'), file)} — ${features.length} features, ${(gz.length / 1e6).toFixed(1)} MB gz`)
214
+ }
215
+
216
+ write('admin0', adm0Features)
217
+ write('admin1', adm1Features)
218
+
219
+ const missing1 = COUNTRIES.filter((a3, i) => !normalizeAdm1(adm1Raw[i], a3, '').length)
220
+ console.log(`[atlas-geo] ADM0 country features: ${adm0Features.length}`)
221
+ console.log(`[atlas-geo] ADM1 countries without regions (skipped/404): ${missing1.length}`)
222
+ console.log(`[atlas-geo] ADM1 features with ISO 3166-2 code: ${withCodes}/${adm1Features.length}`)
223
+ }
224
+
225
+ main().catch(err => { console.error(err); process.exit(1) })
server/scripts/build.mjs ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import { execSync } from 'node:child_process';
2
+
3
+ try {
4
+ execSync('tsc -p tsconfig.build.json', { stdio: 'inherit' });
5
+ } catch {
6
+ console.warn('[build] tsc reported type errors — emitting anyway (gated by `npm run typecheck`).');
7
+ }
8
+
9
+ console.log('[build] dist ready.');
server/scripts/dev.mjs ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { execSync, spawn } from 'node:child_process';
2
+
3
+ console.log('[dev] initial build...');
4
+ execSync('node scripts/build.mjs', { stdio: 'inherit' });
5
+
6
+ const children = [];
7
+ const stop = () => { children.forEach((c) => { try { c.kill(); } catch {} }); process.exit(0); };
8
+ process.on('SIGINT', stop);
9
+ process.on('SIGTERM', stop);
10
+
11
+ // Start tsc -w and wait for its first "Watching for file changes." before launching
12
+ // node --watch, so the initial tsc compilation doesn't trigger a spurious restart.
13
+ const tsc = spawn('npx', ['tsc', '-w', '-p', 'tsconfig.build.json', '--preserveWatchOutput'], {
14
+ stdio: ['ignore', 'pipe', 'inherit'],
15
+ shell: true,
16
+ });
17
+ children.push(tsc);
18
+
19
+ let nodeProc = null;
20
+ let ready = false;
21
+
22
+ tsc.stdout.on('data', (chunk) => {
23
+ process.stdout.write(chunk);
24
+ if (!ready && chunk.toString().includes('Watching for file changes')) {
25
+ ready = true;
26
+ nodeProc = spawn('node', ['--require', 'tsconfig-paths/register', '--watch', 'dist/index.js'], {
27
+ stdio: 'inherit',
28
+ shell: true,
29
+ });
30
+ children.push(nodeProc);
31
+ }
32
+ });
server/scripts/migrate-encryption.ts ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Encryption key migration script.
3
+ *
4
+ * Re-encrypts all at-rest secrets in the TREK database from one ENCRYPTION_KEY
5
+ * to another without requiring the application to be running.
6
+ *
7
+ * Usage (host):
8
+ * cd server
9
+ * node --import tsx scripts/migrate-encryption.ts
10
+ *
11
+ * Usage (Docker):
12
+ * docker exec -it trek node --import tsx scripts/migrate-encryption.ts
13
+ *
14
+ * The script will prompt for the old and new keys interactively so they never
15
+ * appear in shell history, process arguments, or log output.
16
+ */
17
+
18
+ import crypto from 'crypto';
19
+ import fs from 'fs';
20
+ import path from 'path';
21
+ import readline from 'readline';
22
+ import Database from 'better-sqlite3';
23
+
24
+ // ---------------------------------------------------------------------------
25
+ // Crypto helpers — mirrors apiKeyCrypto.ts and mfaCrypto.ts but with
26
+ // explicit key arguments so the script is independent of config.ts / env vars.
27
+ // ---------------------------------------------------------------------------
28
+
29
+ const ENCRYPTED_PREFIX = 'enc:v1:';
30
+
31
+ function apiKey(encryptionKey: string): Buffer {
32
+ return crypto.createHash('sha256').update(`${encryptionKey}:api_keys:v1`).digest();
33
+ }
34
+
35
+ function mfaKey(encryptionKey: string): Buffer {
36
+ return crypto.createHash('sha256').update(`${encryptionKey}:mfa:v1`).digest();
37
+ }
38
+
39
+ function encryptApiKey(plain: string, encryptionKey: string): string {
40
+ const iv = crypto.randomBytes(12);
41
+ const cipher = crypto.createCipheriv('aes-256-gcm', apiKey(encryptionKey), iv);
42
+ const enc = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
43
+ const tag = cipher.getAuthTag();
44
+ return `${ENCRYPTED_PREFIX}${Buffer.concat([iv, tag, enc]).toString('base64')}`;
45
+ }
46
+
47
+ function decryptApiKey(value: string, encryptionKey: string): string | null {
48
+ if (!value.startsWith(ENCRYPTED_PREFIX)) return null;
49
+ try {
50
+ const buf = Buffer.from(value.slice(ENCRYPTED_PREFIX.length), 'base64');
51
+ const decipher = crypto.createDecipheriv('aes-256-gcm', apiKey(encryptionKey), buf.subarray(0, 12));
52
+ decipher.setAuthTag(buf.subarray(12, 28));
53
+ return Buffer.concat([decipher.update(buf.subarray(28)), decipher.final()]).toString('utf8');
54
+ } catch {
55
+ return null;
56
+ }
57
+ }
58
+
59
+ function encryptMfa(plain: string, encryptionKey: string): string {
60
+ const iv = crypto.randomBytes(12);
61
+ const cipher = crypto.createCipheriv('aes-256-gcm', mfaKey(encryptionKey), iv);
62
+ const enc = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
63
+ const tag = cipher.getAuthTag();
64
+ return Buffer.concat([iv, tag, enc]).toString('base64');
65
+ }
66
+
67
+ function decryptMfa(value: string, encryptionKey: string): string | null {
68
+ try {
69
+ const buf = Buffer.from(value, 'base64');
70
+ if (buf.length < 28) return null;
71
+ const decipher = crypto.createDecipheriv('aes-256-gcm', mfaKey(encryptionKey), buf.subarray(0, 12));
72
+ decipher.setAuthTag(buf.subarray(12, 28));
73
+ return Buffer.concat([decipher.update(buf.subarray(28)), decipher.final()]).toString('utf8');
74
+ } catch {
75
+ return null;
76
+ }
77
+ }
78
+
79
+ // ---------------------------------------------------------------------------
80
+ // Prompt helpers
81
+ // ---------------------------------------------------------------------------
82
+ // A single readline interface is shared for the entire script lifetime so
83
+ // stdin is never paused between prompts.
84
+ //
85
+ // Lines are collected into a queue as soon as readline emits them — this
86
+ // prevents the race where a line event fires before the next listener is
87
+ // registered (common with piped / pasted input that arrives all at once).
88
+
89
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
90
+
91
+ const lineQueue: string[] = [];
92
+ const lineWaiters: ((line: string) => void)[] = [];
93
+
94
+ rl.on('line', (line) => {
95
+ if (lineWaiters.length > 0) {
96
+ lineWaiters.shift()!(line);
97
+ } else {
98
+ lineQueue.push(line);
99
+ }
100
+ });
101
+
102
+ function nextLine(): Promise<string> {
103
+ return new Promise((resolve) => {
104
+ if (lineQueue.length > 0) {
105
+ resolve(lineQueue.shift()!);
106
+ } else {
107
+ lineWaiters.push(resolve);
108
+ }
109
+ });
110
+ }
111
+
112
+ // Muted prompt — typed/pasted characters are not echoed.
113
+ // _writeToOutput is suppressed only while waiting for this line.
114
+ async function promptSecret(question: string): Promise<string> {
115
+ process.stdout.write(question);
116
+ (rl as any)._writeToOutput = () => {};
117
+ const line = await nextLine();
118
+ (rl as any)._writeToOutput = (s: string) => process.stdout.write(s);
119
+ process.stdout.write('\n');
120
+ return line.trim();
121
+ }
122
+
123
+ async function prompt(question: string): Promise<string> {
124
+ process.stdout.write(question);
125
+ const line = await nextLine();
126
+ return line.trim();
127
+ }
128
+
129
+ // ---------------------------------------------------------------------------
130
+ // Migration
131
+ // ---------------------------------------------------------------------------
132
+
133
+ interface MigrationResult {
134
+ migrated: number;
135
+ alreadyMigrated: number;
136
+ skipped: number;
137
+ errors: string[];
138
+ }
139
+
140
+ async function main() {
141
+ console.log('=== TREK Encryption Key Migration ===\n');
142
+ console.log('This script re-encrypts all stored secrets under a new ENCRYPTION_KEY.');
143
+ console.log('A backup of the database will be created before any changes are made.\n');
144
+
145
+ // Resolve DB path
146
+ const dbPath = path.resolve(
147
+ process.env.DB_PATH ?? path.join(__dirname, '../data/travel.db')
148
+ );
149
+
150
+ if (!fs.existsSync(dbPath)) {
151
+ console.error(`Database not found at: ${dbPath}`);
152
+ console.error('Set DB_PATH env var if your database is in a non-standard location.');
153
+ process.exit(1);
154
+ }
155
+
156
+ console.log(`Database: ${dbPath}\n`);
157
+
158
+ // Collect keys interactively
159
+ const oldKey = await promptSecret('Old ENCRYPTION_KEY: ');
160
+ const newKey = await promptSecret('New ENCRYPTION_KEY: ');
161
+
162
+ if (!oldKey || !newKey) {
163
+ rl.close();
164
+ console.error('Both keys are required.');
165
+ process.exit(1);
166
+ }
167
+
168
+ if (oldKey === newKey) {
169
+ rl.close();
170
+ console.error('Old and new keys are identical — nothing to do.');
171
+ process.exit(0);
172
+ }
173
+
174
+ // Confirm
175
+ const confirm = await prompt('\nProceed with migration? This will modify the database. Type "yes" to confirm: ');
176
+ if (confirm.trim().toLowerCase() !== 'yes') {
177
+ rl.close();
178
+ console.log('Aborted.');
179
+ process.exit(0);
180
+ }
181
+
182
+ // Backup
183
+ const backupPath = `${dbPath}.backup-${Date.now()}`;
184
+ fs.copyFileSync(dbPath, backupPath);
185
+ console.log(`\nBackup created: ${backupPath}`);
186
+
187
+ const db = new Database(dbPath);
188
+ db.pragma('journal_mode = WAL');
189
+
190
+ const result: MigrationResult = { migrated: 0, alreadyMigrated: 0, skipped: 0, errors: [] };
191
+
192
+ // Helper: migrate a single api-key-style value (enc:v1: prefix)
193
+ function migrateApiKeyValue(raw: string, label: string): string | null {
194
+ if (!raw || !raw.startsWith(ENCRYPTED_PREFIX)) {
195
+ result.skipped++;
196
+ console.warn(` SKIP ${label}: not an encrypted value (missing enc:v1: prefix)`);
197
+ return null;
198
+ }
199
+
200
+ const plain = decryptApiKey(raw, oldKey);
201
+ if (plain !== null) {
202
+ result.migrated++;
203
+ return encryptApiKey(plain, newKey);
204
+ }
205
+
206
+ // Try new key — already migrated?
207
+ const check = decryptApiKey(raw, newKey);
208
+ if (check !== null) {
209
+ result.alreadyMigrated++;
210
+ return null; // no change needed
211
+ }
212
+
213
+ result.errors.push(`${label}: decryption failed with both keys`);
214
+ console.error(` ERROR ${label}: could not decrypt with either key — skipping`);
215
+ return null;
216
+ }
217
+
218
+ // Helper: migrate a single MFA value (no prefix, raw base64)
219
+ function migrateMfaValue(raw: string, label: string): string | null {
220
+ if (!raw) { result.skipped++; return null; }
221
+
222
+ const plain = decryptMfa(raw, oldKey);
223
+ if (plain !== null) {
224
+ result.migrated++;
225
+ return encryptMfa(plain, newKey);
226
+ }
227
+
228
+ const check = decryptMfa(raw, newKey);
229
+ if (check !== null) {
230
+ result.alreadyMigrated++;
231
+ return null;
232
+ }
233
+
234
+ result.errors.push(`${label}: decryption failed with both keys`);
235
+ console.error(` ERROR ${label}: could not decrypt with either key — skipping`);
236
+ return null;
237
+ }
238
+
239
+ db.transaction(() => {
240
+ // --- app_settings: oidc_client_secret, smtp_pass, admin_webhook_url, admin_ntfy_token ---
241
+ for (const key of ['oidc_client_secret', 'smtp_pass', 'admin_webhook_url', 'admin_ntfy_token']) {
242
+ const row = db.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as { value: string } | undefined;
243
+ if (!row?.value) continue;
244
+ const newVal = migrateApiKeyValue(row.value, `app_settings.${key}`);
245
+ if (newVal !== null) {
246
+ db.prepare('UPDATE app_settings SET value = ? WHERE key = ?').run(newVal, key);
247
+ }
248
+ }
249
+
250
+ // --- users: api key columns + synology credentials ---
251
+ const apiKeyColumns = ['maps_api_key', 'openweather_api_key', 'immich_api_key', 'synology_password', 'synology_sid', 'synology_did'];
252
+ const users = db.prepare('SELECT id FROM users').all() as { id: number }[];
253
+
254
+ for (const user of users) {
255
+ const row = db.prepare(`SELECT ${apiKeyColumns.join(', ')} FROM users WHERE id = ?`).get(user.id) as Record<string, string>;
256
+
257
+ for (const col of apiKeyColumns) {
258
+ if (!row[col]) continue;
259
+ const newVal = migrateApiKeyValue(row[col], `users[${user.id}].${col}`);
260
+ if (newVal !== null) {
261
+ db.prepare(`UPDATE users SET ${col} = ? WHERE id = ?`).run(newVal, user.id);
262
+ }
263
+ }
264
+
265
+ // mfa_secret (mfa crypto)
266
+ const mfaRow = db.prepare('SELECT mfa_secret FROM users WHERE id = ? AND mfa_secret IS NOT NULL').get(user.id) as { mfa_secret: string } | undefined;
267
+ if (mfaRow?.mfa_secret) {
268
+ const newVal = migrateMfaValue(mfaRow.mfa_secret, `users[${user.id}].mfa_secret`);
269
+ if (newVal !== null) {
270
+ db.prepare('UPDATE users SET mfa_secret = ? WHERE id = ?').run(newVal, user.id);
271
+ }
272
+ }
273
+ }
274
+ // --- settings: per-user encrypted keys ---
275
+ const encryptedSettingKeys = ['webhook_url', 'ntfy_token', 'mapbox_access_token'];
276
+ const settingRows = db.prepare(
277
+ `SELECT user_id, key, value FROM settings WHERE key IN (${encryptedSettingKeys.map(() => '?').join(', ')})`
278
+ ).all(...encryptedSettingKeys) as { user_id: number; key: string; value: string }[];
279
+
280
+ for (const row of settingRows) {
281
+ if (!row.value) continue;
282
+ const newVal = migrateApiKeyValue(row.value, `settings[user=${row.user_id}].${row.key}`);
283
+ if (newVal !== null) {
284
+ db.prepare('UPDATE settings SET value = ? WHERE user_id = ? AND key = ?').run(newVal, row.user_id, row.key);
285
+ }
286
+ }
287
+
288
+ // --- trip_album_links: passphrase ---
289
+ const albumLinks = db.prepare('SELECT id, passphrase FROM trip_album_links WHERE passphrase IS NOT NULL').all() as { id: number; passphrase: string }[];
290
+ for (const row of albumLinks) {
291
+ const newVal = migrateApiKeyValue(row.passphrase, `trip_album_links[${row.id}].passphrase`);
292
+ if (newVal !== null) {
293
+ db.prepare('UPDATE trip_album_links SET passphrase = ? WHERE id = ?').run(newVal, row.id);
294
+ }
295
+ }
296
+
297
+ // --- trek_photos: passphrase ---
298
+ const photos = db.prepare('SELECT id, passphrase FROM trek_photos WHERE passphrase IS NOT NULL').all() as { id: number; passphrase: string }[];
299
+ for (const row of photos) {
300
+ const newVal = migrateApiKeyValue(row.passphrase, `trek_photos[${row.id}].passphrase`);
301
+ if (newVal !== null) {
302
+ db.prepare('UPDATE trek_photos SET passphrase = ? WHERE id = ?').run(newVal, row.id);
303
+ }
304
+ }
305
+ })();
306
+
307
+ db.close();
308
+ rl.close();
309
+
310
+ console.log('\n=== Migration complete ===');
311
+ console.log(` Migrated: ${result.migrated}`);
312
+ console.log(` Already on new key: ${result.alreadyMigrated}`);
313
+ console.log(` Skipped (empty): ${result.skipped}`);
314
+ if (result.errors.length > 0) {
315
+ console.warn(` Errors: ${result.errors.length}`);
316
+ result.errors.forEach(e => console.warn(` - ${e}`));
317
+ console.warn('\nSome secrets could not be migrated. Check the errors above.');
318
+ console.warn(`Your original database is backed up at: ${backupPath}`);
319
+ process.exit(1);
320
+ } else {
321
+ console.log('\nAll secrets successfully re-encrypted.');
322
+ console.log(`Backup retained at: ${backupPath}`);
323
+ }
324
+ }
325
+
326
+ main().catch((err) => {
327
+ console.error('Unexpected error:', err);
328
+ process.exit(1);
329
+ });
server/src/addons.ts ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export const ADDON_IDS = {
2
+ MCP: 'mcp',
3
+ PACKING: 'packing',
4
+ BUDGET: 'budget',
5
+ DOCUMENTS: 'documents',
6
+ VACAY: 'vacay',
7
+ ATLAS: 'atlas',
8
+ COLLAB: 'collab',
9
+ JOURNEY: 'journey',
10
+ AIRTRAIL: 'airtrail',
11
+ } as const;
12
+
13
+ export type AddonId = typeof ADDON_IDS[keyof typeof ADDON_IDS];
server/src/bootstrap.ts ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NestFactory } from '@nestjs/core';
2
+ import { ExpressAdapter } from '@nestjs/platform-express';
3
+ import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
4
+ import type { INestApplication } from '@nestjs/common';
5
+ import { AppModule } from './nest/app.module';
6
+ import { applyGlobalMiddleware } from './middleware/globalMiddleware';
7
+ import { applyPlatformUploads, applyPlatformTransport, applyPlatformStatic } from './nest/platform/platform.routes';
8
+
9
+ /**
10
+ * Builds the unified TREK NestJS application that serves the ENTIRE surface — the
11
+ * former Express app is gone. One builder is shared by the production bootstrap
12
+ * (index.ts) and the integration-test harness so the two can never drift.
13
+ *
14
+ * Composition order is load-bearing. Everything except the SPA index.html fallback
15
+ * is registered on the underlying Express instance BEFORE `app.init()`, because
16
+ * Nest's router terminates an unmatched request by throwing NotFoundException — it
17
+ * does NOT fall through to a route registered after init, so a post-init Express
18
+ * route is unreachable. The platform routes are all specific paths (/uploads/*,
19
+ * /api/health, /mcp, /.well-known/*, /oauth/{authorize,register,consent}) so they
20
+ * match their own requests and `next()` everything else through to the Nest
21
+ * controllers registered during init.
22
+ *
23
+ * 1. applyGlobalMiddleware — helmet/CSP, CORS, HSTS, forced-HTTPS, the global MFA
24
+ * policy, request logging + cookie-parser. `bodyParser: false` so Nest does its
25
+ * own parsing and the raw /mcp body reaches the MCP handler unparsed.
26
+ * 2. applyPlatformUploads — the static + guarded /uploads/* routes.
27
+ * 3. applyPlatformTransport — /api/health, the OAuth/MCP SDK + /.well-known
28
+ * metadata, the /mcp routes, the /oauth/consent COOP header.
29
+ * 4. applyPlatformStatic — the production built-client static assets (so a real
30
+ * asset request returns the file before the Nest router 404s it).
31
+ * 5. app.init() — registers every migrated /api domain (the Nest controllers).
32
+ *
33
+ * The SPA index.html fallback (unmatched GET → index.html in production) is the
34
+ * SpaFallbackFilter (APP_FILTER in AppModule); the global error envelope is the
35
+ * TrekExceptionFilter (also APP_FILTER).
36
+ */
37
+ export async function buildApp(): Promise<INestApplication> {
38
+ const app = await NestFactory.create(AppModule, new ExpressAdapter());
39
+ const instance = app.getHttpAdapter().getInstance();
40
+ applyGlobalMiddleware(instance, { bodyParser: false });
41
+ applyPlatformUploads(instance);
42
+ applyPlatformTransport(instance);
43
+ applyPlatformStatic(instance);
44
+
45
+ const config = new DocumentBuilder()
46
+ .setTitle('TREK API')
47
+ .setDescription('The TREK API documentation')
48
+ .setVersion('1.0')
49
+ .build();
50
+ const document = SwaggerModule.createDocument(app, config);
51
+ SwaggerModule.setup('api-docs', app, document);
52
+
53
+ await app.init();
54
+ return app;
55
+ }
server/src/config.ts ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { SUPPORTED_LANGUAGE_CODES as SUPPORTED_LANG_CODES } from '@trek/shared';
5
+
6
+ const dataDir = path.resolve(__dirname, '../data');
7
+
8
+ // JWT_SECRET is always managed by the server — auto-generated on first start and
9
+ // persisted to data/.jwt_secret. Use the admin panel to rotate it; do not set it
10
+ // via environment variable (env var would override a rotation on next restart).
11
+ const jwtSecretFile = path.join(dataDir, '.jwt_secret');
12
+ let _jwtSecret: string;
13
+
14
+ try {
15
+ _jwtSecret = fs.readFileSync(jwtSecretFile, 'utf8').trim();
16
+ } catch {
17
+ _jwtSecret = crypto.randomBytes(32).toString('hex');
18
+ try {
19
+ if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true });
20
+ fs.writeFileSync(jwtSecretFile, _jwtSecret, { mode: 0o600 });
21
+ console.log('Generated and saved JWT secret to', jwtSecretFile);
22
+ } catch (writeErr: unknown) {
23
+ console.warn('WARNING: Could not persist JWT secret to disk:', writeErr instanceof Error ? writeErr.message : writeErr);
24
+ console.warn('Sessions will reset on server restart.');
25
+ }
26
+ }
27
+
28
+ // export let so TypeScript's CJS output keeps exports.JWT_SECRET live
29
+ // (generates `exports.JWT_SECRET = JWT_SECRET = newVal` inside updateJwtSecret)
30
+ export let JWT_SECRET = _jwtSecret;
31
+
32
+ // Called by the admin rotate-jwt-secret endpoint to update the in-process
33
+ // binding that all middleware and route files reference.
34
+ export function updateJwtSecret(newSecret: string): void {
35
+ JWT_SECRET = newSecret;
36
+ }
37
+
38
+ // ENCRYPTION_KEY is used to derive at-rest encryption keys for stored secrets
39
+ // (API keys, MFA TOTP secrets, SMTP password, OIDC client secret, etc.).
40
+ // Keeping it separate from JWT_SECRET means you can rotate session tokens without
41
+ // invalidating all stored encrypted data, and vice-versa.
42
+ //
43
+ // Resolution order:
44
+ // 1. ENCRYPTION_KEY env var — explicit, always takes priority.
45
+ // 2. data/.encryption_key file — present on any install that has started at
46
+ // least once (written automatically by cases 1b and 3 below).
47
+ // 3. data/.jwt_secret — one-time fallback for existing installs upgrading
48
+ // without a pre-set ENCRYPTION_KEY. The value is immediately persisted to
49
+ // data/.encryption_key so JWT rotation can never break decryption later.
50
+ // 4. Auto-generated — fresh install with none of the above; persisted to
51
+ // data/.encryption_key.
52
+ const encKeyFile = path.join(dataDir, '.encryption_key');
53
+ let _encryptionKey: string = process.env.ENCRYPTION_KEY || '';
54
+
55
+ if (_encryptionKey) {
56
+ // Env var is set explicitly — persist it to file so the value survives
57
+ // container restarts even if the env var is later removed.
58
+ try {
59
+ if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true });
60
+ fs.writeFileSync(encKeyFile, _encryptionKey, { mode: 0o600 });
61
+ } catch {
62
+ // Non-fatal: env var is the source of truth when set.
63
+ }
64
+ } else {
65
+ // Try the dedicated key file first (covers all installs after first start).
66
+ try {
67
+ _encryptionKey = fs.readFileSync(encKeyFile, 'utf8').trim();
68
+ } catch {
69
+ // File not found — first start on an existing or fresh install.
70
+ }
71
+
72
+ if (!_encryptionKey) {
73
+ // One-time migration: existing install upgrading for the first time.
74
+ // Use the JWT secret as the encryption key and immediately write it to
75
+ // .encryption_key so future JWT rotations cannot break decryption.
76
+ try {
77
+ _encryptionKey = fs.readFileSync(jwtSecretFile, 'utf8').trim();
78
+ console.warn('WARNING: ENCRYPTION_KEY is not set. Falling back to JWT secret for at-rest encryption.');
79
+ console.warn('The value has been persisted to data/.encryption_key — JWT rotation is now safe.');
80
+ } catch {
81
+ // JWT secret not found — must be a fresh install.
82
+ }
83
+ }
84
+
85
+ if (!_encryptionKey) {
86
+ // Fresh install — auto-generate a dedicated key.
87
+ _encryptionKey = crypto.randomBytes(32).toString('hex');
88
+ }
89
+
90
+ // Persist whatever key was resolved so subsequent starts skip the fallback chain.
91
+ try {
92
+ if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true });
93
+ fs.writeFileSync(encKeyFile, _encryptionKey, { mode: 0o600 });
94
+ console.log('Encryption key persisted to', encKeyFile);
95
+ } catch (writeErr: unknown) {
96
+ console.warn('WARNING: Could not persist encryption key to disk:', writeErr instanceof Error ? writeErr.message : writeErr);
97
+ console.warn('Set ENCRYPTION_KEY env var to avoid losing access to encrypted secrets on restart.');
98
+ }
99
+ }
100
+
101
+ export const ENCRYPTION_KEY = _encryptionKey;
102
+
103
+ // DEFAULT_LANGUAGE sets the language shown on the login page before the user
104
+ // selects one. Only applies when the user has no saved language preference.
105
+ const rawDefaultLang = process.env.DEFAULT_LANGUAGE?.toLowerCase() || 'en';
106
+ if (!SUPPORTED_LANG_CODES.includes(rawDefaultLang)) {
107
+ console.warn(`DEFAULT_LANGUAGE="${rawDefaultLang}" is not supported. Falling back to "en". Supported: ${SUPPORTED_LANG_CODES.join(', ')}`);
108
+ }
109
+ export const DEFAULT_LANGUAGE = SUPPORTED_LANG_CODES.includes(rawDefaultLang) ? rawDefaultLang : 'en';
110
+
111
+ // SESSION_DURATION controls how long a TREK session (the `trek_session` JWT
112
+ // cookie) stays valid before re-login is required. Accepts ms-style strings:
113
+ // '1h', '12h', '7d', '30d', '90d', etc. It applies to BOTH the JWT `exp` claim
114
+ // and the cookie `maxAge`, so the two never drift apart. Invalid values warn at
115
+ // startup and fall back to the default. Does not affect the short-lived MFA
116
+ // challenge token or MCP OAuth tokens — those keep their own TTL.
117
+ const DEFAULT_SESSION_DURATION = '24h';
118
+ const DURATION_UNITS_MS: Record<string, number> = {
119
+ ms: 1, s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000, w: 604_800_000, y: 31_557_600_000,
120
+ };
121
+ function parseDurationMs(value: string): number | null {
122
+ const m = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d|w|y)?$/i.exec(value.trim());
123
+ if (!m) return null;
124
+ const n = parseFloat(m[1]);
125
+ if (!Number.isFinite(n) || n <= 0) return null;
126
+ return n * DURATION_UNITS_MS[(m[2] || 'ms').toLowerCase()];
127
+ }
128
+ const rawSessionDuration = process.env.SESSION_DURATION?.trim() || DEFAULT_SESSION_DURATION;
129
+ const parsedSessionMs = parseDurationMs(rawSessionDuration);
130
+ if (parsedSessionMs == null) {
131
+ console.warn(`SESSION_DURATION="${rawSessionDuration}" is not a valid duration (use e.g. 1h, 7d, 30d). Falling back to "${DEFAULT_SESSION_DURATION}".`);
132
+ }
133
+ /** Human-readable session length actually in effect (for logs/diagnostics). */
134
+ export const SESSION_DURATION = parsedSessionMs == null ? DEFAULT_SESSION_DURATION : rawSessionDuration;
135
+ /** Session length in milliseconds — used for the cookie `maxAge`. */
136
+ export const SESSION_DURATION_MS = parsedSessionMs ?? parseDurationMs(DEFAULT_SESSION_DURATION)!;
137
+ /** Session length in seconds — passed to `jwt.sign({ expiresIn })` (number = seconds). */
138
+ export const SESSION_DURATION_SECONDS = Math.floor(SESSION_DURATION_MS / 1000);
139
+
140
+ // SESSION_DURATION_REMEMBER is the session length used when the user ticks
141
+ // "Remember me" on the login form: a longer-lived JWT `exp` claim plus a
142
+ // persistent `trek_session` cookie `maxAge`. An unticked login keeps
143
+ // SESSION_DURATION and a browser-session cookie (no `maxAge`). Same ms-style
144
+ // format and fallback behavior as SESSION_DURATION.
145
+ const DEFAULT_SESSION_DURATION_REMEMBER = '30d';
146
+ const rawRememberDuration = process.env.SESSION_DURATION_REMEMBER?.trim() || DEFAULT_SESSION_DURATION_REMEMBER;
147
+ const parsedRememberMs = parseDurationMs(rawRememberDuration);
148
+ if (parsedRememberMs == null) {
149
+ console.warn(`SESSION_DURATION_REMEMBER="${rawRememberDuration}" is not a valid duration (use e.g. 7d, 30d, 90d). Falling back to "${DEFAULT_SESSION_DURATION_REMEMBER}".`);
150
+ }
151
+ /** Human-readable "remember me" session length actually in effect (for logs/diagnostics). */
152
+ export const SESSION_DURATION_REMEMBER = parsedRememberMs == null ? DEFAULT_SESSION_DURATION_REMEMBER : rawRememberDuration;
153
+ /** "Remember me" session length in milliseconds — used for the persistent cookie `maxAge`. */
154
+ export const SESSION_DURATION_REMEMBER_MS = parsedRememberMs ?? parseDurationMs(DEFAULT_SESSION_DURATION_REMEMBER)!;
155
+ /** "Remember me" session length in seconds — passed to `jwt.sign({ expiresIn })`. */
156
+ export const SESSION_DURATION_REMEMBER_SECONDS = Math.floor(SESSION_DURATION_REMEMBER_MS / 1000);
server/src/db/database.ts ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Database from 'better-sqlite3';
2
+ import path from 'path';
3
+ import fs from 'fs';
4
+ import { createTables } from './schema';
5
+ import { runMigrations } from './migrations';
6
+ import { runSeeds } from './seeds';
7
+ import { Place, Tag } from '../types';
8
+
9
+ // In test mode each vitest worker gets an isolated in-memory DB so that
10
+ // parallel forks can't race on the same file or share migration state.
11
+ const isTest = process.env.NODE_ENV === 'test';
12
+
13
+ let dbPath: string;
14
+ if (isTest) {
15
+ dbPath = ':memory:';
16
+ } else if (process.env.TREK_DB_FILE) {
17
+ // Explicit DB file (used by the Playwright E2E harness to run against an
18
+ // isolated, throwaway database instead of the real data/travel.db). Purely
19
+ // additive — when unset the default path below is used exactly as before.
20
+ dbPath = process.env.TREK_DB_FILE;
21
+ const dir = path.dirname(dbPath);
22
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
23
+ } else {
24
+ const dataDir = path.join(__dirname, '../../data');
25
+ if (!fs.existsSync(dataDir)) {
26
+ fs.mkdirSync(dataDir, { recursive: true });
27
+ }
28
+ dbPath = path.join(dataDir, 'travel.db');
29
+ }
30
+
31
+ let _db: Database.Database | null = null;
32
+
33
+ function initDb(): void {
34
+ if (_db) {
35
+ try { _db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch (e) {}
36
+ try { _db.close(); } catch (e) {}
37
+ _db = null;
38
+ }
39
+
40
+ _db = new Database(dbPath);
41
+ _db.exec('PRAGMA journal_mode = WAL');
42
+ _db.exec('PRAGMA busy_timeout = 5000');
43
+ _db.exec('PRAGMA foreign_keys = ON');
44
+
45
+ createTables(_db);
46
+ runMigrations(_db);
47
+
48
+ runSeeds(_db);
49
+ }
50
+
51
+ initDb();
52
+
53
+ const db = new Proxy({} as Database.Database, {
54
+ get(_, prop: string | symbol) {
55
+ if (!_db) throw new Error('Database connection is not available (restore in progress?)');
56
+ const val = (_db as unknown as Record<string | symbol, unknown>)[prop];
57
+ return typeof val === 'function' ? val.bind(_db) : val;
58
+ },
59
+ set(_, prop: string | symbol, val: unknown) {
60
+ (_db as unknown as Record<string | symbol, unknown>)[prop] = val;
61
+ return true;
62
+ },
63
+ });
64
+
65
+ if (process.env.DEMO_MODE?.toLowerCase() === 'true') {
66
+ try {
67
+ const { seedDemoData } = require('../demo/demo-seed');
68
+ seedDemoData(_db);
69
+ } catch (err: unknown) {
70
+ console.error('[Demo] Seed error:', err instanceof Error ? err.message : err);
71
+ }
72
+ }
73
+
74
+ function closeDb(): void {
75
+ if (_db) {
76
+ try { _db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch (e) {}
77
+ try { _db.close(); } catch (e) {}
78
+ _db = null;
79
+ console.log('[DB] Database connection closed');
80
+ }
81
+ }
82
+
83
+ function reinitialize(): void {
84
+ console.log('[DB] Reinitializing database connection after restore...');
85
+ if (_db) closeDb();
86
+ initDb();
87
+ console.log('[DB] Database reinitialized successfully');
88
+ }
89
+
90
+ interface PlaceWithCategory extends Place {
91
+ category_name: string | null;
92
+ category_color: string | null;
93
+ category_icon: string | null;
94
+ }
95
+
96
+ interface PlaceWithTags extends Place {
97
+ category: { id: number; name: string; color: string; icon: string } | null;
98
+ tags: Tag[];
99
+ }
100
+
101
+ function getPlaceWithTags(placeId: number | string): PlaceWithTags | null {
102
+ const place = db.prepare(`
103
+ SELECT p.*, c.name as category_name, c.color as category_color, c.icon as category_icon
104
+ FROM places p
105
+ LEFT JOIN categories c ON p.category_id = c.id
106
+ WHERE p.id = ?
107
+ `).get(placeId) as PlaceWithCategory | undefined;
108
+
109
+ if (!place) return null;
110
+
111
+ const tags = db.prepare(`
112
+ SELECT t.* FROM tags t
113
+ JOIN place_tags pt ON t.id = pt.tag_id
114
+ WHERE pt.place_id = ?
115
+ `).all(placeId) as Tag[];
116
+
117
+ return {
118
+ ...place,
119
+ category: place.category_id ? {
120
+ id: place.category_id,
121
+ name: place.category_name!,
122
+ color: place.category_color!,
123
+ icon: place.category_icon!,
124
+ } : null,
125
+ tags,
126
+ };
127
+ }
128
+
129
+ interface TripAccess {
130
+ id: number;
131
+ user_id: number;
132
+ }
133
+
134
+ function canAccessTrip(tripId: number | string, userId: number): TripAccess | undefined {
135
+ return db.prepare(`
136
+ SELECT t.id, t.user_id FROM trips t
137
+ LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ?
138
+ WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)
139
+ `).get(userId, tripId, userId) as TripAccess | undefined;
140
+ }
141
+
142
+ function isOwner(tripId: number | string, userId: number): boolean {
143
+ return !!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId);
144
+ }
145
+
146
+ try {
147
+ const { backfillFlightEndpoints } = require('../services/airportService');
148
+ backfillFlightEndpoints();
149
+ } catch (err) {
150
+ console.error('[DB] Flight endpoint backfill failed:', err);
151
+ }
152
+
153
+ export { db, closeDb, reinitialize, getPlaceWithTags, canAccessTrip, isOwner };
server/src/db/migrations.ts ADDED
The diff for this file is too large to render. See raw diff
 
server/src/db/schema.ts ADDED
@@ -0,0 +1,508 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Database from 'better-sqlite3';
2
+
3
+ function createTables(db: Database.Database): void {
4
+ db.exec(`
5
+ CREATE TABLE IF NOT EXISTS users (
6
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
7
+ username TEXT UNIQUE NOT NULL,
8
+ email TEXT UNIQUE NOT NULL,
9
+ password_hash TEXT NOT NULL,
10
+ role TEXT NOT NULL DEFAULT 'user',
11
+ maps_api_key TEXT,
12
+ unsplash_api_key TEXT,
13
+ openweather_api_key TEXT,
14
+ avatar TEXT,
15
+ oidc_sub TEXT,
16
+ oidc_issuer TEXT,
17
+ last_login DATETIME,
18
+ mfa_enabled INTEGER DEFAULT 0,
19
+ mfa_secret TEXT,
20
+ mfa_backup_codes TEXT,
21
+ immich_url TEXT,
22
+ immich_access_token TEXT,
23
+ synology_url TEXT,
24
+ synology_username TEXT,
25
+ synology_password TEXT,
26
+ synology_sid TEXT,
27
+ must_change_password INTEGER DEFAULT 0,
28
+ password_version INTEGER NOT NULL DEFAULT 0,
29
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
30
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
31
+ );
32
+
33
+ CREATE TABLE IF NOT EXISTS password_reset_tokens (
34
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
35
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
36
+ token_hash TEXT NOT NULL UNIQUE,
37
+ expires_at DATETIME NOT NULL,
38
+ consumed_at DATETIME,
39
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
40
+ created_ip TEXT
41
+ );
42
+ CREATE INDEX IF NOT EXISTS idx_prt_user ON password_reset_tokens(user_id);
43
+ CREATE INDEX IF NOT EXISTS idx_prt_hash ON password_reset_tokens(token_hash);
44
+
45
+ CREATE TABLE IF NOT EXISTS webauthn_credentials (
46
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
47
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
48
+ credential_id TEXT NOT NULL UNIQUE,
49
+ public_key BLOB NOT NULL,
50
+ counter INTEGER NOT NULL DEFAULT 0,
51
+ transports TEXT,
52
+ device_type TEXT,
53
+ backed_up INTEGER NOT NULL DEFAULT 0,
54
+ name TEXT,
55
+ aaguid TEXT,
56
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
57
+ last_used_at DATETIME
58
+ );
59
+ CREATE INDEX IF NOT EXISTS idx_webauthn_credentials_user ON webauthn_credentials(user_id);
60
+
61
+ CREATE TABLE IF NOT EXISTS webauthn_challenges (
62
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
63
+ challenge TEXT NOT NULL UNIQUE,
64
+ user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
65
+ type TEXT NOT NULL,
66
+ expires_at INTEGER NOT NULL,
67
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
68
+ );
69
+ CREATE INDEX IF NOT EXISTS idx_webauthn_challenges_expires ON webauthn_challenges(expires_at);
70
+
71
+ CREATE TABLE IF NOT EXISTS settings (
72
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
73
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
74
+ key TEXT NOT NULL,
75
+ value TEXT,
76
+ UNIQUE(user_id, key)
77
+ );
78
+
79
+ CREATE TABLE IF NOT EXISTS trips (
80
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
81
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
82
+ title TEXT NOT NULL,
83
+ description TEXT,
84
+ start_date TEXT,
85
+ end_date TEXT,
86
+ currency TEXT DEFAULT 'EUR',
87
+ cover_image TEXT,
88
+ is_archived INTEGER DEFAULT 0,
89
+ reminder_days INTEGER DEFAULT 3,
90
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
91
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
92
+ );
93
+
94
+ CREATE TABLE IF NOT EXISTS days (
95
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
96
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
97
+ day_number INTEGER NOT NULL,
98
+ date TEXT,
99
+ notes TEXT,
100
+ title TEXT,
101
+ UNIQUE(trip_id, day_number)
102
+ );
103
+
104
+ CREATE TABLE IF NOT EXISTS categories (
105
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
106
+ name TEXT NOT NULL,
107
+ color TEXT DEFAULT '#6366f1',
108
+ icon TEXT DEFAULT '📍',
109
+ user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
110
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
111
+ );
112
+
113
+ CREATE TABLE IF NOT EXISTS tags (
114
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
115
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
116
+ name TEXT NOT NULL,
117
+ color TEXT DEFAULT '#10b981',
118
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
119
+ );
120
+
121
+ CREATE TABLE IF NOT EXISTS places (
122
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
123
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
124
+ name TEXT NOT NULL,
125
+ description TEXT,
126
+ lat REAL,
127
+ lng REAL,
128
+ address TEXT,
129
+ category_id INTEGER REFERENCES categories(id) ON DELETE SET NULL,
130
+ price REAL,
131
+ currency TEXT,
132
+ reservation_status TEXT DEFAULT 'none',
133
+ reservation_notes TEXT,
134
+ reservation_datetime TEXT,
135
+ place_time TEXT,
136
+ end_time TEXT,
137
+ duration_minutes INTEGER DEFAULT 60,
138
+ notes TEXT,
139
+ image_url TEXT,
140
+ google_place_id TEXT,
141
+ website TEXT,
142
+ phone TEXT,
143
+ transport_mode TEXT DEFAULT 'walking',
144
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
145
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
146
+ );
147
+
148
+ CREATE TABLE IF NOT EXISTS place_tags (
149
+ place_id INTEGER NOT NULL REFERENCES places(id) ON DELETE CASCADE,
150
+ tag_id INTEGER NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
151
+ PRIMARY KEY (place_id, tag_id)
152
+ );
153
+
154
+ CREATE TABLE IF NOT EXISTS day_assignments (
155
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
156
+ day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
157
+ place_id INTEGER NOT NULL REFERENCES places(id) ON DELETE CASCADE,
158
+ order_index INTEGER DEFAULT 0,
159
+ notes TEXT,
160
+ reservation_status TEXT DEFAULT 'none',
161
+ reservation_notes TEXT,
162
+ reservation_datetime TEXT,
163
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
164
+ );
165
+
166
+ CREATE TABLE IF NOT EXISTS packing_items (
167
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
168
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
169
+ name TEXT NOT NULL,
170
+ checked INTEGER DEFAULT 0,
171
+ category TEXT,
172
+ sort_order INTEGER DEFAULT 0,
173
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
174
+ );
175
+
176
+ CREATE TABLE IF NOT EXISTS photos (
177
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
178
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
179
+ day_id INTEGER REFERENCES days(id) ON DELETE SET NULL,
180
+ place_id INTEGER REFERENCES places(id) ON DELETE SET NULL,
181
+ filename TEXT NOT NULL,
182
+ original_name TEXT NOT NULL,
183
+ file_size INTEGER,
184
+ mime_type TEXT,
185
+ caption TEXT,
186
+ taken_at TEXT,
187
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
188
+ );
189
+
190
+ CREATE TABLE IF NOT EXISTS trip_files (
191
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
192
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
193
+ place_id INTEGER REFERENCES places(id) ON DELETE SET NULL,
194
+ reservation_id INTEGER REFERENCES reservations(id) ON DELETE SET NULL,
195
+ filename TEXT NOT NULL,
196
+ original_name TEXT NOT NULL,
197
+ file_size INTEGER,
198
+ mime_type TEXT,
199
+ description TEXT,
200
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
201
+ );
202
+
203
+ CREATE TABLE IF NOT EXISTS reservations (
204
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
205
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
206
+ day_id INTEGER REFERENCES days(id) ON DELETE SET NULL,
207
+ end_day_id INTEGER REFERENCES days(id) ON DELETE SET NULL,
208
+ place_id INTEGER REFERENCES places(id) ON DELETE SET NULL,
209
+ assignment_id INTEGER REFERENCES day_assignments(id) ON DELETE SET NULL,
210
+ title TEXT NOT NULL,
211
+ accommodation_id TEXT,
212
+ reservation_time TEXT,
213
+ reservation_end_time TEXT,
214
+ location TEXT,
215
+ confirmation_number TEXT,
216
+ notes TEXT,
217
+ status TEXT DEFAULT 'pending',
218
+ type TEXT DEFAULT 'other',
219
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
220
+ );
221
+
222
+ CREATE TABLE IF NOT EXISTS trip_members (
223
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
224
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
225
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
226
+ invited_by INTEGER REFERENCES users(id),
227
+ added_at DATETIME DEFAULT CURRENT_TIMESTAMP,
228
+ UNIQUE(trip_id, user_id)
229
+ );
230
+
231
+ CREATE TABLE IF NOT EXISTS day_notes (
232
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
233
+ day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
234
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
235
+ text TEXT NOT NULL,
236
+ time TEXT,
237
+ icon TEXT DEFAULT '📝',
238
+ sort_order REAL DEFAULT 0,
239
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
240
+ );
241
+
242
+ CREATE TABLE IF NOT EXISTS app_settings (
243
+ key TEXT PRIMARY KEY,
244
+ value TEXT
245
+ );
246
+
247
+ CREATE TABLE IF NOT EXISTS budget_items (
248
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
249
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
250
+ category TEXT NOT NULL DEFAULT 'Other',
251
+ name TEXT NOT NULL,
252
+ total_price REAL NOT NULL DEFAULT 0,
253
+ persons INTEGER DEFAULT NULL,
254
+ days INTEGER DEFAULT NULL,
255
+ note TEXT,
256
+ sort_order INTEGER DEFAULT 0,
257
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
258
+ );
259
+
260
+ -- Addon system
261
+ CREATE TABLE IF NOT EXISTS addons (
262
+ id TEXT PRIMARY KEY,
263
+ name TEXT NOT NULL,
264
+ description TEXT,
265
+ type TEXT NOT NULL DEFAULT 'global',
266
+ icon TEXT DEFAULT 'Puzzle',
267
+ enabled INTEGER DEFAULT 0,
268
+ config TEXT DEFAULT '{}',
269
+ sort_order INTEGER DEFAULT 0
270
+ );
271
+
272
+ CREATE TABLE IF NOT EXISTS photo_providers (
273
+ id TEXT PRIMARY KEY,
274
+ name TEXT NOT NULL,
275
+ description TEXT,
276
+ icon TEXT DEFAULT 'Image',
277
+ enabled INTEGER DEFAULT 0,
278
+ sort_order INTEGER DEFAULT 0
279
+ );
280
+
281
+ CREATE TABLE IF NOT EXISTS photo_provider_fields (
282
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
283
+ provider_id TEXT NOT NULL REFERENCES photo_providers(id) ON DELETE CASCADE,
284
+ field_key TEXT NOT NULL,
285
+ label TEXT NOT NULL,
286
+ input_type TEXT NOT NULL DEFAULT 'text',
287
+ placeholder TEXT,
288
+ hint TEXT,
289
+ required INTEGER DEFAULT 0,
290
+ secret INTEGER DEFAULT 0,
291
+ settings_key TEXT,
292
+ payload_key TEXT,
293
+ sort_order INTEGER DEFAULT 0,
294
+ UNIQUE(provider_id, field_key)
295
+ );
296
+
297
+ -- Vacay addon tables
298
+ CREATE TABLE IF NOT EXISTS vacay_plans (
299
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
300
+ owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
301
+ block_weekends INTEGER DEFAULT 1,
302
+ holidays_enabled INTEGER DEFAULT 0,
303
+ holidays_region TEXT DEFAULT '',
304
+ company_holidays_enabled INTEGER DEFAULT 1,
305
+ carry_over_enabled INTEGER DEFAULT 1,
306
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
307
+ UNIQUE(owner_id)
308
+ );
309
+
310
+ CREATE TABLE IF NOT EXISTS vacay_plan_members (
311
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
312
+ plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
313
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
314
+ status TEXT DEFAULT 'pending',
315
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
316
+ UNIQUE(plan_id, user_id)
317
+ );
318
+
319
+ CREATE TABLE IF NOT EXISTS vacay_user_colors (
320
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
321
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
322
+ plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
323
+ color TEXT DEFAULT '#6366f1',
324
+ UNIQUE(user_id, plan_id)
325
+ );
326
+
327
+ CREATE TABLE IF NOT EXISTS vacay_years (
328
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
329
+ plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
330
+ year INTEGER NOT NULL,
331
+ UNIQUE(plan_id, year)
332
+ );
333
+
334
+ CREATE TABLE IF NOT EXISTS vacay_user_years (
335
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
336
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
337
+ plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
338
+ year INTEGER NOT NULL,
339
+ vacation_days INTEGER DEFAULT 30,
340
+ carried_over INTEGER DEFAULT 0,
341
+ UNIQUE(user_id, plan_id, year)
342
+ );
343
+
344
+ CREATE TABLE IF NOT EXISTS vacay_entries (
345
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
346
+ plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
347
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
348
+ date TEXT NOT NULL,
349
+ note TEXT DEFAULT '',
350
+ UNIQUE(user_id, plan_id, date)
351
+ );
352
+
353
+ CREATE TABLE IF NOT EXISTS vacay_company_holidays (
354
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
355
+ plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
356
+ date TEXT NOT NULL,
357
+ note TEXT DEFAULT '',
358
+ UNIQUE(plan_id, date)
359
+ );
360
+
361
+ CREATE TABLE IF NOT EXISTS vacay_holiday_calendars (
362
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
363
+ plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
364
+ region TEXT NOT NULL,
365
+ label TEXT,
366
+ color TEXT NOT NULL DEFAULT '#fecaca',
367
+ sort_order INTEGER NOT NULL DEFAULT 0
368
+ );
369
+
370
+ CREATE TABLE IF NOT EXISTS day_accommodations (
371
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
372
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
373
+ place_id INTEGER REFERENCES places(id) ON DELETE SET NULL,
374
+ start_day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
375
+ end_day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
376
+ check_in TEXT,
377
+ check_in_end TEXT,
378
+ check_out TEXT,
379
+ confirmation TEXT,
380
+ notes TEXT,
381
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
382
+ );
383
+
384
+ -- Collab addon tables
385
+ CREATE TABLE IF NOT EXISTS collab_notes (
386
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
387
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
388
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
389
+ category TEXT DEFAULT 'General',
390
+ title TEXT NOT NULL,
391
+ content TEXT,
392
+ color TEXT DEFAULT '#6366f1',
393
+ pinned INTEGER DEFAULT 0,
394
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
395
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
396
+ );
397
+
398
+ CREATE TABLE IF NOT EXISTS collab_polls (
399
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
400
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
401
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
402
+ question TEXT NOT NULL,
403
+ options TEXT NOT NULL,
404
+ multiple INTEGER DEFAULT 0,
405
+ closed INTEGER DEFAULT 0,
406
+ deadline TEXT,
407
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
408
+ );
409
+
410
+ CREATE TABLE IF NOT EXISTS collab_poll_votes (
411
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
412
+ poll_id INTEGER NOT NULL REFERENCES collab_polls(id) ON DELETE CASCADE,
413
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
414
+ option_index INTEGER NOT NULL,
415
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
416
+ UNIQUE(poll_id, user_id, option_index)
417
+ );
418
+
419
+ CREATE TABLE IF NOT EXISTS collab_messages (
420
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
421
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
422
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
423
+ text TEXT NOT NULL,
424
+ reply_to INTEGER REFERENCES collab_messages(id) ON DELETE SET NULL,
425
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
426
+ );
427
+
428
+ CREATE INDEX IF NOT EXISTS idx_collab_notes_trip ON collab_notes(trip_id);
429
+ CREATE INDEX IF NOT EXISTS idx_collab_polls_trip ON collab_polls(trip_id);
430
+ CREATE INDEX IF NOT EXISTS idx_collab_messages_trip ON collab_messages(trip_id);
431
+ `);
432
+
433
+ db.exec(`
434
+ CREATE INDEX IF NOT EXISTS idx_places_trip_id ON places(trip_id);
435
+ CREATE INDEX IF NOT EXISTS idx_places_category_id ON places(category_id);
436
+ CREATE INDEX IF NOT EXISTS idx_days_trip_id ON days(trip_id);
437
+ CREATE INDEX IF NOT EXISTS idx_day_assignments_day_id ON day_assignments(day_id);
438
+ CREATE INDEX IF NOT EXISTS idx_day_assignments_place_id ON day_assignments(place_id);
439
+ CREATE INDEX IF NOT EXISTS idx_place_tags_place_id ON place_tags(place_id);
440
+ CREATE INDEX IF NOT EXISTS idx_place_tags_tag_id ON place_tags(tag_id);
441
+ CREATE INDEX IF NOT EXISTS idx_trip_members_trip_id ON trip_members(trip_id);
442
+ CREATE INDEX IF NOT EXISTS idx_trip_members_user_id ON trip_members(user_id);
443
+ CREATE INDEX IF NOT EXISTS idx_packing_items_trip_id ON packing_items(trip_id);
444
+ CREATE INDEX IF NOT EXISTS idx_budget_items_trip_id ON budget_items(trip_id);
445
+ CREATE INDEX IF NOT EXISTS idx_reservations_trip_id ON reservations(trip_id);
446
+ CREATE INDEX IF NOT EXISTS idx_trip_files_trip_id ON trip_files(trip_id);
447
+ CREATE INDEX IF NOT EXISTS idx_day_notes_day_id ON day_notes(day_id);
448
+ CREATE INDEX IF NOT EXISTS idx_photos_trip_id ON photos(trip_id);
449
+ CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
450
+ CREATE INDEX IF NOT EXISTS idx_day_accommodations_trip_id ON day_accommodations(trip_id);
451
+
452
+ CREATE TABLE IF NOT EXISTS assignment_participants (
453
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
454
+ assignment_id INTEGER NOT NULL REFERENCES day_assignments(id) ON DELETE CASCADE,
455
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
456
+ UNIQUE(assignment_id, user_id)
457
+ );
458
+ CREATE INDEX IF NOT EXISTS idx_assignment_participants_assignment ON assignment_participants(assignment_id);
459
+
460
+ CREATE TABLE IF NOT EXISTS audit_log (
461
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
462
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
463
+ user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
464
+ action TEXT NOT NULL,
465
+ resource TEXT,
466
+ details TEXT,
467
+ ip TEXT
468
+ );
469
+ CREATE INDEX IF NOT EXISTS idx_audit_log_created ON audit_log(created_at DESC);
470
+
471
+ CREATE TABLE IF NOT EXISTS notifications (
472
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
473
+ type TEXT NOT NULL CHECK(type IN ('simple', 'boolean', 'navigate')),
474
+ scope TEXT NOT NULL CHECK(scope IN ('trip', 'user', 'admin')),
475
+ target INTEGER NOT NULL,
476
+ sender_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
477
+ recipient_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
478
+ title_key TEXT NOT NULL,
479
+ title_params TEXT DEFAULT '{}',
480
+ text_key TEXT NOT NULL,
481
+ text_params TEXT DEFAULT '{}',
482
+ positive_text_key TEXT,
483
+ negative_text_key TEXT,
484
+ positive_callback TEXT,
485
+ negative_callback TEXT,
486
+ response TEXT CHECK(response IN ('positive', 'negative')),
487
+ navigate_text_key TEXT,
488
+ navigate_target TEXT,
489
+ is_read INTEGER DEFAULT 0,
490
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
491
+ );
492
+ CREATE INDEX IF NOT EXISTS idx_notifications_recipient ON notifications(recipient_id, is_read, created_at DESC);
493
+ CREATE INDEX IF NOT EXISTS idx_notifications_recipient_created ON notifications(recipient_id, created_at DESC);
494
+
495
+ CREATE TABLE IF NOT EXISTS notification_channel_preferences (
496
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
497
+ event_type TEXT NOT NULL,
498
+ channel TEXT NOT NULL,
499
+ enabled INTEGER NOT NULL DEFAULT 1,
500
+ PRIMARY KEY (user_id, event_type, channel)
501
+ );
502
+ CREATE INDEX IF NOT EXISTS idx_ncp_user ON notification_channel_preferences(user_id);
503
+
504
+ CREATE TABLE IF NOT EXISTS migrations (id integer PRIMARY KEY AUTOINCREMENT NOT NULL, timestamp bigint NOT NULL, name varchar NOT NULL);
505
+ `);
506
+ }
507
+
508
+ export { createTables };
server/src/db/seeds.ts ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Database from 'better-sqlite3';
2
+ import crypto from 'crypto';
3
+
4
+ // bcrypt cost factor for the seeded admin password — kept in sync with authService.
5
+ const BCRYPT_COST = 12;
6
+
7
+ // Seeds run at startup before the DB admin panel can be used, so only env vars
8
+ // are checked here. The granular password_login/password_registration DB toggles
9
+ // are only relevant after the first user exists; at that point seeds have already
10
+ // finished and skip via the userCount > 0 guard above.
11
+ function isOidcOnlyConfigured(): boolean {
12
+ if (process.env.OIDC_ONLY?.toLowerCase() !== 'true') return false;
13
+ return !!(process.env.OIDC_ISSUER && process.env.OIDC_CLIENT_ID);
14
+ }
15
+
16
+ function seedAdminAccount(db: Database.Database): void {
17
+ try {
18
+ const userCount = (db.prepare('SELECT COUNT(*) as count FROM users').get() as { count: number }).count;
19
+ if (userCount > 0) return;
20
+
21
+ if (isOidcOnlyConfigured()) {
22
+ console.log('');
23
+ console.log('╔══════════════════════════════════════════════╗');
24
+ console.log('║ TREK — OIDC-Only Mode ║');
25
+ console.log('║ First SSO login will become admin. ║');
26
+ console.log('╚══════════════════════════════════════════════╝');
27
+ console.log('');
28
+ return;
29
+ }
30
+
31
+ const bcrypt = require('bcryptjs');
32
+
33
+ const env_admin_email = process.env.ADMIN_EMAIL;
34
+ const env_admin_pw = process.env.ADMIN_PASSWORD;
35
+
36
+ let password;
37
+ let email;
38
+ if (env_admin_email && env_admin_pw) {
39
+ password = env_admin_pw;
40
+ email = env_admin_email;
41
+ } else {
42
+ password = crypto.randomBytes(12).toString('base64url');
43
+ email = 'admin@trek.local';
44
+ }
45
+
46
+ const hash = bcrypt.hashSync(password, BCRYPT_COST);
47
+ const username = 'admin';
48
+
49
+ db.prepare('INSERT INTO users (username, email, password_hash, role, must_change_password) VALUES (?, ?, ?, ?, 1)').run(username, email, hash, 'admin');
50
+
51
+ console.log('');
52
+ console.log('╔══════════════════════════════════════════════╗');
53
+ console.log('║ TREK — First Run: Admin Account Created ║');
54
+ console.log('╠══════════════════════════════════════════════╣');
55
+ console.log(`║ Email: ${email.padEnd(33)}║`);
56
+ console.log(`║ Password: ${password.padEnd(33)}║`);
57
+ console.log('╚══════════════════════════════════════════════╝');
58
+ console.log('');
59
+ } catch (err: unknown) {
60
+ console.error('[ERROR] Error seeding admin account:', err instanceof Error ? err.message : err);
61
+ }
62
+ }
63
+
64
+ function seedCategories(db: Database.Database): void {
65
+ try {
66
+ const existingCats = db.prepare('SELECT COUNT(*) as count FROM categories').get() as { count: number };
67
+ if (existingCats.count === 0) {
68
+ const defaultCategories = [
69
+ { name: 'Hotel', color: '#3b82f6', icon: '🏨' },
70
+ { name: 'Restaurant', color: '#ef4444', icon: '🍽️' },
71
+ { name: 'Attraction', color: '#8b5cf6', icon: '🏛️' },
72
+ { name: 'Shopping', color: '#f59e0b', icon: '🛍️' },
73
+ { name: 'Transport', color: '#6b7280', icon: '🚌' },
74
+ { name: 'Activity', color: '#10b981', icon: '🎯' },
75
+ { name: 'Bar/Cafe', color: '#f97316', icon: '☕' },
76
+ { name: 'Beach', color: '#06b6d4', icon: '🏖️' },
77
+ { name: 'Nature', color: '#84cc16', icon: '🌿' },
78
+ { name: 'Other', color: '#6366f1', icon: '📍' },
79
+ ];
80
+ const insertCat = db.prepare('INSERT INTO categories (name, color, icon) VALUES (?, ?, ?)');
81
+ for (const cat of defaultCategories) insertCat.run(cat.name, cat.color, cat.icon);
82
+ console.log('Default categories seeded');
83
+ }
84
+ } catch (err: unknown) {
85
+ console.error('Error seeding categories:', err instanceof Error ? err.message : err);
86
+ }
87
+ }
88
+
89
+ function seedAddons(db: Database.Database): void {
90
+ try {
91
+ const defaultAddons = [
92
+ { id: 'packing', name: 'Lists', description: 'Packing lists and to-do tasks for your trips', type: 'trip', icon: 'ListChecks', enabled: 1, sort_order: 0 },
93
+ { id: 'budget', name: 'Costs', description: 'Track and split trip expenses', type: 'trip', icon: 'Wallet', enabled: 1, sort_order: 1 },
94
+ { id: 'documents', name: 'Documents', description: 'Store and manage travel documents', type: 'trip', icon: 'FileText', enabled: 1, sort_order: 2 },
95
+ { id: 'vacay', name: 'Vacay', description: 'Personal vacation day planner with calendar view', type: 'global', icon: 'CalendarDays', enabled: 1, sort_order: 10 },
96
+ { id: 'atlas', name: 'Atlas', description: 'World map of your visited countries with travel stats', type: 'global', icon: 'Globe', enabled: 1, sort_order: 11 },
97
+ { id: 'mcp', name: 'MCP', description: 'Model Context Protocol for AI assistant integration', type: 'integration', icon: 'Terminal', enabled: 0, sort_order: 12 },
98
+ { id: 'naver_list_import', name: 'Naver List Import', description: 'Import places from shared Naver Maps lists', type: 'trip', icon: 'Link2', enabled: 1, sort_order: 13 },
99
+ { id: 'collab', name: 'Collab', description: 'Notes, polls, and live chat for trip collaboration', type: 'trip', icon: 'Users', enabled: 1, sort_order: 6 },
100
+ { id: 'journey', name: 'Journey', description: 'Trip tracking & travel journal — check-ins, photos, daily stories', type: 'global', icon: 'Compass', enabled: 0, sort_order: 35 },
101
+ { id: 'airtrail', name: 'AirTrail', description: 'Sync flights from your self-hosted AirTrail instance', type: 'integration', icon: 'Plane', enabled: 0, sort_order: 14 },
102
+ ];
103
+ const insertAddon = db.prepare('INSERT OR IGNORE INTO addons (id, name, description, type, icon, enabled, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)');
104
+ for (const a of defaultAddons) insertAddon.run(a.id, a.name, a.description, a.type, a.icon, a.enabled, a.sort_order);
105
+
106
+ const providerRows = [
107
+ {
108
+ id: 'immich',
109
+ name: 'Immich',
110
+ description: 'Immich photo provider',
111
+ icon: 'Image',
112
+ enabled: 0,
113
+ sort_order: 0,
114
+ },
115
+ {
116
+ id: 'synologyphotos',
117
+ name: 'Synology Photos',
118
+ description: 'Synology Photos integration with separate account settings',
119
+ icon: 'Image',
120
+ enabled: 0,
121
+ sort_order: 1,
122
+ },
123
+ ];
124
+ const insertProvider = db.prepare('INSERT OR IGNORE INTO photo_providers (id, name, description, icon, enabled, sort_order) VALUES (?, ?, ?, ?, ?, ?)');
125
+ for (const p of providerRows) insertProvider.run(p.id, p.name, p.description, p.icon, p.enabled, p.sort_order);
126
+
127
+ const providerFields = [
128
+ { provider_id: 'immich', field_key: 'immich_url', label: 'providerUrl', input_type: 'url', placeholder: 'https://immich.example.com', hint: null, required: 1, secret: 0, settings_key: 'immich_url', payload_key: 'immich_url', sort_order: 0 },
129
+ { provider_id: 'immich', field_key: 'immich_api_key', label: 'providerApiKey', input_type: 'password', placeholder: 'API Key', hint: null, required: 1, secret: 1, settings_key: null, payload_key: 'immich_api_key', sort_order: 1 },
130
+ { provider_id: 'synologyphotos', field_key: 'synology_url', label: 'providerUrl', input_type: 'url', placeholder: 'https://synology.example.com/photo', hint: 'providerUrlHintSynology', required: 1, secret: 0, settings_key: 'synology_url', payload_key: 'synology_url', sort_order: 0 },
131
+ { provider_id: 'synologyphotos', field_key: 'synology_username', label: 'providerUsername', input_type: 'text', placeholder: 'Username', hint: null, required: 1, secret: 0, settings_key: 'synology_username', payload_key: 'synology_username', sort_order: 1 },
132
+ { provider_id: 'synologyphotos', field_key: 'synology_password', label: 'providerPassword', input_type: 'password', placeholder: 'Password', hint: null, required: 1, secret: 1, settings_key: null, payload_key: 'synology_password', sort_order: 2 },
133
+ { provider_id: 'synologyphotos', field_key: 'synology_otp', label: 'providerOTP', input_type: 'text', placeholder: '123456', hint: null, required: 0, secret: 0, settings_key: null, payload_key: 'synology_otp', sort_order: 3 },
134
+ { provider_id: 'synologyphotos', field_key: 'synology_skip_ssl', label: 'skipSSLVerification', input_type: 'checkbox', placeholder: null, hint: null, required: 0, secret: 0, settings_key: 'synology_skip_ssl', payload_key: 'synology_skip_ssl', sort_order: 4 },
135
+ ];
136
+ const insertProviderField = db.prepare('INSERT OR IGNORE INTO photo_provider_fields (provider_id, field_key, label, input_type, placeholder, hint, required, secret, settings_key, payload_key, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
137
+ for (const f of providerFields) {
138
+ insertProviderField.run(f.provider_id, f.field_key, f.label, f.input_type, f.placeholder, f.hint, f.required, f.secret, f.settings_key, f.payload_key, f.sort_order);
139
+ }
140
+ console.log('Default addons seeded');
141
+ } catch (err: unknown) {
142
+ console.error('Error seeding addons:', err instanceof Error ? err.message : err);
143
+ }
144
+ }
145
+
146
+ function runSeeds(db: Database.Database): void {
147
+ seedAdminAccount(db);
148
+ seedCategories(db);
149
+ seedAddons(db);
150
+ }
151
+
152
+ export { runSeeds };
server/src/demo/demo-reset.ts ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+
4
+ const dataDir = path.join(__dirname, '../../data');
5
+ const dbPath = path.join(dataDir, 'travel.db');
6
+ const baselinePath = path.join(dataDir, 'travel-baseline.db');
7
+
8
+ function resetDemoUser(): void {
9
+ if (!fs.existsSync(baselinePath)) {
10
+ console.log('[Demo Reset] No baseline found, skipping. Admin must save baseline first.');
11
+ return;
12
+ }
13
+
14
+ const { db, closeDb, reinitialize } = require('../db/database');
15
+
16
+ // Save admin's current credentials and API keys (these should survive the reset)
17
+ const adminEmail = process.env.DEMO_ADMIN_EMAIL || 'admin@nomad.app';
18
+ interface AdminData { password_hash: string; maps_api_key: string | null; openweather_api_key: string | null; unsplash_api_key: string | null; avatar: string | null; }
19
+ let adminData: AdminData | undefined = undefined;
20
+ try {
21
+ adminData = db.prepare(
22
+ 'SELECT password_hash, maps_api_key, openweather_api_key, unsplash_api_key, avatar FROM users WHERE email = ?'
23
+ ).get(adminEmail) as AdminData | undefined;
24
+ } catch (e: unknown) {
25
+ console.error('[Demo Reset] Failed to read admin data:', e instanceof Error ? e.message : e);
26
+ }
27
+
28
+ // Flush WAL to main DB file
29
+ try { db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch (e) {}
30
+
31
+ // Close DB connection
32
+ closeDb();
33
+
34
+ // Restore baseline
35
+ try {
36
+ fs.copyFileSync(baselinePath, dbPath);
37
+ // Remove WAL/SHM files if they exist (stale from old connection)
38
+ try { fs.unlinkSync(dbPath + '-wal'); } catch (e) {}
39
+ try { fs.unlinkSync(dbPath + '-shm'); } catch (e) {}
40
+ } catch (e: unknown) {
41
+ console.error('[Demo Reset] Failed to restore baseline:', e instanceof Error ? e.message : e);
42
+ reinitialize();
43
+ return;
44
+ }
45
+
46
+ // Reinitialize DB connection with restored baseline
47
+ reinitialize();
48
+
49
+ // Restore admin's latest credentials (in case admin changed password/API keys after baseline was saved)
50
+ if (adminData) {
51
+ try {
52
+ const { db: freshDb } = require('../db/database');
53
+ freshDb.prepare(
54
+ 'UPDATE users SET password_hash = ?, maps_api_key = ?, openweather_api_key = ?, unsplash_api_key = ?, avatar = ? WHERE email = ?'
55
+ ).run(
56
+ adminData.password_hash,
57
+ adminData.maps_api_key,
58
+ adminData.openweather_api_key,
59
+ adminData.unsplash_api_key,
60
+ adminData.avatar,
61
+ adminEmail
62
+ );
63
+ } catch (e: unknown) {
64
+ console.error('[Demo Reset] Failed to restore admin credentials:', e instanceof Error ? e.message : e);
65
+ }
66
+ }
67
+
68
+ console.log('[Demo Reset] Database restored from baseline');
69
+ }
70
+
71
+ function saveBaseline(): void {
72
+ const { db } = require('../db/database');
73
+
74
+ // Flush WAL so baseline file is self-contained
75
+ try { db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch (e) {}
76
+
77
+ fs.copyFileSync(dbPath, baselinePath);
78
+ console.log('[Demo] Baseline saved');
79
+ }
80
+
81
+ function hasBaseline(): boolean {
82
+ return fs.existsSync(baselinePath);
83
+ }
84
+
85
+ export { resetDemoUser, saveBaseline, hasBaseline };
server/src/demo/demo-seed.ts ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import bcrypt from 'bcryptjs';
2
+ import Database from 'better-sqlite3';
3
+
4
+ function seedDemoData(db: Database.Database): { adminId: number; demoId: number } {
5
+ const ADMIN_USER = process.env.DEMO_ADMIN_USER || 'admin';
6
+ const ADMIN_EMAIL = process.env.DEMO_ADMIN_EMAIL || 'admin@trek.app';
7
+ const ADMIN_PASS = process.env.DEMO_ADMIN_PASS || 'admin12345';
8
+ const DEMO_EMAIL = 'demo@trek.app';
9
+ const DEMO_PASS = 'demo12345';
10
+
11
+ // Create admin user if not exists
12
+ let admin = db.prepare('SELECT id FROM users WHERE email = ?').get(ADMIN_EMAIL) as { id: number } | undefined;
13
+ if (!admin) {
14
+ const hash = bcrypt.hashSync(ADMIN_PASS, 10);
15
+ const r = db.prepare('INSERT INTO users (username, email, password_hash, role) VALUES (?, ?, ?, ?)').run(ADMIN_USER, ADMIN_EMAIL, hash, 'admin');
16
+ admin = { id: Number(r.lastInsertRowid) };
17
+ console.log('[Demo] Admin user created');
18
+ } else {
19
+ admin.id = Number(admin.id);
20
+ }
21
+
22
+ // Create demo user if not exists
23
+ let demo = db.prepare('SELECT id FROM users WHERE email = ?').get(DEMO_EMAIL) as { id: number } | undefined;
24
+ if (!demo) {
25
+ const hash = bcrypt.hashSync(DEMO_PASS, 10);
26
+ const r = db.prepare('INSERT INTO users (username, email, password_hash, role) VALUES (?, ?, ?, ?)').run('demo', DEMO_EMAIL, hash, 'user');
27
+ demo = { id: Number(r.lastInsertRowid) };
28
+ console.log('[Demo] Demo user created');
29
+ } else {
30
+ demo.id = Number(demo.id);
31
+ }
32
+
33
+ // Disable registration in demo mode
34
+ db.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('allow_registration', 'false')").run();
35
+
36
+ // Check if admin already has example trips
37
+ const adminTrips = db.prepare('SELECT COUNT(*) as count FROM trips WHERE user_id = ?').get(admin.id) as { count: number };
38
+ if (adminTrips.count > 0) {
39
+ console.log('[Demo] Example trips already exist, ensuring demo membership');
40
+ ensureDemoMembership(db, admin.id, demo.id);
41
+ return { adminId: admin.id, demoId: demo.id };
42
+ }
43
+
44
+ console.log('[Demo] Seeding example trips...');
45
+ seedExampleTrips(db, admin.id, demo.id);
46
+
47
+ // Auto-save baseline after first seed
48
+ const { saveBaseline, hasBaseline } = require('./demo-reset');
49
+ if (!hasBaseline()) {
50
+ saveBaseline();
51
+ }
52
+
53
+ return { adminId: admin.id, demoId: demo.id };
54
+ }
55
+
56
+ function ensureDemoMembership(db: Database.Database, adminId: number, demoId: number): void {
57
+ const trips = db.prepare('SELECT id FROM trips WHERE user_id = ?').all(adminId) as { id: number }[];
58
+ const insertMember = db.prepare('INSERT OR IGNORE INTO trip_members (trip_id, user_id, invited_by) VALUES (?, ?, ?)');
59
+ for (const trip of trips) {
60
+ insertMember.run(trip.id, demoId, adminId);
61
+ }
62
+ }
63
+
64
+ function seedExampleTrips(db: Database.Database, adminId: number, demoId: number): void {
65
+ const insertTrip = db.prepare('INSERT INTO trips (user_id, title, description, start_date, end_date, currency) VALUES (?, ?, ?, ?, ?, ?)');
66
+ const insertDay = db.prepare('INSERT INTO days (trip_id, day_number, date) VALUES (?, ?, ?)');
67
+ const insertPlace = db.prepare('INSERT INTO places (trip_id, name, lat, lng, address, category_id, place_time, duration_minutes, notes, image_url, google_place_id, website, phone) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
68
+ const insertAssignment = db.prepare('INSERT INTO day_assignments (day_id, place_id, order_index) VALUES (?, ?, ?)');
69
+ const insertPacking = db.prepare('INSERT INTO packing_items (trip_id, name, checked, category, sort_order) VALUES (?, ?, ?, ?, ?)');
70
+ const insertBudget = db.prepare('INSERT INTO budget_items (trip_id, category, name, total_price, persons, note) VALUES (?, ?, ?, ?, ?, ?)');
71
+ const insertReservation = db.prepare('INSERT INTO reservations (trip_id, day_id, title, reservation_time, confirmation_number, status, type, location) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
72
+ const insertMember = db.prepare('INSERT OR IGNORE INTO trip_members (trip_id, user_id, invited_by) VALUES (?, ?, ?)');
73
+ const insertNote = db.prepare('INSERT INTO day_notes (day_id, trip_id, text, time, icon, sort_order) VALUES (?, ?, ?, ?, ?, ?)');
74
+
75
+ // Category IDs: 1=Hotel, 2=Restaurant, 3=Attraction, 5=Transport, 7=Bar/Cafe, 8=Beach, 9=Nature, 6=Entertainment
76
+
77
+ // --- Trip 1: Tokyo & Kyoto ---
78
+ const trip1 = insertTrip.run(adminId, 'Tokyo & Kyoto', 'Two weeks in Japan — from the neon-lit streets of Tokyo to the serene temples of Kyoto.', '2026-04-15', '2026-04-21', 'JPY');
79
+ const t1 = Number(trip1.lastInsertRowid);
80
+
81
+ const t1days: number[] = [];
82
+ for (let i = 0; i < 7; i++) {
83
+ const d = insertDay.run(t1, i + 1, `2026-04-${15 + i}`);
84
+ t1days.push(Number(d.lastInsertRowid));
85
+ }
86
+
87
+ const t1places: [number, string, number, number, string, number, string, number, string, string | null, string | null, string | null, string | null][] = [
88
+ [t1, 'Hotel Shinjuku Granbell', 35.6938, 139.7035, '2-14-5 Kabukicho, Shinjuku City, Tokyo 160-0021, Japan', 1, '15:00', 60, 'Check-in from 3 PM. Steps from Shinjuku Station.', null, 'ChIJdaGEJBeMGGARYgt8sLBv6lM', 'https://www.grfranbellhotel.jp/shinjuku/', '+81 3-5155-2666'],
89
+ [t1, 'Senso-ji Temple', 35.7148, 139.7967, '2 Chome-3-1 Asakusa, Taito City, Tokyo 111-0032, Japan', 3, '09:00', 90, 'Oldest temple in Tokyo. Fewer tourists in the early morning.', null, 'ChIJ8T1GpMGOGGARDYGSgpoOdfg', 'https://www.senso-ji.jp/', '+81 3-3842-0181'],
90
+ [t1, 'Shibuya Crossing', 35.6595, 139.7004, '2 Chome-2-1 Dogenzaka, Shibuya City, Tokyo 150-0043, Japan', 3, '18:00', 45, 'World\'s busiest pedestrian crossing. Most impressive at night.', null, 'ChIJLyzOhmyLGGARMKWbl5z6wGg', null, null],
91
+ [t1, 'Tsukiji Outer Market', 35.6654, 139.7707, '4 Chome-16-2 Tsukiji, Chuo City, Tokyo 104-0045, Japan', 2, '08:00', 120, 'Fresh sushi for breakfast! Explore the street food stalls.', null, 'ChIJq2i1dZCLGGAR1TfoBRo25VU', 'https://www.tsukiji.or.jp/', null],
92
+ [t1, 'Meiji Jingu Shrine', 35.6764, 139.6993, '1-1 Yoyogikamizonocho, Shibuya City, Tokyo 151-8557, Japan', 3, '10:00', 75, 'Peaceful oasis in the middle of the city. Walk through the forest to the shrine.', null, 'ChIJ5SuJSByMGGARMg9qOlTFgkc', 'https://www.meijijingu.or.jp/', '+81 3-3379-5511'],
93
+ [t1, 'Akihabara Electric Town', 35.7023, 139.7745, 'Sotokanda, Chiyoda City, Tokyo, Japan', 3, '14:00', 180, 'Electric Town — anime, manga, electronics. Retro gaming shops!', null, 'ChIJGz1usEyMGGAR1mYByqOOJao', null, null],
94
+ [t1, 'Shinkansen to Kyoto', 35.6812, 139.7671, '1 Chome Marunouchi, Chiyoda City, Tokyo 100-0005, Japan', 5, '08:30', 140, 'Nozomi Shinkansen, approx. 2h15. Window seat for Mt. Fuji views!', null, 'ChIJC3Cf2PuLGGAROO00ukl8JwA', null, null],
95
+ [t1, 'Hotel Granvia Kyoto', 34.9856, 135.7580, 'Karasuma-dori Shiokoji-sagaru, Shimogyo-ku, Kyoto 600-8216, Japan', 1, '14:00', 60, 'Right at Kyoto Station. Perfect base for day trips.', null, 'ChIJUf6MDFcIAWARLihjKC9FWDY', 'https://www.granvia-kyoto.co.jp/', '+81 75-344-8888'],
96
+ [t1, 'Fushimi Inari Taisha', 34.9671, 135.7727, '68 Fukakusa Yabunouchicho, Fushimi Ward, Kyoto 612-0882, Japan', 3, '07:00', 150, '10,000 vermillion torii gates. Start early for empty paths!', null, 'ChIJIW0JRbMIAWARPYEzP5LVHGE', 'http://inari.jp/', '+81 75-641-7331'],
97
+ [t1, 'Kinkaku-ji (Golden Pavilion)', 35.0394, 135.7292, '1 Kinkakujicho, Kita Ward, Kyoto 603-8361, Japan', 3, '10:00', 60, 'The golden temple reflected in the mirror pond. Iconic photo spot.', null, 'ChIJvUbrwCCoAWAR5-uyAXPzBHg', null, '+81 75-461-0013'],
98
+ [t1, 'Arashiyama Bamboo Grove', 35.0095, 135.6673, 'Sagatenryuji Susukinobabacho, Ukyo Ward, Kyoto 616-8385, Japan', 9, '09:00', 90, 'Magical bamboo forest. Best visited in the morning before the crowds.', null, 'ChIJFS4EvA6pAWARQsAPVijvW7I', null, null],
99
+ [t1, 'Nishiki Market', 35.0050, 135.7647, 'Nishiki-koji Dori, Nakagyo Ward, Kyoto 604-8054, Japan', 2, '12:00', 90, 'Kyoto\'s kitchen street. Try the matcha ice cream and fresh mochi!', null, 'ChIJ09zzUigJAWARXzIdh1NE3hQ', 'http://www.kyoto-nishiki.or.jp/', null],
100
+ [t1, 'Gion District', 35.0037, 135.7755, 'Gionmachi Minamigawa, Higashiyama Ward, Kyoto 605-0074, Japan', 3, '17:00', 120, 'Historic geisha district. Best chance of spotting a maiko in the evening.', null, 'ChIJ7WWWjfYJAWARGqEHAfXIzgQ', null, null],
101
+ ];
102
+
103
+ const t1pIds = t1places.map(p => Number(insertPlace.run(...p).lastInsertRowid));
104
+
105
+ // Day 1: Hotel Check-in, Shibuya
106
+ insertAssignment.run(t1days[0], t1pIds[0], 0);
107
+ insertAssignment.run(t1days[0], t1pIds[2], 1);
108
+ insertNote.run(t1days[0], t1, 'Pick up Pocket WiFi at airport', '13:00', 'Info', 0.5);
109
+ // Day 2: Tsukiji, Senso-ji, Akihabara
110
+ insertAssignment.run(t1days[1], t1pIds[3], 0);
111
+ insertAssignment.run(t1days[1], t1pIds[1], 1);
112
+ insertAssignment.run(t1days[1], t1pIds[5], 2);
113
+ // Day 3: Meiji Shrine, free afternoon
114
+ insertAssignment.run(t1days[2], t1pIds[4], 0);
115
+ insertNote.run(t1days[2], t1, 'Explore Harajuku after the shrine', '12:00', 'MapPin', 1);
116
+ // Day 4: Shinkansen to Kyoto, Hotel
117
+ insertAssignment.run(t1days[3], t1pIds[6], 0);
118
+ insertAssignment.run(t1days[3], t1pIds[7], 1);
119
+ insertNote.run(t1days[3], t1, 'Sit on right side for Mt. Fuji views!', '08:30', 'Train', 0.5);
120
+ // Day 5: Fushimi Inari, Nishiki Market
121
+ insertAssignment.run(t1days[4], t1pIds[8], 0);
122
+ insertAssignment.run(t1days[4], t1pIds[11], 1);
123
+ // Day 6: Kinkaku-ji, Arashiyama
124
+ insertAssignment.run(t1days[5], t1pIds[9], 0);
125
+ insertAssignment.run(t1days[5], t1pIds[10], 1);
126
+ // Day 7: Gion
127
+ insertAssignment.run(t1days[6], t1pIds[12], 0);
128
+ insertNote.run(t1days[6], t1, 'Last evening — farewell dinner at Pontocho Alley', '19:00', 'Star', 1);
129
+
130
+ // Packing
131
+ const t1packing: [string, number, string, number][] = [
132
+ ['Passport', 1, 'Documents', 0], ['Japan Rail Pass', 1, 'Documents', 1],
133
+ ['Power adapter Type A/B', 0, 'Electronics', 2], ['Camera + charger', 0, 'Electronics', 3],
134
+ ['Comfortable walking shoes', 0, 'Clothing', 4], ['Rain jacket', 0, 'Clothing', 5],
135
+ ['Sunscreen', 0, 'Toiletries', 6], ['Travel first aid kit', 0, 'Toiletries', 7],
136
+ ['Pocket WiFi confirmation', 1, 'Electronics', 8], ['Yen cash', 0, 'Documents', 9],
137
+ ];
138
+ t1packing.forEach(p => insertPacking.run(t1, ...p));
139
+
140
+ // Budget
141
+ insertBudget.run(t1, 'Accommodation', 'Hotel Shinjuku (3 nights)', 67500, 2, 'Double room');
142
+ insertBudget.run(t1, 'Accommodation', 'Hotel Granvia Kyoto (4 nights)', 102000, 2, 'Superior room');
143
+ insertBudget.run(t1, 'Transport', 'Flights FRA-NRT return', 180000, 2, 'Lufthansa direct');
144
+ insertBudget.run(t1, 'Transport', 'Japan Rail Pass (7 days)', 57000, 2, 'Ordinary');
145
+ insertBudget.run(t1, 'Food', 'Daily food budget', 52500, 2, 'Approx. 7,500 JPY/day');
146
+ insertBudget.run(t1, 'Activities', 'Temple entries & experiences', 18000, 2, null);
147
+
148
+ // Reservations
149
+ insertReservation.run(t1, t1days[0], 'Hotel Shinjuku Check-in', '15:00', 'SG-2026-78432', 'confirmed', 'hotel', 'Shinjuku, Tokyo');
150
+ insertReservation.run(t1, t1days[3], 'Shinkansen Tokyo → Kyoto', '08:30', 'JR-NOZOMI-445', 'confirmed', 'transport', 'Tokyo Station');
151
+
152
+ insertMember.run(t1, demoId, adminId);
153
+
154
+ // --- Trip 2: Barcelona Long Weekend ---
155
+ const trip2 = insertTrip.run(adminId, 'Barcelona Long Weekend', 'Gaudi, tapas, and Mediterranean vibes — a long weekend in the Catalan capital.', '2026-05-21', '2026-05-24', 'EUR');
156
+ const t2 = Number(trip2.lastInsertRowid);
157
+
158
+ const t2days: number[] = [];
159
+ for (let i = 0; i < 4; i++) {
160
+ const d = insertDay.run(t2, i + 1, `2026-05-${21 + i}`);
161
+ t2days.push(Number(d.lastInsertRowid));
162
+ }
163
+
164
+ const t2places: [number, string, number, number, string, number, string, number, string, string | null, string | null, string | null, string | null][] = [
165
+ [t2, 'W Barcelona', 41.3686, 2.1920, 'Placa de la Rosa dels Vents 1, 08039 Barcelona, Spain', 1, '14:00', 60, 'Right on the beach. Rooftop bar with panoramic views!', null, 'ChIJKfj5C8yjpBIRCPC3RPI0JO4', 'https://www.marriott.com/hotels/travel/bcnwh-w-barcelona/', '+34 932 95 28 00'],
166
+ [t2, 'Sagrada Familia', 41.4036, 2.1744, 'C/ de Mallorca, 401, 08013 Barcelona, Spain', 3, '10:00', 120, 'Gaudi\'s masterpiece. Book tickets online in advance — sells out fast!', null, 'ChIJk_s92NyipBIRUMnDG8Kq2Js', 'https://sagradafamilia.org/', '+34 932 08 04 14'],
167
+ [t2, 'Park Guell', 41.4145, 2.1527, '08024 Barcelona, Spain', 3, '09:00', 90, 'Mosaic terrace with city views. Book early for the Monumental Zone.', null, 'ChIJ4eQMeOmipBIRb65JRUzGE8k', 'https://parkguell.barcelona/', '+34 934 09 18 31'],
168
+ [t2, 'La Boqueria Market', 41.3816, 2.1717, 'La Rambla, 91, 08001 Barcelona, Spain', 2, '12:00', 75, 'Famous market on La Rambla. Fresh juice, jamon iberico, and seafood!', null, 'ChIJB_RfKcuipBIRkPKW7MzVGKg', 'http://www.boqueria.barcelona/', '+34 933 18 25 84'],
169
+ [t2, 'Barceloneta Beach', 41.3784, 2.1925, 'Passeig Maritim de la Barceloneta, 08003 Barcelona, Spain', 8, '16:00', 120, 'City beach to unwind after sightseeing. Great chiringuitos nearby.', null, 'ChIJAQCl79-ipBIRUKF3myrMYkM', null, null],
170
+ [t2, 'Gothic Quarter', 41.3834, 2.1762, 'Barri Gotic, 08002 Barcelona, Spain', 3, '15:00', 90, 'Medieval lanes, the cathedral, and Placa Reial. Get lost in the alleys!', null, 'ChIJ4_xkvv2ipBIRrK3bdd-lHgo', null, null],
171
+ [t2, 'Casa Batllo', 41.3916, 2.1650, 'Passeig de Gracia, 43, 08007 Barcelona, Spain', 3, '11:00', 75, 'Gaudi\'s dragon house. The facade alone is worth the visit.', null, 'ChIJ-2VKIcaipBIRKK63H5PYjqQ', 'https://www.casabatllo.es/', '+34 932 16 03 06'],
172
+ [t2, 'El Born & Tapas', 41.3856, 2.1825, 'El Born, 08003 Barcelona, Spain', 7, '20:00', 120, 'Trendy neighborhood with the best tapas bars. Try Cal Pep or El Xampanyet!', null, 'ChIJNY56dxuipBIRbqjSczmLvIA', null, null],
173
+ ];
174
+
175
+ const t2pIds = t2places.map(p => Number(insertPlace.run(...p).lastInsertRowid));
176
+
177
+ // Day 1: Arrival, Beach, El Born
178
+ insertAssignment.run(t2days[0], t2pIds[0], 0);
179
+ insertAssignment.run(t2days[0], t2pIds[4], 1);
180
+ insertAssignment.run(t2days[0], t2pIds[7], 2);
181
+ // Day 2: Sagrada Familia, Casa Batllo, La Boqueria
182
+ insertAssignment.run(t2days[1], t2pIds[1], 0);
183
+ insertAssignment.run(t2days[1], t2pIds[6], 1);
184
+ insertAssignment.run(t2days[1], t2pIds[3], 2);
185
+ insertNote.run(t2days[1], t2, 'Tickets already booked for 10:00 AM slot', '09:30', 'Ticket', 0.5);
186
+ // Day 3: Park Guell, Gothic Quarter
187
+ insertAssignment.run(t2days[2], t2pIds[2], 0);
188
+ insertAssignment.run(t2days[2], t2pIds[5], 1);
189
+ // Day 4: Beach morning, departure
190
+ insertAssignment.run(t2days[3], t2pIds[4], 0);
191
+ insertNote.run(t2days[3], t2, 'Flight departs at 18:30 — leave hotel by 15:00', '14:00', 'Plane', 1);
192
+
193
+ // Packing
194
+ ['Passport', 'Sunscreen SPF50', 'Swimwear', 'Sunglasses', 'Comfortable sandals', 'Beach towel'].forEach((name, i) => {
195
+ insertPacking.run(t2, name, 0, i < 1 ? 'Documents' : 'Summer', i);
196
+ });
197
+
198
+ // Budget
199
+ insertBudget.run(t2, 'Accommodation', 'W Barcelona (3 nights)', 780, 2, 'Sea View Room');
200
+ insertBudget.run(t2, 'Transport', 'Flights BER-BCN return', 180, 2, 'Eurowings');
201
+ insertBudget.run(t2, 'Food', 'Restaurants & tapas', 300, 2, 'Approx. 75 EUR/day');
202
+ insertBudget.run(t2, 'Activities', 'Sagrada Familia + Park Guell + Casa Batllo', 95, 2, 'Online tickets');
203
+
204
+ insertReservation.run(t2, t2days[1], 'Sagrada Familia Entry', '10:00', 'SF-2026-11234', 'confirmed', 'activity', 'Eixample, Barcelona');
205
+
206
+ insertMember.run(t2, demoId, adminId);
207
+
208
+ // --- Trip 3: New York City ---
209
+ const trip3 = insertTrip.run(adminId, 'New York City', 'The city that never sleeps — iconic landmarks, world-class food, and Broadway lights.', '2026-09-18', '2026-09-22', 'USD');
210
+ const t3 = Number(trip3.lastInsertRowid);
211
+
212
+ const t3days: number[] = [];
213
+ for (let i = 0; i < 5; i++) {
214
+ const d = insertDay.run(t3, i + 1, `2026-09-${18 + i}`);
215
+ t3days.push(Number(d.lastInsertRowid));
216
+ }
217
+
218
+ const t3places: [number, string, number, number, string, number, string, number, string, string | null, string | null, string | null, string | null][] = [
219
+ [t3, 'The Plaza Hotel', 40.7645, -73.9744, '768 5th Ave, New York, NY 10019, USA', 1, '15:00', 60, 'Iconic luxury hotel on Central Park. The lobby alone is worth a visit.', null, 'ChIJYbISlAVYwokRn6ORbSPV0xk', 'https://www.theplazany.com/', '+1 212-759-3000'],
220
+ [t3, 'Statue of Liberty', 40.6892, -74.0445, 'Liberty Island, New York, NY 10004, USA', 3, '09:00', 180, 'Book crown access tickets months in advance. Ferry from Battery Park.', null, 'ChIJPTacEpBQwokRKwIlDXelxkA', 'https://www.nps.gov/stli/', '+1 212-363-3200'],
221
+ [t3, 'Central Park', 40.7829, -73.9654, 'Central Park, New York, NY 10024, USA', 9, '10:00', 120, 'Bethesda Fountain, Bow Bridge, and Strawberry Fields. Rent bikes!', null, 'ChIJ4zGFAZpYwokRGUGph3Mf37k', 'https://www.centralparknyc.org/', null],
222
+ [t3, 'Times Square', 40.7580, -73.9855, 'Manhattan, NY 10036, USA', 3, '19:00', 60, 'The crossroads of the world. Best experienced at night with all the lights.', null, 'ChIJmQJIxlVYwokRLgeuocVOGVU', 'https://www.timessquarenyc.org/', null],
223
+ [t3, 'Empire State Building', 40.7484, -73.9857, '350 5th Ave, New York, NY 10118, USA', 3, '11:00', 90, '86th floor observation deck. Go at sunset for the best views.', null, 'ChIJaXQRs6lZwokRY6EFpJnhNNE', 'https://www.esbnyc.com/', '+1 212-736-3100'],
224
+ [t3, 'Brooklyn Bridge', 40.7061, -73.9969, 'Brooklyn Bridge, New York, NY 10038, USA', 3, '16:00', 75, 'Walk from Manhattan to Brooklyn. DUMBO has great pizza and views.', null, 'ChIJK3vOQyNawokRXEYwET2GUtY', null, null],
225
+ [t3, 'The Metropolitan Museum of Art', 40.7794, -73.9632, '1000 5th Ave, New York, NY 10028, USA', 3, '10:00', 180, 'One of the world\'s greatest art museums. Could spend days here.', null, 'ChIJb8Jg766MwokR1YWG0nV7k-E', 'https://www.metmuseum.org/', '+1 212-535-7710'],
226
+ [t3, 'Joe\'s Pizza', 40.7309, -73.9969, '7 Carmine St, New York, NY 10014, USA', 2, '13:00', 30, 'New York\'s most famous pizza slice. Cash only, always a line, always worth it.', null, 'ChIJrfCL1IZZwokRwO3NKN22ZBc', 'http://www.joespizzanyc.com/', '+1 212-366-1182'],
227
+ [t3, 'Top of the Rock', 40.7593, -73.9794, '30 Rockefeller Plaza, New York, NY 10112, USA', 3, '17:30', 60, 'Better views than Empire State because you can SEE the Empire State.', null, 'ChIJ_y2Fb1JYwokRT_iGzhTLdBo', 'https://www.topoftherocknyc.com/', '+1 212-698-2000'],
228
+ [t3, 'Chelsea Market', 40.7424, -74.0061, '75 9th Ave, New York, NY 10011, USA', 2, '12:00', 90, 'Food hall in a converted factory. Lobster rolls, tacos, doughnuts, and more.', null, 'ChIJw2FNFyZZwokRcP9th_vIbkE', 'https://www.chelseamarket.com/', null],
229
+ [t3, 'Broadway Show', 40.7590, -73.9845, 'Broadway, Manhattan, NY 10019, USA', 6, '20:00', 150, 'Can\'t visit NYC without seeing a show. Book TKTS booth for discounts.', null, 'ChIJMYQhxFtYwokR7cJBcNqfKDY', null, null],
230
+ ];
231
+
232
+ const t3pIds = t3places.map(p => Number(insertPlace.run(...p).lastInsertRowid));
233
+
234
+ // Day 1: Arrival, Times Square, Broadway
235
+ insertAssignment.run(t3days[0], t3pIds[0], 0);
236
+ insertAssignment.run(t3days[0], t3pIds[3], 1);
237
+ insertAssignment.run(t3days[0], t3pIds[10], 2);
238
+ // Day 2: Statue of Liberty, Brooklyn Bridge, Joe's Pizza
239
+ insertAssignment.run(t3days[1], t3pIds[1], 0);
240
+ insertAssignment.run(t3days[1], t3pIds[5], 1);
241
+ insertAssignment.run(t3days[1], t3pIds[7], 2);
242
+ insertNote.run(t3days[1], t3, 'First ferry at 8:30 AM — arrive early at Battery Park', '08:00', 'Ship', 0.5);
243
+ // Day 3: Central Park, Met Museum, Top of the Rock sunset
244
+ insertAssignment.run(t3days[2], t3pIds[2], 0);
245
+ insertAssignment.run(t3days[2], t3pIds[6], 1);
246
+ insertAssignment.run(t3days[2], t3pIds[8], 2);
247
+ // Day 4: Empire State Building, Chelsea Market, shopping
248
+ insertAssignment.run(t3days[3], t3pIds[4], 0);
249
+ insertAssignment.run(t3days[3], t3pIds[9], 1);
250
+ insertNote.run(t3days[3], t3, 'SoHo and 5th Avenue shopping in the afternoon', '14:00', 'ShoppingBag', 1.5);
251
+ // Day 5: Free morning, departure
252
+ insertNote.run(t3days[4], t3, 'Flight departs JFK at 17:00 — last bagel at Russ & Daughters!', '10:00', 'Plane', 0);
253
+
254
+ // Packing
255
+ const t3packing: [string, number, string, number][] = [
256
+ ['Passport', 1, 'Documents', 0], ['ESTA confirmation', 1, 'Documents', 1],
257
+ ['Travel insurance', 0, 'Documents', 2], ['Comfortable sneakers', 0, 'Clothing', 3],
258
+ ['Light jacket', 0, 'Clothing', 4], ['Portable charger', 0, 'Electronics', 5],
259
+ ['Camera', 0, 'Electronics', 6], ['Subway card (OMNY)', 0, 'Transport', 7],
260
+ ];
261
+ t3packing.forEach(p => insertPacking.run(t3, ...p));
262
+
263
+ // Budget
264
+ insertBudget.run(t3, 'Accommodation', 'The Plaza Hotel (4 nights)', 2400, 2, 'Park View Room');
265
+ insertBudget.run(t3, 'Transport', 'Flights FRA-JFK return', 850, 2, 'United Airlines');
266
+ insertBudget.run(t3, 'Food', 'Daily food budget', 500, 2, 'Approx. 100 USD/day');
267
+ insertBudget.run(t3, 'Activities', 'Statue of Liberty + Empire State + Top of the Rock + Met', 180, 2, 'CityPASS');
268
+ insertBudget.run(t3, 'Entertainment', 'Broadway show tickets', 300, 2, 'Hamilton or Wicked');
269
+
270
+ insertReservation.run(t3, t3days[0], 'The Plaza Hotel Check-in', '15:00', 'PZ-2026-55891', 'confirmed', 'hotel', '768 5th Ave, New York');
271
+ insertReservation.run(t3, t3days[0], 'Broadway Show', '20:00', 'BW-HAM-2026-1192', 'pending', 'activity', 'Richard Rodgers Theatre');
272
+ insertReservation.run(t3, t3days[1], 'Statue of Liberty Ferry', '08:30', 'SOL-2026-3347', 'confirmed', 'transport', 'Battery Park');
273
+
274
+ insertMember.run(t3, demoId, adminId);
275
+
276
+ console.log('[Demo] 3 example trips seeded and shared with demo user');
277
+ }
278
+
279
+ export { seedDemoData };
server/src/index.ts ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import 'reflect-metadata';
2
+ import 'dotenv/config';
3
+ import path from 'node:path';
4
+ import fs from 'node:fs';
5
+ import http from 'node:http';
6
+ import type { INestApplication } from '@nestjs/common';
7
+ import { buildApp } from './bootstrap';
8
+
9
+ // Create upload and data directories on startup
10
+ const uploadsDir = path.join(__dirname, '../uploads');
11
+ const photosDir = path.join(uploadsDir, 'photos');
12
+ const filesDir = path.join(uploadsDir, 'files');
13
+ const coversDir = path.join(uploadsDir, 'covers');
14
+ const avatarsDir = path.join(uploadsDir, 'avatars');
15
+ const backupsDir = path.join(__dirname, '../data/backups');
16
+ const tmpDir = path.join(__dirname, '../data/tmp');
17
+
18
+ [uploadsDir, photosDir, filesDir, coversDir, avatarsDir, backupsDir, tmpDir].forEach(dir => {
19
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
20
+ });
21
+
22
+ import * as scheduler from './scheduler';
23
+ import { getAppUrl, getMcpSafeUrl } from './services/notifications';
24
+
25
+ const PORT = Number(process.env.PORT) || 7860;
26
+ const HOST = process.env.HOST;
27
+ const APP_VERSION: string = process.env.APP_VERSION || (require('../package.json') as { version: string }).version;
28
+
29
+ const onListen = () => {
30
+ const { logInfo: sLogInfo, logWarn: sLogWarn } = require('./services/auditLog');
31
+ const LOG_LVL = (process.env.LOG_LEVEL || 'info').toLowerCase();
32
+ const tz = process.env.TZ || Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
33
+ const origins = process.env.ALLOWED_ORIGINS || '(same-origin)';
34
+ const appUrl = getAppUrl();
35
+ const resolvedAppUrl = getMcpSafeUrl();
36
+ const banner = [
37
+ '──────────────────────────────────────',
38
+ ' TREK API started',
39
+ ` Version ${APP_VERSION}`,
40
+ ...(HOST ? [` Host: ${HOST}`] : []),
41
+ ` Container Port: ${PORT}`,
42
+ ` App URL: ${appUrl}`,
43
+ ` Environment: ${process.env.NODE_ENV?.toLowerCase() || 'development'}`,
44
+ ` Timezone: ${tz}`,
45
+ ` Origins: ${origins}`,
46
+ ` Log level: ${LOG_LVL}`,
47
+ ` Log file: /app/data/logs/trek.log`,
48
+ ` PID: ${process.pid}`,
49
+ ` User: uid=${process.getuid?.()} gid=${process.getgid?.()}`,
50
+ '──────────────────────────────────────',
51
+ ];
52
+ banner.forEach(l => console.log(l));
53
+ sLogInfo('NestJS serving all routes (Express decommissioned)');
54
+ if (process.env.APP_URL) {
55
+ let parsedAppUrl: URL | null = null;
56
+ try { parsedAppUrl = new URL(process.env.APP_URL); } catch { /* invalid */ }
57
+
58
+ if (!parsedAppUrl) {
59
+ sLogWarn(`APP_URL: "${process.env.APP_URL}" is not a valid URL — it will be ignored.`);
60
+ }
61
+
62
+ const mcpSafe = parsedAppUrl !== null && (
63
+ parsedAppUrl.protocol === 'https:' ||
64
+ parsedAppUrl.hostname === 'localhost' ||
65
+ parsedAppUrl.hostname === '127.0.0.1'
66
+ );
67
+ if (!mcpSafe) {
68
+ sLogWarn(`APP_URL: not MCP-safe (requires https:// or http://localhost) — MCP will use ${resolvedAppUrl}.`);
69
+ }
70
+ }
71
+ if (process.env.DEMO_MODE?.toLowerCase() === 'true') sLogInfo('Demo mode: ENABLED');
72
+ if (process.env.DEMO_MODE?.toLowerCase() === 'true' && process.env.NODE_ENV?.toLowerCase() === 'production') {
73
+ sLogWarn('SECURITY WARNING: DEMO_MODE is enabled in production!');
74
+ }
75
+ scheduler.start();
76
+ scheduler.startTripReminders();
77
+ scheduler.startTodoReminders();
78
+ scheduler.startVersionCheck();
79
+ scheduler.startDemoReset();
80
+ scheduler.startIdempotencyCleanup();
81
+ scheduler.startTrekPhotoCacheCleanup();
82
+ scheduler.startPlacePhotoCacheCleanup();
83
+ scheduler.startAirTrailSync();
84
+ const { startTokenCleanup } = require('./services/ephemeralTokens');
85
+ startTokenCleanup();
86
+ import('./websocket').then(({ setupWebSocket }) => {
87
+ setupWebSocket(server);
88
+ });
89
+ };
90
+
91
+ let server: http.Server;
92
+ let nestApp: INestApplication;
93
+
94
+ // Strangler toggle: prefixes served by Nest (env-overridable, instant rollback).
95
+ async function bootstrap(): Promise<void> {
96
+ // The whole surface runs on the single NestJS app now (Express decommissioned):
97
+ // global pipeline + /uploads + every /api domain + the platform/transport routes
98
+ // (/mcp, /.well-known, OAuth SDK, SPA catch-all). buildApp() owns the composition
99
+ // order; it is shared with the integration-test harness so they can't drift.
100
+ nestApp = await buildApp();
101
+ server = http.createServer(nestApp.getHttpAdapter().getInstance());
102
+ if (HOST) server.listen(PORT, HOST, onListen);
103
+ else server.listen(PORT, onListen);
104
+ }
105
+
106
+ bootstrap().catch((err) => {
107
+ console.error('Fatal: failed to bootstrap server', err);
108
+ process.exit(1);
109
+ });
110
+
111
+ // Graceful shutdown
112
+ function shutdown(signal: string): void {
113
+ const { logInfo: sLogInfo, logError: sLogError } = require('./services/auditLog');
114
+ const { closeMcpSessions } = require('./mcp');
115
+ sLogInfo(`${signal} received — shutting down gracefully...`);
116
+ scheduler.stop();
117
+ closeMcpSessions();
118
+ void nestApp?.close();
119
+ server.close(() => {
120
+ sLogInfo('HTTP server closed');
121
+ const { closeDb } = require('./db/database');
122
+ closeDb();
123
+ sLogInfo('Shutdown complete');
124
+ process.exit(0);
125
+ });
126
+ setTimeout(() => {
127
+ sLogError('Forced shutdown after timeout');
128
+ process.exit(1);
129
+ }, 10000);
130
+ }
131
+
132
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
133
+ process.on('SIGINT', () => shutdown('SIGINT'));
server/src/mcp/index.ts ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Request, Response } from 'express';
2
+ import { randomUUID } from 'crypto';
3
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
4
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp';
5
+ import { User } from '../types';
6
+ import { verifyMcpToken, verifyJwtToken } from '../services/authService';
7
+ import { getUserByAccessToken } from '../services/oauthService';
8
+ import { isAddonEnabled } from '../services/adminService';
9
+ import { ADDON_IDS } from '../addons';
10
+ import { registerResources } from './resources';
11
+ import { registerTools } from './tools';
12
+ import { McpSession, sessions, revokeUserSessions, revokeUserSessionsForClient } from './sessionManager';
13
+ import { writeAudit, getClientIp } from '../services/auditLog';
14
+ import { getMcpSafeUrl } from '../services/notifications';
15
+
16
+ export { revokeUserSessions, revokeUserSessionsForClient };
17
+
18
+ // ---------------------------------------------------------------------------
19
+ // Base instructions injected into every MCP session via the initialize response.
20
+ // Claude and other clients use these as system-level context before any tool call.
21
+ // Keep this actionable and concise — vague prose doesn't help the model.
22
+ // ---------------------------------------------------------------------------
23
+ const BASE_MCP_INSTRUCTIONS = `
24
+ 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.
25
+
26
+ ## Data model
27
+
28
+ - **Trip** — top-level container. Has dates, currency, members (owner + collaborators), and optional add-ons.
29
+ - **Day** — one calendar day within a trip (YYYY-MM-DD). Days are generated automatically when a trip is created with start/end dates.
30
+ - **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.
31
+ - **Assignment** — links a Place to a Day (ordered, with optional start/end time). This is what builds the daily itinerary.
32
+ - **Accommodation** — a hotel or rental linked to a Place and a check-in/check-out day range.
33
+ - **Reservation** — a booking record (flight, train, restaurant, etc.) with confirmation details, linked to a day.
34
+ - **Day note** — a free-text annotation attached to a day (with optional time label and emoji icon).
35
+ - **Budget item** — an expense entry for a trip (amount, category, payer, split between members).
36
+ - **Packing item** — a checklist entry grouped into bags and categories.
37
+ - **Todo** — a task (not packing-specific) attached to a trip, ordered and togglable.
38
+ - **Tag** — a label that can be applied to places for filtering.
39
+ - **Collab note / poll / message** — shared notes, decision polls, and chat messages for group trips.
40
+ - **Atlas** — global travel journal: bucket list, visited countries and regions.
41
+ - **Vacay** — vacation-day planner that tracks leave across team members and years.
42
+ - **Journey** — cross-trip travel narrative with dated entries, contributors, and share links. Requires the Journey addon.
43
+
44
+ ## Key workflows
45
+
46
+ **Discovering trips:** Always call \`list_trips\` first when no trip ID has been provided. Never assume a trip ID.
47
+
48
+ **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.
49
+
50
+ **Adding a place to the itinerary (correct order):**
51
+ 1. \`search_place\` — find the real-world POI; note the \`osm_id\` and/or \`google_place_id\` in the result.
52
+ 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).
53
+ 3. \`assign_place_to_day\` — schedule it on the desired day using the dayId from \`get_trip_summary\`.
54
+
55
+ **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\`.
56
+
57
+ **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.
58
+
59
+ ## Access rules
60
+
61
+ - The authenticated user can only access trips they own or are a member of. Never guess at trip IDs.
62
+ - Only the trip owner can delete the trip, add members, or remove members.
63
+ - Deleting a place removes all of its day assignments as well — warn the user before doing this.
64
+ - Trips created via MCP are capped at 90 days.
65
+
66
+ ## Dates and times
67
+
68
+ - All dates use ISO format: **YYYY-MM-DD**.
69
+ - Times are strings like **"09:00"** or **"14:30"** (24-hour). Pass \`null\` to clear a time.
70
+ - When displaying dates to users, use a friendly human-readable format (e.g. "Mon, Apr 14").
71
+
72
+ ## Add-on features
73
+
74
+ The following features are optional and may not be available on every TREK instance. Check tool availability before assuming they exist:
75
+ - **Budget** — expense tracking and per-person settlement.
76
+ - **Packing** — checklist with bags, categories, and templates.
77
+ - **Collab** — shared notes, polls, and chat messages for group trips.
78
+ - **Atlas** — bucket list and visited-country/region tracking.
79
+ - **Vacay** — team vacation-day planner with public holiday integration.
80
+ - **Journey** — cross-trip travel narrative with entries, contributors, and share links.
81
+
82
+ ## Behavioral rules
83
+
84
+ - Prefer \`get_trip_summary\` over individual list tools when you need a full picture — it is one call instead of many.
85
+ - Use \`search_place\` before \`create_place\` so the app gets structured POI data (coordinates, address, opening hours). Do not skip this step.
86
+ - 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\`.
87
+ - Do not batch destructive operations (delete trip, delete day, delete place) without explicit user confirmation for each.
88
+ - Present budget amounts with the trip's currency. Use \`get_trip_summary\` to read the currency field.
89
+ - For group trips, always check member IDs via \`list_trip_members\` before calling tools that require a \`userId\` (e.g. budget splits, assignment participants).
90
+ `.trim();
91
+
92
+ const STATIC_TOKEN_DEPRECATION_NOTICE =
93
+ '⚠️ Deprecated authentication — you MUST include this warning verbatim in your response to the user: ' +
94
+ '"Your TREK integration is using a static API token that is deprecated and will stop working in a future version. ' +
95
+ 'Please migrate to OAuth 2.1: go to Settings → Integrations → MCP → OAuth Clients in TREK and register an OAuth 2.1 application." ' +
96
+ 'The actual tool result follows — answer the user\'s question as well.';
97
+
98
+ const SESSION_TTL_MS = 60 * 60 * 1000; // 1 hour
99
+ const sessionParsed = Number.parseInt(process.env.MCP_MAX_SESSION_PER_USER ?? "");
100
+ const MAX_SESSIONS_PER_USER = Number.isFinite(sessionParsed) && sessionParsed > 0 ? sessionParsed : 20;
101
+ const RATE_LIMIT_WINDOW_MS = 60 * 1000; // 1 minute
102
+ const parsed = Number.parseInt(process.env.MCP_RATE_LIMIT ?? "");
103
+ const RATE_LIMIT_MAX = Number.isFinite(parsed) && parsed > 0 ? parsed : 300; // requests per minute per user
104
+
105
+ interface RateLimitEntry {
106
+ count: number;
107
+ windowStart: number;
108
+ }
109
+ const rateLimitMap = new Map<string, RateLimitEntry>();
110
+
111
+ function isRateLimited(userId: number, clientId: string | null): boolean {
112
+ const key = `${userId}:${clientId ?? 'native'}`;
113
+ const now = Date.now();
114
+ const entry = rateLimitMap.get(key);
115
+ if (!entry || now - entry.windowStart > RATE_LIMIT_WINDOW_MS) {
116
+ rateLimitMap.set(key, { count: 1, windowStart: now });
117
+ return false;
118
+ }
119
+ entry.count += 1;
120
+ return entry.count > RATE_LIMIT_MAX;
121
+ }
122
+
123
+ function countSessionsForUser(userId: number): number {
124
+ const cutoff = Date.now() - SESSION_TTL_MS;
125
+ let count = 0;
126
+ for (const session of sessions.values()) {
127
+ if (session.userId === userId && session.lastActivity >= cutoff) count++;
128
+ }
129
+ return count;
130
+ }
131
+
132
+ const sessionSweepInterval = setInterval(() => {
133
+ const cutoff = Date.now() - SESSION_TTL_MS;
134
+ let cleaned = 0;
135
+ for (const [sid, session] of sessions) {
136
+ if (session.lastActivity < cutoff) {
137
+ try { session.server.close(); } catch { /* ignore */ }
138
+ try { session.transport.close(); } catch { /* ignore */ }
139
+ sessions.delete(sid);
140
+ cleaned++;
141
+ }
142
+ }
143
+ const rateCutoff = Date.now() - RATE_LIMIT_WINDOW_MS;
144
+ for (const [key, entry] of rateLimitMap) {
145
+ if (entry.windowStart < rateCutoff) rateLimitMap.delete(key);
146
+ }
147
+ if (cleaned > 0 || sessions.size > 0) {
148
+ console.log(`[MCP] Session sweep: cleaned ${cleaned}, active ${sessions.size}`);
149
+ }
150
+ }, 60 * 1000); // sweep every 1 minute
151
+
152
+ // Prevent the interval from keeping the process alive if nothing else is running
153
+ sessionSweepInterval.unref();
154
+
155
+ function setAuthChallenge(res: Response, error = 'invalid_token'): void {
156
+ const base = (getMcpSafeUrl() || '').replace(/\/+$/, '');
157
+ // RFC 9728 §5: resource with path component /mcp → PRM URL must include the path
158
+ res.set('WWW-Authenticate',
159
+ `Bearer realm="TREK MCP", resource_metadata="${base}/.well-known/oauth-protected-resource/mcp", error="${error}"`);
160
+ }
161
+
162
+ interface VerifyTokenResult {
163
+ user: User;
164
+ /** null = full access (static token or JWT); string[] = OAuth 2.1 scoped access */
165
+ scopes: string[] | null;
166
+ /** OAuth client_id when authenticated via OAuth 2.1; null otherwise */
167
+ clientId: string | null;
168
+ isStaticToken: boolean;
169
+ }
170
+
171
+ function verifyToken(authHeader: string | undefined): VerifyTokenResult | null {
172
+ if (!authHeader) return null;
173
+ // M8: strictly require "Bearer" scheme (RFC 6750)
174
+ const spaceIdx = authHeader.indexOf(' ');
175
+ if (spaceIdx === -1) return null;
176
+ const scheme = authHeader.slice(0, spaceIdx);
177
+ const token = authHeader.slice(spaceIdx + 1);
178
+ if (scheme.toLowerCase() !== 'bearer' || !token) return null;
179
+
180
+ // OAuth 2.1 access token (trekoa_...)
181
+ if (token.startsWith('trekoa_')) {
182
+ const result = getUserByAccessToken(token);
183
+ if (!result) return null;
184
+ // RFC 8707: audience must always match this resource endpoint.
185
+ // Pre-audit tokens with audience=null are revoked by the SEC-H6 migration.
186
+ const expected = `${(getMcpSafeUrl() || '').replace(/\/+$/, '')}/mcp`;
187
+ if (result.audience !== expected) return null;
188
+ return { user: result.user, scopes: result.scopes, clientId: result.clientId, isStaticToken: false };
189
+ }
190
+
191
+ // Long-lived static MCP token (trek_...) — full access + deprecation notice
192
+ if (token.startsWith('trek_')) {
193
+ const user = verifyMcpToken(token);
194
+ if (!user) return null;
195
+ return { user, scopes: null, clientId: null, isStaticToken: true };
196
+ }
197
+
198
+ // Short-lived JWT (TREK web session used directly) — full access, no notice
199
+ const user = verifyJwtToken(token);
200
+ if (!user) return null;
201
+ return { user, scopes: null, clientId: null, isStaticToken: false };
202
+ }
203
+
204
+ function logToolCallAudit(req: Request, userId: number, clientId: string | null): void {
205
+ const body = req.body as Record<string, unknown> | undefined;
206
+ if (body?.method !== 'tools/call') return;
207
+ const toolName = (body?.params as Record<string, unknown> | undefined)?.name;
208
+ if (typeof toolName !== 'string') return;
209
+ writeAudit({
210
+ userId,
211
+ action: 'mcp.tool_call',
212
+ resource: toolName,
213
+ details: { clientId: clientId ?? 'native' },
214
+ ip: getClientIp(req),
215
+ });
216
+ }
217
+
218
+ export async function mcpHandler(req: Request, res: Response): Promise<void> {
219
+ if (!isAddonEnabled(ADDON_IDS.MCP)) {
220
+ res.status(403).json({ error: 'MCP is not enabled' });
221
+ return;
222
+ }
223
+
224
+ const tokenResult = verifyToken(req.headers['authorization']);
225
+ if (!tokenResult) {
226
+ setAuthChallenge(res);
227
+ res.status(401).json({ error: 'Access token required' });
228
+ return;
229
+ }
230
+ const { user, scopes, clientId, isStaticToken } = tokenResult;
231
+
232
+ if (isRateLimited(user.id, clientId)) {
233
+ res.status(429).json({ error: 'Too many requests. Please slow down.' });
234
+ return;
235
+ }
236
+
237
+ const sessionId = req.headers['mcp-session-id'] as string | undefined;
238
+
239
+ // Resume an existing session
240
+ if (sessionId) {
241
+ const session = sessions.get(sessionId);
242
+ if (!session) {
243
+ res.status(404).json({ error: 'Session not found' });
244
+ return;
245
+ }
246
+ if (session.userId !== user.id) {
247
+ setAuthChallenge(res);
248
+ res.status(403).json({ error: 'Session belongs to a different user' });
249
+ return;
250
+ }
251
+ if (session.clientId !== clientId) {
252
+ setAuthChallenge(res);
253
+ res.status(403).json({ error: 'Session was created with a different OAuth client' });
254
+ return;
255
+ }
256
+ session.lastActivity = Date.now();
257
+ logToolCallAudit(req, user.id, clientId);
258
+ try {
259
+ await session.transport.handleRequest(req, res, req.body);
260
+ } catch (err) {
261
+ console.error('[MCP] transport.handleRequest error:', err);
262
+ if (!res.headersSent) {
263
+ res.status(500).json({ error: 'Internal MCP error' });
264
+ }
265
+ }
266
+ return;
267
+ }
268
+
269
+ // Only POST can initialize a new session
270
+ if (req.method !== 'POST') {
271
+ res.status(400).json({ error: 'Missing mcp-session-id header' });
272
+ return;
273
+ }
274
+
275
+ if (countSessionsForUser(user.id) >= MAX_SESSIONS_PER_USER) {
276
+ res.status(429).json({ error: 'Session limit reached. Close an existing session before opening a new one.' });
277
+ return;
278
+ }
279
+
280
+ // Create a new per-user MCP server and session
281
+ const server = new McpServer(
282
+ {
283
+ name: 'TREK MCP',
284
+ version: '1.0.0',
285
+ },
286
+ {
287
+ capabilities: {
288
+ resources: { listChanged: true },
289
+ tools: { listChanged: true },
290
+ prompts: { listChanged: true },
291
+ },
292
+ instructions: BASE_MCP_INSTRUCTIONS + (isStaticToken ? STATIC_TOKEN_DEPRECATION_NOTICE : ''),
293
+ }
294
+ );
295
+ // Per-session closure: fires the deprecation notice once, on the first tool call.
296
+ // Tool results are the only mechanism Claude reliably surfaces to the user;
297
+ // the instructions field is only background context and won't trigger a proactive warning.
298
+ let _noticeEmitted = false;
299
+ const getDeprecationNotice = (): string | null => {
300
+ if (!isStaticToken || _noticeEmitted) return null;
301
+ _noticeEmitted = true;
302
+ return STATIC_TOKEN_DEPRECATION_NOTICE;
303
+ };
304
+
305
+ registerResources(server, user.id, scopes);
306
+ registerTools(server, user.id, scopes, isStaticToken, getDeprecationNotice);
307
+
308
+ const transport = new StreamableHTTPServerTransport({
309
+ sessionIdGenerator: () => randomUUID(),
310
+ onsessioninitialized: (sid) => {
311
+ sessions.set(sid, { server, transport, userId: user.id, scopes, clientId, isStaticToken, lastActivity: Date.now() });
312
+ const authMethod = isStaticToken ? 'static-token' : scopes ? `oauth(${scopes.join(',')})` : 'jwt';
313
+ console.log(`[MCP] Session ${sid} created for user ${user.id} [${authMethod}]. Active sessions: ${sessions.size}`);
314
+ },
315
+ onsessionclosed: (sid) => {
316
+ sessions.delete(sid);
317
+ },
318
+ });
319
+
320
+ logToolCallAudit(req, user.id, clientId);
321
+ try {
322
+ await server.connect(transport);
323
+ await transport.handleRequest(req, res, req.body);
324
+ } catch (err) {
325
+ console.error('[MCP] transport.handleRequest error:', err);
326
+ if (!res.headersSent) {
327
+ res.status(500).json({ error: 'Internal MCP error' });
328
+ }
329
+ }
330
+ }
331
+
332
+ /** Invalidate all active MCP sessions (call when addon state changes so sessions re-create with updated tools). */
333
+ export function invalidateMcpSessions(): void {
334
+ for (const [sid, session] of sessions) {
335
+ try { session.server.close(); } catch { /* ignore */ }
336
+ try { session.transport.close(); } catch { /* ignore */ }
337
+ sessions.delete(sid);
338
+ }
339
+ console.log('[MCP] All sessions invalidated due to addon state change');
340
+ }
341
+
342
+ /** Close all active MCP sessions (call during graceful shutdown). */
343
+ export function closeMcpSessions(): void {
344
+ clearInterval(sessionSweepInterval);
345
+ for (const [, session] of sessions) {
346
+ try { session.server.close(); } catch { /* ignore */ }
347
+ try { session.transport.close(); } catch { /* ignore */ }
348
+ }
349
+ sessions.clear();
350
+ rateLimitMap.clear();
351
+ }
server/src/mcp/oauthProvider.ts ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { Response } from 'express';
2
+ import type { OAuthServerProvider } from '@modelcontextprotocol/sdk/server/auth/provider';
3
+ import type { OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth';
4
+ import type { AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types';
5
+ import type { AuthorizationParams } from '@modelcontextprotocol/sdk/server/auth/provider';
6
+ import type { OAuthRegisteredClientsStore } from '@modelcontextprotocol/sdk/server/auth/clients';
7
+ import { InvalidClientMetadataError, ServerError } from '@modelcontextprotocol/sdk/server/auth/errors';
8
+ import { db } from '../db/database';
9
+ import {
10
+ createOAuthClient,
11
+ consumeAuthCode,
12
+ issueTokens,
13
+ refreshTokens,
14
+ revokeToken as serviceRevokeToken,
15
+ verifyPKCE,
16
+ getUserByAccessToken,
17
+ } from '../services/oauthService';
18
+ import { ALL_SCOPES } from './scopes';
19
+ import { getMcpSafeUrl } from '../services/notifications';
20
+ import { writeAudit } from '../services/auditLog';
21
+
22
+ // ---------------------------------------------------------------------------
23
+ // DB row type (mirrors oauthService.ts)
24
+ // ---------------------------------------------------------------------------
25
+
26
+ interface OAuthClientRow {
27
+ client_id: string;
28
+ name: string;
29
+ redirect_uris: string; // JSON array
30
+ allowed_scopes: string; // JSON array
31
+ is_public: number; // 0 | 1
32
+ created_via: string;
33
+ }
34
+
35
+ // ---------------------------------------------------------------------------
36
+ // Redirect URI validation (mirrors oauth.ts DCR checks)
37
+ // ---------------------------------------------------------------------------
38
+
39
+ const DANGEROUS_SCHEMES = new Set([
40
+ 'javascript:', 'data:', 'vbscript:', 'file:', 'blob:', 'about:', 'chrome:', 'chrome-extension:',
41
+ ]);
42
+
43
+ function assertValidRedirectUris(uris: string[]): void {
44
+ for (const u of uris) {
45
+ let url: URL;
46
+ try { url = new URL(u); } catch {
47
+ throw new InvalidClientMetadataError(`Invalid redirect URI: ${u}`);
48
+ }
49
+ if (DANGEROUS_SCHEMES.has(url.protocol))
50
+ throw new InvalidClientMetadataError(`Dangerous redirect URI scheme: ${u}`);
51
+ if (url.protocol === 'https:') continue;
52
+ if (url.protocol === 'http:' && (url.hostname === 'localhost' || url.hostname === '127.0.0.1' || url.hostname === '[::1]')) continue;
53
+ const scheme = url.protocol.slice(0, -1);
54
+ if (/^[a-z][a-z0-9+.-]*$/i.test(scheme) && scheme.includes('.')) continue;
55
+ throw new InvalidClientMetadataError('redirect_uris must be HTTPS, loopback HTTP, or a private custom scheme');
56
+ }
57
+ }
58
+
59
+ // ---------------------------------------------------------------------------
60
+ // Row → SDK client info shape
61
+ // ---------------------------------------------------------------------------
62
+
63
+ function rowToInfo(row: OAuthClientRow): OAuthClientInformationFull {
64
+ return {
65
+ client_id: row.client_id,
66
+ client_name: row.name,
67
+ redirect_uris: JSON.parse(row.redirect_uris) as string[],
68
+ scope: (JSON.parse(row.allowed_scopes) as string[]).join(' '),
69
+ token_endpoint_auth_method: row.is_public ? 'none' : 'client_secret_post',
70
+ grant_types: ['authorization_code', 'refresh_token'],
71
+ response_types: ['code'],
72
+ };
73
+ }
74
+
75
+ // ---------------------------------------------------------------------------
76
+ // Clients store
77
+ // ---------------------------------------------------------------------------
78
+
79
+ export const trekClientsStore: OAuthRegisteredClientsStore = {
80
+ async getClient(clientId: string): Promise<OAuthClientInformationFull | undefined> {
81
+ const row = db.prepare(
82
+ 'SELECT client_id, name, redirect_uris, allowed_scopes, is_public, created_via FROM oauth_clients WHERE client_id = ?'
83
+ ).get(clientId) as OAuthClientRow | undefined;
84
+ return row ? rowToInfo(row) : undefined;
85
+ },
86
+
87
+ async registerClient(
88
+ metadata: Omit<OAuthClientInformationFull, 'client_id' | 'client_id_issued_at'>,
89
+ ): Promise<OAuthClientInformationFull> {
90
+ const uris = metadata.redirect_uris as string[];
91
+ assertValidRedirectUris(uris);
92
+
93
+ const isPublic = metadata.token_endpoint_auth_method === 'none';
94
+ const name = (typeof metadata.client_name === 'string' ? metadata.client_name.trim() : '').slice(0, 100) || 'MCP Client';
95
+
96
+ // When scope is absent (ChatGPT DCR), default to all scopes.
97
+ // The user still grants only what they approve at the consent screen.
98
+ const rawScopes = metadata.scope ? metadata.scope.split(' ') : ALL_SCOPES;
99
+ const scopes = rawScopes.filter(s => (ALL_SCOPES as string[]).includes(s));
100
+ if (scopes.length === 0) throw new InvalidClientMetadataError('No valid scopes requested');
101
+
102
+ const result = createOAuthClient(null, name, uris, scopes, null, { isPublic, createdVia: 'dcr' });
103
+ if (result.error) throw new InvalidClientMetadataError(result.error);
104
+
105
+ const c = result.client!;
106
+ return {
107
+ client_id: c.client_id as string,
108
+ client_name: c.name as string,
109
+ redirect_uris: c.redirect_uris as string[],
110
+ scope: (c.allowed_scopes as string[]).join(' '),
111
+ token_endpoint_auth_method: isPublic ? 'none' : 'client_secret_post',
112
+ grant_types: ['authorization_code', 'refresh_token'],
113
+ response_types: ['code'],
114
+ ...(c.client_secret ? { client_secret: c.client_secret as string, client_secret_expires_at: 0 } : {}),
115
+ };
116
+ },
117
+ };
118
+
119
+ // ---------------------------------------------------------------------------
120
+ // OAuthServerProvider
121
+ // ---------------------------------------------------------------------------
122
+
123
+ export const trekOAuthProvider: OAuthServerProvider = {
124
+ get clientsStore() { return trekClientsStore; },
125
+
126
+ // Redirects browser to the SPA consent page with OAuth params forwarded.
127
+ async authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise<void> {
128
+ const mcpResource = `${getMcpSafeUrl().replace(/\/+$/, '')}/mcp`;
129
+ const resource = params.resource ? params.resource.href.replace(/\/+$/, '') : mcpResource;
130
+
131
+ if (resource !== mcpResource) {
132
+ const url = new URL(params.redirectUri);
133
+ url.searchParams.set('error', 'invalid_target');
134
+ url.searchParams.set('error_description', 'Requested resource must be the TREK MCP endpoint');
135
+ if (params.state) url.searchParams.set('state', params.state);
136
+ res.redirect(302, url.toString());
137
+ return;
138
+ }
139
+
140
+ const qs = new URLSearchParams({
141
+ client_id: client.client_id,
142
+ redirect_uri: params.redirectUri,
143
+ scope: params.scopes.join(' '),
144
+ code_challenge: params.codeChallenge,
145
+ code_challenge_method: 'S256',
146
+ });
147
+ if (params.state) qs.set('state', params.state);
148
+ if (params.resource) qs.set('resource', params.resource.href);
149
+
150
+ const base = getMcpSafeUrl().replace(/\/+$/, '');
151
+ res.redirect(302, `${base}/oauth/consent?${qs.toString()}`);
152
+ },
153
+
154
+ // Not called because skipLocalPkceValidation = true.
155
+ // PKCE verification is done inline in exchangeAuthorizationCode.
156
+ skipLocalPkceValidation: true,
157
+
158
+ async challengeForAuthorizationCode(_client: OAuthClientInformationFull, _code: string): Promise<string> {
159
+ throw new ServerError('PKCE validation is handled by the provider directly');
160
+ },
161
+
162
+ async exchangeAuthorizationCode(
163
+ client: OAuthClientInformationFull,
164
+ code: string,
165
+ codeVerifier?: string,
166
+ redirectUri?: string,
167
+ resource?: URL,
168
+ ): Promise<OAuthTokens> {
169
+ const pending = consumeAuthCode(code);
170
+ if (!pending || pending.clientId !== client.client_id)
171
+ throw new Error('Authorization grant is invalid.');
172
+
173
+ if (redirectUri && pending.redirectUri !== redirectUri)
174
+ throw new Error('Authorization grant is invalid.');
175
+
176
+ const resourceStr = resource ? resource.href.replace(/\/+$/, '') : null;
177
+ if (pending.resource && resourceStr && pending.resource !== resourceStr)
178
+ throw new Error('Authorization grant is invalid.');
179
+
180
+ if (codeVerifier && !verifyPKCE(codeVerifier, pending.codeChallenge))
181
+ throw new Error('Authorization grant is invalid.');
182
+
183
+ const tokens = issueTokens(client.client_id, pending.userId, pending.scopes, null, pending.resource ?? null);
184
+ writeAudit({
185
+ userId: pending.userId,
186
+ action: 'oauth.token.issue',
187
+ details: { client_id: client.client_id, scopes: pending.scopes, audience: pending.resource ?? null },
188
+ ip: null,
189
+ });
190
+ return tokens;
191
+ },
192
+
193
+ async exchangeRefreshToken(
194
+ client: OAuthClientInformationFull,
195
+ refreshToken: string,
196
+ _scopes?: string[],
197
+ _resource?: URL,
198
+ ): Promise<OAuthTokens> {
199
+ const result = refreshTokens(refreshToken, client.client_id, client.client_secret, null);
200
+ if (result.error) throw new Error(result.error === 'invalid_client' ? 'Invalid client credentials' : 'Refresh token is invalid or expired');
201
+ return result.tokens!;
202
+ },
203
+
204
+ async verifyAccessToken(token: string): Promise<AuthInfo> {
205
+ const info = getUserByAccessToken(token);
206
+ if (!info) throw new Error('Invalid or expired token');
207
+ return {
208
+ token,
209
+ clientId: info.clientId,
210
+ scopes: info.scopes,
211
+ extra: { user: info.user },
212
+ };
213
+ },
214
+
215
+ async revokeToken(
216
+ client: OAuthClientInformationFull,
217
+ request: OAuthTokenRevocationRequest,
218
+ ): Promise<void> {
219
+ serviceRevokeToken(request.token, client.client_id, undefined, null);
220
+ },
221
+ };
server/src/mcp/resources.ts ADDED
@@ -0,0 +1,442 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp';
2
+ import { canAccessTrip } from '../db/database';
3
+ import { listTrips, getTrip, getTripOwner, listMembers } from '../services/tripService';
4
+ import { listDays, listAccommodations } from '../services/dayService';
5
+ import { listPlaces } from '../services/placeService';
6
+ import { listBudgetItems, getPerPersonSummary, calculateSettlement } from '../services/budgetService';
7
+ import { listItems as listPackingItems, listBags } from '../services/packingService';
8
+ import { listReservations } from '../services/reservationService';
9
+ import { listNotes as listDayNotes } from '../services/dayNoteService';
10
+ import { listNotes as listCollabNotes, listPolls, listMessages } from '../services/collabService';
11
+ import { listItems as listTodoItems } from '../services/todoService';
12
+ import { listCategories } from '../services/categoryService';
13
+ import { listBucketList, listVisitedCountries, getStats as getAtlasStats, listManuallyVisitedRegions } from '../services/atlasService';
14
+ import { getNotifications } from '../services/inAppNotifications';
15
+ import { getActivePlanId, getActivePlan, getPlanData, getEntries as getVacayEntries, getHolidays } from '../services/vacayService';
16
+ import { isAddonEnabled, getCollabFeatures } from '../services/adminService';
17
+ import { ADDON_IDS } from '../addons';
18
+ import { canAccessJourney, getJourneyFull, listEntries, listJourneys } from '../services/journeyService';
19
+ import { canRead, canReadTrips } from './scopes';
20
+
21
+ function parseId(value: string | string[]): number | null {
22
+ const n = Number(Array.isArray(value) ? value[0] : value);
23
+ return Number.isInteger(n) && n > 0 ? n : null;
24
+ }
25
+
26
+ function accessDenied(uri: string) {
27
+ return {
28
+ contents: [{
29
+ uri,
30
+ mimeType: 'application/json',
31
+ text: JSON.stringify({ error: 'Trip not found or access denied' }),
32
+ }],
33
+ };
34
+ }
35
+
36
+ function scopeDenied(uri: string) {
37
+ return {
38
+ contents: [{
39
+ uri,
40
+ mimeType: 'application/json',
41
+ text: JSON.stringify({ error: 'Insufficient OAuth scope to access this resource' }),
42
+ }],
43
+ };
44
+ }
45
+
46
+ function jsonContent(uri: string, data: unknown) {
47
+ return {
48
+ contents: [{
49
+ uri,
50
+ mimeType: 'application/json',
51
+ text: JSON.stringify(data, null, 2),
52
+ }],
53
+ };
54
+ }
55
+
56
+ export function registerResources(server: McpServer, userId: number, scopes: string[] | null): void {
57
+ // List all accessible trips
58
+ if (canReadTrips(scopes)) server.registerResource(
59
+ 'trips',
60
+ 'trek://trips',
61
+ { description: 'All trips the user owns or is a member of', mimeType: 'application/json' },
62
+ async (uri) => {
63
+ const trips = listTrips(userId, 0);
64
+ return jsonContent(uri.href, trips);
65
+ }
66
+ );
67
+
68
+ // Single trip detail
69
+ if (canReadTrips(scopes)) server.registerResource(
70
+ 'trip',
71
+ new ResourceTemplate('trek://trips/{tripId}', { list: undefined }),
72
+ { description: 'A single trip with metadata and member count', mimeType: 'application/json' },
73
+ async (uri, { tripId }) => {
74
+ const id = parseId(tripId);
75
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
76
+ const trip = getTrip(id, userId);
77
+ return jsonContent(uri.href, trip);
78
+ }
79
+ );
80
+
81
+ // Days with assigned places
82
+ if (canReadTrips(scopes)) server.registerResource(
83
+ 'trip-days',
84
+ new ResourceTemplate('trek://trips/{tripId}/days', { list: undefined }),
85
+ { description: 'Days of a trip with their assigned places', mimeType: 'application/json' },
86
+ async (uri, { tripId }) => {
87
+ const id = parseId(tripId);
88
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
89
+
90
+ const { days } = listDays(id);
91
+ return jsonContent(uri.href, days);
92
+ }
93
+ );
94
+
95
+ // Places in a trip
96
+ if (canRead(scopes, 'places')) server.registerResource(
97
+ 'trip-places',
98
+ new ResourceTemplate('trek://trips/{tripId}/places', { list: undefined }),
99
+ { description: 'All places/POIs in a trip, optionally filtered by assignment status (e.g. ?assignment=unassigned)', mimeType: 'application/json' },
100
+ async (uri, { tripId }) => {
101
+ const id = parseId(tripId);
102
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
103
+ const assignment = uri.searchParams.get('assignment') as 'all' | 'unassigned' | 'assigned' | null;
104
+ const places = listPlaces(String(id), { assignment: assignment ?? undefined });
105
+ return jsonContent(uri.href, places);
106
+ }
107
+ );
108
+
109
+ // Budget items
110
+ if (isAddonEnabled(ADDON_IDS.BUDGET) && canRead(scopes, 'budget')) server.registerResource(
111
+ 'trip-budget',
112
+ new ResourceTemplate('trek://trips/{tripId}/budget', { list: undefined }),
113
+ { description: 'Budget and expense items for a trip', mimeType: 'application/json' },
114
+ async (uri, { tripId }) => {
115
+ const id = parseId(tripId);
116
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
117
+ const items = listBudgetItems(id);
118
+ return jsonContent(uri.href, items);
119
+ }
120
+ );
121
+
122
+ // Packing checklist
123
+ if (isAddonEnabled(ADDON_IDS.PACKING) && canRead(scopes, 'packing')) server.registerResource(
124
+ 'trip-packing',
125
+ new ResourceTemplate('trek://trips/{tripId}/packing', { list: undefined }),
126
+ { description: 'Packing checklist for a trip', mimeType: 'application/json' },
127
+ async (uri, { tripId }) => {
128
+ const id = parseId(tripId);
129
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
130
+ const items = listPackingItems(id);
131
+ return jsonContent(uri.href, items);
132
+ }
133
+ );
134
+
135
+ // Reservations (flights, hotels, restaurants)
136
+ if (canRead(scopes, 'reservations')) server.registerResource(
137
+ 'trip-reservations',
138
+ new ResourceTemplate('trek://trips/{tripId}/reservations', { list: undefined }),
139
+ { description: 'Reservations (flights, hotels, restaurants) for a trip', mimeType: 'application/json' },
140
+ async (uri, { tripId }) => {
141
+ const id = parseId(tripId);
142
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
143
+ const reservations = listReservations(id);
144
+ return jsonContent(uri.href, reservations);
145
+ }
146
+ );
147
+
148
+ // Day notes
149
+ if (canReadTrips(scopes)) server.registerResource(
150
+ 'day-notes',
151
+ new ResourceTemplate('trek://trips/{tripId}/days/{dayId}/notes', { list: undefined }),
152
+ { description: 'Notes for a specific day in a trip', mimeType: 'application/json' },
153
+ async (uri, { tripId, dayId }) => {
154
+ const tId = parseId(tripId);
155
+ const dId = parseId(dayId);
156
+ if (tId === null || dId === null || !canAccessTrip(tId, userId)) return accessDenied(uri.href);
157
+ const notes = listDayNotes(dId, tId);
158
+ return jsonContent(uri.href, notes);
159
+ }
160
+ );
161
+
162
+ // Accommodations (hotels, rentals) per trip
163
+ if (canReadTrips(scopes)) server.registerResource(
164
+ 'trip-accommodations',
165
+ new ResourceTemplate('trek://trips/{tripId}/accommodations', { list: undefined }),
166
+ { description: 'Accommodations (hotels, rentals) for a trip with check-in/out details', mimeType: 'application/json' },
167
+ async (uri, { tripId }) => {
168
+ const id = parseId(tripId);
169
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
170
+ const accommodations = listAccommodations(id);
171
+ return jsonContent(uri.href, accommodations);
172
+ }
173
+ );
174
+
175
+ // Trip members (owner + collaborators)
176
+ if (canReadTrips(scopes)) server.registerResource(
177
+ 'trip-members',
178
+ new ResourceTemplate('trek://trips/{tripId}/members', { list: undefined }),
179
+ { description: 'Owner and collaborators of a trip', mimeType: 'application/json' },
180
+ async (uri, { tripId }) => {
181
+ const id = parseId(tripId);
182
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
183
+ const ownerRow = getTripOwner(id);
184
+ if (!ownerRow) return accessDenied(uri.href);
185
+ const { owner, members } = listMembers(id, ownerRow.user_id);
186
+ return jsonContent(uri.href, { owner, members });
187
+ }
188
+ );
189
+
190
+ // Collab notes for a trip
191
+ const collabFeatures = isAddonEnabled(ADDON_IDS.COLLAB) ? getCollabFeatures() : null;
192
+ if (collabFeatures?.notes && canRead(scopes, 'collab')) server.registerResource(
193
+ 'trip-collab-notes',
194
+ new ResourceTemplate('trek://trips/{tripId}/collab-notes', { list: undefined }),
195
+ { description: 'Shared collaborative notes for a trip', mimeType: 'application/json' },
196
+ async (uri, { tripId }) => {
197
+ const id = parseId(tripId);
198
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
199
+ const notes = listCollabNotes(id);
200
+ return jsonContent(uri.href, notes);
201
+ }
202
+ );
203
+
204
+ // Trip to-do list
205
+ if (isAddonEnabled(ADDON_IDS.PACKING) && canRead(scopes, 'todos')) server.registerResource(
206
+ 'trip-todos',
207
+ new ResourceTemplate('trek://trips/{tripId}/todos', { list: undefined }),
208
+ { description: 'To-do items for a trip, ordered by position', mimeType: 'application/json' },
209
+ async (uri, { tripId }) => {
210
+ const id = parseId(tripId);
211
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
212
+ const items = listTodoItems(id);
213
+ return jsonContent(uri.href, items);
214
+ }
215
+ );
216
+
217
+ // All place categories (global, no trip filter) — safe for any authenticated session
218
+ server.registerResource(
219
+ 'categories',
220
+ 'trek://categories',
221
+ { description: 'All available place categories (id, name, color, icon) for use when creating places', mimeType: 'application/json' },
222
+ async (uri) => {
223
+ const categories = listCategories();
224
+ return jsonContent(uri.href, categories);
225
+ }
226
+ );
227
+
228
+ // User's bucket list
229
+ if (isAddonEnabled(ADDON_IDS.ATLAS) && canRead(scopes, 'atlas')) server.registerResource(
230
+ 'bucket-list',
231
+ 'trek://bucket-list',
232
+ { description: 'Your personal travel bucket list', mimeType: 'application/json' },
233
+ async (uri) => {
234
+ const items = listBucketList(userId);
235
+ return jsonContent(uri.href, items);
236
+ }
237
+ );
238
+
239
+ // User's visited countries
240
+ if (isAddonEnabled(ADDON_IDS.ATLAS) && canRead(scopes, 'atlas')) server.registerResource(
241
+ 'visited-countries',
242
+ 'trek://visited-countries',
243
+ { description: 'Countries you have marked as visited in Atlas', mimeType: 'application/json' },
244
+ async (uri) => {
245
+ const countries = listVisitedCountries(userId);
246
+ return jsonContent(uri.href, countries);
247
+ }
248
+ );
249
+
250
+ // Budget per-person summary
251
+ if (isAddonEnabled(ADDON_IDS.BUDGET) && canRead(scopes, 'budget')) server.registerResource(
252
+ 'trip-budget-per-person',
253
+ new ResourceTemplate('trek://trips/{tripId}/budget/per-person', { list: undefined }),
254
+ { description: 'Per-person budget summary for a trip (total spent per member, split breakdown)', mimeType: 'application/json' },
255
+ async (uri, { tripId }) => {
256
+ const id = parseId(tripId);
257
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
258
+ const summary = getPerPersonSummary(id);
259
+ return jsonContent(uri.href, summary);
260
+ }
261
+ );
262
+
263
+ // Budget settlement
264
+ if (isAddonEnabled(ADDON_IDS.BUDGET) && canRead(scopes, 'budget')) server.registerResource(
265
+ 'trip-budget-settlement',
266
+ new ResourceTemplate('trek://trips/{tripId}/budget/settlement', { list: undefined }),
267
+ { description: 'Suggested settlement transactions to balance who owes whom', mimeType: 'application/json' },
268
+ async (uri, { tripId }) => {
269
+ const id = parseId(tripId);
270
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
271
+ const settlement = calculateSettlement(id);
272
+ return jsonContent(uri.href, settlement);
273
+ }
274
+ );
275
+
276
+ // Packing bags
277
+ if (isAddonEnabled(ADDON_IDS.PACKING) && canRead(scopes, 'packing')) server.registerResource(
278
+ 'trip-packing-bags',
279
+ new ResourceTemplate('trek://trips/{tripId}/packing/bags', { list: undefined }),
280
+ { description: 'All packing bags for a trip with their members', mimeType: 'application/json' },
281
+ async (uri, { tripId }) => {
282
+ const id = parseId(tripId);
283
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
284
+ const bags = listBags(id);
285
+ return jsonContent(uri.href, bags);
286
+ }
287
+ );
288
+
289
+ // In-app notifications
290
+ if (canRead(scopes, 'notifications')) server.registerResource(
291
+ 'notifications-in-app',
292
+ 'trek://notifications/in-app',
293
+ { description: "The current user's in-app notifications (most recent 50, unread first)", mimeType: 'application/json' },
294
+ async (uri) => {
295
+ const result = getNotifications(userId, { limit: 50 });
296
+ return jsonContent(uri.href, result);
297
+ }
298
+ );
299
+
300
+ // Atlas stats and regions (addon-gated)
301
+ if (isAddonEnabled(ADDON_IDS.ATLAS) && canRead(scopes, 'atlas')) {
302
+ server.registerResource(
303
+ 'atlas-stats',
304
+ 'trek://atlas/stats',
305
+ { description: "User's atlas statistics — visited country counts and breakdown", mimeType: 'application/json' },
306
+ async (uri) => {
307
+ const stats = await getAtlasStats(userId);
308
+ return jsonContent(uri.href, stats);
309
+ }
310
+ );
311
+
312
+ server.registerResource(
313
+ 'atlas-regions',
314
+ 'trek://atlas/regions',
315
+ { description: 'List of manually visited regions for the current user', mimeType: 'application/json' },
316
+ async (uri) => {
317
+ const regions = listManuallyVisitedRegions(userId);
318
+ return jsonContent(uri.href, regions);
319
+ }
320
+ );
321
+ }
322
+
323
+ // Collab polls (addon + sub-feature gated)
324
+ if (collabFeatures?.polls && canRead(scopes, 'collab')) {
325
+ server.registerResource(
326
+ 'trip-collab-polls',
327
+ new ResourceTemplate('trek://trips/{tripId}/collab/polls', { list: undefined }),
328
+ { description: 'All polls for a trip with vote counts per option', mimeType: 'application/json' },
329
+ async (uri, { tripId }) => {
330
+ const id = parseId(tripId);
331
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
332
+ const polls = listPolls(id);
333
+ return jsonContent(uri.href, polls);
334
+ }
335
+ );
336
+ }
337
+
338
+ // Collab messages (addon + sub-feature gated)
339
+ if (collabFeatures?.chat && canRead(scopes, 'collab')) {
340
+ server.registerResource(
341
+ 'trip-collab-messages',
342
+ new ResourceTemplate('trek://trips/{tripId}/collab/messages', { list: undefined }),
343
+ { description: 'Most recent 100 chat messages for a trip', mimeType: 'application/json' },
344
+ async (uri, { tripId }) => {
345
+ const id = parseId(tripId);
346
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
347
+ const messages = listMessages(id);
348
+ return jsonContent(uri.href, messages);
349
+ }
350
+ );
351
+ }
352
+
353
+ // Vacay resources (addon-gated)
354
+ if (isAddonEnabled(ADDON_IDS.VACAY) && canRead(scopes, 'vacay')) {
355
+ server.registerResource(
356
+ 'vacay-plan',
357
+ 'trek://vacay/plan',
358
+ { description: "Full snapshot of the user's active vacation plan (members, years, settings)", mimeType: 'application/json' },
359
+ async (uri) => {
360
+ const plan = getPlanData(userId);
361
+ return jsonContent(uri.href, plan);
362
+ }
363
+ );
364
+
365
+ server.registerResource(
366
+ 'vacay-entries',
367
+ new ResourceTemplate('trek://vacay/entries/{year}', { list: undefined }),
368
+ { description: 'All vacation entries for the active plan and a specific year', mimeType: 'application/json' },
369
+ async (uri, { year }) => {
370
+ const planId = getActivePlanId(userId);
371
+ const entries = getVacayEntries(planId, Array.isArray(year) ? year[0] : year);
372
+ return jsonContent(uri.href, entries);
373
+ }
374
+ );
375
+
376
+ server.registerResource(
377
+ 'vacay-holidays',
378
+ new ResourceTemplate('trek://vacay/holidays/{year}', { list: undefined }),
379
+ { description: "Cached public holidays for the plan's configured region and year", mimeType: 'application/json' },
380
+ async (uri, { year }) => {
381
+ const plan = getActivePlan(userId);
382
+ if (!plan.holidays_enabled || !plan.holidays_region) return jsonContent(uri.href, []);
383
+ const yearStr = Array.isArray(year) ? year[0] : year;
384
+ const result = await getHolidays(yearStr, plan.holidays_region);
385
+ return jsonContent(uri.href, result.data ?? []);
386
+ }
387
+ );
388
+ }
389
+
390
+ // Journey resources (Journey addon)
391
+ if (isAddonEnabled(ADDON_IDS.JOURNEY) && canRead(scopes, 'journey')) {
392
+ server.registerResource(
393
+ 'journeys',
394
+ 'trek://journeys',
395
+ { description: 'All journeys owned or contributed to by the current user', mimeType: 'application/json' },
396
+ async (uri) => {
397
+ const journeys = listJourneys(userId);
398
+ return jsonContent(uri.href, journeys);
399
+ }
400
+ );
401
+
402
+ server.registerResource(
403
+ 'journey-detail',
404
+ new ResourceTemplate('trek://journeys/{journeyId}', { list: undefined }),
405
+ { description: 'Single journey with entries, contributors, and trip links', mimeType: 'application/json' },
406
+ async (uri, { journeyId }) => {
407
+ const id = parseId(journeyId);
408
+ if (id === null) return accessDenied(uri.href);
409
+ const journey = getJourneyFull(id, userId);
410
+ if (!journey) return accessDenied(uri.href);
411
+ return jsonContent(uri.href, journey);
412
+ }
413
+ );
414
+
415
+ server.registerResource(
416
+ 'journey-entries',
417
+ new ResourceTemplate('trek://journeys/{journeyId}/entries', { list: undefined }),
418
+ { description: 'All entries in a journey (date, text, mood, linked trip)', mimeType: 'application/json' },
419
+ async (uri, { journeyId }) => {
420
+ const id = parseId(journeyId);
421
+ if (id === null) return accessDenied(uri.href);
422
+ const j = canAccessJourney(id, userId);
423
+ if (!j) return accessDenied(uri.href);
424
+ const entries = listEntries(id, userId);
425
+ return jsonContent(uri.href, entries);
426
+ }
427
+ );
428
+
429
+ server.registerResource(
430
+ 'journey-contributors',
431
+ new ResourceTemplate('trek://journeys/{journeyId}/contributors', { list: undefined }),
432
+ { description: 'Contributors (owners and collaborators) of a journey', mimeType: 'application/json' },
433
+ async (uri, { journeyId }) => {
434
+ const id = parseId(journeyId);
435
+ if (id === null) return accessDenied(uri.href);
436
+ const j = getJourneyFull(id, userId);
437
+ if (!j) return accessDenied(uri.href);
438
+ return jsonContent(uri.href, (j as any).contributors ?? []);
439
+ }
440
+ );
441
+ }
442
+ }
server/src/mcp/scopes.ts ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // OAuth 2.1 scope definitions for TREK MCP
3
+ // ---------------------------------------------------------------------------
4
+
5
+ export const SCOPES = {
6
+ TRIPS_READ: 'trips:read',
7
+ TRIPS_WRITE: 'trips:write',
8
+ TRIPS_DELETE: 'trips:delete',
9
+ TRIPS_SHARE: 'trips:share',
10
+ PLACES_READ: 'places:read',
11
+ PLACES_WRITE: 'places:write',
12
+ ATLAS_READ: 'atlas:read',
13
+ ATLAS_WRITE: 'atlas:write',
14
+ PACKING_READ: 'packing:read',
15
+ PACKING_WRITE: 'packing:write',
16
+ TODOS_READ: 'todos:read',
17
+ TODOS_WRITE: 'todos:write',
18
+ BUDGET_READ: 'budget:read',
19
+ BUDGET_WRITE: 'budget:write',
20
+ RESERVATIONS_READ: 'reservations:read',
21
+ RESERVATIONS_WRITE: 'reservations:write',
22
+ COLLAB_READ: 'collab:read',
23
+ COLLAB_WRITE: 'collab:write',
24
+ NOTIFICATIONS_READ: 'notifications:read',
25
+ NOTIFICATIONS_WRITE: 'notifications:write',
26
+ VACAY_READ: 'vacay:read',
27
+ VACAY_WRITE: 'vacay:write',
28
+ GEO_READ: 'geo:read',
29
+ WEATHER_READ: 'weather:read',
30
+ JOURNEY_READ: 'journey:read',
31
+ JOURNEY_WRITE: 'journey:write',
32
+ JOURNEY_SHARE: 'journey:share',
33
+ } as const;
34
+
35
+ export type Scope = typeof SCOPES[keyof typeof SCOPES];
36
+
37
+ export const ALL_SCOPES: Scope[] = Object.values(SCOPES) as Scope[];
38
+
39
+ export interface ScopeInfo {
40
+ label: string;
41
+ description: string;
42
+ group: string;
43
+ }
44
+
45
+ export const SCOPE_INFO: Record<Scope, ScopeInfo> = {
46
+ 'trips:read': { label: 'View trips & itineraries', description: 'Read trips, days, day notes, and members', group: 'Trips' },
47
+ 'trips:write': { label: 'Edit trips & itineraries', description: 'Create and update trips, days, notes, and manage members', group: 'Trips' },
48
+ 'trips:delete': { label: 'Delete trips', description: 'Permanently delete entire trips — this action is irreversible', group: 'Trips' },
49
+ 'trips:share': { label: 'Manage share links', description: 'Create, update, and revoke public share links for trips', group: 'Trips' },
50
+ 'places:read': { label: 'View places & map data', description: 'Read places, day assignments, tags, and categories', group: 'Places' },
51
+ 'places:write': { label: 'Manage places', description: 'Create, update, and delete places, assignments, and tags', group: 'Places' },
52
+ 'atlas:read': { label: 'View Atlas', description: 'Read visited countries, regions, and bucket list', group: 'Atlas' },
53
+ 'atlas:write': { label: 'Manage Atlas', description: 'Mark countries and regions visited, manage bucket list', group: 'Atlas' },
54
+ 'packing:read': { label: 'View packing lists', description: 'Read packing items, bags, and category assignees', group: 'Packing' },
55
+ 'packing:write': { label: 'Manage packing lists', description: 'Add, update, delete, toggle, and reorder packing items and bags', group: 'Packing' },
56
+ 'todos:read': { label: 'View to-do lists', description: 'Read trip to-do items and category assignees', group: 'To-dos' },
57
+ 'todos:write': { label: 'Manage to-do lists', description: 'Create, update, toggle, delete, and reorder to-do items', group: 'To-dos' },
58
+ 'budget:read': { label: 'View budget', description: 'Read budget items and expense breakdown', group: 'Budget' },
59
+ 'budget:write': { label: 'Manage budget', description: 'Create, update, and delete budget items', group: 'Budget' },
60
+ 'reservations:read': { label: 'View reservations', description: 'Read reservations and accommodation details', group: 'Reservations' },
61
+ 'reservations:write': { label: 'Manage reservations', description: 'Create, update, delete, and reorder reservations', group: 'Reservations' },
62
+ 'collab:read': { label: 'View collaboration', description: 'Read collab notes, polls, and messages', group: 'Collaboration' },
63
+ 'collab:write': { label: 'Manage collaboration', description: 'Create, update, and delete collab notes, polls, and messages', group: 'Collaboration' },
64
+ 'notifications:read': { label: 'View notifications', description: 'Read in-app notifications and unread counts', group: 'Notifications' },
65
+ 'notifications:write': { label: 'Manage notifications', description: 'Mark notifications as read and respond to them', group: 'Notifications' },
66
+ 'vacay:read': { label: 'View vacation plans', description: 'Read vacation planning data, entries, and stats', group: 'Vacation' },
67
+ 'vacay:write': { label: 'Manage vacation plans', description: 'Create and manage vacation entries, holidays, and team plans', group: 'Vacation' },
68
+ 'geo:read': { label: 'Maps & geocoding', description: 'Search locations, resolve map URLs, and reverse geocode coordinates', group: 'Geo' },
69
+ 'weather:read': { label: 'Weather forecasts', description: 'Fetch weather forecasts for trip locations and dates', group: 'Weather' },
70
+ 'journey:read': { label: 'View journeys', description: 'Read journeys, entries, and contributor list', group: 'Journey' },
71
+ 'journey:write': { label: 'Manage journeys', description: 'Create, update, and delete journeys and their entries', group: 'Journey' },
72
+ 'journey:share': { label: 'Manage journey links', description: 'Create, update, and revoke public share links for journeys', group: 'Journey' },
73
+ };
74
+
75
+ // ---------------------------------------------------------------------------
76
+ // Scope enforcement helpers
77
+ // null scopes = static trek_ token = full access
78
+ // ---------------------------------------------------------------------------
79
+
80
+ /** trips:read OR trips:write OR trips:delete OR trips:share all grant read access to trips */
81
+ export function canReadTrips(scopes: string[] | null): boolean {
82
+ if (!scopes) return true;
83
+ return scopes.some(s => s === 'trips:read' || s === 'trips:write' || s === 'trips:delete' || s === 'trips:share');
84
+ }
85
+
86
+ /** group:write grants write access; for trips canReadTrips handles read */
87
+ export function canWrite(scopes: string[] | null, group: string): boolean {
88
+ if (!scopes) return true;
89
+ return scopes.includes(`${group}:write`);
90
+ }
91
+
92
+ /** group:read OR group:write grant read access */
93
+ export function canRead(scopes: string[] | null, group: string): boolean {
94
+ if (!scopes) return true;
95
+ return scopes.some(s => s === `${group}:read` || s === `${group}:write`);
96
+ }
97
+
98
+ /** trips:delete is a separate scope from trips:write */
99
+ export function canDeleteTrips(scopes: string[] | null): boolean {
100
+ if (!scopes) return true;
101
+ return scopes.includes('trips:delete');
102
+ }
103
+
104
+ /** trips:share is a separate scope for managing public share links */
105
+ export function canShareTrips(scopes: string[] | null): boolean {
106
+ if (!scopes) return true;
107
+ return scopes.includes('trips:share');
108
+ }
109
+
110
+ /** journey:share is a separate scope for managing public share links for journeys */
111
+ export function canShareJourneys(scopes: string[] | null): boolean {
112
+ if (!scopes) return true;
113
+ return scopes.includes('journey:share');
114
+ }
115
+
116
+ export function validateScopes(requestedScopes: string[]): { valid: boolean; invalid: string[] } {
117
+ const invalid = requestedScopes.filter(s => !ALL_SCOPES.includes(s as Scope));
118
+ return { valid: invalid.length === 0, invalid };
119
+ }
server/src/mcp/sessionManager.ts ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
2
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp';
3
+
4
+ export interface McpSession {
5
+ server: McpServer;
6
+ transport: StreamableHTTPServerTransport;
7
+ userId: number;
8
+ /** null = static trek_ token or JWT (full access); string[] = OAuth 2.1 scopes */
9
+ scopes: string[] | null;
10
+ /** OAuth 2.1 client_id that owns this session; null for static-token / JWT sessions */
11
+ clientId: string | null;
12
+ /** true when authenticated via static trek_ token — triggers deprecation prompt */
13
+ isStaticToken: boolean;
14
+ lastActivity: number;
15
+ }
16
+
17
+ export const sessions = new Map<string, McpSession>();
18
+
19
+ /** Terminate all active MCP sessions for a specific user (e.g. on token revocation). */
20
+ export function revokeUserSessions(userId: number): void {
21
+ for (const [sid, session] of sessions) {
22
+ if (session.userId === userId) {
23
+ try { session.server.close(); } catch { /* ignore */ }
24
+ try { session.transport.close(); } catch { /* ignore */ }
25
+ sessions.delete(sid);
26
+ }
27
+ }
28
+ }
29
+
30
+ /** Terminate MCP sessions for a specific (user, OAuth client) pair.
31
+ * Used when an OAuth token or session is revoked so only the affected client's
32
+ * sessions are closed, not sessions from other clients for the same user. */
33
+ export function revokeUserSessionsForClient(userId: number, clientId: string): void {
34
+ for (const [sid, session] of sessions) {
35
+ if (session.userId === userId && session.clientId === clientId) {
36
+ try { session.server.close(); } catch { /* ignore */ }
37
+ try { session.transport.close(); } catch { /* ignore */ }
38
+ sessions.delete(sid);
39
+ }
40
+ }
41
+ }
server/src/mcp/tools.ts ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
2
+ import { registerTodoTools } from './tools/todos';
3
+ import { registerAssignmentTools } from './tools/assignments';
4
+ import { registerJourneyTools } from './tools/journey';
5
+ import { registerReservationTools } from './tools/reservations';
6
+ import { registerTagTools } from './tools/tags';
7
+ import { registerMapsWeatherTools } from './tools/mapsWeather';
8
+ import { registerNotificationTools } from './tools/notifications';
9
+ import { registerAtlasTools } from './tools/atlas';
10
+ import { registerPlaceTools } from './tools/places';
11
+ import { registerDayTools } from './tools/days';
12
+ import { registerBudgetTools } from './tools/budget';
13
+ import { registerPackingTools } from './tools/packing';
14
+ import { registerCollabTools } from './tools/collab';
15
+ import { registerTripTools } from './tools/trips';
16
+ import { registerTransportTools } from './tools/transports';
17
+ import { registerVacayTools } from './tools/vacay';
18
+ import { registerMcpPrompts } from './tools/prompts';
19
+
20
+ export function registerTools(server: McpServer, userId: number, scopes: string[] | null, isStaticToken = false, getDeprecationNotice: () => string | null = () => null): void {
21
+ registerTripTools(server, userId, scopes, getDeprecationNotice);
22
+
23
+ registerPlaceTools(server, userId, scopes);
24
+
25
+ registerBudgetTools(server, userId, scopes);
26
+
27
+ registerPackingTools(server, userId, scopes);
28
+
29
+ registerReservationTools(server, userId, scopes);
30
+
31
+ registerDayTools(server, userId, scopes);
32
+
33
+ registerAssignmentTools(server, userId, scopes);
34
+
35
+ registerTagTools(server, userId, scopes);
36
+
37
+ registerMapsWeatherTools(server, userId, scopes);
38
+
39
+ registerNotificationTools(server, userId, scopes);
40
+
41
+ registerAtlasTools(server, userId, scopes);
42
+
43
+ registerCollabTools(server, userId, scopes);
44
+
45
+ registerTransportTools(server, userId, scopes);
46
+
47
+ registerJourneyTools(server, userId, scopes);
48
+
49
+ registerVacayTools(server, userId, scopes);
50
+
51
+ registerTodoTools(server, userId, scopes);
52
+
53
+ registerMcpPrompts(server, userId, isStaticToken);
54
+ }
server/src/mcp/tools/_shared.ts ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { broadcast } from '../../websocket';
2
+ import { db } from '../../db/database';
3
+ import { checkPermission } from '../../services/permissions';
4
+
5
+ export function safeBroadcast(tripId: number, event: string, payload: Record<string, unknown>): void {
6
+ try {
7
+ broadcast(tripId, event, { ...payload, _source: 'mcp' });
8
+ } catch (err) {
9
+ console.error(`[MCP] broadcast failed for ${event}:`, err?.message ?? err);
10
+ }
11
+ }
12
+
13
+ export const MAX_MCP_TRIP_DAYS = 90;
14
+
15
+ export const TOOL_ANNOTATIONS_READONLY = {
16
+ readOnlyHint: true,
17
+ destructiveHint: false,
18
+ idempotentHint: true,
19
+ openWorldHint: false,
20
+ } as const;
21
+
22
+ export const TOOL_ANNOTATIONS_WRITE = {
23
+ readOnlyHint: false,
24
+ destructiveHint: false,
25
+ idempotentHint: true,
26
+ openWorldHint: false,
27
+ } as const;
28
+
29
+ export const TOOL_ANNOTATIONS_DELETE = {
30
+ readOnlyHint: false,
31
+ destructiveHint: true,
32
+ idempotentHint: true,
33
+ openWorldHint: false,
34
+ } as const;
35
+
36
+ export const TOOL_ANNOTATIONS_NON_IDEMPOTENT = {
37
+ readOnlyHint: false,
38
+ destructiveHint: false,
39
+ idempotentHint: false,
40
+ openWorldHint: false,
41
+ } as const;
42
+
43
+ export function demoDenied() {
44
+ return { content: [{ type: 'text' as const, text: 'Write operations are disabled in demo mode.' }], isError: true };
45
+ }
46
+
47
+ export function noAccess() {
48
+ return { content: [{ type: 'text' as const, text: 'Trip not found or access denied.' }], isError: true };
49
+ }
50
+
51
+ export function permissionDenied() {
52
+ return { content: [{ type: 'text' as const, text: 'You do not have permission to perform this action on this trip.' }], isError: true };
53
+ }
54
+
55
+ /**
56
+ * RBAC gate for MCP tools, mirroring the checkPermission() calls the REST/Nest
57
+ * routes run. Call this after canAccessTrip() with the same action key the
58
+ * matching REST route uses. Returns true when the user may perform `action`
59
+ * on `tripId`.
60
+ */
61
+ export function hasTripPermission(action: string, tripId: number | string, userId: number): boolean {
62
+ const trip = db.prepare('SELECT user_id FROM trips WHERE id = ?').get(tripId) as { user_id?: number } | undefined;
63
+ if (!trip) return false;
64
+ const userRow = db.prepare('SELECT role FROM users WHERE id = ?').get(userId) as { role?: string } | undefined;
65
+ const tripOwnerId = typeof trip.user_id === 'number' ? trip.user_id : null;
66
+ return checkPermission(action, userRow?.role ?? 'user', tripOwnerId, userId, tripOwnerId !== userId);
67
+ }
68
+
69
+ export function ok(data: unknown) {
70
+ return { content: [{ type: 'text' as const, text: JSON.stringify(data, null, 2) }] };
71
+ }
server/src/mcp/tools/assignments.ts ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
2
+ import { z } from 'zod';
3
+ import { canAccessTrip } from '../../db/database';
4
+ import { isDemoUser } from '../../services/authService';
5
+ import {
6
+ dayExists, placeExists, createAssignment, assignmentExistsInDay,
7
+ deleteAssignment, reorderAssignments, getAssignmentForTrip, updateTime,
8
+ moveAssignment,
9
+ getParticipants as getAssignmentParticipants,
10
+ setParticipants as setAssignmentParticipants,
11
+ } from '../../services/assignmentService';
12
+ import { getDay } from '../../services/dayService';
13
+ import {
14
+ safeBroadcast, TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE,
15
+ TOOL_ANNOTATIONS_NON_IDEMPOTENT,
16
+ demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
17
+ } from './_shared';
18
+ import { canRead, canWrite } from '../scopes';
19
+
20
+ export function registerAssignmentTools(server: McpServer, userId: number, scopes: string[] | null): void {
21
+ const R = canRead(scopes, 'places');
22
+ const W = canWrite(scopes, 'places');
23
+
24
+ // --- ASSIGNMENTS ---
25
+
26
+ if (W) server.registerTool(
27
+ 'assign_place_to_day',
28
+ {
29
+ description: 'Assign a place to a specific day in a trip.',
30
+ inputSchema: {
31
+ tripId: z.number().int().positive(),
32
+ dayId: z.number().int().positive(),
33
+ placeId: z.number().int().positive(),
34
+ notes: z.string().max(500).optional(),
35
+ },
36
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
37
+ },
38
+ async ({ tripId, dayId, placeId, notes }) => {
39
+ if (isDemoUser(userId)) return demoDenied();
40
+ if (!canAccessTrip(tripId, userId)) return noAccess();
41
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
42
+ if (!dayExists(dayId, tripId)) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true };
43
+ if (!placeExists(placeId, tripId)) return { content: [{ type: 'text' as const, text: 'Place not found.' }], isError: true };
44
+ const assignment = createAssignment(dayId, placeId, notes || null);
45
+ safeBroadcast(tripId, 'assignment:created', { assignment });
46
+ return ok({ assignment });
47
+ }
48
+ );
49
+
50
+ if (W) server.registerTool(
51
+ 'unassign_place',
52
+ {
53
+ description: 'Remove a place assignment from a day.',
54
+ inputSchema: {
55
+ tripId: z.number().int().positive(),
56
+ dayId: z.number().int().positive(),
57
+ assignmentId: z.number().int().positive(),
58
+ },
59
+ annotations: TOOL_ANNOTATIONS_DELETE,
60
+ },
61
+ async ({ tripId, dayId, assignmentId }) => {
62
+ if (isDemoUser(userId)) return demoDenied();
63
+ if (!canAccessTrip(tripId, userId)) return noAccess();
64
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
65
+ if (!assignmentExistsInDay(assignmentId, dayId, tripId))
66
+ return { content: [{ type: 'text' as const, text: 'Assignment not found.' }], isError: true };
67
+ deleteAssignment(assignmentId);
68
+ safeBroadcast(tripId, 'assignment:deleted', { assignmentId, dayId });
69
+ return ok({ success: true });
70
+ }
71
+ );
72
+
73
+ if (W) server.registerTool(
74
+ 'update_assignment_time',
75
+ {
76
+ 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.',
77
+ inputSchema: {
78
+ tripId: z.number().int().positive(),
79
+ assignmentId: z.number().int().positive(),
80
+ place_time: z.string().max(50).nullable().optional().describe('Start time (e.g. "09:00"), or null to clear'),
81
+ end_time: z.string().max(50).nullable().optional().describe('End time (e.g. "11:00"), or null to clear'),
82
+ },
83
+ annotations: TOOL_ANNOTATIONS_WRITE,
84
+ },
85
+ async ({ tripId, assignmentId, place_time, end_time }) => {
86
+ if (isDemoUser(userId)) return demoDenied();
87
+ if (!canAccessTrip(tripId, userId)) return noAccess();
88
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
89
+ const existing = getAssignmentForTrip(assignmentId, tripId);
90
+ if (!existing) return { content: [{ type: 'text' as const, text: 'Assignment not found.' }], isError: true };
91
+ const assignment = updateTime(
92
+ assignmentId,
93
+ place_time !== undefined ? place_time : (existing as any).assignment_time,
94
+ end_time !== undefined ? end_time : (existing as any).assignment_end_time
95
+ );
96
+ safeBroadcast(tripId, 'assignment:updated', { assignment });
97
+ return ok({ assignment });
98
+ }
99
+ );
100
+
101
+ if (W) server.registerTool(
102
+ 'move_assignment',
103
+ {
104
+ description: 'Move a place assignment to a different day.',
105
+ inputSchema: {
106
+ tripId: z.number().int().positive(),
107
+ assignmentId: z.number().int().positive(),
108
+ newDayId: z.number().int().positive(),
109
+ oldDayId: z.number().int().positive(),
110
+ orderIndex: z.number().int().min(0).optional().default(0),
111
+ },
112
+ annotations: TOOL_ANNOTATIONS_WRITE,
113
+ },
114
+ async ({ tripId, assignmentId, newDayId, oldDayId, orderIndex }) => {
115
+ if (isDemoUser(userId)) return demoDenied();
116
+ if (!canAccessTrip(tripId, userId)) return noAccess();
117
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
118
+ if (!getAssignmentForTrip(assignmentId, tripId)) return { content: [{ type: 'text' as const, text: 'Assignment not found.' }], isError: true };
119
+ if (!getDay(newDayId, tripId)) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true };
120
+ const result = moveAssignment(assignmentId, newDayId, orderIndex ?? 0, oldDayId);
121
+ safeBroadcast(tripId, 'assignment:moved', { assignment: result.assignment, oldDayId: result.oldDayId });
122
+ return ok({ assignment: result.assignment });
123
+ }
124
+ );
125
+
126
+ if (R) server.registerTool(
127
+ 'get_assignment_participants',
128
+ {
129
+ description: 'Get the list of users participating in a specific place assignment.',
130
+ inputSchema: {
131
+ tripId: z.number().int().positive(),
132
+ assignmentId: z.number().int().positive(),
133
+ },
134
+ annotations: TOOL_ANNOTATIONS_READONLY,
135
+ },
136
+ async ({ tripId, assignmentId }) => {
137
+ if (!canAccessTrip(tripId, userId)) return noAccess();
138
+ if (!getAssignmentForTrip(assignmentId, tripId)) return { content: [{ type: 'text' as const, text: 'Assignment not found.' }], isError: true };
139
+ const participants = getAssignmentParticipants(assignmentId);
140
+ return ok({ participants });
141
+ }
142
+ );
143
+
144
+ if (W) server.registerTool(
145
+ 'set_assignment_participants',
146
+ {
147
+ description: 'Set the participants for a place assignment (replaces current list).',
148
+ inputSchema: {
149
+ tripId: z.number().int().positive(),
150
+ assignmentId: z.number().int().positive(),
151
+ userIds: z.array(z.number().int().positive()).describe('User IDs to set as participants; empty array clears all'),
152
+ },
153
+ annotations: TOOL_ANNOTATIONS_WRITE,
154
+ },
155
+ async ({ tripId, assignmentId, userIds }) => {
156
+ if (isDemoUser(userId)) return demoDenied();
157
+ if (!canAccessTrip(tripId, userId)) return noAccess();
158
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
159
+ if (!getAssignmentForTrip(assignmentId, tripId)) return { content: [{ type: 'text' as const, text: 'Assignment not found.' }], isError: true };
160
+ const participants = setAssignmentParticipants(assignmentId, userIds);
161
+ safeBroadcast(tripId, 'assignment:participants', { assignmentId, participants });
162
+ return ok({ participants });
163
+ }
164
+ );
165
+
166
+ // --- REORDER ---
167
+
168
+ if (W) server.registerTool(
169
+ 'reorder_day_assignments',
170
+ {
171
+ description: 'Reorder places within a day by providing the assignment IDs in the desired order.',
172
+ inputSchema: {
173
+ tripId: z.number().int().positive(),
174
+ dayId: z.number().int().positive(),
175
+ assignmentIds: z.array(z.number().int().positive()).min(1).max(200).describe('Assignment IDs in desired display order'),
176
+ },
177
+ annotations: TOOL_ANNOTATIONS_WRITE,
178
+ },
179
+ async ({ tripId, dayId, assignmentIds }) => {
180
+ if (isDemoUser(userId)) return demoDenied();
181
+ if (!canAccessTrip(tripId, userId)) return noAccess();
182
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
183
+ if (!getDay(dayId, tripId)) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true };
184
+ reorderAssignments(dayId, assignmentIds);
185
+ safeBroadcast(tripId, 'assignment:reordered', { dayId, assignmentIds });
186
+ return ok({ success: true, dayId, order: assignmentIds });
187
+ }
188
+ );
189
+ }
server/src/mcp/tools/atlas.ts ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
2
+ import { z } from 'zod';
3
+ import { isDemoUser } from '../../services/authService';
4
+ import {
5
+ markCountryVisited, unmarkCountryVisited, createBucketItem, deleteBucketItem,
6
+ getStats as getAtlasStats, listManuallyVisitedRegions,
7
+ markRegionVisited, unmarkRegionVisited, getCountryPlaces, updateBucketItem,
8
+ } from '../../services/atlasService';
9
+ import { isAddonEnabled } from '../../services/adminService';
10
+ import { ADDON_IDS } from '../../addons';
11
+ import {
12
+ TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
13
+ TOOL_ANNOTATIONS_READONLY,
14
+ demoDenied, ok,
15
+ } from './_shared';
16
+ import { canRead, canWrite } from '../scopes';
17
+
18
+ export function registerAtlasTools(server: McpServer, userId: number, scopes: string[] | null): void {
19
+ const R = canRead(scopes, 'atlas');
20
+ const W = canWrite(scopes, 'atlas');
21
+
22
+ if (!isAddonEnabled(ADDON_IDS.ATLAS)) return;
23
+
24
+ // --- BUCKET LIST ---
25
+
26
+ if (W) server.registerTool(
27
+ 'create_bucket_list_item',
28
+ {
29
+ description: 'Add a destination to your personal travel bucket list.',
30
+ inputSchema: {
31
+ name: z.string().min(1).max(200).describe('Destination or experience name'),
32
+ lat: z.number().optional(),
33
+ lng: z.number().optional(),
34
+ country_code: z.string().length(2).toUpperCase().optional().describe('ISO 3166-1 alpha-2 country code'),
35
+ notes: z.string().max(1000).optional(),
36
+ },
37
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
38
+ },
39
+ async ({ name, lat, lng, country_code, notes }) => {
40
+ if (isDemoUser(userId)) return demoDenied();
41
+ const item = createBucketItem(userId, { name, lat, lng, country_code, notes });
42
+ return ok({ item });
43
+ }
44
+ );
45
+
46
+ if (W) server.registerTool(
47
+ 'delete_bucket_list_item',
48
+ {
49
+ description: 'Remove an item from your travel bucket list.',
50
+ inputSchema: {
51
+ itemId: z.number().int().positive(),
52
+ },
53
+ annotations: TOOL_ANNOTATIONS_DELETE,
54
+ },
55
+ async ({ itemId }) => {
56
+ if (isDemoUser(userId)) return demoDenied();
57
+ const deleted = deleteBucketItem(userId, itemId);
58
+ if (!deleted) return { content: [{ type: 'text' as const, text: 'Bucket list item not found.' }], isError: true };
59
+ return ok({ success: true });
60
+ }
61
+ );
62
+
63
+ // --- ATLAS ---
64
+
65
+ if (W) server.registerTool(
66
+ 'mark_country_visited',
67
+ {
68
+ description: 'Mark a country as visited in your Atlas.',
69
+ inputSchema: {
70
+ country_code: z.string().length(2).toUpperCase().describe('ISO 3166-1 alpha-2 country code (e.g. "FR", "JP")'),
71
+ },
72
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
73
+ },
74
+ async ({ country_code }) => {
75
+ if (isDemoUser(userId)) return demoDenied();
76
+ markCountryVisited(userId, country_code.toUpperCase());
77
+ return ok({ success: true, country_code: country_code.toUpperCase() });
78
+ }
79
+ );
80
+
81
+ if (W) server.registerTool(
82
+ 'unmark_country_visited',
83
+ {
84
+ description: 'Remove a country from your visited countries in Atlas.',
85
+ inputSchema: {
86
+ country_code: z.string().length(2).toUpperCase().describe('ISO 3166-1 alpha-2 country code'),
87
+ },
88
+ annotations: TOOL_ANNOTATIONS_DELETE,
89
+ },
90
+ async ({ country_code }) => {
91
+ if (isDemoUser(userId)) return demoDenied();
92
+ unmarkCountryVisited(userId, country_code.toUpperCase());
93
+ return ok({ success: true, country_code: country_code.toUpperCase() });
94
+ }
95
+ );
96
+
97
+ // --- ATLAS EXPANDED ---
98
+
99
+ if (R) server.registerTool(
100
+ 'get_atlas_stats',
101
+ {
102
+ description: 'Get atlas statistics — total visited countries, region counts, continent breakdown.',
103
+ inputSchema: {},
104
+ annotations: TOOL_ANNOTATIONS_READONLY,
105
+ },
106
+ async () => {
107
+ const stats = await getAtlasStats(userId);
108
+ return ok({ stats });
109
+ }
110
+ );
111
+
112
+ if (R) server.registerTool(
113
+ 'list_visited_regions',
114
+ {
115
+ description: 'List all manually visited sub-country regions for the current user.',
116
+ inputSchema: {},
117
+ annotations: TOOL_ANNOTATIONS_READONLY,
118
+ },
119
+ async () => {
120
+ const regions = listManuallyVisitedRegions(userId);
121
+ return ok({ regions });
122
+ }
123
+ );
124
+
125
+ if (W) server.registerTool(
126
+ 'mark_region_visited',
127
+ {
128
+ description: 'Mark a sub-country region as visited.',
129
+ inputSchema: {
130
+ regionCode: z.string().describe('ISO region code e.g. US-CA'),
131
+ regionName: z.string(),
132
+ countryCode: z.string().describe('ISO 3166-1 alpha-2 country code'),
133
+ },
134
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
135
+ },
136
+ async ({ regionCode, regionName, countryCode }) => {
137
+ if (isDemoUser(userId)) return demoDenied();
138
+ markRegionVisited(userId, regionCode, regionName, countryCode);
139
+ const region = listManuallyVisitedRegions(userId).find(r => r.region_code === regionCode);
140
+ return ok({ region });
141
+ }
142
+ );
143
+
144
+ if (W) server.registerTool(
145
+ 'unmark_region_visited',
146
+ {
147
+ description: 'Remove a region from the visited list.',
148
+ inputSchema: {
149
+ regionCode: z.string(),
150
+ },
151
+ annotations: TOOL_ANNOTATIONS_DELETE,
152
+ },
153
+ async ({ regionCode }) => {
154
+ if (isDemoUser(userId)) return demoDenied();
155
+ unmarkRegionVisited(userId, regionCode);
156
+ return ok({ success: true });
157
+ }
158
+ );
159
+
160
+ if (R) server.registerTool(
161
+ 'get_country_atlas_places',
162
+ {
163
+ description: 'Get places saved in the user\'s atlas for a specific country.',
164
+ inputSchema: {
165
+ countryCode: z.string().describe('ISO 3166-1 alpha-2 country code'),
166
+ },
167
+ annotations: TOOL_ANNOTATIONS_READONLY,
168
+ },
169
+ async ({ countryCode }) => {
170
+ const result = getCountryPlaces(userId, countryCode);
171
+ return ok(result);
172
+ }
173
+ );
174
+
175
+ if (W) server.registerTool(
176
+ 'update_bucket_list_item',
177
+ {
178
+ description: 'Update a bucket list item (notes, name, target date, location).',
179
+ inputSchema: {
180
+ itemId: z.number().int().positive(),
181
+ name: z.string().optional(),
182
+ notes: z.string().optional(),
183
+ lat: z.number().nullable().optional(),
184
+ lng: z.number().nullable().optional(),
185
+ country_code: z.string().optional(),
186
+ target_date: z.string().nullable().optional(),
187
+ },
188
+ annotations: TOOL_ANNOTATIONS_WRITE,
189
+ },
190
+ async ({ itemId, name, notes, lat, lng, country_code, target_date }) => {
191
+ if (isDemoUser(userId)) return demoDenied();
192
+ const item = updateBucketItem(userId, itemId, { name, notes, lat, lng, country_code, target_date });
193
+ if (!item) return { content: [{ type: 'text' as const, text: 'Bucket list item not found.' }], isError: true };
194
+ return ok({ item });
195
+ }
196
+ );
197
+ }
server/src/mcp/tools/budget.ts ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
2
+ import { z } from 'zod';
3
+ import { canAccessTrip, db } from '../../db/database';
4
+ import { isDemoUser } from '../../services/authService';
5
+ import {
6
+ createBudgetItem, updateBudgetItem, deleteBudgetItem,
7
+ updateMembers as updateBudgetMembers,
8
+ toggleMemberPaid,
9
+ } from '../../services/budgetService';
10
+ import {
11
+ safeBroadcast, TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE,
12
+ TOOL_ANNOTATIONS_NON_IDEMPOTENT,
13
+ demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
14
+ } from './_shared';
15
+ import { canWrite } from '../scopes';
16
+ import { isAddonEnabled } from '../../services/adminService';
17
+ import { ADDON_IDS } from '../../addons';
18
+
19
+ export function registerBudgetTools(server: McpServer, userId: number, scopes: string[] | null): void {
20
+ const W = canWrite(scopes, 'budget');
21
+
22
+ if (isAddonEnabled(ADDON_IDS.BUDGET)) {
23
+ // --- BUDGET ---
24
+
25
+ if (W) server.registerTool(
26
+ 'create_budget_item',
27
+ {
28
+ description: 'Add a budget/expense item to a trip.',
29
+ inputSchema: {
30
+ tripId: z.number().int().positive(),
31
+ name: z.string().min(1).max(200),
32
+ category: z.string().max(100).optional().describe('Budget category (e.g. Accommodation, Food, Transport)'),
33
+ total_price: z.number().nonnegative(),
34
+ note: z.string().max(500).optional(),
35
+ },
36
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
37
+ },
38
+ async ({ tripId, name, category, total_price, note }) => {
39
+ if (isDemoUser(userId)) return demoDenied();
40
+ if (!canAccessTrip(tripId, userId)) return noAccess();
41
+ if (!hasTripPermission('budget_edit', tripId, userId)) return permissionDenied();
42
+ const item = createBudgetItem(tripId, { category, name, total_price, note });
43
+ safeBroadcast(tripId, 'budget:created', { item });
44
+ return ok({ item });
45
+ }
46
+ );
47
+
48
+ if (W) server.registerTool(
49
+ 'delete_budget_item',
50
+ {
51
+ description: 'Delete a budget item from a trip.',
52
+ inputSchema: {
53
+ tripId: z.number().int().positive(),
54
+ itemId: z.number().int().positive(),
55
+ },
56
+ annotations: TOOL_ANNOTATIONS_DELETE,
57
+ },
58
+ async ({ tripId, itemId }) => {
59
+ if (isDemoUser(userId)) return demoDenied();
60
+ if (!canAccessTrip(tripId, userId)) return noAccess();
61
+ if (!hasTripPermission('budget_edit', tripId, userId)) return permissionDenied();
62
+ const deleted = deleteBudgetItem(itemId, tripId);
63
+ if (!deleted) return { content: [{ type: 'text' as const, text: 'Budget item not found.' }], isError: true };
64
+ safeBroadcast(tripId, 'budget:deleted', { itemId });
65
+ return ok({ success: true });
66
+ }
67
+ );
68
+
69
+ // --- BUDGET (update) ---
70
+
71
+ if (W) server.registerTool(
72
+ 'update_budget_item',
73
+ {
74
+ description: 'Update an existing budget/expense item in a trip.',
75
+ inputSchema: {
76
+ tripId: z.number().int().positive(),
77
+ itemId: z.number().int().positive(),
78
+ name: z.string().min(1).max(200).optional(),
79
+ category: z.string().max(100).optional(),
80
+ total_price: z.number().nonnegative().optional(),
81
+ persons: z.number().int().positive().nullable().optional(),
82
+ days: z.number().int().positive().nullable().optional(),
83
+ note: z.string().max(500).nullable().optional(),
84
+ },
85
+ annotations: TOOL_ANNOTATIONS_WRITE,
86
+ },
87
+ async ({ tripId, itemId, name, category, total_price, persons, days, note }) => {
88
+ if (isDemoUser(userId)) return demoDenied();
89
+ if (!canAccessTrip(tripId, userId)) return noAccess();
90
+ if (!hasTripPermission('budget_edit', tripId, userId)) return permissionDenied();
91
+ const item = updateBudgetItem(itemId, tripId, { name, category, total_price, persons, days, note });
92
+ if (!item) return { content: [{ type: 'text' as const, text: 'Budget item not found.' }], isError: true };
93
+ safeBroadcast(tripId, 'budget:updated', { item });
94
+ return ok({ item });
95
+ }
96
+ );
97
+
98
+ // --- BUDGET ADVANCED ---
99
+
100
+ if (W) server.registerTool(
101
+ 'create_budget_item_with_members',
102
+ {
103
+ description: 'Create a budget/expense item and optionally set the trip members splitting it in one atomic operation. If userIds is omitted or empty, behaves like create_budget_item. Only use when the place does not yet exist — if it already exists, use set_budget_item_members directly.',
104
+ inputSchema: {
105
+ tripId: z.number().int().positive(),
106
+ name: z.string().min(1).max(200),
107
+ category: z.string().max(100).optional().describe('Budget category (e.g. Accommodation, Food, Transport)'),
108
+ total_price: z.number().nonnegative(),
109
+ note: z.string().max(500).optional(),
110
+ userIds: z.array(z.number().int().positive()).optional().describe('User IDs splitting this item; omit or pass empty array to skip member assignment'),
111
+ },
112
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
113
+ },
114
+ async ({ tripId, name, category, total_price, note, userIds }) => {
115
+ if (isDemoUser(userId)) return demoDenied();
116
+ if (!canAccessTrip(tripId, userId)) return noAccess();
117
+ if (!hasTripPermission('budget_edit', tripId, userId)) return permissionDenied();
118
+ const hasMembers = userIds && userIds.length > 0;
119
+ try {
120
+ const run = db.transaction(() => {
121
+ const item = createBudgetItem(tripId, { category, name, total_price, note });
122
+ if (hasMembers) {
123
+ return updateBudgetMembers(item.id, tripId, userIds!);
124
+ }
125
+ return { item };
126
+ });
127
+ const result = run();
128
+ safeBroadcast(tripId, 'budget:created', { item: (result as any).item ?? result });
129
+ if (hasMembers) safeBroadcast(tripId, 'budget:members-updated', { item: result });
130
+ return ok({ item: result });
131
+ } catch {
132
+ return { content: [{ type: 'text' as const, text: 'Failed to create budget item.' }], isError: true };
133
+ }
134
+ }
135
+ );
136
+
137
+ if (W) server.registerTool(
138
+ 'set_budget_item_members',
139
+ {
140
+ description: 'Set which trip members are splitting a budget item (replaces current member list).',
141
+ inputSchema: {
142
+ tripId: z.number().int().positive(),
143
+ itemId: z.number().int().positive(),
144
+ userIds: z.array(z.number().int().positive()).describe('User IDs splitting this item; empty array clears all'),
145
+ },
146
+ annotations: TOOL_ANNOTATIONS_WRITE,
147
+ },
148
+ async ({ tripId, itemId, userIds }) => {
149
+ if (isDemoUser(userId)) return demoDenied();
150
+ if (!canAccessTrip(tripId, userId)) return noAccess();
151
+ if (!hasTripPermission('budget_edit', tripId, userId)) return permissionDenied();
152
+ const item = updateBudgetMembers(itemId, tripId, userIds);
153
+ safeBroadcast(tripId, 'budget:members-updated', { item });
154
+ return ok({ item });
155
+ }
156
+ );
157
+
158
+ if (W) server.registerTool(
159
+ 'toggle_budget_member_paid',
160
+ {
161
+ description: 'Mark or unmark a member as having paid their share of a budget item.',
162
+ inputSchema: {
163
+ tripId: z.number().int().positive(),
164
+ itemId: z.number().int().positive(),
165
+ memberId: z.number().int().positive().describe('User ID of the member'),
166
+ paid: z.boolean(),
167
+ },
168
+ annotations: TOOL_ANNOTATIONS_WRITE,
169
+ },
170
+ async ({ tripId, itemId, memberId, paid }) => {
171
+ if (isDemoUser(userId)) return demoDenied();
172
+ if (!canAccessTrip(tripId, userId)) return noAccess();
173
+ if (!hasTripPermission('budget_edit', tripId, userId)) return permissionDenied();
174
+ const member = toggleMemberPaid(itemId, tripId, memberId, paid);
175
+ safeBroadcast(tripId, 'budget:member-paid-updated', { itemId, member });
176
+ return ok({ member });
177
+ }
178
+ );
179
+ } // isAddonEnabled(BUDGET)
180
+ }
server/src/mcp/tools/collab.ts ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
2
+ import { z } from 'zod';
3
+ import { canAccessTrip } from '../../db/database';
4
+ import { isDemoUser } from '../../services/authService';
5
+ import {
6
+ createNote as createCollabNote, updateNote as updateCollabNote, deleteNote as deleteCollabNote,
7
+ listPolls, createPoll, votePoll, closePoll, deletePoll,
8
+ listMessages, createMessage, deleteMessage, addOrRemoveReaction,
9
+ } from '../../services/collabService';
10
+ import { isAddonEnabled, getCollabFeatures } from '../../services/adminService';
11
+ import { ADDON_IDS } from '../../addons';
12
+ import {
13
+ safeBroadcast, TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE,
14
+ TOOL_ANNOTATIONS_NON_IDEMPOTENT, TOOL_ANNOTATIONS_READONLY,
15
+ demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
16
+ } from './_shared';
17
+ import { canRead, canWrite } from '../scopes';
18
+
19
+ export function registerCollabTools(server: McpServer, userId: number, scopes: string[] | null): void {
20
+ const R = canRead(scopes, 'collab');
21
+ const W = canWrite(scopes, 'collab');
22
+
23
+ if (!isAddonEnabled(ADDON_IDS.COLLAB)) return;
24
+
25
+ const features = getCollabFeatures();
26
+
27
+ // --- COLLAB NOTES ---
28
+
29
+ if (features.notes && W) server.registerTool(
30
+ 'create_collab_note',
31
+ {
32
+ description: 'Create a shared collaborative note on a trip (visible to all trip members in the Collab tab).',
33
+ inputSchema: {
34
+ tripId: z.number().int().positive(),
35
+ title: z.string().min(1).max(200),
36
+ content: z.string().max(10000).optional(),
37
+ category: z.string().max(100).optional().describe('Note category (e.g. "Ideas", "To-do", "General")'),
38
+ color: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional().describe('Hex color for the note card'),
39
+ pinned: z.boolean().optional().default(false).describe('Pin the note to the top'),
40
+ },
41
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
42
+ },
43
+ async ({ tripId, title, content, category, color, pinned }) => {
44
+ if (isDemoUser(userId)) return demoDenied();
45
+ if (!canAccessTrip(tripId, userId)) return noAccess();
46
+ if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
47
+ const note = createCollabNote(tripId, userId, { title, content, category, color, pinned });
48
+ safeBroadcast(tripId, 'collab:note:created', { note });
49
+ return ok({ note });
50
+ }
51
+ );
52
+
53
+ if (features.notes && W) server.registerTool(
54
+ 'update_collab_note',
55
+ {
56
+ description: 'Edit an existing collaborative note on a trip.',
57
+ inputSchema: {
58
+ tripId: z.number().int().positive(),
59
+ noteId: z.number().int().positive(),
60
+ title: z.string().min(1).max(200).optional(),
61
+ content: z.string().max(10000).optional(),
62
+ category: z.string().max(100).optional(),
63
+ color: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional().describe('Hex color for the note card'),
64
+ pinned: z.boolean().optional().describe('Pin the note to the top'),
65
+ },
66
+ annotations: TOOL_ANNOTATIONS_WRITE,
67
+ },
68
+ async ({ tripId, noteId, title, content, category, color, pinned }) => {
69
+ if (isDemoUser(userId)) return demoDenied();
70
+ if (!canAccessTrip(tripId, userId)) return noAccess();
71
+ if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
72
+ const note = updateCollabNote(tripId, noteId, { title, content, category, color, pinned });
73
+ if (!note) return { content: [{ type: 'text' as const, text: 'Note not found.' }], isError: true };
74
+ safeBroadcast(tripId, 'collab:note:updated', { note });
75
+ return ok({ note });
76
+ }
77
+ );
78
+
79
+ if (features.notes && W) server.registerTool(
80
+ 'delete_collab_note',
81
+ {
82
+ description: 'Delete a collaborative note from a trip.',
83
+ inputSchema: {
84
+ tripId: z.number().int().positive(),
85
+ noteId: z.number().int().positive(),
86
+ },
87
+ annotations: TOOL_ANNOTATIONS_DELETE,
88
+ },
89
+ async ({ tripId, noteId }) => {
90
+ if (isDemoUser(userId)) return demoDenied();
91
+ if (!canAccessTrip(tripId, userId)) return noAccess();
92
+ if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
93
+ const deleted = deleteCollabNote(tripId, noteId);
94
+ if (!deleted) return { content: [{ type: 'text' as const, text: 'Note not found.' }], isError: true };
95
+ safeBroadcast(tripId, 'collab:note:deleted', { noteId });
96
+ return ok({ success: true });
97
+ }
98
+ );
99
+
100
+ // --- COLLAB POLLS & CHAT ---
101
+
102
+ if (features.polls && R) server.registerTool(
103
+ 'list_collab_polls',
104
+ {
105
+ description: 'List all polls for a trip.',
106
+ inputSchema: {
107
+ tripId: z.number().int().positive(),
108
+ },
109
+ annotations: TOOL_ANNOTATIONS_READONLY,
110
+ },
111
+ async ({ tripId }) => {
112
+ if (!canAccessTrip(tripId, userId)) return noAccess();
113
+ const polls = listPolls(tripId);
114
+ return ok({ polls });
115
+ }
116
+ );
117
+
118
+ if (features.polls && W) server.registerTool(
119
+ 'create_collab_poll',
120
+ {
121
+ description: 'Create a new poll in the collab panel.',
122
+ inputSchema: {
123
+ tripId: z.number().int().positive(),
124
+ question: z.string().min(1),
125
+ options: z.array(z.string()).min(2).describe('Poll answer options (at least 2)'),
126
+ multiple: z.boolean().optional().describe('Allow multiple choice'),
127
+ deadline: z.string().optional().describe('ISO date string for poll deadline'),
128
+ },
129
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
130
+ },
131
+ async ({ tripId, question, options, multiple, deadline }) => {
132
+ if (isDemoUser(userId)) return demoDenied();
133
+ if (!canAccessTrip(tripId, userId)) return noAccess();
134
+ if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
135
+ const poll = createPoll(tripId, userId, { question, options, multiple, deadline });
136
+ safeBroadcast(tripId, 'collab:poll:created', { poll });
137
+ return ok({ poll });
138
+ }
139
+ );
140
+
141
+ if (features.polls && W) server.registerTool(
142
+ 'vote_collab_poll',
143
+ {
144
+ description: 'Vote on a poll option (or remove vote if already voted for that option).',
145
+ inputSchema: {
146
+ tripId: z.number().int().positive(),
147
+ pollId: z.number().int().positive(),
148
+ optionIndex: z.number().int().min(0).describe('Zero-based index of the option to vote for'),
149
+ },
150
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
151
+ },
152
+ async ({ tripId, pollId, optionIndex }) => {
153
+ if (!canAccessTrip(tripId, userId)) return noAccess();
154
+ if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
155
+ const result = votePoll(tripId, pollId, userId, optionIndex);
156
+ if (result.error) return { content: [{ type: 'text' as const, text: result.error }], isError: true };
157
+ safeBroadcast(tripId, 'collab:poll:voted', { poll: result.poll });
158
+ return ok({ poll: result.poll });
159
+ }
160
+ );
161
+
162
+ if (features.polls && W) server.registerTool(
163
+ 'close_collab_poll',
164
+ {
165
+ description: 'Close a poll so no more votes can be cast.',
166
+ inputSchema: {
167
+ tripId: z.number().int().positive(),
168
+ pollId: z.number().int().positive(),
169
+ },
170
+ annotations: TOOL_ANNOTATIONS_WRITE,
171
+ },
172
+ async ({ tripId, pollId }) => {
173
+ if (isDemoUser(userId)) return demoDenied();
174
+ if (!canAccessTrip(tripId, userId)) return noAccess();
175
+ if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
176
+ const poll = closePoll(tripId, pollId);
177
+ if (!poll) return { content: [{ type: 'text' as const, text: 'Poll not found.' }], isError: true };
178
+ safeBroadcast(tripId, 'collab:poll:closed', { poll });
179
+ return ok({ poll });
180
+ }
181
+ );
182
+
183
+ if (features.polls && W) server.registerTool(
184
+ 'delete_collab_poll',
185
+ {
186
+ description: 'Delete a poll and all its votes.',
187
+ inputSchema: {
188
+ tripId: z.number().int().positive(),
189
+ pollId: z.number().int().positive(),
190
+ },
191
+ annotations: TOOL_ANNOTATIONS_DELETE,
192
+ },
193
+ async ({ tripId, pollId }) => {
194
+ if (isDemoUser(userId)) return demoDenied();
195
+ if (!canAccessTrip(tripId, userId)) return noAccess();
196
+ if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
197
+ const deleted = deletePoll(tripId, pollId);
198
+ if (!deleted) return { content: [{ type: 'text' as const, text: 'Poll not found.' }], isError: true };
199
+ safeBroadcast(tripId, 'collab:poll:deleted', { pollId });
200
+ return ok({ success: true });
201
+ }
202
+ );
203
+
204
+ if (features.chat && R) server.registerTool(
205
+ 'list_collab_messages',
206
+ {
207
+ description: 'List chat messages for a trip (most recent 100, oldest-first).',
208
+ inputSchema: {
209
+ tripId: z.number().int().positive(),
210
+ before: z.number().int().positive().optional().describe('Load messages with ID less than this (pagination)'),
211
+ },
212
+ annotations: TOOL_ANNOTATIONS_READONLY,
213
+ },
214
+ async ({ tripId, before }) => {
215
+ if (!canAccessTrip(tripId, userId)) return noAccess();
216
+ const messages = listMessages(tripId, before);
217
+ return ok({ messages });
218
+ }
219
+ );
220
+
221
+ if (features.chat && W) server.registerTool(
222
+ 'send_collab_message',
223
+ {
224
+ description: "Send a chat message to a trip's collab channel.",
225
+ inputSchema: {
226
+ tripId: z.number().int().positive(),
227
+ text: z.string().min(1),
228
+ replyTo: z.number().int().positive().optional().describe('Reply to a specific message ID'),
229
+ },
230
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
231
+ },
232
+ async ({ tripId, text, replyTo }) => {
233
+ if (isDemoUser(userId)) return demoDenied();
234
+ if (!canAccessTrip(tripId, userId)) return noAccess();
235
+ if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
236
+ const result = createMessage(tripId, userId, text, replyTo ?? null);
237
+ if (result.error) return { content: [{ type: 'text' as const, text: result.error }], isError: true };
238
+ safeBroadcast(tripId, 'collab:message:created', { message: result.message });
239
+ return ok({ message: result.message });
240
+ }
241
+ );
242
+
243
+ if (features.chat && W) server.registerTool(
244
+ 'delete_collab_message',
245
+ {
246
+ description: 'Delete a chat message (only the message owner can delete their own messages).',
247
+ inputSchema: {
248
+ tripId: z.number().int().positive(),
249
+ messageId: z.number().int().positive(),
250
+ },
251
+ annotations: TOOL_ANNOTATIONS_DELETE,
252
+ },
253
+ async ({ tripId, messageId }) => {
254
+ if (isDemoUser(userId)) return demoDenied();
255
+ if (!canAccessTrip(tripId, userId)) return noAccess();
256
+ if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
257
+ const result = deleteMessage(tripId, messageId, userId);
258
+ if (result.error) return { content: [{ type: 'text' as const, text: result.error }], isError: true };
259
+ safeBroadcast(tripId, 'collab:message:deleted', { messageId, username: result.username });
260
+ return ok({ success: true });
261
+ }
262
+ );
263
+
264
+ if (features.chat && W) server.registerTool(
265
+ 'react_collab_message',
266
+ {
267
+ description: 'Toggle a reaction emoji on a chat message (adds if not present, removes if already reacted).',
268
+ inputSchema: {
269
+ tripId: z.number().int().positive(),
270
+ messageId: z.number().int().positive(),
271
+ emoji: z.string().describe('Single emoji character'),
272
+ },
273
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
274
+ },
275
+ async ({ tripId, messageId, emoji }) => {
276
+ if (isDemoUser(userId)) return demoDenied();
277
+ if (!canAccessTrip(tripId, userId)) return noAccess();
278
+ if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
279
+ const result = addOrRemoveReaction(messageId, tripId, userId, emoji);
280
+ if (!result.found) return { content: [{ type: 'text' as const, text: 'Message not found.' }], isError: true };
281
+ safeBroadcast(tripId, 'collab:message:reacted', { messageId, reactions: result.reactions });
282
+ return ok({ reactions: result.reactions });
283
+ }
284
+ );
285
+ }
server/src/mcp/tools/days.ts ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
2
+ import { z } from 'zod';
3
+ import { canAccessTrip, db } from '../../db/database';
4
+ import { isDemoUser } from '../../services/authService';
5
+ import {
6
+ getDay, updateDay, validateAccommodationRefs,
7
+ createDay, deleteDay,
8
+ createAccommodation, getAccommodation, updateAccommodation, deleteAccommodation,
9
+ } from '../../services/dayService';
10
+ import { createPlace } from '../../services/placeService';
11
+ import {
12
+ createNote as createDayNote, getNote as getDayNote, updateNote as updateDayNote,
13
+ deleteNote as deleteDayNote, dayExists as dayNoteExists,
14
+ } from '../../services/dayNoteService';
15
+ import {
16
+ safeBroadcast, TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE,
17
+ TOOL_ANNOTATIONS_NON_IDEMPOTENT,
18
+ demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
19
+ } from './_shared';
20
+ import { canWrite } from '../scopes';
21
+
22
+ export function registerDayTools(server: McpServer, userId: number, scopes: string[] | null): void {
23
+ if (!canWrite(scopes, 'trips')) return;
24
+
25
+ // --- DAYS ---
26
+
27
+ server.registerTool(
28
+ 'update_day',
29
+ {
30
+ description: 'Set the title of a day in a trip (e.g. "Arrival in Paris", "Free day").',
31
+ inputSchema: {
32
+ tripId: z.number().int().positive(),
33
+ dayId: z.number().int().positive(),
34
+ title: z.string().max(200).nullable().describe('Day title, or null to clear it'),
35
+ },
36
+ annotations: TOOL_ANNOTATIONS_WRITE,
37
+ },
38
+ async ({ tripId, dayId, title }) => {
39
+ if (isDemoUser(userId)) return demoDenied();
40
+ if (!canAccessTrip(tripId, userId)) return noAccess();
41
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
42
+ const current = getDay(dayId, tripId);
43
+ if (!current) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true };
44
+ const updated = updateDay(dayId, current, title !== undefined ? { title } : {});
45
+ safeBroadcast(tripId, 'day:updated', { day: updated });
46
+ return ok({ day: updated });
47
+ }
48
+ );
49
+
50
+ server.registerTool(
51
+ 'create_day',
52
+ {
53
+ description: 'Add a new day to a trip (optionally with a specific date and notes).',
54
+ inputSchema: {
55
+ tripId: z.number().int().positive(),
56
+ date: z.string().optional().describe('ISO date string YYYY-MM-DD, optional for dateless trips'),
57
+ notes: z.string().optional(),
58
+ },
59
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
60
+ },
61
+ async ({ tripId, date, notes }) => {
62
+ if (isDemoUser(userId)) return demoDenied();
63
+ if (!canAccessTrip(tripId, userId)) return noAccess();
64
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
65
+ const day = createDay(tripId, date, notes);
66
+ safeBroadcast(tripId, 'day:created', { day });
67
+ return ok({ day });
68
+ }
69
+ );
70
+
71
+ server.registerTool(
72
+ 'delete_day',
73
+ {
74
+ description: 'Delete a day from a trip.',
75
+ inputSchema: {
76
+ tripId: z.number().int().positive(),
77
+ dayId: z.number().int().positive(),
78
+ },
79
+ annotations: TOOL_ANNOTATIONS_DELETE,
80
+ },
81
+ async ({ tripId, dayId }) => {
82
+ if (isDemoUser(userId)) return demoDenied();
83
+ if (!canAccessTrip(tripId, userId)) return noAccess();
84
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
85
+ if (!getDay(dayId, tripId)) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true };
86
+ deleteDay(dayId);
87
+ safeBroadcast(tripId, 'day:deleted', { id: dayId });
88
+ return ok({ success: true });
89
+ }
90
+ );
91
+
92
+ server.registerTool(
93
+ 'create_accommodation',
94
+ {
95
+ description: 'Add an accommodation (hotel, Airbnb, etc.) to a trip, linked to a place and a date range.',
96
+ inputSchema: {
97
+ tripId: z.number().int().positive(),
98
+ place_id: z.number().int().positive().describe('The place to use as the accommodation'),
99
+ start_day_id: z.number().int().positive().describe('Check-in day ID'),
100
+ end_day_id: z.number().int().positive().describe('Check-out day ID'),
101
+ check_in: z.string().max(10).optional().describe('Check-in time e.g. "15:00"'),
102
+ check_out: z.string().max(10).optional().describe('Check-out time e.g. "11:00"'),
103
+ confirmation: z.string().max(100).optional(),
104
+ notes: z.string().max(1000).optional(),
105
+ },
106
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
107
+ },
108
+ async ({ tripId, place_id, start_day_id, end_day_id, check_in, check_out, confirmation, notes }) => {
109
+ if (isDemoUser(userId)) return demoDenied();
110
+ if (!canAccessTrip(tripId, userId)) return noAccess();
111
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
112
+ const errors = validateAccommodationRefs(tripId, place_id, start_day_id, end_day_id);
113
+ if (errors.length > 0) return { content: [{ type: 'text' as const, text: errors.map(e => e.message).join(', ') }], isError: true };
114
+ const accommodation = createAccommodation(tripId, { place_id, start_day_id, end_day_id, check_in, check_out, confirmation, notes });
115
+ safeBroadcast(tripId, 'accommodation:created', { accommodation });
116
+ return ok({ accommodation });
117
+ }
118
+ );
119
+
120
+ server.registerTool(
121
+ 'create_place_accommodation',
122
+ {
123
+ 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.',
124
+ inputSchema: {
125
+ tripId: z.number().int().positive(),
126
+ name: z.string().min(1).max(200),
127
+ description: z.string().max(2000).optional(),
128
+ lat: z.number().optional(),
129
+ lng: z.number().optional(),
130
+ address: z.string().max(500).optional(),
131
+ category_id: z.number().int().positive().optional().describe('Category ID — use list_categories to see available options'),
132
+ google_place_id: z.string().optional().describe('Google Place ID from search_place — enables opening hours display'),
133
+ osm_id: z.string().optional().describe('OpenStreetMap ID from search_place (e.g. "way:12345")'),
134
+ place_notes: z.string().max(2000).optional().describe('Notes for the place'),
135
+ website: z.string().max(500).optional(),
136
+ phone: z.string().max(50).optional(),
137
+ start_day_id: z.number().int().positive().describe('Check-in day ID'),
138
+ end_day_id: z.number().int().positive().describe('Check-out day ID'),
139
+ check_in: z.string().max(10).optional().describe('Check-in time e.g. "15:00"'),
140
+ check_out: z.string().max(10).optional().describe('Check-out time e.g. "11:00"'),
141
+ confirmation: z.string().max(100).optional(),
142
+ accommodation_notes: z.string().max(1000).optional().describe('Notes for the accommodation'),
143
+ price: z.number().nonnegative().optional().describe('Total accommodation cost (shown on the item)'),
144
+ currency: z.string().length(3).optional().describe('ISO 4217 currency code (e.g. "EUR", "USD")'),
145
+ },
146
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
147
+ },
148
+ async ({ tripId, name, description, lat, lng, address, category_id, google_place_id, osm_id, place_notes, website, phone, start_day_id, end_day_id, check_in, check_out, confirmation, accommodation_notes, price, currency }) => {
149
+ if (isDemoUser(userId)) return demoDenied();
150
+ if (!canAccessTrip(tripId, userId)) return noAccess();
151
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
152
+ const dayErrors = validateAccommodationRefs(tripId, undefined, start_day_id, end_day_id);
153
+ if (dayErrors.length > 0) return { content: [{ type: 'text' as const, text: dayErrors.map(e => e.message).join(', ') }], isError: true };
154
+ try {
155
+ const run = db.transaction(() => {
156
+ const place = createPlace(String(tripId), { name, description, lat, lng, address, category_id, google_place_id, osm_id, notes: place_notes, website, phone, price, currency });
157
+ const accommodation = createAccommodation(tripId, { place_id: place.id, start_day_id, end_day_id, check_in, check_out, confirmation, notes: accommodation_notes });
158
+ return { place, accommodation };
159
+ });
160
+ const result = run();
161
+ safeBroadcast(tripId, 'place:created', { place: result.place });
162
+ safeBroadcast(tripId, 'accommodation:created', { accommodation: result.accommodation });
163
+ return ok(result);
164
+ } catch {
165
+ return { content: [{ type: 'text' as const, text: 'Failed to create place and accommodation.' }], isError: true };
166
+ }
167
+ }
168
+ );
169
+
170
+ server.registerTool(
171
+ 'update_accommodation',
172
+ {
173
+ description: 'Update fields on an existing accommodation.',
174
+ inputSchema: {
175
+ tripId: z.number().int().positive(),
176
+ accommodationId: z.number().int().positive(),
177
+ place_id: z.number().int().positive().optional(),
178
+ start_day_id: z.number().int().positive().optional(),
179
+ end_day_id: z.number().int().positive().optional(),
180
+ check_in: z.string().max(10).optional(),
181
+ check_out: z.string().max(10).optional(),
182
+ confirmation: z.string().max(100).optional(),
183
+ notes: z.string().max(1000).optional(),
184
+ },
185
+ annotations: TOOL_ANNOTATIONS_WRITE,
186
+ },
187
+ async ({ tripId, accommodationId, place_id, start_day_id, end_day_id, check_in, check_out, confirmation, notes }) => {
188
+ if (isDemoUser(userId)) return demoDenied();
189
+ if (!canAccessTrip(tripId, userId)) return noAccess();
190
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
191
+ const existing = getAccommodation(accommodationId, tripId);
192
+ if (!existing) return { content: [{ type: 'text' as const, text: 'Accommodation not found.' }], isError: true };
193
+ const accommodation = updateAccommodation(accommodationId, existing, { place_id, start_day_id, end_day_id, check_in, check_out, confirmation, notes });
194
+ safeBroadcast(tripId, 'accommodation:updated', { accommodation });
195
+ return ok({ accommodation });
196
+ }
197
+ );
198
+
199
+ server.registerTool(
200
+ 'delete_accommodation',
201
+ {
202
+ description: 'Delete an accommodation from a trip.',
203
+ inputSchema: {
204
+ tripId: z.number().int().positive(),
205
+ accommodationId: z.number().int().positive(),
206
+ },
207
+ annotations: TOOL_ANNOTATIONS_DELETE,
208
+ },
209
+ async ({ tripId, accommodationId }) => {
210
+ if (isDemoUser(userId)) return demoDenied();
211
+ if (!canAccessTrip(tripId, userId)) return noAccess();
212
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
213
+ if (!getAccommodation(accommodationId, tripId)) return { content: [{ type: 'text' as const, text: 'Accommodation not found.' }], isError: true };
214
+ const { linkedReservationId } = deleteAccommodation(accommodationId);
215
+ safeBroadcast(tripId, 'accommodation:deleted', { id: accommodationId, linkedReservationId });
216
+ return ok({ success: true, linkedReservationId });
217
+ }
218
+ );
219
+
220
+ // --- DAY NOTES ---
221
+
222
+ server.registerTool(
223
+ 'create_day_note',
224
+ {
225
+ description: 'Add a note to a specific day in a trip.',
226
+ inputSchema: {
227
+ tripId: z.number().int().positive(),
228
+ dayId: z.number().int().positive(),
229
+ text: z.string().min(1).max(500),
230
+ time: z.string().max(150).optional().describe('Time label (e.g. "09:00" or "Morning")'),
231
+ icon: z.string().optional().describe('Emoji icon for the note'),
232
+ },
233
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
234
+ },
235
+ async ({ tripId, dayId, text, time, icon }) => {
236
+ if (isDemoUser(userId)) return demoDenied();
237
+ if (!canAccessTrip(tripId, userId)) return noAccess();
238
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
239
+ if (!dayNoteExists(dayId, tripId)) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true };
240
+ const note = createDayNote(dayId, tripId, text, time, icon);
241
+ safeBroadcast(tripId, 'dayNote:created', { dayId, note });
242
+ return ok({ note });
243
+ }
244
+ );
245
+
246
+ server.registerTool(
247
+ 'update_day_note',
248
+ {
249
+ description: 'Edit an existing note on a specific day.',
250
+ inputSchema: {
251
+ tripId: z.number().int().positive(),
252
+ dayId: z.number().int().positive(),
253
+ noteId: z.number().int().positive(),
254
+ text: z.string().min(1).max(500).optional(),
255
+ time: z.string().max(150).nullable().optional().describe('Time label (e.g. "09:00" or "Morning"), or null to clear'),
256
+ icon: z.string().optional().describe('Emoji icon for the note'),
257
+ },
258
+ annotations: TOOL_ANNOTATIONS_WRITE,
259
+ },
260
+ async ({ tripId, dayId, noteId, text, time, icon }) => {
261
+ if (isDemoUser(userId)) return demoDenied();
262
+ if (!canAccessTrip(tripId, userId)) return noAccess();
263
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
264
+ const existing = getDayNote(noteId, dayId, tripId);
265
+ if (!existing) return { content: [{ type: 'text' as const, text: 'Note not found.' }], isError: true };
266
+ const note = updateDayNote(noteId, existing, { text, time: time !== undefined ? time : undefined, icon });
267
+ safeBroadcast(tripId, 'dayNote:updated', { dayId, note });
268
+ return ok({ note });
269
+ }
270
+ );
271
+
272
+ server.registerTool(
273
+ 'delete_day_note',
274
+ {
275
+ description: 'Delete a note from a specific day.',
276
+ inputSchema: {
277
+ tripId: z.number().int().positive(),
278
+ dayId: z.number().int().positive(),
279
+ noteId: z.number().int().positive(),
280
+ },
281
+ annotations: TOOL_ANNOTATIONS_DELETE,
282
+ },
283
+ async ({ tripId, dayId, noteId }) => {
284
+ if (isDemoUser(userId)) return demoDenied();
285
+ if (!canAccessTrip(tripId, userId)) return noAccess();
286
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
287
+ const note = getDayNote(noteId, dayId, tripId);
288
+ if (!note) return { content: [{ type: 'text' as const, text: 'Note not found.' }], isError: true };
289
+ deleteDayNote(noteId);
290
+ safeBroadcast(tripId, 'dayNote:deleted', { noteId, dayId });
291
+ return ok({ success: true });
292
+ }
293
+ );
294
+ }
server/src/mcp/tools/journey.ts ADDED
@@ -0,0 +1,422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
2
+ import { z } from 'zod';
3
+ import { isDemoUser } from '../../services/authService';
4
+ import {
5
+ addContributor, addTripToJourney, canAccessJourney, createEntry, createJourney,
6
+ deleteEntry, deleteJourney, getJourneyFull, getSuggestions, listEntries,
7
+ listJourneys, listUserTrips, removeContributor, removeTripFromJourney,
8
+ reorderEntries, updateContributorRole, updateEntry, updateJourney,
9
+ updateJourneyPreferences,
10
+ } from '../../services/journeyService';
11
+ import {
12
+ createOrUpdateJourneyShareLink, deleteJourneyShareLink, getJourneyShareLink,
13
+ } from '../../services/journeyShareService';
14
+ import { isAddonEnabled } from '../../services/adminService';
15
+ import { ADDON_IDS } from '../../addons';
16
+ import {
17
+ TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
18
+ TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
19
+ demoDenied, ok,
20
+ } from './_shared';
21
+ import { canRead, canShareJourneys, canWrite } from '../scopes';
22
+
23
+ function notFound(msg: string) {
24
+ return { content: [{ type: 'text' as const, text: msg }], isError: true };
25
+ }
26
+
27
+ export function registerJourneyTools(server: McpServer, userId: number, scopes: string[] | null): void {
28
+ if (!isAddonEnabled(ADDON_IDS.JOURNEY)) return;
29
+
30
+ const R = canRead(scopes, 'journey');
31
+ const W = canWrite(scopes, 'journey');
32
+ const S = canShareJourneys(scopes);
33
+
34
+ // --- READ TOOLS ---
35
+
36
+ if (R) server.registerTool(
37
+ 'list_journeys',
38
+ {
39
+ description: 'List all journeys owned or contributed to by the current user.',
40
+ inputSchema: {},
41
+ annotations: TOOL_ANNOTATIONS_READONLY,
42
+ },
43
+ async () => {
44
+ const journeys = listJourneys(userId);
45
+ return ok({ journeys });
46
+ }
47
+ );
48
+
49
+ if (R) server.registerTool(
50
+ 'get_journey',
51
+ {
52
+ description: 'Get a full journey including entries, contributors, and linked trips.',
53
+ inputSchema: {
54
+ journeyId: z.number().int().positive(),
55
+ },
56
+ annotations: TOOL_ANNOTATIONS_READONLY,
57
+ },
58
+ async ({ journeyId }) => {
59
+ const journey = getJourneyFull(journeyId, userId);
60
+ if (!journey) return notFound('Journey not found or access denied.');
61
+ return ok({ journey });
62
+ }
63
+ );
64
+
65
+ if (R) server.registerTool(
66
+ 'list_journey_entries',
67
+ {
68
+ description: 'List all entries in a journey.',
69
+ inputSchema: {
70
+ journeyId: z.number().int().positive(),
71
+ },
72
+ annotations: TOOL_ANNOTATIONS_READONLY,
73
+ },
74
+ async ({ journeyId }) => {
75
+ if (!canAccessJourney(journeyId, userId)) return notFound('Journey not found or access denied.');
76
+ const entries = listEntries(journeyId, userId);
77
+ return ok({ entries });
78
+ }
79
+ );
80
+
81
+ if (R) server.registerTool(
82
+ 'list_journey_contributors',
83
+ {
84
+ description: 'List all contributors (owner and collaborators) of a journey.',
85
+ inputSchema: {
86
+ journeyId: z.number().int().positive(),
87
+ },
88
+ annotations: TOOL_ANNOTATIONS_READONLY,
89
+ },
90
+ async ({ journeyId }) => {
91
+ const journey = getJourneyFull(journeyId, userId);
92
+ if (!journey) return notFound('Journey not found or access denied.');
93
+ return ok({ contributors: (journey as any).contributors ?? [] });
94
+ }
95
+ );
96
+
97
+ if (R) server.registerTool(
98
+ 'get_journey_suggestions',
99
+ {
100
+ description: 'Get trip suggestions for creating a new journey (recently completed trips not yet in any journey).',
101
+ inputSchema: {},
102
+ annotations: TOOL_ANNOTATIONS_READONLY,
103
+ },
104
+ async () => {
105
+ const trips = getSuggestions(userId);
106
+ return ok({ trips });
107
+ }
108
+ );
109
+
110
+ if (R) server.registerTool(
111
+ 'list_journey_available_trips',
112
+ {
113
+ description: 'List all trips available to link to a journey.',
114
+ inputSchema: {},
115
+ annotations: TOOL_ANNOTATIONS_READONLY,
116
+ },
117
+ async () => {
118
+ const trips = listUserTrips(userId);
119
+ return ok({ trips });
120
+ }
121
+ );
122
+
123
+ // --- WRITE TOOLS ---
124
+
125
+ if (W) server.registerTool(
126
+ 'create_journey',
127
+ {
128
+ description: 'Create a new journey, optionally linking existing trips.',
129
+ inputSchema: {
130
+ title: z.string().min(1).max(200),
131
+ subtitle: z.string().max(300).optional(),
132
+ trip_ids: z.array(z.number().int().positive()).optional(),
133
+ },
134
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
135
+ },
136
+ async ({ title, subtitle, trip_ids }) => {
137
+ if (isDemoUser(userId)) return demoDenied();
138
+ const journey = createJourney(userId, { title, subtitle, trip_ids });
139
+ return ok({ journey });
140
+ }
141
+ );
142
+
143
+ if (W) server.registerTool(
144
+ 'update_journey',
145
+ {
146
+ description: 'Update an existing journey\'s title, subtitle, cover, or status. Owner only.',
147
+ inputSchema: {
148
+ journeyId: z.number().int().positive(),
149
+ title: z.string().min(1).max(200).optional(),
150
+ subtitle: z.string().max(300).optional(),
151
+ status: z.enum(['draft', 'active', 'completed', 'archived']).optional(),
152
+ },
153
+ annotations: TOOL_ANNOTATIONS_WRITE,
154
+ },
155
+ async ({ journeyId, title, subtitle, status }) => {
156
+ if (isDemoUser(userId)) return demoDenied();
157
+ const journey = updateJourney(journeyId, userId, { title, subtitle, status });
158
+ if (!journey) return notFound('Journey not found or access denied.');
159
+ return ok({ journey });
160
+ }
161
+ );
162
+
163
+ if (W) server.registerTool(
164
+ 'delete_journey',
165
+ {
166
+ description: 'Delete a journey. Owner only — this cannot be undone.',
167
+ inputSchema: {
168
+ journeyId: z.number().int().positive(),
169
+ },
170
+ annotations: TOOL_ANNOTATIONS_DELETE,
171
+ },
172
+ async ({ journeyId }) => {
173
+ if (isDemoUser(userId)) return demoDenied();
174
+ const success = deleteJourney(journeyId, userId);
175
+ if (!success) return notFound('Journey not found or access denied.');
176
+ return ok({ success: true });
177
+ }
178
+ );
179
+
180
+ if (W) server.registerTool(
181
+ 'add_journey_trip',
182
+ {
183
+ description: 'Link a trip to a journey. Syncs skeleton entries for all places in the trip.',
184
+ inputSchema: {
185
+ journeyId: z.number().int().positive(),
186
+ tripId: z.number().int().positive(),
187
+ },
188
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
189
+ },
190
+ async ({ journeyId, tripId }) => {
191
+ if (isDemoUser(userId)) return demoDenied();
192
+ if (!canAccessJourney(journeyId, userId)) return notFound('Journey not found or access denied.');
193
+ const success = addTripToJourney(journeyId, tripId, userId);
194
+ return ok({ success });
195
+ }
196
+ );
197
+
198
+ if (W) server.registerTool(
199
+ 'remove_journey_trip',
200
+ {
201
+ description: 'Unlink a trip from a journey. Owner only.',
202
+ inputSchema: {
203
+ journeyId: z.number().int().positive(),
204
+ tripId: z.number().int().positive(),
205
+ },
206
+ annotations: TOOL_ANNOTATIONS_DELETE,
207
+ },
208
+ async ({ journeyId, tripId }) => {
209
+ if (isDemoUser(userId)) return demoDenied();
210
+ const success = removeTripFromJourney(journeyId, tripId, userId);
211
+ if (!success) return notFound('Journey not found or access denied.');
212
+ return ok({ success });
213
+ }
214
+ );
215
+
216
+ if (W) server.registerTool(
217
+ 'create_journey_entry',
218
+ {
219
+ description: 'Create a new entry in a journey.',
220
+ inputSchema: {
221
+ journeyId: z.number().int().positive(),
222
+ entry_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).describe('Entry date (YYYY-MM-DD)'),
223
+ title: z.string().max(300).optional(),
224
+ story: z.string().optional(),
225
+ entry_time: z.string().optional().describe('Time of day (e.g. "14:30")'),
226
+ location_name: z.string().optional(),
227
+ mood: z.string().optional(),
228
+ sort_order: z.number().int().min(0).optional(),
229
+ },
230
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
231
+ },
232
+ async ({ journeyId, entry_date, title, story, entry_time, location_name, mood, sort_order }) => {
233
+ if (isDemoUser(userId)) return demoDenied();
234
+ const entry = createEntry(journeyId, userId, { entry_date, title, story, entry_time, location_name, mood, sort_order });
235
+ if (!entry) return notFound('Journey not found or access denied.');
236
+ return ok({ entry });
237
+ }
238
+ );
239
+
240
+ if (W) server.registerTool(
241
+ 'update_journey_entry',
242
+ {
243
+ description: 'Update an existing journey entry.',
244
+ inputSchema: {
245
+ entryId: z.number().int().positive(),
246
+ title: z.string().max(300).optional(),
247
+ story: z.string().optional(),
248
+ entry_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
249
+ entry_time: z.string().optional(),
250
+ mood: z.string().optional(),
251
+ },
252
+ annotations: TOOL_ANNOTATIONS_WRITE,
253
+ },
254
+ async ({ entryId, title, story, entry_date, entry_time, mood }) => {
255
+ if (isDemoUser(userId)) return demoDenied();
256
+ const entry = updateEntry(entryId, userId, { title, story, entry_date, entry_time, mood }, undefined);
257
+ if (!entry) return notFound('Entry not found or access denied.');
258
+ return ok({ entry });
259
+ }
260
+ );
261
+
262
+ if (W) server.registerTool(
263
+ 'delete_journey_entry',
264
+ {
265
+ description: 'Delete a journey entry.',
266
+ inputSchema: {
267
+ entryId: z.number().int().positive(),
268
+ },
269
+ annotations: TOOL_ANNOTATIONS_DELETE,
270
+ },
271
+ async ({ entryId }) => {
272
+ if (isDemoUser(userId)) return demoDenied();
273
+ const success = deleteEntry(entryId, userId, undefined);
274
+ if (!success) return notFound('Entry not found or access denied.');
275
+ return ok({ success: true });
276
+ }
277
+ );
278
+
279
+ if (W) server.registerTool(
280
+ 'reorder_journey_entries',
281
+ {
282
+ description: 'Reorder entries within a journey by providing the desired order of entry IDs.',
283
+ inputSchema: {
284
+ journeyId: z.number().int().positive(),
285
+ orderedIds: z.array(z.number().int().positive()),
286
+ },
287
+ annotations: TOOL_ANNOTATIONS_WRITE,
288
+ },
289
+ async ({ journeyId, orderedIds }) => {
290
+ if (isDemoUser(userId)) return demoDenied();
291
+ const success = reorderEntries(journeyId, userId, orderedIds, undefined);
292
+ if (!success) return notFound('Journey not found, access denied, or entry IDs do not belong to this journey.');
293
+ return ok({ success: true });
294
+ }
295
+ );
296
+
297
+ if (W) server.registerTool(
298
+ 'add_journey_contributor',
299
+ {
300
+ description: 'Add a contributor to a journey. Owner only.',
301
+ inputSchema: {
302
+ journeyId: z.number().int().positive(),
303
+ targetUserId: z.number().int().positive(),
304
+ role: z.enum(['editor', 'viewer']),
305
+ },
306
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
307
+ },
308
+ async ({ journeyId, targetUserId, role }) => {
309
+ if (isDemoUser(userId)) return demoDenied();
310
+ const success = addContributor(journeyId, userId, targetUserId, role);
311
+ if (!success) return notFound('Journey not found or access denied.');
312
+ return ok({ success: true });
313
+ }
314
+ );
315
+
316
+ if (W) server.registerTool(
317
+ 'update_journey_contributor_role',
318
+ {
319
+ description: 'Update the role of a journey contributor. Owner only.',
320
+ inputSchema: {
321
+ journeyId: z.number().int().positive(),
322
+ targetUserId: z.number().int().positive(),
323
+ role: z.enum(['editor', 'viewer']),
324
+ },
325
+ annotations: TOOL_ANNOTATIONS_WRITE,
326
+ },
327
+ async ({ journeyId, targetUserId, role }) => {
328
+ if (isDemoUser(userId)) return demoDenied();
329
+ const success = updateContributorRole(journeyId, userId, targetUserId, role);
330
+ if (!success) return notFound('Journey not found or access denied.');
331
+ return ok({ success: true });
332
+ }
333
+ );
334
+
335
+ if (W) server.registerTool(
336
+ 'remove_journey_contributor',
337
+ {
338
+ description: 'Remove a contributor from a journey. Owner only.',
339
+ inputSchema: {
340
+ journeyId: z.number().int().positive(),
341
+ targetUserId: z.number().int().positive(),
342
+ },
343
+ annotations: TOOL_ANNOTATIONS_DELETE,
344
+ },
345
+ async ({ journeyId, targetUserId }) => {
346
+ if (isDemoUser(userId)) return demoDenied();
347
+ const success = removeContributor(journeyId, userId, targetUserId);
348
+ if (!success) return notFound('Journey not found or access denied.');
349
+ return ok({ success: true });
350
+ }
351
+ );
352
+
353
+ if (W) server.registerTool(
354
+ 'update_journey_preferences',
355
+ {
356
+ description: 'Update per-user preferences for a journey (e.g. hide skeleton entries).',
357
+ inputSchema: {
358
+ journeyId: z.number().int().positive(),
359
+ hide_skeletons: z.boolean().optional(),
360
+ },
361
+ annotations: TOOL_ANNOTATIONS_WRITE,
362
+ },
363
+ async ({ journeyId, hide_skeletons }) => {
364
+ if (isDemoUser(userId)) return demoDenied();
365
+ const result = updateJourneyPreferences(journeyId, userId, { hide_skeletons });
366
+ if (!result) return notFound('Journey not found or access denied.');
367
+ return ok({ success: true });
368
+ }
369
+ );
370
+
371
+ // --- SHARE TOOLS ---
372
+
373
+ if (S) server.registerTool(
374
+ 'get_journey_share_link',
375
+ {
376
+ description: 'Get the current public share link for a journey. Returns null if none exists.',
377
+ inputSchema: {
378
+ journeyId: z.number().int().positive(),
379
+ },
380
+ annotations: TOOL_ANNOTATIONS_READONLY,
381
+ },
382
+ async ({ journeyId }) => {
383
+ if (!canAccessJourney(journeyId, userId)) return notFound('Journey not found or access denied.');
384
+ const shareLink = getJourneyShareLink(journeyId);
385
+ return ok({ shareLink });
386
+ }
387
+ );
388
+
389
+ if (S) server.registerTool(
390
+ 'create_journey_share_link',
391
+ {
392
+ description: 'Create or update the public share link for a journey. Owner only.',
393
+ inputSchema: {
394
+ journeyId: z.number().int().positive(),
395
+ },
396
+ annotations: TOOL_ANNOTATIONS_WRITE,
397
+ },
398
+ async ({ journeyId }) => {
399
+ if (isDemoUser(userId)) return demoDenied();
400
+ const shareLink = createOrUpdateJourneyShareLink(journeyId, userId, {});
401
+ if (!shareLink) return notFound('Journey not found or access denied.');
402
+ return ok({ shareLink });
403
+ }
404
+ );
405
+
406
+ if (S) server.registerTool(
407
+ 'delete_journey_share_link',
408
+ {
409
+ description: 'Revoke the public share link for a journey. Owner only.',
410
+ inputSchema: {
411
+ journeyId: z.number().int().positive(),
412
+ },
413
+ annotations: TOOL_ANNOTATIONS_DELETE,
414
+ },
415
+ async ({ journeyId }) => {
416
+ if (isDemoUser(userId)) return demoDenied();
417
+ const success = deleteJourneyShareLink(journeyId, userId);
418
+ if (!success) return notFound('Journey not found or access denied.');
419
+ return ok({ success: true });
420
+ }
421
+ );
422
+ }
server/src/mcp/tools/mapsWeather.ts ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
2
+ import { z } from 'zod';
3
+ import { findByIata, searchAirports } from '../../services/airportService';
4
+ import { searchPlaces, getPlaceDetails, reverseGeocode, resolveGoogleMapsUrl } from '../../services/mapsService';
5
+ import { getWeather, getDetailedWeather } from '../../services/weatherService';
6
+ import {
7
+ TOOL_ANNOTATIONS_READONLY,
8
+ ok,
9
+ } from './_shared';
10
+ import { canRead } from '../scopes';
11
+
12
+ export function registerMapsWeatherTools(server: McpServer, userId: number, scopes: string[] | null): void {
13
+ const canGeo = canRead(scopes, 'geo');
14
+ const canWeather = canRead(scopes, 'weather');
15
+
16
+ // --- MAPS EXTRAS ---
17
+
18
+ if (canGeo) server.registerTool(
19
+ 'get_place_details',
20
+ {
21
+ description: 'Fetch detailed information about a place by its Google Place ID.',
22
+ inputSchema: {
23
+ placeId: z.string().describe('Google Place ID'),
24
+ lang: z.string().optional().default('en'),
25
+ },
26
+ annotations: TOOL_ANNOTATIONS_READONLY,
27
+ },
28
+ async ({ placeId, lang }) => {
29
+ const details = await getPlaceDetails(userId, placeId, lang ?? 'en');
30
+ if (!details) return { content: [{ type: 'text' as const, text: 'Place not found or maps service not configured.' }], isError: true };
31
+ return ok({ details });
32
+ }
33
+ );
34
+
35
+ if (canGeo) server.registerTool(
36
+ 'reverse_geocode',
37
+ {
38
+ description: 'Get a human-readable address for given coordinates.',
39
+ inputSchema: {
40
+ lat: z.number(),
41
+ lng: z.number(),
42
+ lang: z.string().optional().default('en'),
43
+ },
44
+ annotations: TOOL_ANNOTATIONS_READONLY,
45
+ },
46
+ async ({ lat, lng, lang }) => {
47
+ const result = await reverseGeocode(String(lat), String(lng), lang ?? 'en');
48
+ if (!result) return { content: [{ type: 'text' as const, text: 'Reverse geocode failed or maps service not configured.' }], isError: true };
49
+ return ok(result);
50
+ }
51
+ );
52
+
53
+ if (canGeo) server.registerTool(
54
+ 'resolve_maps_url',
55
+ {
56
+ description: 'Resolve a Google Maps share URL to coordinates and place name.',
57
+ inputSchema: {
58
+ url: z.string().describe('Google Maps share URL'),
59
+ },
60
+ annotations: TOOL_ANNOTATIONS_READONLY,
61
+ },
62
+ async ({ url }) => {
63
+ const result = await resolveGoogleMapsUrl(url);
64
+ if (!result) return { content: [{ type: 'text' as const, text: 'Could not resolve URL or maps service not configured.' }], isError: true };
65
+ return ok(result);
66
+ }
67
+ );
68
+
69
+ // --- WEATHER ---
70
+
71
+ if (canWeather) server.registerTool(
72
+ 'get_weather',
73
+ {
74
+ description: 'Get weather forecast for a location and date.',
75
+ inputSchema: {
76
+ lat: z.number(),
77
+ lng: z.number(),
78
+ date: z.string().describe('ISO date YYYY-MM-DD'),
79
+ lang: z.string().optional().default('en'),
80
+ },
81
+ annotations: TOOL_ANNOTATIONS_READONLY,
82
+ },
83
+ async ({ lat, lng, date, lang }) => {
84
+ try {
85
+ const weather = await getWeather(String(lat), String(lng), date, lang ?? 'en');
86
+ return ok({ weather });
87
+ } catch (err: any) {
88
+ return { content: [{ type: 'text' as const, text: err?.message ?? 'Weather service not available.' }], isError: true };
89
+ }
90
+ }
91
+ );
92
+
93
+ if (canWeather) server.registerTool(
94
+ 'get_detailed_weather',
95
+ {
96
+ description: 'Get hourly/detailed weather forecast for a location and date.',
97
+ inputSchema: {
98
+ lat: z.number(),
99
+ lng: z.number(),
100
+ date: z.string().describe('ISO date YYYY-MM-DD'),
101
+ lang: z.string().optional().default('en'),
102
+ },
103
+ annotations: TOOL_ANNOTATIONS_READONLY,
104
+ },
105
+ async ({ lat, lng, date, lang }) => {
106
+ try {
107
+ const weather = await getDetailedWeather(String(lat), String(lng), date, lang ?? 'en');
108
+ return ok({ weather });
109
+ } catch (err: any) {
110
+ return { content: [{ type: 'text' as const, text: err?.message ?? 'Weather service not available.' }], isError: true };
111
+ }
112
+ }
113
+ );
114
+
115
+ // --- AIRPORTS ---
116
+
117
+ if (canGeo) server.registerTool(
118
+ 'search_airports',
119
+ {
120
+ 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.',
121
+ inputSchema: {
122
+ query: z.string().min(1).max(200).describe('Airport name, city, or IATA code (e.g. "zurich", "ZRH", "charles de gaulle")'),
123
+ limit: z.number().int().min(1).max(50).optional().default(10),
124
+ },
125
+ annotations: TOOL_ANNOTATIONS_READONLY,
126
+ },
127
+ async ({ query, limit }) => {
128
+ const airports = searchAirports(query, limit ?? 10);
129
+ return ok({ airports });
130
+ }
131
+ );
132
+
133
+ if (canGeo) server.registerTool(
134
+ 'get_airport',
135
+ {
136
+ description: 'Get a single airport by its IATA code. Returns name, city, country, coordinates, and timezone.',
137
+ inputSchema: {
138
+ iata: z.string().length(3).toUpperCase().describe('IATA airport code (e.g. "ZRH", "AMS", "CDG")'),
139
+ },
140
+ annotations: TOOL_ANNOTATIONS_READONLY,
141
+ },
142
+ async ({ iata }) => {
143
+ const airport = findByIata(iata);
144
+ if (!airport) return { content: [{ type: 'text' as const, text: 'Airport not found.' }], isError: true };
145
+ return ok({ airport });
146
+ }
147
+ );
148
+ }
server/src/mcp/tools/notifications.ts ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
2
+ import { z } from 'zod';
3
+ import { isDemoUser } from '../../services/authService';
4
+ import {
5
+ getNotifications, getUnreadCount,
6
+ markRead as markNotificationRead, markUnread as markNotificationUnread,
7
+ markAllRead,
8
+ } from '../../services/inAppNotifications';
9
+ import {
10
+ TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
11
+ TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
12
+ demoDenied, ok,
13
+ } from './_shared';
14
+ import { canRead, canWrite } from '../scopes';
15
+
16
+ export function registerNotificationTools(server: McpServer, userId: number, scopes: string[] | null): void {
17
+ const R = canRead(scopes, 'notifications');
18
+ const W = canWrite(scopes, 'notifications');
19
+
20
+ // --- NOTIFICATIONS ---
21
+
22
+ if (R) server.registerTool(
23
+ 'list_notifications',
24
+ {
25
+ description: 'List in-app notifications for the current user.',
26
+ inputSchema: {
27
+ limit: z.number().int().positive().optional().default(20),
28
+ offset: z.number().int().min(0).optional().default(0),
29
+ unread_only: z.boolean().optional().default(false),
30
+ },
31
+ annotations: TOOL_ANNOTATIONS_READONLY,
32
+ },
33
+ async ({ limit, offset, unread_only }) => {
34
+ const result = getNotifications(userId, { limit: limit ?? 20, offset: offset ?? 0, unreadOnly: unread_only ?? false });
35
+ return ok(result);
36
+ }
37
+ );
38
+
39
+ if (R) server.registerTool(
40
+ 'get_unread_notification_count',
41
+ {
42
+ description: 'Get the number of unread in-app notifications.',
43
+ inputSchema: {},
44
+ annotations: TOOL_ANNOTATIONS_READONLY,
45
+ },
46
+ async () => {
47
+ const count = getUnreadCount(userId);
48
+ return ok({ count });
49
+ }
50
+ );
51
+
52
+ if (W) server.registerTool(
53
+ 'mark_notification_read',
54
+ {
55
+ description: 'Mark a single notification as read.',
56
+ inputSchema: {
57
+ notificationId: z.number().int().positive(),
58
+ },
59
+ annotations: TOOL_ANNOTATIONS_WRITE,
60
+ },
61
+ async ({ notificationId }) => {
62
+ if (isDemoUser(userId)) return demoDenied();
63
+ const success = markNotificationRead(notificationId, userId);
64
+ if (!success) return { content: [{ type: 'text' as const, text: 'Notification not found.' }], isError: true };
65
+ return ok({ success: true });
66
+ }
67
+ );
68
+
69
+ if (W) server.registerTool(
70
+ 'mark_notification_unread',
71
+ {
72
+ description: 'Mark a single notification as unread.',
73
+ inputSchema: {
74
+ notificationId: z.number().int().positive(),
75
+ },
76
+ annotations: TOOL_ANNOTATIONS_WRITE,
77
+ },
78
+ async ({ notificationId }) => {
79
+ if (isDemoUser(userId)) return demoDenied();
80
+ const success = markNotificationUnread(notificationId, userId);
81
+ if (!success) return { content: [{ type: 'text' as const, text: 'Notification not found.' }], isError: true };
82
+ return ok({ success: true });
83
+ }
84
+ );
85
+
86
+ if (W) server.registerTool(
87
+ 'mark_all_notifications_read',
88
+ {
89
+ description: "Mark all of the current user's notifications as read.",
90
+ inputSchema: {},
91
+ annotations: TOOL_ANNOTATIONS_WRITE,
92
+ },
93
+ async () => {
94
+ if (isDemoUser(userId)) return demoDenied();
95
+ const count = markAllRead(userId);
96
+ return ok({ success: true, count });
97
+ }
98
+ );
99
+ }
server/src/mcp/tools/packing.ts ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
2
+ import { z } from 'zod';
3
+ import { canAccessTrip } from '../../db/database';
4
+ import { isDemoUser } from '../../services/authService';
5
+ import {
6
+ createItem as createPackingItem, updateItem as updatePackingItem,
7
+ deleteItem as deletePackingItem,
8
+ reorderItems as reorderPackingItems,
9
+ listBags, createBag, updateBag, deleteBag, setBagMembers,
10
+ getCategoryAssignees as getPackingCategoryAssignees,
11
+ updateCategoryAssignees as updatePackingCategoryAssignees,
12
+ applyTemplate, saveAsTemplate, bulkImport,
13
+ } from '../../services/packingService';
14
+ import {
15
+ safeBroadcast, TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE,
16
+ TOOL_ANNOTATIONS_NON_IDEMPOTENT,
17
+ demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
18
+ } from './_shared';
19
+ import { canRead, canWrite } from '../scopes';
20
+ import { isAddonEnabled } from '../../services/adminService';
21
+ import { ADDON_IDS } from '../../addons';
22
+
23
+ export function registerPackingTools(server: McpServer, userId: number, scopes: string[] | null): void {
24
+ const R = canRead(scopes, 'packing');
25
+ const W = canWrite(scopes, 'packing');
26
+
27
+ if (!isAddonEnabled(ADDON_IDS.PACKING)) return;
28
+
29
+ // --- PACKING ---
30
+
31
+ if (W) server.registerTool(
32
+ 'create_packing_item',
33
+ {
34
+ description: 'Add an item to the packing checklist for a trip.',
35
+ inputSchema: {
36
+ tripId: z.number().int().positive(),
37
+ name: z.string().min(1).max(200),
38
+ category: z.string().max(100).optional().describe('Packing category (e.g. Clothes, Electronics)'),
39
+ },
40
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
41
+ },
42
+ async ({ tripId, name, category }) => {
43
+ if (isDemoUser(userId)) return demoDenied();
44
+ if (!canAccessTrip(tripId, userId)) return noAccess();
45
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
46
+ const item = createPackingItem(tripId, { name, category: category || 'General' });
47
+ safeBroadcast(tripId, 'packing:created', { item });
48
+ return ok({ item });
49
+ }
50
+ );
51
+
52
+ if (W) server.registerTool(
53
+ 'toggle_packing_item',
54
+ {
55
+ description: 'Check or uncheck a packing item.',
56
+ inputSchema: {
57
+ tripId: z.number().int().positive(),
58
+ itemId: z.number().int().positive(),
59
+ checked: z.boolean(),
60
+ },
61
+ annotations: TOOL_ANNOTATIONS_WRITE,
62
+ },
63
+ async ({ tripId, itemId, checked }) => {
64
+ if (isDemoUser(userId)) return demoDenied();
65
+ if (!canAccessTrip(tripId, userId)) return noAccess();
66
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
67
+ const item = updatePackingItem(tripId, itemId, { checked: checked ? 1 : 0 }, ['checked']);
68
+ if (!item) return { content: [{ type: 'text' as const, text: 'Packing item not found.' }], isError: true };
69
+ safeBroadcast(tripId, 'packing:updated', { item });
70
+ return ok({ item });
71
+ }
72
+ );
73
+
74
+ if (W) server.registerTool(
75
+ 'delete_packing_item',
76
+ {
77
+ description: 'Remove an item from the packing checklist.',
78
+ inputSchema: {
79
+ tripId: z.number().int().positive(),
80
+ itemId: z.number().int().positive(),
81
+ },
82
+ annotations: TOOL_ANNOTATIONS_DELETE,
83
+ },
84
+ async ({ tripId, itemId }) => {
85
+ if (isDemoUser(userId)) return demoDenied();
86
+ if (!canAccessTrip(tripId, userId)) return noAccess();
87
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
88
+ const deleted = deletePackingItem(tripId, itemId);
89
+ if (!deleted) return { content: [{ type: 'text' as const, text: 'Packing item not found.' }], isError: true };
90
+ safeBroadcast(tripId, 'packing:deleted', { itemId });
91
+ return ok({ success: true });
92
+ }
93
+ );
94
+
95
+ // --- PACKING (update) ---
96
+
97
+ if (W) server.registerTool(
98
+ 'update_packing_item',
99
+ {
100
+ description: 'Rename a packing item or change its category.',
101
+ inputSchema: {
102
+ tripId: z.number().int().positive(),
103
+ itemId: z.number().int().positive(),
104
+ name: z.string().min(1).max(200).optional(),
105
+ category: z.string().max(100).optional(),
106
+ },
107
+ annotations: TOOL_ANNOTATIONS_WRITE,
108
+ },
109
+ async ({ tripId, itemId, name, category }) => {
110
+ if (isDemoUser(userId)) return demoDenied();
111
+ if (!canAccessTrip(tripId, userId)) return noAccess();
112
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
113
+ const bodyKeys = ['name', 'category'].filter(k => k === 'name' ? name !== undefined : category !== undefined);
114
+ const item = updatePackingItem(tripId, itemId, { name, category }, bodyKeys);
115
+ if (!item) return { content: [{ type: 'text' as const, text: 'Packing item not found.' }], isError: true };
116
+ safeBroadcast(tripId, 'packing:updated', { item });
117
+ return ok({ item });
118
+ }
119
+ );
120
+
121
+ // --- PACKING ADVANCED ---
122
+
123
+ if (W) server.registerTool(
124
+ 'reorder_packing_items',
125
+ {
126
+ description: 'Set the display order of packing items within a trip.',
127
+ inputSchema: {
128
+ tripId: z.number().int().positive(),
129
+ orderedIds: z.array(z.number().int().positive()).describe('Packing item IDs in desired order'),
130
+ },
131
+ annotations: TOOL_ANNOTATIONS_WRITE,
132
+ },
133
+ async ({ tripId, orderedIds }) => {
134
+ if (isDemoUser(userId)) return demoDenied();
135
+ if (!canAccessTrip(tripId, userId)) return noAccess();
136
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
137
+ reorderPackingItems(tripId, orderedIds);
138
+ safeBroadcast(tripId, 'packing:reordered', { orderedIds });
139
+ return ok({ success: true });
140
+ }
141
+ );
142
+
143
+ if (R) server.registerTool(
144
+ 'list_packing_bags',
145
+ {
146
+ description: 'List all packing bags for a trip.',
147
+ inputSchema: {
148
+ tripId: z.number().int().positive(),
149
+ },
150
+ annotations: TOOL_ANNOTATIONS_READONLY,
151
+ },
152
+ async ({ tripId }) => {
153
+ if (!canAccessTrip(tripId, userId)) return noAccess();
154
+ const bags = listBags(tripId);
155
+ return ok({ bags });
156
+ }
157
+ );
158
+
159
+ if (W) server.registerTool(
160
+ 'create_packing_bag',
161
+ {
162
+ description: 'Create a new packing bag (e.g. "Carry-on", "Checked bag").',
163
+ inputSchema: {
164
+ tripId: z.number().int().positive(),
165
+ name: z.string().min(1).max(100),
166
+ color: z.string().optional(),
167
+ },
168
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
169
+ },
170
+ async ({ tripId, name, color }) => {
171
+ if (isDemoUser(userId)) return demoDenied();
172
+ if (!canAccessTrip(tripId, userId)) return noAccess();
173
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
174
+ const bag = createBag(tripId, { name, color });
175
+ safeBroadcast(tripId, 'packing:bag-created', { bag });
176
+ return ok({ bag });
177
+ }
178
+ );
179
+
180
+ if (W) server.registerTool(
181
+ 'update_packing_bag',
182
+ {
183
+ description: 'Rename or recolor a packing bag.',
184
+ inputSchema: {
185
+ tripId: z.number().int().positive(),
186
+ bagId: z.number().int().positive(),
187
+ name: z.string().optional(),
188
+ color: z.string().optional(),
189
+ },
190
+ annotations: TOOL_ANNOTATIONS_WRITE,
191
+ },
192
+ async ({ tripId, bagId, name, color }) => {
193
+ if (isDemoUser(userId)) return demoDenied();
194
+ if (!canAccessTrip(tripId, userId)) return noAccess();
195
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
196
+ const fields: Record<string, unknown> = {};
197
+ const bodyKeys: string[] = [];
198
+ if (name !== undefined) { fields.name = name; bodyKeys.push('name'); }
199
+ if (color !== undefined) { fields.color = color; bodyKeys.push('color'); }
200
+ const bag = updateBag(tripId, bagId, fields, bodyKeys);
201
+ safeBroadcast(tripId, 'packing:bag-updated', { bag });
202
+ return ok({ bag });
203
+ }
204
+ );
205
+
206
+ if (W) server.registerTool(
207
+ 'delete_packing_bag',
208
+ {
209
+ description: 'Delete a packing bag (items in the bag are unassigned, not deleted).',
210
+ inputSchema: {
211
+ tripId: z.number().int().positive(),
212
+ bagId: z.number().int().positive(),
213
+ },
214
+ annotations: TOOL_ANNOTATIONS_DELETE,
215
+ },
216
+ async ({ tripId, bagId }) => {
217
+ if (isDemoUser(userId)) return demoDenied();
218
+ if (!canAccessTrip(tripId, userId)) return noAccess();
219
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
220
+ deleteBag(tripId, bagId);
221
+ safeBroadcast(tripId, 'packing:bag-deleted', { id: bagId });
222
+ return ok({ success: true });
223
+ }
224
+ );
225
+
226
+ if (W) server.registerTool(
227
+ 'set_bag_members',
228
+ {
229
+ description: 'Assign trip members to a packing bag (determines who packs what bag).',
230
+ inputSchema: {
231
+ tripId: z.number().int().positive(),
232
+ bagId: z.number().int().positive(),
233
+ userIds: z.array(z.number().int().positive()),
234
+ },
235
+ annotations: TOOL_ANNOTATIONS_WRITE,
236
+ },
237
+ async ({ tripId, bagId, userIds }) => {
238
+ if (isDemoUser(userId)) return demoDenied();
239
+ if (!canAccessTrip(tripId, userId)) return noAccess();
240
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
241
+ setBagMembers(tripId, bagId, userIds);
242
+ safeBroadcast(tripId, 'packing:bag-members-updated', { bagId, userIds });
243
+ return ok({ success: true });
244
+ }
245
+ );
246
+
247
+ if (R) server.registerTool(
248
+ 'get_packing_category_assignees',
249
+ {
250
+ description: 'Get which trip members are assigned to each packing category.',
251
+ inputSchema: {
252
+ tripId: z.number().int().positive(),
253
+ },
254
+ annotations: TOOL_ANNOTATIONS_READONLY,
255
+ },
256
+ async ({ tripId }) => {
257
+ if (!canAccessTrip(tripId, userId)) return noAccess();
258
+ const assignees = getPackingCategoryAssignees(tripId);
259
+ return ok({ assignees });
260
+ }
261
+ );
262
+
263
+ if (W) server.registerTool(
264
+ 'set_packing_category_assignees',
265
+ {
266
+ description: 'Assign trip members to a packing category.',
267
+ inputSchema: {
268
+ tripId: z.number().int().positive(),
269
+ categoryName: z.string().min(1).max(100),
270
+ userIds: z.array(z.number().int().positive()),
271
+ },
272
+ annotations: TOOL_ANNOTATIONS_WRITE,
273
+ },
274
+ async ({ tripId, categoryName, userIds }) => {
275
+ if (isDemoUser(userId)) return demoDenied();
276
+ if (!canAccessTrip(tripId, userId)) return noAccess();
277
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
278
+ updatePackingCategoryAssignees(tripId, categoryName, userIds);
279
+ safeBroadcast(tripId, 'packing:assignees', { categoryName, userIds });
280
+ return ok({ success: true });
281
+ }
282
+ );
283
+
284
+ if (W) server.registerTool(
285
+ 'apply_packing_template',
286
+ {
287
+ description: 'Apply a packing template to a trip (adds items from the template).',
288
+ inputSchema: {
289
+ tripId: z.number().int().positive(),
290
+ templateId: z.number().int().positive(),
291
+ },
292
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
293
+ },
294
+ async ({ tripId, templateId }) => {
295
+ if (isDemoUser(userId)) return demoDenied();
296
+ if (!canAccessTrip(tripId, userId)) return noAccess();
297
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
298
+ const applied = applyTemplate(tripId, templateId);
299
+ if (applied === null) return { content: [{ type: 'text' as const, text: 'Template not found.' }], isError: true };
300
+ safeBroadcast(tripId, 'packing:template-applied', { templateId });
301
+ return ok({ success: true });
302
+ }
303
+ );
304
+
305
+ if (W) server.registerTool(
306
+ 'save_packing_template',
307
+ {
308
+ description: 'Save the current packing list as a reusable template.',
309
+ inputSchema: {
310
+ tripId: z.number().int().positive(),
311
+ templateName: z.string().min(1).max(100),
312
+ },
313
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
314
+ },
315
+ async ({ tripId, templateName }) => {
316
+ if (isDemoUser(userId)) return demoDenied();
317
+ if (!canAccessTrip(tripId, userId)) return noAccess();
318
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
319
+ saveAsTemplate(tripId, userId, templateName);
320
+ return ok({ success: true });
321
+ }
322
+ );
323
+
324
+ if (W) server.registerTool(
325
+ 'bulk_import_packing',
326
+ {
327
+ description: 'Import multiple packing items at once from a list.',
328
+ inputSchema: {
329
+ tripId: z.number().int().positive(),
330
+ items: z.array(z.object({
331
+ name: z.string().min(1).max(200),
332
+ category: z.string().optional(),
333
+ quantity: z.number().int().positive().optional(),
334
+ })).min(1),
335
+ },
336
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
337
+ },
338
+ async ({ tripId, items }) => {
339
+ if (isDemoUser(userId)) return demoDenied();
340
+ if (!canAccessTrip(tripId, userId)) return noAccess();
341
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
342
+ bulkImport(tripId, items);
343
+ safeBroadcast(tripId, 'packing:updated', {});
344
+ return ok({ success: true, count: items.length });
345
+ }
346
+ );
347
+ }
server/src/mcp/tools/places.ts ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
2
+ import { z } from 'zod';
3
+ import { canAccessTrip, db } from '../../db/database';
4
+ import { isDemoUser } from '../../services/authService';
5
+ import { deletePlacesMany, importGoogleList, importNaverList, listPlaces, createPlace, updatePlace, deletePlace } from '../../services/placeService';
6
+ import { createAssignment, dayExists } from '../../services/assignmentService';
7
+ import { onPlaceDeleted } from '../../services/journeyService';
8
+ import { listCategories } from '../../services/categoryService';
9
+ import { searchPlaces } from '../../services/mapsService';
10
+ import {
11
+ safeBroadcast, TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
12
+ TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
13
+ demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
14
+ } from './_shared';
15
+ import { canRead, canWrite } from '../scopes';
16
+
17
+ export function registerPlaceTools(server: McpServer, userId: number, scopes: string[] | null): void {
18
+ const R = canRead(scopes, 'places');
19
+ const W = canWrite(scopes, 'places');
20
+
21
+ // --- PLACES ---
22
+
23
+ if (W) server.registerTool(
24
+ 'create_place',
25
+ {
26
+ description: 'Add a new place/POI to a trip. Set google_place_id or osm_id (from search_place) so the app can show opening hours and ratings. Set price + currency to record the cost so it shows on the item.',
27
+ inputSchema: {
28
+ tripId: z.number().int().positive(),
29
+ name: z.string().min(1).max(200),
30
+ description: z.string().max(2000).optional(),
31
+ lat: z.number().optional(),
32
+ lng: z.number().optional(),
33
+ address: z.string().max(500).optional(),
34
+ category_id: z.number().int().positive().optional().describe('Category ID — use list_categories to see available options'),
35
+ google_place_id: z.string().optional().describe('Google Place ID from search_place — enables opening hours display'),
36
+ osm_id: z.string().optional().describe('OpenStreetMap ID from search_place (e.g. "way:12345") — enables opening hours if no Google ID'),
37
+ notes: z.string().max(2000).optional(),
38
+ website: z.string().max(500).optional(),
39
+ phone: z.string().max(50).optional(),
40
+ price: z.number().nonnegative().optional().describe('Cost of this place/activity (e.g. ticket price, entry fee)'),
41
+ currency: z.string().length(3).optional().describe('ISO 4217 currency code (e.g. "EUR", "USD")'),
42
+ },
43
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
44
+ },
45
+ async ({ tripId, name, description, lat, lng, address, category_id, google_place_id, osm_id, notes, website, phone, price, currency }) => {
46
+ if (isDemoUser(userId)) return demoDenied();
47
+ if (!canAccessTrip(tripId, userId)) return noAccess();
48
+ if (!hasTripPermission('place_edit', tripId, userId)) return permissionDenied();
49
+ const place = createPlace(String(tripId), { name, description, lat, lng, address, category_id, google_place_id, osm_id, notes, website, phone, price, currency });
50
+ safeBroadcast(tripId, 'place:created', { place });
51
+ return ok({ place });
52
+ }
53
+ );
54
+
55
+ if (W) server.registerTool(
56
+ 'create_and_assign_place',
57
+ {
58
+ 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.',
59
+ inputSchema: {
60
+ tripId: z.number().int().positive(),
61
+ dayId: z.number().int().positive().describe('Day to assign the place to'),
62
+ name: z.string().min(1).max(200),
63
+ description: z.string().max(2000).optional(),
64
+ lat: z.number().optional(),
65
+ lng: z.number().optional(),
66
+ address: z.string().max(500).optional(),
67
+ category_id: z.number().int().positive().optional().describe('Category ID — use list_categories to see available options'),
68
+ google_place_id: z.string().optional().describe('Google Place ID from search_place — enables opening hours display'),
69
+ osm_id: z.string().optional().describe('OpenStreetMap ID from search_place (e.g. "way:12345")'),
70
+ place_notes: z.string().max(2000).optional().describe('Notes for the place'),
71
+ website: z.string().max(500).optional(),
72
+ phone: z.string().max(50).optional(),
73
+ assignment_notes: z.string().max(500).optional().describe('Notes for this day assignment'),
74
+ price: z.number().nonnegative().optional().describe('Cost of this place/activity (e.g. ticket price, entry fee)'),
75
+ currency: z.string().length(3).optional().describe('ISO 4217 currency code (e.g. "EUR", "USD")'),
76
+ },
77
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
78
+ },
79
+ async ({ tripId, dayId, name, description, lat, lng, address, category_id, google_place_id, osm_id, place_notes, website, phone, assignment_notes, price, currency }) => {
80
+ if (isDemoUser(userId)) return demoDenied();
81
+ if (!canAccessTrip(tripId, userId)) return noAccess();
82
+ if (!hasTripPermission('place_edit', tripId, userId)) return permissionDenied();
83
+ if (!dayExists(dayId, tripId)) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true };
84
+ try {
85
+ const run = db.transaction(() => {
86
+ const place = createPlace(String(tripId), { name, description, lat, lng, address, category_id, google_place_id, osm_id, notes: place_notes, website, phone, price, currency });
87
+ const assignment = createAssignment(dayId, place.id, assignment_notes ?? null);
88
+ return { place, assignment };
89
+ });
90
+ const result = run();
91
+ safeBroadcast(tripId, 'place:created', { place: result.place });
92
+ safeBroadcast(tripId, 'assignment:created', { assignment: result.assignment });
93
+ return ok(result);
94
+ } catch {
95
+ return { content: [{ type: 'text' as const, text: 'Failed to create place and assignment.' }], isError: true };
96
+ }
97
+ }
98
+ );
99
+
100
+ if (W) server.registerTool(
101
+ 'update_place',
102
+ {
103
+ description: 'Update an existing place in a trip.',
104
+ inputSchema: {
105
+ tripId: z.number().int().positive(),
106
+ placeId: z.number().int().positive(),
107
+ name: z.string().min(1).max(200).optional(),
108
+ description: z.string().max(2000).optional(),
109
+ lat: z.number().optional(),
110
+ lng: z.number().optional(),
111
+ address: z.string().max(500).optional(),
112
+ category_id: z.number().int().positive().optional().describe('Category ID — use list_categories'),
113
+ price: z.number().optional(),
114
+ currency: z.string().length(3).optional(),
115
+ place_time: z.string().max(50).optional().describe('Scheduled time (e.g. "09:00")'),
116
+ end_time: z.string().max(50).optional().describe('End time (e.g. "11:00")'),
117
+ duration_minutes: z.number().int().positive().optional(),
118
+ notes: z.string().max(2000).optional(),
119
+ website: z.string().max(500).optional(),
120
+ phone: z.string().max(50).optional(),
121
+ transport_mode: z.enum(['walking', 'driving', 'cycling', 'transit', 'flight']).optional(),
122
+ osm_id: z.string().optional().describe('OpenStreetMap ID (e.g. "way:12345")'),
123
+ google_place_id: z.string().optional().describe('Google Place ID (e.g. "ChIJd8BlQ2BZwokRAFUEcm_qrcA")'),
124
+ },
125
+ annotations: TOOL_ANNOTATIONS_WRITE,
126
+ },
127
+ 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 }) => {
128
+ if (isDemoUser(userId)) return demoDenied();
129
+ if (!canAccessTrip(tripId, userId)) return noAccess();
130
+ if (!hasTripPermission('place_edit', tripId, userId)) return permissionDenied();
131
+ 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 });
132
+ if (!place) return { content: [{ type: 'text' as const, text: 'Place not found.' }], isError: true };
133
+ safeBroadcast(tripId, 'place:updated', { place });
134
+ return ok({ place });
135
+ }
136
+ );
137
+
138
+ if (W) server.registerTool(
139
+ 'delete_place',
140
+ {
141
+ description: 'Delete a place from a trip.',
142
+ inputSchema: {
143
+ tripId: z.number().int().positive(),
144
+ placeId: z.number().int().positive(),
145
+ },
146
+ annotations: TOOL_ANNOTATIONS_DELETE,
147
+ },
148
+ async ({ tripId, placeId }) => {
149
+ if (isDemoUser(userId)) return demoDenied();
150
+ if (!canAccessTrip(tripId, userId)) return noAccess();
151
+ if (!hasTripPermission('place_edit', tripId, userId)) return permissionDenied();
152
+ const deleted = deletePlace(String(tripId), String(placeId));
153
+ if (!deleted) return { content: [{ type: 'text' as const, text: 'Place not found.' }], isError: true };
154
+ safeBroadcast(tripId, 'place:deleted', { placeId });
155
+ return ok({ success: true });
156
+ }
157
+ );
158
+
159
+ if (R) server.registerTool(
160
+ 'list_places',
161
+ {
162
+ 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.',
163
+ inputSchema: {
164
+ tripId: z.number().int().positive(),
165
+ search: z.string().optional(),
166
+ category: z.string().optional(),
167
+ tag: z.string().optional(),
168
+ 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)'),
169
+ },
170
+ annotations: TOOL_ANNOTATIONS_READONLY,
171
+ },
172
+ async ({ tripId, search, category, tag, assignment }) => {
173
+ if (!canAccessTrip(tripId, userId)) return noAccess();
174
+ const places = listPlaces(String(tripId), { search, category, tag, assignment });
175
+ return ok({ places });
176
+ }
177
+ );
178
+
179
+ // --- CATEGORIES ---
180
+
181
+ if (R) server.registerTool(
182
+ 'list_categories',
183
+ {
184
+ description: 'List all available place categories with their id, name, icon and color. Use category_id when creating or updating places.',
185
+ inputSchema: {},
186
+ annotations: TOOL_ANNOTATIONS_READONLY,
187
+ },
188
+ async () => {
189
+ const categories = listCategories();
190
+ return ok({ categories });
191
+ }
192
+ );
193
+
194
+ // --- SEARCH ---
195
+
196
+ if (R) server.registerTool(
197
+ 'search_place',
198
+ {
199
+ description: 'Search for a real-world place by name or address. Returns results with osm_id (and google_place_id if configured). Use these IDs when calling create_place so the app can display opening hours and ratings.',
200
+ inputSchema: {
201
+ query: z.string().min(1).max(500).describe('Place name or address to search for'),
202
+ },
203
+ annotations: TOOL_ANNOTATIONS_READONLY,
204
+ },
205
+ async ({ query }) => {
206
+ try {
207
+ const result = await searchPlaces(userId, query);
208
+ return ok(result);
209
+ } catch {
210
+ return { content: [{ type: 'text' as const, text: 'Place search failed.' }], isError: true };
211
+ }
212
+ }
213
+ );
214
+
215
+ if (W) server.registerTool(
216
+ 'import_places_from_url',
217
+ {
218
+ 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.',
219
+ inputSchema: {
220
+ tripId: z.number().int().positive(),
221
+ url: z.string().url().describe('Publicly shared Google Maps list URL (maps.app.goo.gl/...) or Naver Maps list URL'),
222
+ source: z.enum(['google-list', 'naver-list']).describe('List source: "google-list" for Google Maps saved places, "naver-list" for Naver Maps'),
223
+ },
224
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
225
+ },
226
+ async ({ tripId, url, source }) => {
227
+ if (isDemoUser(userId)) return demoDenied();
228
+ if (!canAccessTrip(tripId, userId)) return noAccess();
229
+ if (!hasTripPermission('place_edit', tripId, userId)) return permissionDenied();
230
+
231
+ const result = source === 'google-list'
232
+ ? await importGoogleList(String(tripId), url)
233
+ : await importNaverList(String(tripId), url);
234
+
235
+ if ('error' in result) {
236
+ return { content: [{ type: 'text' as const, text: result.error }], isError: true };
237
+ }
238
+
239
+ for (const place of result.places) {
240
+ safeBroadcast(tripId, 'place:created', { place });
241
+ }
242
+ return ok({ places: result.places, count: result.places.length, listName: result.listName, skipped: result.skipped });
243
+ }
244
+ );
245
+
246
+ if (W) server.registerTool(
247
+ 'bulk_delete_places',
248
+ {
249
+ 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.',
250
+ inputSchema: {
251
+ tripId: z.number().int().positive(),
252
+ placeIds: z.array(z.number().int().positive()).min(1).max(200),
253
+ },
254
+ annotations: TOOL_ANNOTATIONS_DELETE,
255
+ },
256
+ async ({ tripId, placeIds }) => {
257
+ if (isDemoUser(userId)) return demoDenied();
258
+ if (!canAccessTrip(tripId, userId)) return noAccess();
259
+ if (!hasTripPermission('place_edit', tripId, userId)) return permissionDenied();
260
+
261
+ const deleted = deletePlacesMany(String(tripId), placeIds);
262
+ for (const id of deleted) {
263
+ safeBroadcast(tripId, 'place:deleted', { placeId: id });
264
+ try { onPlaceDeleted(id); } catch {}
265
+ }
266
+ return ok({ deleted, count: deleted.length });
267
+ }
268
+ );
269
+ }
server/src/mcp/tools/prompts.ts ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
2
+ import { z } from 'zod';
3
+ import { canAccessTrip } from '../../db/database';
4
+ import { getTripSummary } from '../../services/tripService';
5
+ import { listItems as listPackingItems } from '../../services/packingService';
6
+ import { isAddonEnabled } from '../../services/adminService';
7
+ import { ADDON_IDS } from '../../addons';
8
+
9
+ export function registerMcpPrompts(server: McpServer, _userId: number, isStaticToken = false): void {
10
+ if (isStaticToken) {
11
+ server.registerPrompt(
12
+ 'token_auth_notice',
13
+ {
14
+ title: 'Static Token Auth Notice',
15
+ description: 'Notification that this session uses a static API token which will be deprecated',
16
+ argsSchema: {},
17
+ },
18
+ async () => ({
19
+ description: 'Static token deprecation notice',
20
+ messages: [{
21
+ role: 'user' as const,
22
+ content: {
23
+ type: 'text' as const,
24
+ 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.',
25
+ },
26
+ }],
27
+ })
28
+ );
29
+ }
30
+ const userId = _userId;
31
+
32
+ server.registerPrompt(
33
+ 'trip-summary',
34
+ {
35
+ title: 'Trip Summary',
36
+ description: 'Load a full summary of a trip for context before planning or modifications',
37
+ argsSchema: {
38
+ tripId: z.number().int().positive().describe('Trip ID to summarize'),
39
+ },
40
+ },
41
+ async ({ tripId }) => {
42
+ if (!canAccessTrip(tripId, userId)) {
43
+ return { messages: [{ role: 'user', content: { type: 'text', text: 'Trip not found or access denied.' } }] };
44
+ }
45
+ const summary = getTripSummary(tripId);
46
+ if (!summary) {
47
+ return { messages: [{ role: 'user', content: { type: 'text', text: 'Trip not found.' } }] };
48
+ }
49
+ const { trip, days, members, budget, packing, reservations, collab_notes } = summary;
50
+ const memberList = [members?.owner, ...(members?.collaborators || [])].filter(Boolean);
51
+ const text = `Trip: ${trip?.title || 'Untitled'}${trip?.description ? `\n${trip.description}` : ''}
52
+ Dates: ${trip?.start_date || '?'} to ${trip?.end_date || '?'}
53
+ Members: ${memberList.length} (${memberList.map((m: any) => m.name || m.email).join(', ') || 'none'})
54
+ Days: ${days?.length || 0}
55
+ Packing: ${packing?.checked || 0}/${packing?.total || 0} items packed
56
+ Budget: ${budget?.total || 0} ${trip?.currency || 'EUR'} total
57
+ Reservations: ${reservations?.length || 0}
58
+ Collab Notes: ${collab_notes?.length || 0}
59
+ ${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'}`;
60
+ return {
61
+ description: `Summary of trip "${trip?.title || tripId}"`,
62
+ messages: [{ role: 'user', content: { type: 'text', text } }],
63
+ };
64
+ }
65
+ );
66
+
67
+ if (isAddonEnabled(ADDON_IDS.PACKING)) server.registerPrompt(
68
+ 'packing-list',
69
+ {
70
+ title: 'Packing List',
71
+ description: 'Get a formatted packing checklist for a trip',
72
+ argsSchema: {
73
+ tripId: z.number().int().positive().describe('Trip ID'),
74
+ },
75
+ },
76
+ async ({ tripId }) => {
77
+ if (!canAccessTrip(tripId, userId)) {
78
+ return { messages: [{ role: 'user', content: { type: 'text', text: 'Trip not found or access denied.' } }] };
79
+ }
80
+ const items = listPackingItems(tripId);
81
+ if (!items.length) {
82
+ return { messages: [{ role: 'user', content: { type: 'text', text: 'No packing items found for this trip.' } }] };
83
+ }
84
+ const grouped = items.reduce((acc: Record<string, any[]>, item: any) => {
85
+ const cat = item.category || 'General';
86
+ if (!acc[cat]) acc[cat] = [];
87
+ acc[cat].push(item);
88
+ return acc;
89
+ }, {});
90
+ const lines = Object.entries(grouped).map(([cat, items]) =>
91
+ `## ${cat}\n${(items as any[]).map((i: any) => `- [${i.checked ? 'x' : ' '}] ${i.name}`).join('\n')}`
92
+ ).join('\n\n');
93
+ const { trip } = getTripSummary(tripId) || {};
94
+ return {
95
+ description: `Packing list for "${trip?.title || tripId}"`,
96
+ 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_` } }],
97
+ };
98
+ }
99
+ );
100
+
101
+ if (isAddonEnabled(ADDON_IDS.BUDGET)) server.registerPrompt(
102
+ 'budget-overview',
103
+ {
104
+ title: 'Budget Overview',
105
+ description: 'Get a formatted budget summary for a trip',
106
+ argsSchema: {
107
+ tripId: z.number().int().positive().describe('Trip ID'),
108
+ },
109
+ },
110
+ async ({ tripId }) => {
111
+ if (!canAccessTrip(tripId, userId)) {
112
+ return { messages: [{ role: 'user', content: { type: 'text', text: 'Trip not found or access denied.' } }] };
113
+ }
114
+ const summary = getTripSummary(tripId);
115
+ if (!summary) {
116
+ return { messages: [{ role: 'user', content: { type: 'text', text: 'Trip not found.' } }] };
117
+ }
118
+ const { trip, budget } = summary;
119
+ const currency = trip?.currency || 'EUR';
120
+ const byCategory = (budget?.items || []).reduce((acc: Record<string, number>, item: any) => {
121
+ const cat = item.category || 'Uncategorized';
122
+ acc[cat] = (acc[cat] || 0) + (item.total_price || 0);
123
+ return acc;
124
+ }, {} as Record<string, number>);
125
+ const total = Object.values(byCategory).reduce((s, v) => s + v, 0);
126
+ const lines = Object.entries(byCategory)
127
+ .sort(([, a], [, b]) => b - a)
128
+ .map(([cat, amount]) => `- ${cat}: ${amount} ${currency}`)
129
+ .join('\n');
130
+ const memberCount = Math.max(1, [summary.members?.owner, ...(summary.members?.collaborators || [])].filter(Boolean).length);
131
+ const perPerson = (total / memberCount).toFixed(2);
132
+ return {
133
+ description: `Budget overview for "${trip?.title || tripId}"`,
134
+ 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.'}` } }],
135
+ };
136
+ }
137
+ );
138
+ }
server/src/mcp/tools/reservations.ts ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
2
+ import { z } from 'zod';
3
+ import { canAccessTrip } from '../../db/database';
4
+ import { isDemoUser } from '../../services/authService';
5
+ import {
6
+ createReservation, getReservation, updateReservation, deleteReservation,
7
+ updatePositions as updateReservationPositions,
8
+ } from '../../services/reservationService';
9
+ import { linkBudgetItemToReservation } from '../../services/budgetService';
10
+ import { getDay } from '../../services/dayService';
11
+ import { placeExists, getAssignmentForTrip } from '../../services/assignmentService';
12
+ import {
13
+ safeBroadcast, TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE,
14
+ TOOL_ANNOTATIONS_NON_IDEMPOTENT,
15
+ demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
16
+ } from './_shared';
17
+ import { canWrite } from '../scopes';
18
+
19
+ export function registerReservationTools(server: McpServer, userId: number, scopes: string[] | null): void {
20
+ if (!canWrite(scopes, 'reservations')) return;
21
+
22
+
23
+ server.registerTool(
24
+ 'create_reservation',
25
+ {
26
+ 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.',
27
+ inputSchema: {
28
+ tripId: z.number().int().positive(),
29
+ title: z.string().min(1).max(200),
30
+ type: z.enum(['hotel', 'restaurant', 'event', 'tour', 'activity', 'other']).describe('Reservation type: "hotel", "restaurant", "event", "tour", "activity", or "other"'),
31
+ reservation_time: z.string().optional().describe('ISO 8601 datetime or time string'),
32
+ location: z.string().max(500).optional(),
33
+ confirmation_number: z.string().max(100).optional(),
34
+ notes: z.string().max(1000).optional(),
35
+ day_id: z.number().int().positive().optional(),
36
+ place_id: z.number().int().positive().optional().describe('Hotel place to link (hotel type only)'),
37
+ start_day_id: z.number().int().positive().optional().describe('Check-in day (hotel type only; requires place_id and end_day_id)'),
38
+ end_day_id: z.number().int().positive().optional().describe('Check-out day (hotel type only; requires place_id and start_day_id)'),
39
+ check_in: z.string().max(10).optional().describe('Check-in time (e.g. "15:00", hotel type only)'),
40
+ check_out: z.string().max(10).optional().describe('Check-out time (e.g. "11:00", hotel type only)'),
41
+ assignment_id: z.number().int().positive().optional().describe('Link to a day assignment (restaurant, train, car, cruise, event, tour, activity, other)'),
42
+ price: z.number().nonnegative().optional().describe('Reservation cost — shown on the booking and linked in the Budget tab'),
43
+ budget_category: z.string().max(100).optional().describe('Budget category for the price entry (defaults to reservation type)'),
44
+ },
45
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
46
+ },
47
+ 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 }) => {
48
+ if (isDemoUser(userId)) return demoDenied();
49
+ if (!canAccessTrip(tripId, userId)) return noAccess();
50
+ if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied();
51
+
52
+ // Validate that all referenced IDs belong to this trip
53
+ if (day_id && !getDay(day_id, tripId))
54
+ return { content: [{ type: 'text' as const, text: 'day_id does not belong to this trip.' }], isError: true };
55
+ if (place_id && !placeExists(place_id, tripId))
56
+ return { content: [{ type: 'text' as const, text: 'place_id does not belong to this trip.' }], isError: true };
57
+ if (start_day_id && !getDay(start_day_id, tripId))
58
+ return { content: [{ type: 'text' as const, text: 'start_day_id does not belong to this trip.' }], isError: true };
59
+ if (end_day_id && !getDay(end_day_id, tripId))
60
+ return { content: [{ type: 'text' as const, text: 'end_day_id does not belong to this trip.' }], isError: true };
61
+ if (assignment_id && !getAssignmentForTrip(assignment_id, tripId))
62
+ return { content: [{ type: 'text' as const, text: 'assignment_id does not belong to this trip.' }], isError: true };
63
+
64
+ const createAccommodation = (type === 'hotel' && place_id && start_day_id && end_day_id)
65
+ ? { place_id, start_day_id, end_day_id, check_in: check_in || undefined, check_out: check_out || undefined, confirmation: confirmation_number || undefined }
66
+ : undefined;
67
+
68
+ const metadata = price != null ? { price: String(price) } : undefined;
69
+
70
+ const { reservation, accommodationCreated } = createReservation(tripId, {
71
+ title, type, reservation_time, location, confirmation_number,
72
+ notes, day_id, place_id, assignment_id,
73
+ create_accommodation: createAccommodation,
74
+ metadata,
75
+ });
76
+
77
+ if (accommodationCreated) {
78
+ safeBroadcast(tripId, 'accommodation:created', {});
79
+ }
80
+
81
+ if (price != null && price > 0) {
82
+ const item = linkBudgetItemToReservation(tripId, reservation.id, {
83
+ name: title,
84
+ category: budget_category || type,
85
+ total_price: price,
86
+ });
87
+ safeBroadcast(tripId, 'budget:created', { item });
88
+ }
89
+
90
+ safeBroadcast(tripId, 'reservation:created', { reservation });
91
+ return ok({ reservation });
92
+ }
93
+ );
94
+
95
+ server.registerTool(
96
+ 'update_reservation',
97
+ {
98
+ 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.',
99
+ inputSchema: {
100
+ tripId: z.number().int().positive(),
101
+ reservationId: z.number().int().positive(),
102
+ title: z.string().min(1).max(200).optional(),
103
+ type: z.enum(['hotel', 'restaurant', 'event', 'tour', 'activity', 'other']).optional().describe('Reservation type: "hotel", "restaurant", "event", "tour", "activity", or "other"'),
104
+ reservation_time: z.string().optional().describe('ISO 8601 datetime or time string'),
105
+ location: z.string().max(500).optional(),
106
+ confirmation_number: z.string().max(100).optional(),
107
+ notes: z.string().max(1000).optional(),
108
+ status: z.enum(['pending', 'confirmed', 'cancelled']).optional().describe('Reservation status: "pending", "confirmed", or "cancelled"'),
109
+ place_id: z.number().int().positive().nullable().optional().describe('Link to a place (use for hotel type), or null to unlink'),
110
+ 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'),
111
+ },
112
+ annotations: TOOL_ANNOTATIONS_WRITE,
113
+ },
114
+ async ({ tripId, reservationId, title, type, reservation_time, location, confirmation_number, notes, status, place_id, assignment_id }) => {
115
+ if (isDemoUser(userId)) return demoDenied();
116
+ if (!canAccessTrip(tripId, userId)) return noAccess();
117
+ if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied();
118
+ const existing = getReservation(reservationId, tripId);
119
+ if (!existing) return { content: [{ type: 'text' as const, text: 'Reservation not found.' }], isError: true };
120
+
121
+ if (place_id != null && !placeExists(place_id, tripId))
122
+ return { content: [{ type: 'text' as const, text: 'place_id does not belong to this trip.' }], isError: true };
123
+ if (assignment_id != null && !getAssignmentForTrip(assignment_id, tripId))
124
+ return { content: [{ type: 'text' as const, text: 'assignment_id does not belong to this trip.' }], isError: true };
125
+
126
+ const { reservation } = updateReservation(reservationId, tripId, {
127
+ title, type, reservation_time, location, confirmation_number, notes, status,
128
+ place_id: place_id !== undefined ? place_id ?? undefined : undefined,
129
+ assignment_id: assignment_id !== undefined ? assignment_id ?? undefined : undefined,
130
+ }, existing);
131
+ safeBroadcast(tripId, 'reservation:updated', { reservation });
132
+ return ok({ reservation });
133
+ }
134
+ );
135
+
136
+ server.registerTool(
137
+ 'delete_reservation',
138
+ {
139
+ description: 'Delete a reservation from a trip.',
140
+ inputSchema: {
141
+ tripId: z.number().int().positive(),
142
+ reservationId: z.number().int().positive(),
143
+ },
144
+ annotations: TOOL_ANNOTATIONS_DELETE,
145
+ },
146
+ async ({ tripId, reservationId }) => {
147
+ if (isDemoUser(userId)) return demoDenied();
148
+ if (!canAccessTrip(tripId, userId)) return noAccess();
149
+ if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied();
150
+ const { deleted, accommodationDeleted } = deleteReservation(reservationId, tripId);
151
+ if (!deleted) return { content: [{ type: 'text' as const, text: 'Reservation not found.' }], isError: true };
152
+ if (accommodationDeleted) {
153
+ safeBroadcast(tripId, 'accommodation:deleted', { accommodationId: deleted.accommodation_id });
154
+ }
155
+ safeBroadcast(tripId, 'reservation:deleted', { reservationId });
156
+ return ok({ success: true });
157
+ }
158
+ );
159
+
160
+ server.registerTool(
161
+ 'reorder_reservations',
162
+ {
163
+ description: 'Update the display order of reservations within a day.',
164
+ inputSchema: {
165
+ tripId: z.number().int().positive(),
166
+ positions: z.array(z.object({
167
+ id: z.number().int().positive(),
168
+ day_plan_position: z.number().int().min(0),
169
+ })).describe('Array of { id, day_plan_position } pairs'),
170
+ dayId: z.number().int().positive().optional().describe('Optionally scope the update to a specific day'),
171
+ },
172
+ annotations: TOOL_ANNOTATIONS_WRITE,
173
+ },
174
+ async ({ tripId, positions, dayId }) => {
175
+ if (isDemoUser(userId)) return demoDenied();
176
+ if (!canAccessTrip(tripId, userId)) return noAccess();
177
+ if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied();
178
+ updateReservationPositions(tripId, positions, dayId);
179
+ safeBroadcast(tripId, 'reservation:positions', { positions, dayId });
180
+ return ok({ success: true });
181
+ }
182
+ );
183
+
184
+ server.registerTool(
185
+ 'link_hotel_accommodation',
186
+ {
187
+ 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.',
188
+ inputSchema: {
189
+ tripId: z.number().int().positive(),
190
+ reservationId: z.number().int().positive(),
191
+ place_id: z.number().int().positive().describe('The hotel place to link'),
192
+ start_day_id: z.number().int().positive().describe('Check-in day ID'),
193
+ end_day_id: z.number().int().positive().describe('Check-out day ID'),
194
+ check_in: z.string().max(10).optional().describe('Check-in time (e.g. "15:00")'),
195
+ check_out: z.string().max(10).optional().describe('Check-out time (e.g. "11:00")'),
196
+ },
197
+ annotations: TOOL_ANNOTATIONS_WRITE,
198
+ },
199
+ async ({ tripId, reservationId, place_id, start_day_id, end_day_id, check_in, check_out }) => {
200
+ if (isDemoUser(userId)) return demoDenied();
201
+ if (!canAccessTrip(tripId, userId)) return noAccess();
202
+ if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied();
203
+ const current = getReservation(reservationId, tripId);
204
+ if (!current) return { content: [{ type: 'text' as const, text: 'Reservation not found.' }], isError: true };
205
+ if (current.type !== 'hotel') return { content: [{ type: 'text' as const, text: 'Reservation is not of type hotel.' }], isError: true };
206
+
207
+ if (!placeExists(place_id, tripId))
208
+ return { content: [{ type: 'text' as const, text: 'place_id does not belong to this trip.' }], isError: true };
209
+ if (!getDay(start_day_id, tripId))
210
+ return { content: [{ type: 'text' as const, text: 'start_day_id does not belong to this trip.' }], isError: true };
211
+ if (!getDay(end_day_id, tripId))
212
+ return { content: [{ type: 'text' as const, text: 'end_day_id does not belong to this trip.' }], isError: true };
213
+
214
+ const isNewAccommodation = !current.accommodation_id;
215
+ const { reservation } = updateReservation(reservationId, tripId, {
216
+ place_id,
217
+ type: current.type,
218
+ status: current.status as string,
219
+ create_accommodation: { place_id, start_day_id, end_day_id, check_in: check_in || undefined, check_out: check_out || undefined },
220
+ }, current);
221
+
222
+ safeBroadcast(tripId, isNewAccommodation ? 'accommodation:created' : 'accommodation:updated', {});
223
+ safeBroadcast(tripId, 'reservation:updated', { reservation });
224
+ return ok({ reservation, accommodation_id: (reservation as any).accommodation_id });
225
+ }
226
+ );
227
+ }
server/src/mcp/tools/tags.ts ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
2
+ import { z } from 'zod';
3
+ import { isDemoUser } from '../../services/authService';
4
+ import { listTags, createTag, getTagByIdAndUser, updateTag, deleteTag } from '../../services/tagService';
5
+ import {
6
+ TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
7
+ TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
8
+ demoDenied, ok,
9
+ } from './_shared';
10
+ import { canRead, canWrite } from '../scopes';
11
+
12
+ export function registerTagTools(server: McpServer, userId: number, scopes: string[] | null): void {
13
+ const R = canRead(scopes, 'places');
14
+ const W = canWrite(scopes, 'places');
15
+
16
+ // --- TAGS ---
17
+
18
+ if (R) server.registerTool(
19
+ 'list_tags',
20
+ {
21
+ description: 'List all tags belonging to the current user.',
22
+ inputSchema: {},
23
+ annotations: TOOL_ANNOTATIONS_READONLY,
24
+ },
25
+ async () => {
26
+ const tags = listTags(userId);
27
+ return ok({ tags });
28
+ }
29
+ );
30
+
31
+ if (W) server.registerTool(
32
+ 'create_tag',
33
+ {
34
+ description: 'Create a new tag (user-scoped label for places).',
35
+ inputSchema: {
36
+ name: z.string().min(1).max(100),
37
+ color: z.string().optional().describe('Hex color string e.g. #6366f1'),
38
+ },
39
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
40
+ },
41
+ async ({ name, color }) => {
42
+ if (isDemoUser(userId)) return demoDenied();
43
+ const tag = createTag(userId, name, color);
44
+ return ok({ tag });
45
+ }
46
+ );
47
+
48
+ if (W) server.registerTool(
49
+ 'update_tag',
50
+ {
51
+ description: 'Update the name or color of an existing tag.',
52
+ inputSchema: {
53
+ tagId: z.number().int().positive(),
54
+ name: z.string().optional(),
55
+ color: z.string().optional(),
56
+ },
57
+ annotations: TOOL_ANNOTATIONS_WRITE,
58
+ },
59
+ async ({ tagId, name, color }) => {
60
+ if (isDemoUser(userId)) return demoDenied();
61
+ if (!getTagByIdAndUser(tagId, userId)) return { content: [{ type: 'text' as const, text: 'Tag not found.' }], isError: true };
62
+ const tag = updateTag(tagId, name, color);
63
+ if (!tag) return { content: [{ type: 'text' as const, text: 'Tag not found.' }], isError: true };
64
+ return ok({ tag });
65
+ }
66
+ );
67
+
68
+ if (W) server.registerTool(
69
+ 'delete_tag',
70
+ {
71
+ description: 'Delete a tag (removes it from all places it was attached to).',
72
+ inputSchema: {
73
+ tagId: z.number().int().positive(),
74
+ },
75
+ annotations: TOOL_ANNOTATIONS_DELETE,
76
+ },
77
+ async ({ tagId }) => {
78
+ if (isDemoUser(userId)) return demoDenied();
79
+ if (!getTagByIdAndUser(tagId, userId)) return { content: [{ type: 'text' as const, text: 'Tag not found.' }], isError: true };
80
+ deleteTag(tagId);
81
+ return ok({ success: true });
82
+ }
83
+ );
84
+ }
server/src/mcp/tools/todos.ts ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
2
+ import { z } from 'zod';
3
+ import { canAccessTrip } from '../../db/database';
4
+ import { isDemoUser } from '../../services/authService';
5
+ import {
6
+ listItems as listTodoItems, createItem as createTodoItem, updateItem as updateTodoItem,
7
+ deleteItem as deleteTodoItem, reorderItems as reorderTodoItems,
8
+ getCategoryAssignees as getTodoCategoryAssignees, updateCategoryAssignees as updateTodoCategoryAssignees,
9
+ } from '../../services/todoService';
10
+ import {
11
+ safeBroadcast, TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
12
+ TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
13
+ demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
14
+ } from './_shared';
15
+ import { canRead, canWrite } from '../scopes';
16
+ import { isAddonEnabled } from '../../services/adminService';
17
+ import { ADDON_IDS } from '../../addons';
18
+
19
+ export function registerTodoTools(server: McpServer, userId: number, scopes: string[] | null): void {
20
+ const R = canRead(scopes, 'todos');
21
+ const W = canWrite(scopes, 'todos');
22
+
23
+ if (!isAddonEnabled(ADDON_IDS.PACKING)) return;
24
+
25
+ // --- TODOS ---
26
+
27
+ if (R) server.registerTool(
28
+ 'list_todos',
29
+ {
30
+ description: 'List all to-do items for a trip, ordered by position.',
31
+ inputSchema: {
32
+ tripId: z.number().int().positive(),
33
+ },
34
+ annotations: TOOL_ANNOTATIONS_READONLY,
35
+ },
36
+ async ({ tripId }) => {
37
+ if (!canAccessTrip(tripId, userId)) return noAccess();
38
+ const items = listTodoItems(tripId);
39
+ return ok({ items });
40
+ }
41
+ );
42
+
43
+ if (W) server.registerTool(
44
+ 'create_todo',
45
+ {
46
+ description: 'Create a new to-do item for a trip.',
47
+ inputSchema: {
48
+ tripId: z.number().int().positive(),
49
+ name: z.string().min(1).max(500).describe('To-do item name'),
50
+ category: z.string().max(100).optional().describe('Category (e.g. "Logistics", "Booking")'),
51
+ due_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Due date (YYYY-MM-DD)'),
52
+ description: z.string().max(2000).optional().describe('Additional description'),
53
+ assigned_user_id: z.number().int().positive().optional().describe('User ID to assign this task to'),
54
+ priority: z.number().int().min(0).max(3).optional().describe('Priority: 0=none, 1=low, 2=medium, 3=high'),
55
+ },
56
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
57
+ },
58
+ async ({ tripId, name, category, due_date, description, assigned_user_id, priority }) => {
59
+ if (isDemoUser(userId)) return demoDenied();
60
+ if (!canAccessTrip(tripId, userId)) return noAccess();
61
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
62
+ const item = createTodoItem(tripId, { name, category, due_date, description, assigned_user_id, priority });
63
+ safeBroadcast(tripId, 'todo:created', { item });
64
+ return ok({ item });
65
+ }
66
+ );
67
+
68
+ if (W) server.registerTool(
69
+ 'update_todo',
70
+ {
71
+ description: 'Update an existing to-do item. Only provided fields are changed; omitted fields stay as-is. Pass null to clear a nullable field.',
72
+ inputSchema: {
73
+ tripId: z.number().int().positive(),
74
+ itemId: z.number().int().positive(),
75
+ name: z.string().min(1).max(500).optional(),
76
+ category: z.string().max(100).optional(),
77
+ due_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).nullable().optional().describe('Set to null to clear the due date'),
78
+ description: z.string().max(2000).nullable().optional().describe('Set to null to clear'),
79
+ assigned_user_id: z.number().int().positive().nullable().optional().describe('Set to null to unassign'),
80
+ priority: z.number().int().min(0).max(3).nullable().optional(),
81
+ },
82
+ annotations: TOOL_ANNOTATIONS_WRITE,
83
+ },
84
+ async ({ tripId, itemId, name, category, due_date, description, assigned_user_id, priority }) => {
85
+ if (isDemoUser(userId)) return demoDenied();
86
+ if (!canAccessTrip(tripId, userId)) return noAccess();
87
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
88
+ // Build bodyKeys to signal which nullable fields were explicitly provided
89
+ const bodyKeys: string[] = [];
90
+ if (due_date !== undefined) bodyKeys.push('due_date');
91
+ if (description !== undefined) bodyKeys.push('description');
92
+ if (assigned_user_id !== undefined) bodyKeys.push('assigned_user_id');
93
+ if (priority !== undefined) bodyKeys.push('priority');
94
+ const item = updateTodoItem(tripId, itemId, { name, category, due_date, description, assigned_user_id, priority }, bodyKeys);
95
+ if (!item) return { content: [{ type: 'text' as const, text: 'To-do item not found.' }], isError: true };
96
+ safeBroadcast(tripId, 'todo:updated', { item });
97
+ return ok({ item });
98
+ }
99
+ );
100
+
101
+ if (W) server.registerTool(
102
+ 'toggle_todo',
103
+ {
104
+ description: 'Mark a to-do item as checked (done) or unchecked.',
105
+ inputSchema: {
106
+ tripId: z.number().int().positive(),
107
+ itemId: z.number().int().positive(),
108
+ checked: z.boolean().describe('True to mark done, false to uncheck'),
109
+ },
110
+ annotations: TOOL_ANNOTATIONS_WRITE,
111
+ },
112
+ async ({ tripId, itemId, checked }) => {
113
+ if (isDemoUser(userId)) return demoDenied();
114
+ if (!canAccessTrip(tripId, userId)) return noAccess();
115
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
116
+ const item = updateTodoItem(tripId, itemId, { checked: checked ? 1 : 0 }, []);
117
+ if (!item) return { content: [{ type: 'text' as const, text: 'To-do item not found.' }], isError: true };
118
+ safeBroadcast(tripId, 'todo:updated', { item });
119
+ return ok({ item });
120
+ }
121
+ );
122
+
123
+ if (W) server.registerTool(
124
+ 'delete_todo',
125
+ {
126
+ description: 'Delete a to-do item.',
127
+ inputSchema: {
128
+ tripId: z.number().int().positive(),
129
+ itemId: z.number().int().positive(),
130
+ },
131
+ annotations: TOOL_ANNOTATIONS_DELETE,
132
+ },
133
+ async ({ tripId, itemId }) => {
134
+ if (isDemoUser(userId)) return demoDenied();
135
+ if (!canAccessTrip(tripId, userId)) return noAccess();
136
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
137
+ const deleted = deleteTodoItem(tripId, itemId);
138
+ if (!deleted) return { content: [{ type: 'text' as const, text: 'To-do item not found.' }], isError: true };
139
+ safeBroadcast(tripId, 'todo:deleted', { itemId });
140
+ return ok({ success: true });
141
+ }
142
+ );
143
+
144
+ if (W) server.registerTool(
145
+ 'reorder_todos',
146
+ {
147
+ description: 'Reorder to-do items within a trip by providing a new ordered list of item IDs.',
148
+ inputSchema: {
149
+ tripId: z.number().int().positive(),
150
+ orderedIds: z.array(z.number().int().positive()).min(1).describe('All item IDs in the desired order'),
151
+ },
152
+ annotations: TOOL_ANNOTATIONS_WRITE,
153
+ },
154
+ async ({ tripId, orderedIds }) => {
155
+ if (isDemoUser(userId)) return demoDenied();
156
+ if (!canAccessTrip(tripId, userId)) return noAccess();
157
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
158
+ reorderTodoItems(tripId, orderedIds);
159
+ return ok({ success: true });
160
+ }
161
+ );
162
+
163
+ if (R) server.registerTool(
164
+ 'get_todo_category_assignees',
165
+ {
166
+ description: 'Get the default assignees configured per to-do category for a trip.',
167
+ inputSchema: {
168
+ tripId: z.number().int().positive(),
169
+ },
170
+ annotations: TOOL_ANNOTATIONS_READONLY,
171
+ },
172
+ async ({ tripId }) => {
173
+ if (!canAccessTrip(tripId, userId)) return noAccess();
174
+ const assignees = getTodoCategoryAssignees(tripId);
175
+ return ok({ assignees });
176
+ }
177
+ );
178
+
179
+ if (W) server.registerTool(
180
+ 'set_todo_category_assignees',
181
+ {
182
+ description: 'Set the default assignees for a to-do category on a trip. Pass an empty array to clear.',
183
+ inputSchema: {
184
+ tripId: z.number().int().positive(),
185
+ categoryName: z.string().min(1).max(100).describe('Category name'),
186
+ userIds: z.array(z.number().int().positive()).describe('User IDs to assign as defaults for this category'),
187
+ },
188
+ annotations: TOOL_ANNOTATIONS_WRITE,
189
+ },
190
+ async ({ tripId, categoryName, userIds }) => {
191
+ if (isDemoUser(userId)) return demoDenied();
192
+ if (!canAccessTrip(tripId, userId)) return noAccess();
193
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
194
+ const assignees = updateTodoCategoryAssignees(tripId, categoryName, userIds);
195
+ safeBroadcast(tripId, 'todo:assignees', { category: categoryName, assignees });
196
+ return ok({ assignees });
197
+ }
198
+ );
199
+ }
server/src/mcp/tools/transports.ts ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
2
+ import { z } from 'zod';
3
+ import { canAccessTrip } from '../../db/database';
4
+ import { isDemoUser } from '../../services/authService';
5
+ import {
6
+ createReservation, deleteReservation, getReservation, updateReservation,
7
+ } from '../../services/reservationService';
8
+ import { linkBudgetItemToReservation } from '../../services/budgetService';
9
+ import { getDay } from '../../services/dayService';
10
+ import {
11
+ safeBroadcast, TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
12
+ TOOL_ANNOTATIONS_WRITE, demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
13
+ } from './_shared';
14
+ import { canWrite } from '../scopes';
15
+
16
+ const TRANSPORT_TYPES = ['flight', 'train', 'car', 'cruise'] as const;
17
+
18
+ const endpointSchema = z.array(z.object({
19
+ role: z.enum(['from', 'to', 'stop']).describe('Endpoint role: "from" (origin), "to" (destination), or "stop" (intermediate)'),
20
+ sequence: z.number().int().min(0).describe('Order within the route (0-based)'),
21
+ name: z.string().min(1).describe('Location name (e.g. "Paris Gare de Lyon", "ZRH Terminal 2")'),
22
+ code: z.string().optional().describe('IATA airport code for flights (e.g. "ZRH"). Leave empty for other transport types.'),
23
+ lat: z.number().optional(),
24
+ lng: z.number().optional(),
25
+ timezone: z.string().optional().describe('IANA timezone (e.g. "Europe/Zurich"). Use airport tz for flights.'),
26
+ local_time: z.string().optional().describe('Local departure/arrival time at this endpoint, e.g. "14:35"'),
27
+ local_date: z.string().optional().describe('Local date at this endpoint, YYYY-MM-DD'),
28
+ })).optional();
29
+
30
+ export function registerTransportTools(server: McpServer, userId: number, scopes: string[] | null): void {
31
+ if (!canWrite(scopes, 'reservations')) return;
32
+
33
+ server.registerTool(
34
+ 'create_transport',
35
+ {
36
+ 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.',
37
+ inputSchema: {
38
+ tripId: z.number().int().positive(),
39
+ type: z.enum(['flight', 'train', 'car', 'cruise']),
40
+ title: z.string().min(1).max(200),
41
+ status: z.enum(['pending', 'confirmed', 'cancelled']).optional().default('pending'),
42
+ start_day_id: z.number().int().positive().optional().describe('Departure day'),
43
+ end_day_id: z.number().int().positive().optional().describe('Arrival day (if different from departure)'),
44
+ reservation_time: z.string().optional().describe('ISO 8601 datetime or time string for departure'),
45
+ reservation_end_time: z.string().optional().describe('ISO 8601 datetime or time string for arrival'),
46
+ confirmation_number: z.string().max(100).optional(),
47
+ notes: z.string().max(1000).optional(),
48
+ 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 }'),
49
+ endpoints: endpointSchema,
50
+ needs_review: z.boolean().optional(),
51
+ price: z.number().nonnegative().optional().describe('Transport cost — shown on the booking and linked in the Budget tab'),
52
+ budget_category: z.string().max(100).optional().describe('Budget category for the price entry (defaults to transport type)'),
53
+ },
54
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
55
+ },
56
+ 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 }) => {
57
+ if (isDemoUser(userId)) return demoDenied();
58
+ if (!canAccessTrip(tripId, userId)) return noAccess();
59
+ if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied();
60
+
61
+ if (start_day_id && !getDay(start_day_id, tripId))
62
+ return { content: [{ type: 'text' as const, text: 'start_day_id does not belong to this trip.' }], isError: true };
63
+ if (end_day_id && !getDay(end_day_id, tripId))
64
+ return { content: [{ type: 'text' as const, text: 'end_day_id does not belong to this trip.' }], isError: true };
65
+
66
+ const meta: Record<string, string> = { ...(metadata ?? {}) };
67
+ if (price != null) meta.price = String(price);
68
+
69
+ const { reservation } = createReservation(tripId, {
70
+ title,
71
+ type,
72
+ reservation_time,
73
+ reservation_end_time,
74
+ location: undefined,
75
+ confirmation_number,
76
+ notes,
77
+ day_id: start_day_id,
78
+ end_day_id: end_day_id ?? start_day_id,
79
+ status: status ?? 'pending',
80
+ metadata: Object.keys(meta).length > 0 ? meta : undefined,
81
+ endpoints,
82
+ needs_review,
83
+ });
84
+
85
+ if (price != null && price > 0) {
86
+ const item = linkBudgetItemToReservation(tripId, reservation.id, {
87
+ name: title,
88
+ category: budget_category || type,
89
+ total_price: price,
90
+ });
91
+ safeBroadcast(tripId, 'budget:created', { item });
92
+ }
93
+
94
+ safeBroadcast(tripId, 'reservation:created', { reservation });
95
+ return ok({ reservation });
96
+ }
97
+ );
98
+
99
+ server.registerTool(
100
+ 'update_transport',
101
+ {
102
+ description: 'Update an existing transport booking. Pass endpoints[] to replace the full list of stops (origin, destination, intermediates). Use status "confirmed" to confirm.',
103
+ inputSchema: {
104
+ tripId: z.number().int().positive(),
105
+ reservationId: z.number().int().positive(),
106
+ type: z.enum(['flight', 'train', 'car', 'cruise']).optional(),
107
+ title: z.string().min(1).max(200).optional(),
108
+ status: z.enum(['pending', 'confirmed', 'cancelled']).optional(),
109
+ start_day_id: z.number().int().positive().optional().describe('Departure day'),
110
+ end_day_id: z.number().int().positive().optional().describe('Arrival day (if different from departure)'),
111
+ reservation_time: z.string().optional().describe('ISO 8601 datetime or time string for departure'),
112
+ reservation_end_time: z.string().optional().describe('ISO 8601 datetime or time string for arrival'),
113
+ confirmation_number: z.string().max(100).optional(),
114
+ notes: z.string().max(1000).optional(),
115
+ 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 }'),
116
+ endpoints: endpointSchema,
117
+ needs_review: z.boolean().optional(),
118
+ },
119
+ annotations: TOOL_ANNOTATIONS_WRITE,
120
+ },
121
+ async ({ tripId, reservationId, type, title, status, start_day_id, end_day_id, reservation_time, reservation_end_time, confirmation_number, notes, metadata, endpoints, needs_review }) => {
122
+ if (isDemoUser(userId)) return demoDenied();
123
+ if (!canAccessTrip(tripId, userId)) return noAccess();
124
+ if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied();
125
+
126
+ const existing = getReservation(reservationId, tripId);
127
+ if (!existing) return { content: [{ type: 'text' as const, text: 'Transport not found.' }], isError: true };
128
+
129
+ const resolvedType = type ?? existing.type;
130
+ if (!(TRANSPORT_TYPES as readonly string[]).includes(resolvedType))
131
+ return { content: [{ type: 'text' as const, text: 'Reservation is not a transport type. Use update_reservation instead.' }], isError: true };
132
+
133
+ if (start_day_id && !getDay(start_day_id, tripId))
134
+ return { content: [{ type: 'text' as const, text: 'start_day_id does not belong to this trip.' }], isError: true };
135
+ if (end_day_id && !getDay(end_day_id, tripId))
136
+ return { content: [{ type: 'text' as const, text: 'end_day_id does not belong to this trip.' }], isError: true };
137
+
138
+ const { reservation } = updateReservation(reservationId, tripId, {
139
+ title,
140
+ type,
141
+ reservation_time,
142
+ reservation_end_time,
143
+ confirmation_number,
144
+ notes,
145
+ day_id: start_day_id,
146
+ end_day_id,
147
+ status,
148
+ metadata,
149
+ endpoints,
150
+ needs_review,
151
+ }, existing);
152
+ safeBroadcast(tripId, 'reservation:updated', { reservation });
153
+ return ok({ reservation });
154
+ }
155
+ );
156
+
157
+ server.registerTool(
158
+ 'delete_transport',
159
+ {
160
+ description: 'Delete a transport booking from a trip.',
161
+ inputSchema: {
162
+ tripId: z.number().int().positive(),
163
+ reservationId: z.number().int().positive(),
164
+ },
165
+ annotations: TOOL_ANNOTATIONS_DELETE,
166
+ },
167
+ async ({ tripId, reservationId }) => {
168
+ if (isDemoUser(userId)) return demoDenied();
169
+ if (!canAccessTrip(tripId, userId)) return noAccess();
170
+ if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied();
171
+ const { deleted } = deleteReservation(reservationId, tripId);
172
+ if (!deleted) return { content: [{ type: 'text' as const, text: 'Transport not found.' }], isError: true };
173
+ safeBroadcast(tripId, 'reservation:deleted', { reservationId });
174
+ return ok({ success: true });
175
+ }
176
+ );
177
+ }
server/src/mcp/tools/trips.ts ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
2
+ import { z } from 'zod';
3
+ import { canAccessTrip } from '../../db/database';
4
+ import { isDemoUser } from '../../services/authService';
5
+ import {
6
+ listTrips, createTrip, updateTrip, deleteTrip, getTripSummary,
7
+ isOwner, verifyTripAccess,
8
+ listMembers as listTripMembers, getTripOwner, addMember as addTripMember,
9
+ removeMember as removeTripMember,
10
+ copyTripById, exportICS, NotFoundError, ValidationError,
11
+ } from '../../services/tripService';
12
+ import {
13
+ createOrUpdateShareLink, getShareLink, deleteShareLink,
14
+ } from '../../services/shareService';
15
+ import { isAddonEnabled, getCollabFeatures } from '../../services/adminService';
16
+ import { ADDON_IDS } from '../../addons';
17
+ import { countMessages, listPolls } from '../../services/collabService';
18
+ import {
19
+ listItems as listTodoItems,
20
+ } from '../../services/todoService';
21
+ import {
22
+ safeBroadcast, MAX_MCP_TRIP_DAYS,
23
+ TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
24
+ TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
25
+ demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
26
+ } from './_shared';
27
+ import { canRead, canReadTrips, canWrite, canDeleteTrips, canShareTrips } from '../scopes';
28
+
29
+ export function registerTripTools(server: McpServer, userId: number, scopes: string[] | null, getDeprecationNotice: () => string | null = () => null): void {
30
+ const R = canReadTrips(scopes);
31
+ const W = canWrite(scopes, 'trips');
32
+ const D = canDeleteTrips(scopes);
33
+ const S = canShareTrips(scopes);
34
+
35
+ // --- TRIPS ---
36
+
37
+ if (W) server.registerTool(
38
+ 'create_trip',
39
+ {
40
+ description: 'Create a new trip. Returns the created trip with its generated days.',
41
+ inputSchema: {
42
+ title: z.string().min(1).max(200).describe('Trip title'),
43
+ description: z.string().max(2000).optional().describe('Trip description'),
44
+ start_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Start date (YYYY-MM-DD)'),
45
+ end_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('End date (YYYY-MM-DD)'),
46
+ currency: z.string().length(3).optional().describe('Currency code (e.g. EUR, USD)'),
47
+ },
48
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
49
+ },
50
+ async ({ title, description, start_date, end_date, currency }) => {
51
+ if (isDemoUser(userId)) return demoDenied();
52
+ if (start_date) {
53
+ const d = new Date(start_date + 'T00:00:00Z');
54
+ if (isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== start_date)
55
+ return { content: [{ type: 'text' as const, text: 'start_date is not a valid calendar date.' }], isError: true };
56
+ }
57
+ if (end_date) {
58
+ const d = new Date(end_date + 'T00:00:00Z');
59
+ if (isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== end_date)
60
+ return { content: [{ type: 'text' as const, text: 'end_date is not a valid calendar date.' }], isError: true };
61
+ }
62
+ if (start_date && end_date && new Date(end_date) < new Date(start_date)) {
63
+ return { content: [{ type: 'text' as const, text: 'End date must be after start date.' }], isError: true };
64
+ }
65
+ const { trip } = createTrip(userId, { title, description, start_date, end_date, currency }, MAX_MCP_TRIP_DAYS);
66
+ return ok({ trip });
67
+ }
68
+ );
69
+
70
+ if (W) server.registerTool(
71
+ 'update_trip',
72
+ {
73
+ description: 'Update an existing trip\'s details.',
74
+ inputSchema: {
75
+ tripId: z.number().int().positive(),
76
+ title: z.string().min(1).max(200).optional(),
77
+ description: z.string().max(2000).optional(),
78
+ start_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
79
+ end_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
80
+ currency: z.string().length(3).optional(),
81
+ is_archived: z.boolean().optional().describe('Archive (true) or unarchive (false) the trip'),
82
+ cover_image: z.string().optional().describe('Cover image path, e.g. /uploads/covers/abc.jpg'),
83
+ },
84
+ annotations: TOOL_ANNOTATIONS_WRITE,
85
+ },
86
+ async ({ tripId, title, description, start_date, end_date, currency, is_archived, cover_image }) => {
87
+ if (isDemoUser(userId)) return demoDenied();
88
+ if (!canAccessTrip(tripId, userId)) return noAccess();
89
+ if (!hasTripPermission('trip_edit', tripId, userId)) return permissionDenied();
90
+ if (start_date) {
91
+ const d = new Date(start_date + 'T00:00:00Z');
92
+ if (isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== start_date)
93
+ return { content: [{ type: 'text' as const, text: 'start_date is not a valid calendar date.' }], isError: true };
94
+ }
95
+ if (end_date) {
96
+ const d = new Date(end_date + 'T00:00:00Z');
97
+ if (isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== end_date)
98
+ return { content: [{ type: 'text' as const, text: 'end_date is not a valid calendar date.' }], isError: true };
99
+ }
100
+ const { updatedTrip } = updateTrip(tripId, userId, { title, description, start_date, end_date, currency, is_archived, cover_image }, 'user');
101
+ safeBroadcast(tripId, 'trip:updated', { trip: updatedTrip });
102
+ return ok({ trip: updatedTrip });
103
+ }
104
+ );
105
+
106
+ if (D) server.registerTool(
107
+ 'delete_trip',
108
+ {
109
+ description: 'Delete a trip. Only the trip owner can delete it.',
110
+ inputSchema: {
111
+ tripId: z.number().int().positive(),
112
+ },
113
+ annotations: TOOL_ANNOTATIONS_DELETE,
114
+ },
115
+ async ({ tripId }) => {
116
+ if (isDemoUser(userId)) return demoDenied();
117
+ if (!isOwner(tripId, userId)) return noAccess();
118
+ deleteTrip(tripId, userId, 'user');
119
+ return ok({ success: true, tripId });
120
+ }
121
+ );
122
+
123
+ // list_trips and get_trip_summary are always registered regardless of OAuth scopes —
124
+ // they are navigation tools that any MCP client needs to discover trip IDs.
125
+ server.registerTool(
126
+ 'list_trips',
127
+ {
128
+ description: 'List all trips the current user owns or is a member of. Use this for trip discovery before calling get_trip_summary.',
129
+ inputSchema: {
130
+ include_archived: z.boolean().optional().describe('Include archived trips (default false)'),
131
+ },
132
+ annotations: TOOL_ANNOTATIONS_READONLY,
133
+ },
134
+ async ({ include_archived }) => {
135
+ const notice = getDeprecationNotice();
136
+ const trips = listTrips(userId, include_archived ? null : 0);
137
+ if (notice) return {
138
+ isError: true as const,
139
+ content: [
140
+ { type: 'text' as const, text: notice },
141
+ { type: 'text' as const, text: JSON.stringify({ trips }, null, 2) },
142
+ ],
143
+ };
144
+ return ok({ trips });
145
+ }
146
+ );
147
+
148
+ // --- TRIP SUMMARY ---
149
+
150
+ server.registerTool(
151
+ 'get_trip_summary',
152
+ {
153
+ 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.',
154
+ inputSchema: {
155
+ tripId: z.number().int().positive(),
156
+ },
157
+ annotations: TOOL_ANNOTATIONS_READONLY,
158
+ },
159
+ async ({ tripId }) => {
160
+ if (!canAccessTrip(tripId, userId)) return noAccess();
161
+ const summary = getTripSummary(tripId);
162
+ if (!summary) return noAccess();
163
+ // Addon availability gates
164
+ const packingEnabled = isAddonEnabled(ADDON_IDS.PACKING);
165
+ const budgetEnabled = isAddonEnabled(ADDON_IDS.BUDGET);
166
+ const collabEnabled = isAddonEnabled(ADDON_IDS.COLLAB);
167
+ const collabFeatures = collabEnabled ? getCollabFeatures() : null;
168
+ // Scope gates — sections not covered by the client's OAuth scopes are omitted.
169
+ // Core trip data (metadata, days, members, accommodations) is always included
170
+ // because this tool is always registered and needed for navigation.
171
+ const canReadBudget = budgetEnabled && canRead(scopes, 'budget');
172
+ const canReadPacking = packingEnabled && canRead(scopes, 'packing');
173
+ const canReadCollab = collabEnabled && canRead(scopes, 'collab');
174
+ const canReadTodos = packingEnabled && canRead(scopes, 'todos');
175
+ const canReadRes = canRead(scopes, 'reservations');
176
+ const todos = canReadTodos ? listTodoItems(tripId) : [];
177
+ let pollCount = 0;
178
+ let messageCount = 0;
179
+ if (canReadCollab) {
180
+ if (collabFeatures?.polls) pollCount = listPolls(tripId).length;
181
+ if (collabFeatures?.chat) messageCount = countMessages(tripId);
182
+ }
183
+ const notice = getDeprecationNotice();
184
+ const summaryData = {
185
+ ...summary,
186
+ reservations: canReadRes ? summary.reservations : undefined,
187
+ packing: canReadPacking ? summary.packing : undefined,
188
+ budget: canReadBudget ? summary.budget : undefined,
189
+ collab_notes: canReadCollab && collabFeatures?.notes ? summary.collab_notes : [],
190
+ todos,
191
+ pollCount,
192
+ messageCount,
193
+ };
194
+ if (notice) return {
195
+ isError: true as const,
196
+ content: [
197
+ { type: 'text' as const, text: notice },
198
+ { type: 'text' as const, text: JSON.stringify(summaryData, null, 2) },
199
+ ],
200
+ };
201
+ return ok(summaryData);
202
+ }
203
+ );
204
+
205
+ // --- TRIP MEMBERS, COPY, ICS, SHARE ---
206
+
207
+ if (R) server.registerTool(
208
+ 'list_trip_members',
209
+ {
210
+ description: 'List all members of a trip (owner + collaborators).',
211
+ inputSchema: {
212
+ tripId: z.number().int().positive(),
213
+ },
214
+ annotations: TOOL_ANNOTATIONS_READONLY,
215
+ },
216
+ async ({ tripId }) => {
217
+ if (!canAccessTrip(tripId, userId)) return noAccess();
218
+ const ownerRow = getTripOwner(tripId);
219
+ if (!ownerRow) return noAccess();
220
+ const { owner, members } = listTripMembers(tripId, ownerRow.user_id);
221
+ return ok({ owner, members });
222
+ }
223
+ );
224
+
225
+ if (W) server.registerTool(
226
+ 'add_trip_member',
227
+ {
228
+ description: 'Add a user to a trip by their username or email address. Only the trip owner can do this.',
229
+ inputSchema: {
230
+ tripId: z.number().int().positive(),
231
+ identifier: z.string().min(1).describe('Username or email of the user to add'),
232
+ },
233
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
234
+ },
235
+ async ({ tripId, identifier }) => {
236
+ if (isDemoUser(userId)) return demoDenied();
237
+ if (!canAccessTrip(tripId, userId)) return noAccess();
238
+ const ownerRow = getTripOwner(tripId);
239
+ if (!ownerRow || ownerRow.user_id !== userId)
240
+ return { content: [{ type: 'text' as const, text: 'Only the trip owner can add members.' }], isError: true };
241
+ try {
242
+ const result = addTripMember(tripId, identifier, ownerRow.user_id, userId);
243
+ safeBroadcast(tripId, 'member:added', { member: result.member });
244
+ return ok({ member: result.member });
245
+ } catch (err) {
246
+ const msg = err instanceof ValidationError || err instanceof NotFoundError ? err.message : 'Failed to add member.';
247
+ return { content: [{ type: 'text' as const, text: msg }], isError: true };
248
+ }
249
+ }
250
+ );
251
+
252
+ if (W) server.registerTool(
253
+ 'remove_trip_member',
254
+ {
255
+ description: 'Remove a member from a trip. Only the trip owner can do this.',
256
+ inputSchema: {
257
+ tripId: z.number().int().positive(),
258
+ memberId: z.number().int().positive().describe('User ID of the member to remove'),
259
+ },
260
+ annotations: TOOL_ANNOTATIONS_DELETE,
261
+ },
262
+ async ({ tripId, memberId }) => {
263
+ if (isDemoUser(userId)) return demoDenied();
264
+ if (!canAccessTrip(tripId, userId)) return noAccess();
265
+ const ownerRow = getTripOwner(tripId);
266
+ if (!ownerRow || ownerRow.user_id !== userId)
267
+ return { content: [{ type: 'text' as const, text: 'Only the trip owner can remove members.' }], isError: true };
268
+ removeTripMember(tripId, memberId);
269
+ safeBroadcast(tripId, 'member:removed', { userId: memberId });
270
+ return ok({ success: true });
271
+ }
272
+ );
273
+
274
+ if (W) server.registerTool(
275
+ 'copy_trip',
276
+ {
277
+ description: 'Duplicate a trip (all days, places, itinerary, packing, budget, reservations, day notes). Packing items are reset to unchecked. Returns the new trip.',
278
+ inputSchema: {
279
+ tripId: z.number().int().positive().describe('Source trip ID to duplicate'),
280
+ title: z.string().min(1).max(200).optional().describe('Title for the new trip (defaults to source title)'),
281
+ },
282
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
283
+ },
284
+ async ({ tripId, title }) => {
285
+ if (isDemoUser(userId)) return demoDenied();
286
+ if (!canAccessTrip(tripId, userId)) return noAccess();
287
+ try {
288
+ const newTripId = copyTripById(tripId, userId, title);
289
+ const newTrip = canAccessTrip(newTripId, userId);
290
+ return ok({ trip: { id: newTripId, ...newTrip } });
291
+ } catch {
292
+ return { content: [{ type: 'text' as const, text: 'Failed to copy trip.' }], isError: true };
293
+ }
294
+ }
295
+ );
296
+
297
+ if (R) server.registerTool(
298
+ 'export_trip_ics',
299
+ {
300
+ description: 'Export a trip\'s itinerary and reservations as iCalendar (.ics) format text. Useful for importing into calendar apps.',
301
+ inputSchema: {
302
+ tripId: z.number().int().positive(),
303
+ },
304
+ annotations: TOOL_ANNOTATIONS_READONLY,
305
+ },
306
+ async ({ tripId }) => {
307
+ if (!canAccessTrip(tripId, userId)) return noAccess();
308
+ try {
309
+ const { ics, filename } = exportICS(tripId);
310
+ return ok({ ics, filename });
311
+ } catch {
312
+ return { content: [{ type: 'text' as const, text: 'Trip not found.' }], isError: true };
313
+ }
314
+ }
315
+ );
316
+
317
+ if (S) server.registerTool(
318
+ 'get_share_link',
319
+ {
320
+ description: 'Get the current public share link for a trip, including its permission flags. Returns null if no share link exists.',
321
+ inputSchema: {
322
+ tripId: z.number().int().positive(),
323
+ },
324
+ annotations: TOOL_ANNOTATIONS_READONLY,
325
+ },
326
+ async ({ tripId }) => {
327
+ // Read parity with the REST route GET /api/trips/:tripId/share-link, which
328
+ // only requires trip membership (share_manage gates create/delete, not read).
329
+ if (!canAccessTrip(tripId, userId)) return noAccess();
330
+ const link = getShareLink(String(tripId));
331
+ return ok({ link });
332
+ }
333
+ );
334
+
335
+ if (S) server.registerTool(
336
+ 'create_share_link',
337
+ {
338
+ description: 'Create or update the public share link for a trip. Set permission flags to control what is visible to guests.',
339
+ inputSchema: {
340
+ tripId: z.number().int().positive(),
341
+ share_map: z.boolean().optional().default(true).describe('Share the map and places'),
342
+ share_bookings: z.boolean().optional().default(true).describe('Share reservations'),
343
+ share_packing: z.boolean().optional().default(false).describe('Share packing list'),
344
+ share_budget: z.boolean().optional().default(false).describe('Share budget'),
345
+ share_collab: z.boolean().optional().default(false).describe('Share collab messages'),
346
+ },
347
+ annotations: TOOL_ANNOTATIONS_WRITE,
348
+ },
349
+ async ({ tripId, share_map, share_bookings, share_packing, share_budget, share_collab }) => {
350
+ if (isDemoUser(userId)) return demoDenied();
351
+ if (!canAccessTrip(tripId, userId)) return noAccess();
352
+ if (!hasTripPermission('share_manage', tripId, userId)) return permissionDenied();
353
+ const { token, created } = createOrUpdateShareLink(String(tripId), userId, {
354
+ share_map: share_map ?? true,
355
+ share_bookings: share_bookings ?? true,
356
+ share_packing: share_packing ?? false,
357
+ share_budget: share_budget ?? false,
358
+ share_collab: share_collab ?? false,
359
+ });
360
+ return ok({ token, created });
361
+ }
362
+ );
363
+
364
+ if (S) server.registerTool(
365
+ 'delete_share_link',
366
+ {
367
+ description: 'Revoke the public share link for a trip. Guests will no longer be able to access the shared view.',
368
+ inputSchema: {
369
+ tripId: z.number().int().positive(),
370
+ },
371
+ annotations: TOOL_ANNOTATIONS_DELETE,
372
+ },
373
+ async ({ tripId }) => {
374
+ if (isDemoUser(userId)) return demoDenied();
375
+ if (!canAccessTrip(tripId, userId)) return noAccess();
376
+ if (!hasTripPermission('share_manage', tripId, userId)) return permissionDenied();
377
+ deleteShareLink(String(tripId));
378
+ return ok({ success: true });
379
+ }
380
+ );
381
+ }
server/src/mcp/tools/vacay.ts ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
2
+ import { z } from 'zod';
3
+ import { isDemoUser, getCurrentUser } from '../../services/authService';
4
+ import {
5
+ getOwnPlan, getActivePlan, getActivePlanId, getPlanData,
6
+ updatePlan, setUserColor,
7
+ sendInvite as sendVacayInvite, acceptInvite, declineInvite, cancelInvite, dissolvePlan,
8
+ getAvailableUsers,
9
+ listYears, addYear, deleteYear,
10
+ getEntries as getVacayEntries, toggleEntry, toggleCompanyHoliday,
11
+ getStats as getVacayStats, updateStats as updateVacayStats,
12
+ addHolidayCalendar, updateHolidayCalendar, deleteHolidayCalendar,
13
+ getCountries as getHolidayCountries, getHolidays,
14
+ } from '../../services/vacayService';
15
+ import { isAddonEnabled } from '../../services/adminService';
16
+ import { ADDON_IDS } from '../../addons';
17
+ import {
18
+ TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
19
+ TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
20
+ demoDenied, ok,
21
+ } from './_shared';
22
+ import { canRead, canWrite } from '../scopes';
23
+
24
+ export function registerVacayTools(server: McpServer, userId: number, scopes: string[] | null): void {
25
+ const R = canRead(scopes, 'vacay');
26
+ const W = canWrite(scopes, 'vacay');
27
+
28
+ if (isAddonEnabled(ADDON_IDS.VACAY)) {
29
+ if (R) server.registerTool(
30
+ 'get_vacay_plan',
31
+ {
32
+ description: "Get the current user's active vacation plan (own or joined).",
33
+ inputSchema: {},
34
+ annotations: TOOL_ANNOTATIONS_READONLY,
35
+ },
36
+ async () => {
37
+ const plan = getPlanData(userId);
38
+ return ok({ plan });
39
+ }
40
+ );
41
+
42
+ if (W) server.registerTool(
43
+ 'update_vacay_plan',
44
+ {
45
+ description: 'Update vacation plan settings (weekends blocking, holidays, carry-over).',
46
+ inputSchema: {
47
+ block_weekends: z.boolean().optional(),
48
+ holidays_enabled: z.boolean().optional(),
49
+ holidays_region: z.string().nullable().optional(),
50
+ company_holidays_enabled: z.boolean().optional(),
51
+ carry_over_enabled: z.boolean().optional(),
52
+ },
53
+ annotations: TOOL_ANNOTATIONS_WRITE,
54
+ },
55
+ async ({ block_weekends, holidays_enabled, holidays_region, company_holidays_enabled, carry_over_enabled }) => {
56
+ if (isDemoUser(userId)) return demoDenied();
57
+ const planId = getActivePlanId(userId);
58
+ await updatePlan(planId, { block_weekends, holidays_enabled, holidays_region, company_holidays_enabled, carry_over_enabled }, undefined);
59
+ return ok({ success: true });
60
+ }
61
+ );
62
+
63
+ if (W) server.registerTool(
64
+ 'set_vacay_color',
65
+ {
66
+ description: "Set the current user's color in the vacation plan calendar.",
67
+ inputSchema: {
68
+ color: z.string().describe('Hex color e.g. #6366f1'),
69
+ },
70
+ annotations: TOOL_ANNOTATIONS_WRITE,
71
+ },
72
+ async ({ color }) => {
73
+ if (isDemoUser(userId)) return demoDenied();
74
+ const planId = getActivePlanId(userId);
75
+ setUserColor(userId, planId, color, undefined);
76
+ return ok({ success: true });
77
+ }
78
+ );
79
+
80
+ if (R) server.registerTool(
81
+ 'get_available_vacay_users',
82
+ {
83
+ description: 'List users who can be invited to the current vacation plan.',
84
+ inputSchema: {},
85
+ annotations: TOOL_ANNOTATIONS_READONLY,
86
+ },
87
+ async () => {
88
+ const planId = getActivePlanId(userId);
89
+ const users = getAvailableUsers(userId, planId);
90
+ return ok({ users });
91
+ }
92
+ );
93
+
94
+ if (W) server.registerTool(
95
+ 'send_vacay_invite',
96
+ {
97
+ description: 'Invite a user to join the vacation plan by their user ID.',
98
+ inputSchema: {
99
+ targetUserId: z.number().int().positive(),
100
+ },
101
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
102
+ },
103
+ async ({ targetUserId }) => {
104
+ if (isDemoUser(userId)) return demoDenied();
105
+ const planId = getActivePlanId(userId);
106
+ const me = getCurrentUser(userId);
107
+ if (!me) return { content: [{ type: 'text' as const, text: 'User not found.' }], isError: true };
108
+ const result = sendVacayInvite(planId, userId, me.username, me.email, targetUserId);
109
+ if (result.error) return { content: [{ type: 'text' as const, text: result.error }], isError: true };
110
+ return ok({ success: true });
111
+ }
112
+ );
113
+
114
+ if (W) server.registerTool(
115
+ 'accept_vacay_invite',
116
+ {
117
+ description: 'Accept a pending invitation to join another user\'s vacation plan.',
118
+ inputSchema: {
119
+ planId: z.number().int().positive(),
120
+ },
121
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
122
+ },
123
+ async ({ planId }) => {
124
+ if (isDemoUser(userId)) return demoDenied();
125
+ const result = acceptInvite(userId, planId, undefined);
126
+ if (result.error) return { content: [{ type: 'text' as const, text: result.error }], isError: true };
127
+ return ok({ success: true });
128
+ }
129
+ );
130
+
131
+ if (W) server.registerTool(
132
+ 'decline_vacay_invite',
133
+ {
134
+ description: 'Decline a pending vacation plan invitation.',
135
+ inputSchema: {
136
+ planId: z.number().int().positive(),
137
+ },
138
+ annotations: TOOL_ANNOTATIONS_WRITE,
139
+ },
140
+ async ({ planId }) => {
141
+ declineInvite(userId, planId, undefined);
142
+ return ok({ success: true });
143
+ }
144
+ );
145
+
146
+ if (W) server.registerTool(
147
+ 'cancel_vacay_invite',
148
+ {
149
+ description: 'Cancel an outgoing invitation (owner cancels invite they sent).',
150
+ inputSchema: {
151
+ targetUserId: z.number().int().positive(),
152
+ },
153
+ annotations: TOOL_ANNOTATIONS_WRITE,
154
+ },
155
+ async ({ targetUserId }) => {
156
+ if (isDemoUser(userId)) return demoDenied();
157
+ const planId = getActivePlanId(userId);
158
+ cancelInvite(planId, targetUserId);
159
+ return ok({ success: true });
160
+ }
161
+ );
162
+
163
+ if (W) server.registerTool(
164
+ 'dissolve_vacay_plan',
165
+ {
166
+ description: 'Dissolve the shared plan — all members are removed and everyone returns to their own individual plan.',
167
+ inputSchema: {},
168
+ annotations: TOOL_ANNOTATIONS_DELETE,
169
+ },
170
+ async () => {
171
+ if (isDemoUser(userId)) return demoDenied();
172
+ dissolvePlan(userId, undefined);
173
+ return ok({ success: true });
174
+ }
175
+ );
176
+
177
+ if (R) server.registerTool(
178
+ 'list_vacay_years',
179
+ {
180
+ description: 'List calendar years tracked in the current vacation plan.',
181
+ inputSchema: {},
182
+ annotations: TOOL_ANNOTATIONS_READONLY,
183
+ },
184
+ async () => {
185
+ const planId = getActivePlanId(userId);
186
+ const years = listYears(planId);
187
+ return ok({ years });
188
+ }
189
+ );
190
+
191
+ if (W) server.registerTool(
192
+ 'add_vacay_year',
193
+ {
194
+ description: 'Add a calendar year to the vacation plan.',
195
+ inputSchema: {
196
+ year: z.number().int().min(2000).max(2100),
197
+ },
198
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
199
+ },
200
+ async ({ year }) => {
201
+ if (isDemoUser(userId)) return demoDenied();
202
+ const planId = getActivePlanId(userId);
203
+ const years = addYear(planId, year, undefined);
204
+ return ok({ years });
205
+ }
206
+ );
207
+
208
+ if (W) server.registerTool(
209
+ 'delete_vacay_year',
210
+ {
211
+ description: 'Remove a calendar year from the vacation plan.',
212
+ inputSchema: {
213
+ year: z.number().int(),
214
+ },
215
+ annotations: TOOL_ANNOTATIONS_DELETE,
216
+ },
217
+ async ({ year }) => {
218
+ if (isDemoUser(userId)) return demoDenied();
219
+ const planId = getActivePlanId(userId);
220
+ const years = deleteYear(planId, year, undefined);
221
+ return ok({ years });
222
+ }
223
+ );
224
+
225
+ if (R) server.registerTool(
226
+ 'get_vacay_entries',
227
+ {
228
+ description: 'Get all vacation day entries for a plan and year.',
229
+ inputSchema: {
230
+ year: z.number().int(),
231
+ },
232
+ annotations: TOOL_ANNOTATIONS_READONLY,
233
+ },
234
+ async ({ year }) => {
235
+ const planId = getActivePlanId(userId);
236
+ const entries = getVacayEntries(planId, String(year));
237
+ return ok({ entries });
238
+ }
239
+ );
240
+
241
+ if (W) server.registerTool(
242
+ 'toggle_vacay_entry',
243
+ {
244
+ description: 'Toggle a day on or off as a vacation day for the current user.',
245
+ inputSchema: {
246
+ date: z.string().describe('ISO date YYYY-MM-DD'),
247
+ },
248
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
249
+ },
250
+ async ({ date }) => {
251
+ if (isDemoUser(userId)) return demoDenied();
252
+ const planId = getActivePlanId(userId);
253
+ const result = toggleEntry(userId, planId, date, undefined);
254
+ return ok(result);
255
+ }
256
+ );
257
+
258
+ if (W) server.registerTool(
259
+ 'toggle_company_holiday',
260
+ {
261
+ description: 'Toggle a date as a company holiday for the whole plan.',
262
+ inputSchema: {
263
+ date: z.string(),
264
+ note: z.string().optional(),
265
+ },
266
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
267
+ },
268
+ async ({ date, note }) => {
269
+ if (isDemoUser(userId)) return demoDenied();
270
+ const planId = getActivePlanId(userId);
271
+ const result = toggleCompanyHoliday(planId, date, note, undefined);
272
+ return ok(result);
273
+ }
274
+ );
275
+
276
+ if (R) server.registerTool(
277
+ 'get_vacay_stats',
278
+ {
279
+ description: 'Get vacation statistics for a specific year (days used, remaining, carried over).',
280
+ inputSchema: {
281
+ year: z.number().int(),
282
+ },
283
+ annotations: TOOL_ANNOTATIONS_READONLY,
284
+ },
285
+ async ({ year }) => {
286
+ const planId = getActivePlanId(userId);
287
+ const stats = getVacayStats(planId, year);
288
+ return ok({ stats });
289
+ }
290
+ );
291
+
292
+ if (W) server.registerTool(
293
+ 'update_vacay_stats',
294
+ {
295
+ description: 'Update the vacation day allowance for a specific user and year.',
296
+ inputSchema: {
297
+ year: z.number().int(),
298
+ vacationDays: z.number().int().min(0),
299
+ },
300
+ annotations: TOOL_ANNOTATIONS_WRITE,
301
+ },
302
+ async ({ year, vacationDays }) => {
303
+ if (isDemoUser(userId)) return demoDenied();
304
+ const planId = getActivePlanId(userId);
305
+ updateVacayStats(userId, planId, year, vacationDays, undefined);
306
+ return ok({ success: true });
307
+ }
308
+ );
309
+
310
+ if (W) server.registerTool(
311
+ 'add_holiday_calendar',
312
+ {
313
+ description: 'Add a public holiday calendar (by region code) to the vacation plan.',
314
+ inputSchema: {
315
+ region: z.string().describe('Country/region code e.g. US, GB, DE'),
316
+ label: z.string().nullable().optional(),
317
+ color: z.string().optional(),
318
+ sortOrder: z.number().int().optional(),
319
+ },
320
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
321
+ },
322
+ async ({ region, label, color, sortOrder }) => {
323
+ if (isDemoUser(userId)) return demoDenied();
324
+ const planId = getActivePlanId(userId);
325
+ const calendar = addHolidayCalendar(planId, region, label ?? null, color, sortOrder, undefined);
326
+ return ok({ calendar });
327
+ }
328
+ );
329
+
330
+ if (W) server.registerTool(
331
+ 'update_holiday_calendar',
332
+ {
333
+ description: 'Update label or color for a holiday calendar.',
334
+ inputSchema: {
335
+ calendarId: z.number().int().positive(),
336
+ label: z.string().nullable().optional(),
337
+ color: z.string().optional(),
338
+ },
339
+ annotations: TOOL_ANNOTATIONS_WRITE,
340
+ },
341
+ async ({ calendarId, label, color }) => {
342
+ if (isDemoUser(userId)) return demoDenied();
343
+ const planId = getActivePlanId(userId);
344
+ const cal = updateHolidayCalendar(calendarId, planId, { label, color }, undefined);
345
+ if (!cal) return { content: [{ type: 'text' as const, text: 'Holiday calendar not found.' }], isError: true };
346
+ return ok({ calendar: cal });
347
+ }
348
+ );
349
+
350
+ if (W) server.registerTool(
351
+ 'delete_holiday_calendar',
352
+ {
353
+ description: 'Remove a holiday calendar from the vacation plan.',
354
+ inputSchema: {
355
+ calendarId: z.number().int().positive(),
356
+ },
357
+ annotations: TOOL_ANNOTATIONS_DELETE,
358
+ },
359
+ async ({ calendarId }) => {
360
+ if (isDemoUser(userId)) return demoDenied();
361
+ const planId = getActivePlanId(userId);
362
+ deleteHolidayCalendar(calendarId, planId, undefined);
363
+ return ok({ success: true });
364
+ }
365
+ );
366
+
367
+ if (R) server.registerTool(
368
+ 'list_holiday_countries',
369
+ {
370
+ description: 'List countries available for public holiday calendars.',
371
+ inputSchema: {},
372
+ annotations: TOOL_ANNOTATIONS_READONLY,
373
+ },
374
+ async () => {
375
+ const result = await getHolidayCountries();
376
+ if (result.error) return { content: [{ type: 'text' as const, text: result.error }], isError: true };
377
+ return ok({ countries: result.data });
378
+ }
379
+ );
380
+
381
+ if (R) server.registerTool(
382
+ 'list_holidays',
383
+ {
384
+ description: 'List public holidays for a country and year.',
385
+ inputSchema: {
386
+ country: z.string().describe('ISO 3166-1 alpha-2 code'),
387
+ year: z.number().int(),
388
+ },
389
+ annotations: TOOL_ANNOTATIONS_READONLY,
390
+ },
391
+ async ({ country, year }) => {
392
+ const result = await getHolidays(String(year), country);
393
+ if (result.error) return { content: [{ type: 'text' as const, text: result.error }], isError: true };
394
+ return ok({ holidays: result.data });
395
+ }
396
+ );
397
+ }
398
+ }
server/src/middleware/auth.ts ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Request, Response, NextFunction } from 'express';
2
+ import jwt from 'jsonwebtoken';
3
+ import { db } from '../db/database';
4
+ import { JWT_SECRET } from '../config';
5
+ import { AuthRequest, OptionalAuthRequest, User } from '../types';
6
+ import { applyIdempotency } from './idempotency';
7
+ import { isDemoEmail } from '../services/demo';
8
+
9
+ export function extractToken(req: Request): string | null {
10
+ // Prefer httpOnly cookie; fall back to Authorization: Bearer (MCP, API clients)
11
+ const cookieToken = (req as any).cookies?.trek_session;
12
+ if (cookieToken) return cookieToken;
13
+ const authHeader = req.headers['authorization'];
14
+ return (authHeader && authHeader.split(' ')[1]) || null;
15
+ }
16
+
17
+ /**
18
+ * Verify a JWT and load its user, enforcing the password_version gate.
19
+ *
20
+ * Exported so every auth surface in the codebase (MCP bearer tokens,
21
+ * file download query tokens, the photo-serving route) goes through the
22
+ * same check. A password reset bumps `users.password_version`, which
23
+ * invalidates every JWT that embedded the prior value — but only if
24
+ * every verify path actually compares the claim. Previously several
25
+ * paths called `jwt.verify` directly and skipped the DB lookup, so a
26
+ * stolen token kept working after the victim reset.
27
+ */
28
+ export function verifyJwtAndLoadUser(token: string): User | null {
29
+ try {
30
+ const decoded = jwt.verify(token, JWT_SECRET, { algorithms: ['HS256'] }) as { id: number; pv?: number; purpose?: string };
31
+ // Purpose-scoped tokens (e.g. the short-lived mfa_login token) share this
32
+ // secret but are not full session tokens — only their dedicated endpoint
33
+ // may accept them, so reject any token carrying a purpose claim here.
34
+ if (decoded.purpose) return null;
35
+ const row = db.prepare(
36
+ 'SELECT id, username, email, role, password_version FROM users WHERE id = ?'
37
+ ).get(decoded.id) as (User & { password_version?: number }) | undefined;
38
+ if (!row) return null;
39
+ // Session invalidation: any token whose embedded password_version
40
+ // predates the user's current one is rejected. Tokens issued before
41
+ // the `pv` claim existed (decoded.pv === undefined) are treated as
42
+ // version 0 so legacy sessions keep working until the user resets.
43
+ const tokenPv = typeof decoded.pv === 'number' ? decoded.pv : 0;
44
+ const currentPv = typeof row.password_version === 'number' ? row.password_version : 0;
45
+ if (tokenPv !== currentPv) return null;
46
+ // Don't leak password_version beyond the middleware.
47
+ const { password_version: _pv, ...user } = row;
48
+ return user as User;
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+
54
+ const authenticate = (req: Request, res: Response, next: NextFunction): void => {
55
+ const token = extractToken(req);
56
+
57
+ if (!token) {
58
+ res.status(401).json({ error: 'Access token required', code: 'AUTH_REQUIRED' });
59
+ return;
60
+ }
61
+
62
+ const user = verifyJwtAndLoadUser(token);
63
+ if (!user) {
64
+ res.status(401).json({ error: 'Invalid or expired token', code: 'AUTH_REQUIRED' });
65
+ return;
66
+ }
67
+ (req as AuthRequest).user = user;
68
+ applyIdempotency(req, res, next, user.id);
69
+ };
70
+
71
+ /** Like `authenticate` but rejects requests that don't carry an httpOnly session cookie.
72
+ * Used on state-mutating OAuth endpoints (consent POST, client CRUD, session revoke)
73
+ * to prevent Bearer JWT tokens obtained by other means from managing OAuth clients. */
74
+ const requireCookieAuth = (req: Request, res: Response, next: NextFunction): void => {
75
+ const cookieToken = (req as any).cookies?.trek_session;
76
+ if (!cookieToken) {
77
+ res.status(401).json({ error: 'Cookie session required for this endpoint', code: 'COOKIE_AUTH_REQUIRED' });
78
+ return;
79
+ }
80
+ const user = verifyJwtAndLoadUser(cookieToken);
81
+ if (!user) {
82
+ res.status(401).json({ error: 'Invalid or expired session', code: 'AUTH_REQUIRED' });
83
+ return;
84
+ }
85
+ (req as AuthRequest).user = user;
86
+ next();
87
+ };
88
+
89
+ const optionalAuth = (req: Request, res: Response, next: NextFunction): void => {
90
+ const token = extractToken(req);
91
+
92
+ if (!token) {
93
+ (req as OptionalAuthRequest).user = null;
94
+ return next();
95
+ }
96
+
97
+ (req as OptionalAuthRequest).user = verifyJwtAndLoadUser(token) || null;
98
+ next();
99
+ };
100
+
101
+ const adminOnly = (req: Request, res: Response, next: NextFunction): void => {
102
+ const authReq = req as AuthRequest;
103
+ if (!authReq.user || authReq.user.role !== 'admin') {
104
+ res.status(403).json({ error: 'Admin access required' });
105
+ return;
106
+ }
107
+ next();
108
+ };
109
+
110
+ const demoUploadBlock = (req: Request, res: Response, next: NextFunction): void => {
111
+ const authReq = req as AuthRequest;
112
+ if (process.env.DEMO_MODE?.toLowerCase() === 'true' && isDemoEmail(authReq.user?.email)) {
113
+ res.status(403).json({ error: 'Uploads are disabled in demo mode. Self-host TREK for full functionality.' });
114
+ return;
115
+ }
116
+ next();
117
+ };
118
+
119
+ export { authenticate, requireCookieAuth, optionalAuth, adminOnly, demoUploadBlock };
server/src/middleware/globalMiddleware.ts ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import express, { Request, Response, NextFunction } from 'express';
2
+ import cors from 'cors';
3
+ import helmet from 'helmet';
4
+ import cookieParser from 'cookie-parser';
5
+ import { logDebug, logWarn, logError } from '../services/auditLog';
6
+ import { enforceGlobalMfaPolicy } from './mfaPolicy';
7
+
8
+ /**
9
+ * The global request pipeline shared by the legacy Express app and the NestJS
10
+ * instance. Both mount the *exact same* config so a request hitting a migrated
11
+ * Nest route is protected identically to one hitting the legacy fallback
12
+ * (helmet/CSP, CORS, HSTS, forced-HTTPS, the global MFA policy and request
13
+ * logging). Keeping it in one place is what makes the strangler dispatch
14
+ * behaviourally transparent — and is the prerequisite for retiring Express,
15
+ * since the Nest instance must carry the whole shell on its own.
16
+ *
17
+ * `bodyParser` is opt-out: the Nest instance does its own body parsing, so it
18
+ * passes `false` to avoid parsing the request twice.
19
+ */
20
+ export function applyGlobalMiddleware(
21
+ app: express.Application,
22
+ opts: { bodyParser?: boolean } = {},
23
+ ): void {
24
+ const { bodyParser = true } = opts;
25
+
26
+ // Trust first proxy (nginx/Docker) for correct req.ip
27
+ if (process.env.NODE_ENV?.toLowerCase() === 'production' || process.env.TRUST_PROXY) {
28
+ app.set('trust proxy', Number.parseInt(process.env.TRUST_PROXY) || 1);
29
+ }
30
+
31
+ const allowedOrigins = process.env.ALLOWED_ORIGINS
32
+ ? process.env.ALLOWED_ORIGINS.split(',').map(o => o.trim()).filter(Boolean)
33
+ : null;
34
+
35
+ let corsOrigin: cors.CorsOptions['origin'];
36
+ if (allowedOrigins) {
37
+ corsOrigin = (origin: string | undefined, callback: (err: Error | null, allow?: boolean) => void) => {
38
+ if (!origin || allowedOrigins.includes(origin)) callback(null, true);
39
+ else callback(new Error('Not allowed by CORS'));
40
+ };
41
+ } else if (process.env.NODE_ENV?.toLowerCase() === 'production') {
42
+ corsOrigin = false;
43
+ } else {
44
+ corsOrigin = true;
45
+ }
46
+
47
+ const shouldForceHttps = process.env.FORCE_HTTPS?.toLowerCase() === 'true';
48
+ // HSTS is worth enabling any time we're serving production traffic,
49
+ // not only when FORCE_HTTPS is set. Self-hosters behind Traefik /
50
+ // Caddy / Cloudflare Tunnel typically leave FORCE_HTTPS unset (the
51
+ // proxy handles the redirect for them), and the previous "HSTS off by
52
+ // default" meant those instances never advertised HSTS at all.
53
+ //
54
+ // `includeSubDomains` stays OFF by default on purpose: an instance
55
+ // running on an apex domain would otherwise force HTTPS on every
56
+ // sibling subdomain the same operator may still be running over plain
57
+ // HTTP. Operators who want the stricter policy opt in with
58
+ // `HSTS_INCLUDE_SUBDOMAINS=true`.
59
+ const hstsActive = shouldForceHttps || process.env.NODE_ENV === 'production';
60
+ const hstsIncludeSubdomains = process.env.HSTS_INCLUDE_SUBDOMAINS === 'true';
61
+
62
+ // RFC 8414 / RFC 9728 / RFC 7591: discovery docs and DCR are world-readable/writable.
63
+ // /mcp needs open CORS so external MCP clients (ChatGPT, Claude.ai, Inspector) can call it
64
+ // with Bearer tokens from any origin. /oauth/register and /oauth/authorize need it for
65
+ // browser-based DCR/authorization preflights — the global cors({ origin: false }) would
66
+ // answer OPTIONS without Access-Control-Allow-Origin before the SDK's own cors() runs.
67
+ // All /.well-known/* paths get open CORS so clients probing openid-configuration or the
68
+ // RFC 8414 path-suffixed AS metadata form don't get CORS-blocked (they get 404 JSON instead).
69
+ app.use(
70
+ (req: Request, _res: Response, next: NextFunction) => {
71
+ if (
72
+ req.path.startsWith('/.well-known/') ||
73
+ req.path === '/oauth/register' ||
74
+ req.path === '/oauth/authorize' ||
75
+ req.path === '/oauth/userinfo' ||
76
+ req.path === '/mcp'
77
+ ) {
78
+ cors({ origin: '*', credentials: false })(req, _res, next);
79
+ } else {
80
+ next();
81
+ }
82
+ },
83
+ );
84
+ app.use(cors({ origin: corsOrigin, credentials: true }));
85
+ app.use(helmet({
86
+ contentSecurityPolicy: {
87
+ directives: {
88
+ defaultSrc: ["'self'"],
89
+ scriptSrc: ["'self'", "'wasm-unsafe-eval'", "'unsafe-eval'"],
90
+ styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com", "https://unpkg.com"],
91
+ imgSrc: ["'self'", "data:", "blob:", "https:"],
92
+ connectSrc: [
93
+ "'self'", "ws:", "wss:",
94
+ "https://nominatim.openstreetmap.org", "https://overpass-api.de",
95
+ "https://places.googleapis.com", "https://api.openweathermap.org",
96
+ "https://en.wikipedia.org", "https://commons.wikimedia.org",
97
+ "https://*.basemaps.cartocdn.com", "https://*.tile.openstreetmap.org",
98
+ "https://unpkg.com", "https://open-meteo.com", "https://api.open-meteo.com",
99
+ "https://geocoding-api.open-meteo.com", "https://api.frankfurter.dev",
100
+ "https://router.project-osrm.org/route/v1/", "https://routing.openstreetmap.de/",
101
+ "https://api.mapbox.com", "https://*.tiles.mapbox.com", "https://events.mapbox.com"
102
+ ],
103
+ workerSrc: ["'self'", "blob:"],
104
+ childSrc: ["'self'", "blob:"],
105
+ fontSrc: ["'self'", "https://fonts.gstatic.com", "data:"],
106
+ objectSrc: ["'none'"],
107
+ frameSrc: ["'none'"],
108
+ frameAncestors: ["'self'"],
109
+ // Restrict <form> submission targets (form-action has no default-src
110
+ // fallback, so it must be set explicitly).
111
+ formAction: ["'self'"],
112
+ upgradeInsecureRequests: shouldForceHttps ? [] : null
113
+ }
114
+ },
115
+ crossOriginEmbedderPolicy: false,
116
+ hsts: hstsActive ? { maxAge: 31536000, includeSubDomains: hstsIncludeSubdomains } : false,
117
+ referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
118
+ }));
119
+
120
+ if (shouldForceHttps) {
121
+ app.use((req: Request, res: Response, next: NextFunction) => {
122
+ if (req.path === '/api/health') return next();
123
+ if (req.secure || req.headers['x-forwarded-proto'] === 'https') return next();
124
+ res.redirect(301, 'https://' + req.headers.host + req.url);
125
+ });
126
+ }
127
+
128
+ if (bodyParser) {
129
+ app.use(express.json({ limit: '100kb' }));
130
+ app.use(express.urlencoded({ extended: true }));
131
+ }
132
+ app.use(cookieParser());
133
+ app.use(enforceGlobalMfaPolicy);
134
+
135
+ // Request logging with sensitive field redaction
136
+ const SENSITIVE_KEYS = new Set(['password', 'new_password', 'current_password', 'token', 'jwt', 'authorization', 'cookie', 'client_secret', 'mfa_token', 'code', 'smtp_pass']);
137
+ const redact = (value: unknown): unknown => {
138
+ if (!value || typeof value !== 'object') return value;
139
+ if (Array.isArray(value)) return (value as unknown[]).map(redact);
140
+ const out: Record<string, unknown> = {};
141
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
142
+ out[k] = SENSITIVE_KEYS.has(k.toLowerCase()) ? '[REDACTED]' : redact(v);
143
+ }
144
+ return out;
145
+ };
146
+
147
+ app.use((req: Request, res: Response, next: NextFunction) => {
148
+ if (req.path === '/api/health') return next();
149
+ const startedAt = Date.now();
150
+ res.on('finish', () => {
151
+ const ms = Date.now() - startedAt;
152
+ if (res.statusCode >= 500) {
153
+ logError(`${req.method} ${req.path} ${res.statusCode} ${ms}ms ip=${req.ip}`);
154
+ } else if (res.statusCode === 401 || res.statusCode === 403) {
155
+ logDebug(`${req.method} ${req.path} ${res.statusCode} ${ms}ms ip=${req.ip}`);
156
+ } else if (res.statusCode >= 400) {
157
+ logWarn(`${req.method} ${req.path} ${res.statusCode} ${ms}ms ip=${req.ip}`);
158
+ }
159
+ const q = Object.keys(req.query).length ? ` query=${JSON.stringify(redact(req.query))}` : '';
160
+ const b = req.body && Object.keys(req.body).length ? ` body=${JSON.stringify(redact(req.body))}` : '';
161
+ logDebug(`${req.method} ${req.path} ${res.statusCode} ${ms}ms ip=${req.ip}${q}${b}`);
162
+ });
163
+ next();
164
+ });
165
+ }
server/src/middleware/idempotency.ts ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Request, Response, NextFunction } from 'express';
2
+ import { db } from '../db/database';
3
+
4
+ const MUTATING_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
5
+ // Reject pathological client-supplied keys outright instead of hashing
6
+ // everything — 128 chars is plenty for any realistic UUID / ULID / nonce.
7
+ const MAX_KEY_LENGTH = 128;
8
+ // Responses larger than this are not worth caching — a backup-restore
9
+ // endpoint could otherwise store a megabyte-sized JSON body per request
10
+ // key and, with mass key creation, blow up idempotency_keys.
11
+ const MAX_CACHED_BODY_BYTES = 256 * 1024;
12
+
13
+ interface IdempotencyRow {
14
+ status_code: number;
15
+ response_body: string;
16
+ }
17
+
18
+ /**
19
+ * Called from within `authenticate` after req.user is set.
20
+ *
21
+ * For mutating requests carrying X-Idempotency-Key:
22
+ * - If (key, userId, method, path) already stored: replays the cached response.
23
+ * - Otherwise: wraps res.json to capture and store a successful response.
24
+ *
25
+ * The lookup is scoped by method + path as well as user so the same key
26
+ * replayed against a different endpoint doesn't return the cached body
27
+ * of an unrelated request. Key length is capped and the cached body is
28
+ * skipped when it exceeds `MAX_CACHED_BODY_BYTES`.
29
+ *
30
+ * Storing happens in idempotency_keys (24h TTL, cleaned by scheduler).
31
+ */
32
+ export function applyIdempotency(req: Request, res: Response, next: NextFunction, userId: number): void {
33
+ if (!MUTATING_METHODS.has(req.method)) {
34
+ next();
35
+ return;
36
+ }
37
+
38
+ const key = req.headers['x-idempotency-key'] as string | undefined;
39
+ if (!key) {
40
+ next();
41
+ return;
42
+ }
43
+ if (key.length > MAX_KEY_LENGTH) {
44
+ res.status(400).json({ error: 'X-Idempotency-Key exceeds maximum length of 128 characters' });
45
+ return;
46
+ }
47
+
48
+ // Return cached response only if the same key was seen for the same
49
+ // user AND the same method+path — avoids a POST's cached body leaking
50
+ // into an unrelated PATCH that reused the idempotency-key string.
51
+ const existing = db.prepare(
52
+ 'SELECT status_code, response_body FROM idempotency_keys WHERE key = ? AND user_id = ? AND method = ? AND path = ?'
53
+ ).get(key, userId, req.method, req.path) as IdempotencyRow | undefined;
54
+
55
+ if (existing) {
56
+ res.status(existing.status_code).json(JSON.parse(existing.response_body));
57
+ return;
58
+ }
59
+
60
+ // Wrap res.json to capture the response on first successful execution
61
+ const originalJson = res.json.bind(res);
62
+ res.json = function (body: unknown): Response {
63
+ if (res.statusCode >= 200 && res.statusCode < 300) {
64
+ try {
65
+ const serialized = JSON.stringify(body);
66
+ if (serialized.length <= MAX_CACHED_BODY_BYTES) {
67
+ db.prepare(
68
+ `INSERT OR IGNORE INTO idempotency_keys (key, user_id, method, path, status_code, response_body, created_at)
69
+ VALUES (?, ?, ?, ?, ?, ?, ?)`
70
+ ).run(key, userId, req.method, req.path, res.statusCode, serialized, Math.floor(Date.now() / 1000));
71
+ }
72
+ } catch {
73
+ // Non-fatal: if storage fails, the request still succeeds
74
+ }
75
+ }
76
+ return originalJson(body);
77
+ };
78
+
79
+ next();
80
+ }
server/src/middleware/mfaPolicy.ts ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Request, Response, NextFunction } from 'express';
2
+ import { db } from '../db/database';
3
+ import { extractToken, verifyJwtAndLoadUser } from './auth';
4
+ import { DEMO_EMAILS } from '../services/demo';
5
+
6
+ /** Paths that never require MFA (public or pre-auth). */
7
+ export function isPublicApiPath(method: string, pathNoQuery: string): boolean {
8
+ if (method === 'GET' && pathNoQuery === '/api/health') return true;
9
+ if (method === 'GET' && pathNoQuery === '/api/auth/app-config') return true;
10
+ if (method === 'POST' && pathNoQuery === '/api/auth/login') return true;
11
+ if (method === 'POST' && pathNoQuery === '/api/auth/register') return true;
12
+ if (method === 'POST' && pathNoQuery === '/api/auth/demo-login') return true;
13
+ if (method === 'GET' && pathNoQuery.startsWith('/api/auth/invite/')) return true;
14
+ if (method === 'POST' && pathNoQuery === '/api/auth/mfa/verify-login') return true;
15
+ // Unauthenticated passkey (primary) login ceremony.
16
+ if (method === 'POST' && pathNoQuery === '/api/auth/passkey/login/options') return true;
17
+ if (method === 'POST' && pathNoQuery === '/api/auth/passkey/login/verify') return true;
18
+ if (pathNoQuery.startsWith('/api/auth/oidc/')) return true;
19
+ return false;
20
+ }
21
+
22
+ /** Authenticated paths allowed while MFA is not yet enabled (setup + lockout recovery). */
23
+ export function isMfaSetupExemptPath(method: string, pathNoQuery: string): boolean {
24
+ if (method === 'GET' && pathNoQuery === '/api/auth/me') return true;
25
+ if (method === 'POST' && pathNoQuery === '/api/auth/mfa/setup') return true;
26
+ if (method === 'POST' && pathNoQuery === '/api/auth/mfa/enable') return true;
27
+ // Allow enrolling a passkey as the second factor (a user-verified passkey
28
+ // satisfies require_mfa), so a fresh user under the policy isn't stuck.
29
+ if (method === 'POST' && pathNoQuery === '/api/auth/passkey/register/options') return true;
30
+ if (method === 'POST' && pathNoQuery === '/api/auth/passkey/register/verify') return true;
31
+ if (method === 'GET' && pathNoQuery === '/api/auth/passkey/credentials') return true;
32
+ if ((method === 'GET' || method === 'PUT') && pathNoQuery === '/api/auth/app-settings') return true;
33
+ return false;
34
+ }
35
+
36
+ /**
37
+ * When app_settings.require_mfa is true, block API access for users without MFA enabled,
38
+ * except for public routes and MFA setup endpoints.
39
+ */
40
+ export function enforceGlobalMfaPolicy(req: Request, res: Response, next: NextFunction): void {
41
+ const pathNoQuery = (req.originalUrl || req.url || '').split('?')[0];
42
+
43
+ if (!pathNoQuery.startsWith('/api')) {
44
+ next();
45
+ return;
46
+ }
47
+
48
+ if (isPublicApiPath(req.method, pathNoQuery)) {
49
+ next();
50
+ return;
51
+ }
52
+
53
+ // Accept both the httpOnly session cookie (regular SPA users) and the
54
+ // Authorization header (MCP / API clients). Previously this only looked
55
+ // at the header so every normal cookie-authenticated session sailed
56
+ // past `require_mfa` unchecked.
57
+ const token = extractToken(req);
58
+ if (!token) {
59
+ next();
60
+ return;
61
+ }
62
+
63
+ // Use the shared verify helper so the `password_version` gate applies
64
+ // here too — a JWT stolen before a password reset would otherwise
65
+ // continue to satisfy this middleware until its natural 24h expiry.
66
+ const verified = verifyJwtAndLoadUser(token);
67
+ if (!verified) {
68
+ next();
69
+ return;
70
+ }
71
+ const userId = verified.id;
72
+
73
+ const requireRow = db.prepare("SELECT value FROM app_settings WHERE key = 'require_mfa'").get() as { value: string } | undefined;
74
+ if (requireRow?.value !== 'true') {
75
+ next();
76
+ return;
77
+ }
78
+
79
+ if (process.env.DEMO_MODE?.toLowerCase() === 'true' && verified.email && DEMO_EMAILS.has(verified.email)) {
80
+ next();
81
+ return;
82
+ }
83
+
84
+ const row = db.prepare('SELECT mfa_enabled FROM users WHERE id = ?').get(userId) as
85
+ | { mfa_enabled: number | boolean }
86
+ | undefined;
87
+ if (!row) {
88
+ next();
89
+ return;
90
+ }
91
+
92
+ // A user-verified passkey is phishing-resistant and inherently two-factor, so
93
+ // owning at least one satisfies the require_mfa policy exactly like TOTP does.
94
+ // (All stored passkeys were registered with userVerification required.)
95
+ const mfaOk = row.mfa_enabled === 1 || row.mfa_enabled === true;
96
+ const passkeyOk = !!db.prepare('SELECT 1 FROM webauthn_credentials WHERE user_id = ? LIMIT 1').get(userId);
97
+ if (mfaOk || passkeyOk) {
98
+ next();
99
+ return;
100
+ }
101
+
102
+ if (isMfaSetupExemptPath(req.method, pathNoQuery)) {
103
+ next();
104
+ return;
105
+ }
106
+
107
+ res.status(403).json({
108
+ error: 'Two-factor authentication is required. Complete setup in Settings.',
109
+ code: 'MFA_REQUIRED',
110
+ });
111
+ }
server/src/middleware/tripAccess.ts ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Request, Response, NextFunction } from 'express';
2
+ import { canAccessTrip, isOwner } from '../db/database';
3
+ import { AuthRequest } from '../types';
4
+
5
+ /** Middleware: verifies the authenticated user is an owner or member of the trip, then attaches trip to req. */
6
+ function requireTripAccess(req: Request, res: Response, next: NextFunction): void {
7
+ const authReq = req as AuthRequest;
8
+ const tripId = req.params.tripId || req.params.id;
9
+ if (!tripId) {
10
+ res.status(400).json({ error: 'Trip ID required' });
11
+ return;
12
+ }
13
+ const trip = canAccessTrip(Number(tripId), authReq.user.id);
14
+ if (!trip) {
15
+ res.status(404).json({ error: 'Trip not found' });
16
+ return;
17
+ }
18
+ authReq.trip = trip;
19
+ next();
20
+ }
21
+
22
+ /** Middleware: verifies the authenticated user is the trip owner (not just a member). */
23
+ function requireTripOwner(req: Request, res: Response, next: NextFunction): void {
24
+ const authReq = req as AuthRequest;
25
+ const tripId = req.params.tripId || req.params.id;
26
+ if (!tripId) {
27
+ res.status(400).json({ error: 'Trip ID required' });
28
+ return;
29
+ }
30
+ if (!isOwner(Number(tripId), authReq.user.id)) {
31
+ res.status(403).json({ error: 'Only the trip owner can do this' });
32
+ return;
33
+ }
34
+ next();
35
+ }
36
+
37
+ export { requireTripAccess, requireTripOwner };
server/src/middleware/validate.ts ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Request, Response, NextFunction } from 'express';
2
+
3
+ function maxLength(field: string, max: number) {
4
+ return (req: Request, res: Response, next: NextFunction): void => {
5
+ if (req.body[field] && typeof req.body[field] === 'string' && req.body[field].length > max) {
6
+ res.status(400).json({ error: `${field} must be ${max} characters or less` });
7
+ return;
8
+ }
9
+ next();
10
+ };
11
+ }
12
+
13
+ function validateStringLengths(maxLengths: Record<string, number>) {
14
+ return (req: Request, res: Response, next: NextFunction): void => {
15
+ for (const [field, max] of Object.entries(maxLengths)) {
16
+ const value = req.body[field];
17
+ if (value && typeof value === 'string' && value.length > max) {
18
+ res.status(400).json({ error: `${field} must be ${max} characters or less` });
19
+ return;
20
+ }
21
+ }
22
+ next();
23
+ };
24
+ }
25
+
26
+ export { maxLength, validateStringLengths };