diff --git a/server/node_modules/supports-color/package.json b/server/node_modules/supports-color/package.json
new file mode 100644
index 0000000000000000000000000000000000000000..f7182edcea2baa8778219d4aab2c0c1b21f1a30a
--- /dev/null
+++ b/server/node_modules/supports-color/package.json
@@ -0,0 +1,53 @@
+{
+ "name": "supports-color",
+ "version": "7.2.0",
+ "description": "Detect whether a terminal supports color",
+ "license": "MIT",
+ "repository": "chalk/supports-color",
+ "author": {
+ "name": "Sindre Sorhus",
+ "email": "sindresorhus@gmail.com",
+ "url": "sindresorhus.com"
+ },
+ "engines": {
+ "node": ">=8"
+ },
+ "scripts": {
+ "test": "xo && ava"
+ },
+ "files": [
+ "index.js",
+ "browser.js"
+ ],
+ "keywords": [
+ "color",
+ "colour",
+ "colors",
+ "terminal",
+ "console",
+ "cli",
+ "ansi",
+ "styles",
+ "tty",
+ "rgb",
+ "256",
+ "shell",
+ "xterm",
+ "command-line",
+ "support",
+ "supports",
+ "capability",
+ "detect",
+ "truecolor",
+ "16m"
+ ],
+ "dependencies": {
+ "has-flag": "^4.0.0"
+ },
+ "devDependencies": {
+ "ava": "^1.4.1",
+ "import-fresh": "^3.0.0",
+ "xo": "^0.24.0"
+ },
+ "browser": "browser.js"
+}
diff --git a/server/node_modules/supports-color/readme.md b/server/node_modules/supports-color/readme.md
new file mode 100644
index 0000000000000000000000000000000000000000..36542285863330887923979b4c00579738907d49
--- /dev/null
+++ b/server/node_modules/supports-color/readme.md
@@ -0,0 +1,76 @@
+# supports-color [](https://travis-ci.org/chalk/supports-color)
+
+> Detect whether a terminal supports color
+
+
+## Install
+
+```
+$ npm install supports-color
+```
+
+
+## Usage
+
+```js
+const supportsColor = require('supports-color');
+
+if (supportsColor.stdout) {
+ console.log('Terminal stdout supports color');
+}
+
+if (supportsColor.stdout.has256) {
+ console.log('Terminal stdout supports 256 colors');
+}
+
+if (supportsColor.stderr.has16m) {
+ console.log('Terminal stderr supports 16 million colors (truecolor)');
+}
+```
+
+
+## API
+
+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.
+
+The `stdout`/`stderr` objects specifies a level of support for color through a `.level` property and a corresponding flag:
+
+- `.level = 1` and `.hasBasic = true`: Basic color support (16 colors)
+- `.level = 2` and `.has256 = true`: 256 color support
+- `.level = 3` and `.has16m = true`: Truecolor support (16 million colors)
+
+
+## Info
+
+It obeys the `--color` and `--no-color` CLI flags.
+
+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.
+
+Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively.
+
+
+## Related
+
+- [supports-color-cli](https://github.com/chalk/supports-color-cli) - CLI for this module
+- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right
+
+
+## Maintainers
+
+- [Sindre Sorhus](https://github.com/sindresorhus)
+- [Josh Junon](https://github.com/qix-)
+
+
+---
+
+
+
+---
diff --git a/server/package.json b/server/package.json
new file mode 100644
index 0000000000000000000000000000000000000000..a2e002fb9978c3220fb74f367597fe1ab74b28c7
--- /dev/null
+++ b/server/package.json
@@ -0,0 +1,107 @@
+{
+ "name": "@trek/server",
+ "version": "3.1.0",
+ "main": "src/index.ts",
+ "scripts": {
+ "start": "node --require tsconfig-paths/register dist/index.js",
+ "dev": "node scripts/dev.mjs",
+ "build": "node scripts/build.mjs",
+ "start:prod": "node --require tsconfig-paths/register dist/index.js",
+ "typecheck": "tsc --noEmit",
+ "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
+ "format:check": "prettier --check \"src/**/*.ts\" \"test/**/*.ts\"",
+ "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
+ "lint:check": "eslint .",
+ "test": "vitest run",
+ "test:watch": "vitest",
+ "test:unit": "vitest run tests/unit",
+ "test:integration": "vitest run tests/integration",
+ "test:ws": "vitest run tests/websocket",
+ "test:e2e": "vitest run tests/e2e",
+ "test:coverage": "vitest run --coverage"
+ },
+ "dependencies": {
+ "@modelcontextprotocol/sdk": "^1.28.0",
+ "@nestjs/common": "^11.1.24",
+ "@nestjs/core": "^11.1.24",
+ "@nestjs/platform-express": "^11.1.24",
+ "@nestjs/swagger": "^11.4.5",
+ "@simplewebauthn/server": "^13.1.2",
+ "@trek/shared": "*",
+ "archiver": "^6.0.1",
+ "bcryptjs": "^2.4.3",
+ "better-sqlite3": "^12.8.0",
+ "cookie-parser": "^1.4.7",
+ "cors": "^2.8.5",
+ "dotenv": "^16.4.1",
+ "express": "^4.18.3",
+ "fast-xml-parser": "^5.5.10",
+ "helmet": "^8.1.0",
+ "jimp": "^1.6.1",
+ "jsonwebtoken": "^9.0.2",
+ "multer": "^2.1.1",
+ "node-cron": "^4.2.1",
+ "nodemailer": "^8.0.5",
+ "otplib": "^12.0.1",
+ "qrcode": "^1.5.4",
+ "reflect-metadata": "^0.2.2",
+ "rxjs": "^7.8.2",
+ "semver": "^7.7.4",
+ "swagger-ui-express": "^5.0.1",
+ "tsconfig-paths": "^4.2.0",
+ "tsx": "^4.21.0",
+ "typescript": "^6.0.2",
+ "undici": "^7.0.0",
+ "unzipper": "^0.12.3",
+ "uuid": "^14.0.0",
+ "ws": "^8.21.0",
+ "zod": "^4.3.6"
+ },
+ "overrides": {
+ "hono": "^4.12.16",
+ "@hono/node-server": "^1.19.13",
+ "picomatch": "^4.0.4",
+ "ip-address": "^10.1.1",
+ "multer": "^2.1.1",
+ "ws": "^8.21.0",
+ "qs": "^6.15.2",
+ "file-type": "^21.3.4"
+ },
+ "devDependencies": {
+ "@eslint/js": "^10.0.1",
+ "@nestjs/testing": "^11.1.24",
+ "@swc/core": "^1.15.40",
+ "@trivago/prettier-plugin-sort-imports": "^6.0.2",
+ "@types/archiver": "^7.0.0",
+ "@types/bcryptjs": "^2.4.6",
+ "@types/better-sqlite3": "^7.6.13",
+ "@types/cookie-parser": "^1.4.10",
+ "@types/cors": "^2.8.19",
+ "@types/express": "^4.17.25",
+ "@types/jsonwebtoken": "^9.0.10",
+ "@types/multer": "^2.1.0",
+ "@types/node": "^25.5.0",
+ "@types/node-cron": "^3.0.11",
+ "@types/nodemailer": "^7.0.11",
+ "@types/qrcode": "^1.5.5",
+ "@types/semver": "^7.7.1",
+ "@types/supertest": "^6.0.3",
+ "@types/unzipper": "^0.10.11",
+ "@types/uuid": "^10.0.0",
+ "@types/ws": "^8.18.1",
+ "@vitest/coverage-istanbul": "^4.1.9",
+ "@vitest/coverage-v8": "^4.1.9",
+ "eslint": "^9.18.0",
+ "eslint-config-flat-gitignore": "^2.3.0",
+ "eslint-config-prettier": "^10.0.1",
+ "eslint-plugin-prettier": "^5.2.2",
+ "nodemon": "^3.1.0",
+ "prettier": "^3.8.3",
+ "prettier-plugin-organize-imports": "^4.3.0",
+ "supertest": "^7.2.2",
+ "typescript-eslint": "^8.58.2",
+ "tz-lookup": "^6.1.25",
+ "unplugin-swc": "^1.5.9",
+ "vitest": "^4.1.9"
+ }
+}
diff --git a/server/public/.gitkeep b/server/public/.gitkeep
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/server/reset-admin.js b/server/reset-admin.js
new file mode 100644
index 0000000000000000000000000000000000000000..41a2ccca4ac11e3a641b77fd0a732716adab5693
--- /dev/null
+++ b/server/reset-admin.js
@@ -0,0 +1,21 @@
+const path = require('path');
+const Database = require('better-sqlite3');
+const bcrypt = require('bcryptjs');
+
+const dbPath = path.join(__dirname, 'data/travel.db');
+const db = new Database(dbPath);
+
+const hash = bcrypt.hashSync('admin123', 10);
+const existing = db.prepare('SELECT id FROM users WHERE email = ?').get('admin@admin.com');
+
+if (existing) {
+ db.prepare('UPDATE users SET password_hash = ?, role = ? WHERE email = ?')
+ .run(hash, 'admin', 'admin@admin.com');
+ console.log('✓ Admin-Passwort zurückgesetzt: admin@admin.com / admin123');
+} else {
+ db.prepare('INSERT INTO users (username, email, password_hash, role) VALUES (?, ?, ?, ?)')
+ .run('admin', 'admin@admin.com', hash, 'admin');
+ console.log('✓ Admin-User erstellt: admin@admin.com / admin123');
+}
+
+db.close();
diff --git a/server/scripts/build-airports.mjs b/server/scripts/build-airports.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..153fe88f1fdb85f19a2a25a75a4ded1ec9209bb7
--- /dev/null
+++ b/server/scripts/build-airports.mjs
@@ -0,0 +1,108 @@
+#!/usr/bin/env node
+// Build server/assets/airports.json from OurAirports (davidmegginson.github.io/ourairports-data).
+// License: Public Domain. Keeps large/medium airports with an IATA code; timezone derived from coords via tz-lookup.
+
+import fs from 'node:fs'
+import path from 'node:path'
+import https from 'node:https'
+import { fileURLToPath } from 'node:url'
+import tzLookup from 'tz-lookup'
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url))
+const OUT = path.join(__dirname, '..', 'assets', 'airports.json')
+const SRC = 'https://davidmegginson.github.io/ourairports-data/airports.csv'
+
+function fetchText(url) {
+ return new Promise((resolve, reject) => {
+ https.get(url, (res) => {
+ if (res.statusCode !== 200) return reject(new Error(`HTTP ${res.statusCode}`))
+ let data = ''
+ res.setEncoding('utf8')
+ res.on('data', chunk => { data += chunk })
+ res.on('end', () => resolve(data))
+ }).on('error', reject)
+ })
+}
+
+function parseCsv(text) {
+ const rows = []
+ let row = []
+ let cur = ''
+ let inQuotes = false
+ for (let i = 0; i < text.length; i++) {
+ const ch = text[i]
+ if (inQuotes) {
+ if (ch === '"') {
+ if (text[i + 1] === '"') { cur += '"'; i++ } else { inQuotes = false }
+ } else {
+ cur += ch
+ }
+ } else {
+ if (ch === '"') inQuotes = true
+ else if (ch === ',') { row.push(cur); cur = '' }
+ else if (ch === '\n') { row.push(cur); rows.push(row); row = []; cur = '' }
+ else if (ch === '\r') { /* skip */ }
+ else cur += ch
+ }
+ }
+ if (cur.length > 0 || row.length > 0) { row.push(cur); rows.push(row) }
+ return rows
+}
+
+const raw = await fetchText(SRC)
+const rows = parseCsv(raw)
+const header = rows[0]
+const idx = (name) => header.indexOf(name)
+const TYPE = idx('type')
+const NAME = idx('name')
+const LAT = idx('latitude_deg')
+const LNG = idx('longitude_deg')
+const COUNTRY = idx('iso_country')
+const MUNICIPALITY = idx('municipality')
+const SERVICE = idx('scheduled_service')
+const ICAO = idx('icao_code')
+const IATA = idx('iata_code')
+
+const KEEP = new Set(['large_airport', 'medium_airport'])
+const airports = []
+let skippedNoTz = 0
+
+for (let i = 1; i < rows.length; i++) {
+ const r = rows[i]
+ if (!r || r.length < header.length) continue
+ if (!KEEP.has(r[TYPE])) continue
+ const iata = r[IATA]?.trim().toUpperCase()
+ if (!iata || iata.length !== 3) continue
+ if (r[SERVICE] !== 'yes') continue
+ const lat = Number(r[LAT])
+ const lng = Number(r[LNG])
+ if (!Number.isFinite(lat) || !Number.isFinite(lng)) continue
+
+ let tz = null
+ try { tz = tzLookup(lat, lng) } catch { skippedNoTz++; continue }
+ if (!tz) { skippedNoTz++; continue }
+
+ airports.push({
+ iata,
+ icao: r[ICAO]?.trim().toUpperCase() || null,
+ name: r[NAME],
+ city: r[MUNICIPALITY] || '',
+ country: r[COUNTRY] || '',
+ lat: Math.round(lat * 1e6) / 1e6,
+ lng: Math.round(lng * 1e6) / 1e6,
+ tz,
+ })
+}
+
+const seen = new Map()
+for (const a of airports) {
+ const existing = seen.get(a.iata)
+ if (!existing) { seen.set(a.iata, a); continue }
+ if (existing.icao && !a.icao) continue
+ if (!existing.icao && a.icao) seen.set(a.iata, a)
+}
+const unique = Array.from(seen.values()).sort((a, b) => a.iata.localeCompare(b.iata))
+
+fs.writeFileSync(OUT, JSON.stringify(unique))
+const size = fs.statSync(OUT).size
+console.log(`Wrote ${unique.length} airports to ${OUT} (${(size / 1024).toFixed(1)} KB); skipped ${skippedNoTz} without timezone`)
diff --git a/server/scripts/build-atlas-geo.mjs b/server/scripts/build-atlas-geo.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..7d98e446d40bacbec4552d088ed865badb500d30
--- /dev/null
+++ b/server/scripts/build-atlas-geo.mjs
@@ -0,0 +1,225 @@
+#!/usr/bin/env node
+// Build server/assets/atlas/{admin0,admin1}.geojson.gz from geoBoundaries (gbOpen).
+//
+// Why: Atlas previously fetched country + sub-national boundaries from Natural Earth's
+// GitHub `master` at runtime. Natural Earth is stale (e.g. it still shows Norway's
+// pre-2020 counties) and depicts some contested territory in ways the project does not
+// want (see nvkelso/natural-earth-vector#391). geoBoundaries (CC BY 4.0) is current,
+// redistributable, and carries ISO 3166-2 codes on its per-country ADM1 files.
+//
+// This downloads the *simplified* per-country gbOpen ADM0 (countries) and ADM1
+// (regions) layers from a pinned geoBoundaries revision, normalizes each feature to
+// the property names the Atlas client/server already read, and writes two gzipped
+// FeatureCollections that the server serves at runtime (no network at boot).
+//
+// geoBoundaries: CC BY 4.0 — https://www.geoboundaries.org/ (attribution required).
+
+import fs from 'node:fs'
+import path from 'node:path'
+import zlib from 'node:zlib'
+import { fileURLToPath } from 'node:url'
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url))
+const OUT_DIR = path.join(__dirname, '..', 'assets', 'atlas')
+
+// Pinned geoBoundaries revision (override with GB_REF=). The LFS media
+// endpoint resolves a commit SHA, branch, or tag in the [ path segment.
+const GB_REF = process.env.GB_REF || '5c25134028196d43ce97b5071934fd0cfc92f09f'
+const MEDIA = (a3, level) =>
+ `https://media.githubusercontent.com/media/wmgeolab/geoBoundaries/${GB_REF}` +
+ `/releaseData/gbOpen/${a3}/${level}/geoBoundaries-${a3}-${level}_simplified.geojson`
+
+// Country borders come from CGAZ (the Comprehensive Global Administrative Zones composite)
+// rather than per-country gbOpen ADM0: CGAZ is gap-filled, so it includes territories
+// that gbOpen omits or folds away — notably Svalbard (inside Norway's geometry) and
+// Greenland. The country layer only needs A3/A2/name, so CGAZ's lack of `shapeISO` is
+// irrelevant. (gbOpen ADM0 maxes Norway at 71°N and has no Svalbard at all.)
+const CGAZ_ADM0 =
+ `https://media.githubusercontent.com/media/wmgeolab/geoBoundaries/${GB_REF}` +
+ `/releaseData/CGAZ/geoBoundariesCGAZ_ADM0.geojson`
+
+const CONCURRENCY = 8
+const RETRIES = 3
+
+// Complete ISO-3166-1 alpha-3 → alpha-2 map (source: lukes/ISO-3166-Countries-with-
+// Regional-Codes). Drives ADM1 enumeration (one gbOpen request per code; missing ones
+// 404 and are skipped) and stamps `iso_a2`/`ISO_A2` (geoBoundaries keys by alpha-3
+// `shapeGroup`). A complete map — not the client's curated ~180 — is what restores the
+// dropped territories (Greenland, Falklands, French Guiana, …).
+const A3_TO_A2 = {"ABW":"AW", "AFG":"AF", "AGO":"AO", "AIA":"AI", "ALA":"AX", "ALB":"AL", "AND":"AD", "ARE":"AE", "ARG":"AR", "ARM":"AM", "ASM":"AS", "ATA":"AQ", "ATF":"TF", "ATG":"AG", "AUS":"AU", "AUT":"AT", "AZE":"AZ", "BDI":"BI", "BEL":"BE", "BEN":"BJ", "BES":"BQ", "BFA":"BF", "BGD":"BD", "BGR":"BG", "BHR":"BH", "BHS":"BS", "BIH":"BA", "BLM":"BL", "BLR":"BY", "BLZ":"BZ", "BMU":"BM", "BOL":"BO", "BRA":"BR", "BRB":"BB", "BRN":"BN", "BTN":"BT", "BVT":"BV", "BWA":"BW", "CAF":"CF", "CAN":"CA", "CCK":"CC", "CHE":"CH", "CHL":"CL", "CHN":"CN", "CIV":"CI", "CMR":"CM", "COD":"CD", "COG":"CG", "COK":"CK", "COL":"CO", "COM":"KM", "CPV":"CV", "CRI":"CR", "CUB":"CU", "CUW":"CW", "CXR":"CX", "CYM":"KY", "CYP":"CY", "CZE":"CZ", "DEU":"DE", "DJI":"DJ", "DMA":"DM", "DNK":"DK", "DOM":"DO", "DZA":"DZ", "ECU":"EC", "EGY":"EG", "ERI":"ER", "ESH":"EH", "ESP":"ES", "EST":"EE", "ETH":"ET", "FIN":"FI", "FJI":"FJ", "FLK":"FK", "FRA":"FR", "FRO":"FO", "FSM":"FM", "GAB":"GA", "GBR":"GB", "GEO":"GE", "GGY":"GG", "GHA":"GH", "GIB":"GI", "GIN":"GN", "GLP":"GP", "GMB":"GM", "GNB":"GW", "GNQ":"GQ", "GRC":"GR", "GRD":"GD", "GRL":"GL", "GTM":"GT", "GUF":"GF", "GUM":"GU", "GUY":"GY", "HKG":"HK", "HMD":"HM", "HND":"HN", "HRV":"HR", "HTI":"HT", "HUN":"HU", "IDN":"ID", "IMN":"IM", "IND":"IN", "IOT":"IO", "IRL":"IE", "IRN":"IR", "IRQ":"IQ", "ISL":"IS", "ISR":"IL", "ITA":"IT", "JAM":"JM", "JEY":"JE", "JOR":"JO", "JPN":"JP", "KAZ":"KZ", "KEN":"KE", "KGZ":"KG", "KHM":"KH", "KIR":"KI", "KNA":"KN", "KOR":"KR", "KWT":"KW", "LAO":"LA", "LBN":"LB", "LBR":"LR", "LBY":"LY", "LCA":"LC", "LIE":"LI", "LKA":"LK", "LSO":"LS", "LTU":"LT", "LUX":"LU", "LVA":"LV", "MAC":"MO", "MAF":"MF", "MAR":"MA", "MCO":"MC", "MDA":"MD", "MDG":"MG", "MDV":"MV", "MEX":"MX", "MHL":"MH", "MKD":"MK", "MLI":"ML", "MLT":"MT", "MMR":"MM", "MNE":"ME", "MNG":"MN", "MNP":"MP", "MOZ":"MZ", "MRT":"MR", "MSR":"MS", "MTQ":"MQ", "MUS":"MU", "MWI":"MW", "MYS":"MY", "MYT":"YT", "NAM":"NA", "NCL":"NC", "NER":"NE", "NFK":"NF", "NGA":"NG", "NIC":"NI", "NIU":"NU", "NLD":"NL", "NOR":"NO", "NPL":"NP", "NRU":"NR", "NZL":"NZ", "OMN":"OM", "PAK":"PK", "PAN":"PA", "PCN":"PN", "PER":"PE", "PHL":"PH", "PLW":"PW", "PNG":"PG", "POL":"PL", "PRI":"PR", "PRK":"KP", "PRT":"PT", "PRY":"PY", "PSE":"PS", "PYF":"PF", "QAT":"QA", "REU":"RE", "ROU":"RO", "RUS":"RU", "RWA":"RW", "SAU":"SA", "SDN":"SD", "SEN":"SN", "SGP":"SG", "SGS":"GS", "SHN":"SH", "SJM":"SJ", "SLB":"SB", "SLE":"SL", "SLV":"SV", "SMR":"SM", "SOM":"SO", "SPM":"PM", "SRB":"RS", "SSD":"SS", "STP":"ST", "SUR":"SR", "SVK":"SK", "SVN":"SI", "SWE":"SE", "SWZ":"SZ", "SXM":"SX", "SYC":"SC", "SYR":"SY", "TCA":"TC", "TCD":"TD", "TGO":"TG", "THA":"TH", "TJK":"TJ", "TKL":"TK", "TKM":"TM", "TLS":"TL", "TON":"TO", "TTO":"TT", "TUN":"TN", "TUR":"TR", "TUV":"TV", "TWN":"TW", "TZA":"TZ", "UGA":"UG", "UKR":"UA", "UMI":"UM", "URY":"UY", "USA":"US", "UZB":"UZ", "VAT":"VA", "VCT":"VC", "VEN":"VE", "VGB":"VG", "VIR":"VI", "VNM":"VN", "VUT":"VU", "WLF":"WF", "WSM":"WS", "YEM":"YE", "ZAF":"ZA", "ZMB":"ZM", "ZWE":"ZW"}
+
+const COUNTRIES = Object.keys(A3_TO_A2) // every ISO alpha-3 code (ADM1 fetch list)
+
+// Cache raw downloads so re-runs (e.g. to tune simplification) don't re-fetch ~360 files.
+const CACHE_DIR = path.join(__dirname, '..', '.atlas-geo-cache', GB_REF)
+
+async function fetchGeo(url) {
+ const cacheFile = path.join(CACHE_DIR, url.split('/').slice(-1)[0])
+ if (fs.existsSync(cacheFile)) {
+ const cached = fs.readFileSync(cacheFile, 'utf8')
+ return cached === '' ? null : JSON.parse(cached)
+ }
+ for (let attempt = 1; attempt <= RETRIES; attempt++) {
+ try {
+ const res = await fetch(url, { headers: { 'User-Agent': 'TREK atlas builder' } })
+ if (res.status === 404) { fs.writeFileSync(cacheFile, ''); return null } // no file — skip
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
+ const text = await res.text()
+ if (text.startsWith('version https://git-lfs')) throw new Error('got LFS pointer, not content')
+ const parsed = JSON.parse(text)
+ fs.writeFileSync(cacheFile, text)
+ return parsed
+ } catch (err) {
+ if (attempt === RETRIES) {
+ console.warn(` ! ${url.split('/').slice(-1)[0]}: ${err.message}`)
+ return null
+ }
+ await new Promise(r => setTimeout(r, 500 * attempt))
+ }
+ }
+ return null
+}
+
+// Run async tasks with a fixed concurrency cap.
+async function pool(items, worker) {
+ const results = []
+ let i = 0
+ const runners = Array.from({ length: CONCURRENCY }, async () => {
+ while (i < items.length) {
+ const idx = i++
+ results[idx] = await worker(items[idx], idx)
+ }
+ })
+ await Promise.all(runners)
+ return results
+}
+
+// Geometry size control. geoBoundaries' "_simplified" files still carry ~12-decimal
+// coordinates, which dominate the JSON size. Quantizing to a fixed grid (rounding
+// preserves topology — identical input coords map to identical output) and dropping
+// the now-redundant consecutive duplicate points shrinks the bundles ~5-8x with no
+// visible effect at the atlas' zoom range (3-10). ADM0 fills are viewed zoomed out, so
+// they tolerate a coarser grid than ADM1 region borders.
+const ADM0_DECIMALS = 2 // ~1.1 km
+const ADM1_DECIMALS = 3 // ~110 m
+
+function quantizeRing(ring, decimals) {
+ const m = 10 ** decimals
+ const out = []
+ let prevX, prevY
+ for (const pt of ring) {
+ const x = Math.round(pt[0] * m) / m
+ const y = Math.round(pt[1] * m) / m
+ if (x === prevX && y === prevY) continue
+ out.push([x, y])
+ prevX = x; prevY = y
+ }
+ return out
+}
+
+// Quantize a (Multi)Polygon, dropping rings that collapse below a valid ring (<4 pts).
+function quantizeGeometry(geom, decimals) {
+ if (!geom) return null
+ if (geom.type === 'Polygon') {
+ const rings = geom.coordinates.map(r => quantizeRing(r, decimals)).filter(r => r.length >= 4)
+ return rings.length ? { type: 'Polygon', coordinates: rings } : null
+ }
+ if (geom.type === 'MultiPolygon') {
+ const polys = geom.coordinates
+ .map(poly => poly.map(r => quantizeRing(r, decimals)).filter(r => r.length >= 4))
+ .filter(poly => poly.length)
+ return polys.length ? { type: 'MultiPolygon', coordinates: polys } : null
+ }
+ return geom
+}
+
+// Normalize one CGAZ ADM0 feature (keyed by alpha-3 `shapeGroup`) to the property names
+// the client country layer reads (ISO_A2/ADM0_A3/NAME/ADMIN). Returns null for the CRS
+// pseudo-entry or anything without a group/geometry.
+function normalizeAdm0Feature(f) {
+ const a3 = f.properties?.shapeGroup
+ if (!a3) return null
+ const name = f.properties?.shapeName || a3
+ const geometry = quantizeGeometry(f.geometry, ADM0_DECIMALS)
+ if (!geometry) return null
+ return {
+ type: 'Feature',
+ properties: { ISO_A2: A3_TO_A2[a3] || null, ADM0_A3: a3, NAME: name, ADMIN: name },
+ geometry,
+ }
+}
+
+function normalizeAdm1(geo, a3, countryName) {
+ if (!geo?.features) return []
+ return geo.features.map(f => {
+ const name = f.properties?.shapeName || ''
+ const geometry = quantizeGeometry(f.geometry, ADM1_DECIMALS)
+ if (!geometry) return null
+ const a2 = A3_TO_A2[a3] || null
+ // shapeISO is a real ISO 3166-2 code for ~90% of features; geoBoundaries leaves the
+ // rest blank or uses an `XX_YYY` placeholder. Keep real/placeholder codes as-is
+ // (stable per polygon → manual mark/unmark works, real ones match Nominatim). For
+ // blank codes, synthesize a stable id mirroring the server's geocode fallback so
+ // every region is still markable.
+ let code = f.properties?.shapeISO || ''
+ if (!code && a2) code = `${a2}-${name.replace(/[^A-Za-z0-9]/g, '').substring(0, 3).toUpperCase()}`
+ return {
+ type: 'Feature',
+ // Property names the Atlas region layer + server getRegionGeo already read.
+ properties: {
+ iso_a2: a2,
+ iso_3166_2: code,
+ name,
+ name_en: name,
+ admin: countryName,
+ },
+ geometry,
+ }
+ }).filter(Boolean)
+}
+
+async function main() {
+ console.log(`[atlas-geo] geoBoundaries ref ${GB_REF}; ${COUNTRIES.length} countries`)
+ fs.mkdirSync(OUT_DIR, { recursive: true })
+ fs.mkdirSync(CACHE_DIR, { recursive: true })
+
+ // ADM0 (countries) — one comprehensive CGAZ file (large; cached). Also yields the
+ // English country name (shapeGroup → shapeName) used for the ADM1 `admin` field.
+ console.log('[atlas-geo] downloading CGAZ ADM0 (countries)…')
+ const cgaz = await fetchGeo(CGAZ_ADM0)
+ const adm0Features = []
+ const a3ToName = {}
+ for (const f of cgaz?.features || []) {
+ const nf = normalizeAdm0Feature(f)
+ if (nf) { a3ToName[nf.properties.ADM0_A3] = nf.properties.NAME; adm0Features.push(nf) }
+ }
+
+ // ADM1 (sub-national regions) — per-country gbOpen (carries ISO 3166-2 `shapeISO`).
+ console.log('[atlas-geo] downloading ADM1 (regions)…')
+ const adm1Raw = await pool(COUNTRIES, a3 => fetchGeo(MEDIA(a3, 'ADM1')))
+ const adm1Features = []
+ let withCodes = 0
+ COUNTRIES.forEach((a3, idx) => {
+ const feats = normalizeAdm1(adm1Raw[idx], a3, a3ToName[a3] || a3)
+ for (const f of feats) if (f.properties.iso_3166_2) withCodes++
+ adm1Features.push(...feats)
+ })
+
+ const write = (name, features) => {
+ const fc = { type: 'FeatureCollection', features }
+ const gz = zlib.gzipSync(Buffer.from(JSON.stringify(fc)), { level: 9 })
+ const file = path.join(OUT_DIR, `${name}.geojson.gz`)
+ fs.writeFileSync(file, gz)
+ console.log(`[atlas-geo] wrote ${path.relative(path.join(__dirname, '..'), file)} — ${features.length} features, ${(gz.length / 1e6).toFixed(1)} MB gz`)
+ }
+
+ write('admin0', adm0Features)
+ write('admin1', adm1Features)
+
+ const missing1 = COUNTRIES.filter((a3, i) => !normalizeAdm1(adm1Raw[i], a3, '').length)
+ console.log(`[atlas-geo] ADM0 country features: ${adm0Features.length}`)
+ console.log(`[atlas-geo] ADM1 countries without regions (skipped/404): ${missing1.length}`)
+ console.log(`[atlas-geo] ADM1 features with ISO 3166-2 code: ${withCodes}/${adm1Features.length}`)
+}
+
+main().catch(err => { console.error(err); process.exit(1) })
diff --git a/server/scripts/build.mjs b/server/scripts/build.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..24deb830a6b9e58b1ff94c13dd4ef9076f7b7887
--- /dev/null
+++ b/server/scripts/build.mjs
@@ -0,0 +1,9 @@
+import { execSync } from 'node:child_process';
+
+try {
+ execSync('tsc -p tsconfig.build.json', { stdio: 'inherit' });
+} catch {
+ console.warn('[build] tsc reported type errors — emitting anyway (gated by `npm run typecheck`).');
+}
+
+console.log('[build] dist ready.');
diff --git a/server/scripts/dev.mjs b/server/scripts/dev.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..8063174f2205d97869c452235742f0eea2cb799b
--- /dev/null
+++ b/server/scripts/dev.mjs
@@ -0,0 +1,32 @@
+import { execSync, spawn } from 'node:child_process';
+
+console.log('[dev] initial build...');
+execSync('node scripts/build.mjs', { stdio: 'inherit' });
+
+const children = [];
+const stop = () => { children.forEach((c) => { try { c.kill(); } catch {} }); process.exit(0); };
+process.on('SIGINT', stop);
+process.on('SIGTERM', stop);
+
+// Start tsc -w and wait for its first "Watching for file changes." before launching
+// node --watch, so the initial tsc compilation doesn't trigger a spurious restart.
+const tsc = spawn('npx', ['tsc', '-w', '-p', 'tsconfig.build.json', '--preserveWatchOutput'], {
+ stdio: ['ignore', 'pipe', 'inherit'],
+ shell: true,
+});
+children.push(tsc);
+
+let nodeProc = null;
+let ready = false;
+
+tsc.stdout.on('data', (chunk) => {
+ process.stdout.write(chunk);
+ if (!ready && chunk.toString().includes('Watching for file changes')) {
+ ready = true;
+ nodeProc = spawn('node', ['--require', 'tsconfig-paths/register', '--watch', 'dist/index.js'], {
+ stdio: 'inherit',
+ shell: true,
+ });
+ children.push(nodeProc);
+ }
+});
diff --git a/server/scripts/migrate-encryption.ts b/server/scripts/migrate-encryption.ts
new file mode 100644
index 0000000000000000000000000000000000000000..78e19e1a5e54cdcc62f52fea8c97de2ef4b2c8cf
--- /dev/null
+++ b/server/scripts/migrate-encryption.ts
@@ -0,0 +1,329 @@
+/**
+ * Encryption key migration script.
+ *
+ * Re-encrypts all at-rest secrets in the TREK database from one ENCRYPTION_KEY
+ * to another without requiring the application to be running.
+ *
+ * Usage (host):
+ * cd server
+ * node --import tsx scripts/migrate-encryption.ts
+ *
+ * Usage (Docker):
+ * docker exec -it trek node --import tsx scripts/migrate-encryption.ts
+ *
+ * The script will prompt for the old and new keys interactively so they never
+ * appear in shell history, process arguments, or log output.
+ */
+
+import crypto from 'crypto';
+import fs from 'fs';
+import path from 'path';
+import readline from 'readline';
+import Database from 'better-sqlite3';
+
+// ---------------------------------------------------------------------------
+// Crypto helpers — mirrors apiKeyCrypto.ts and mfaCrypto.ts but with
+// explicit key arguments so the script is independent of config.ts / env vars.
+// ---------------------------------------------------------------------------
+
+const ENCRYPTED_PREFIX = 'enc:v1:';
+
+function apiKey(encryptionKey: string): Buffer {
+ return crypto.createHash('sha256').update(`${encryptionKey}:api_keys:v1`).digest();
+}
+
+function mfaKey(encryptionKey: string): Buffer {
+ return crypto.createHash('sha256').update(`${encryptionKey}:mfa:v1`).digest();
+}
+
+function encryptApiKey(plain: string, encryptionKey: string): string {
+ const iv = crypto.randomBytes(12);
+ const cipher = crypto.createCipheriv('aes-256-gcm', apiKey(encryptionKey), iv);
+ const enc = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
+ const tag = cipher.getAuthTag();
+ return `${ENCRYPTED_PREFIX}${Buffer.concat([iv, tag, enc]).toString('base64')}`;
+}
+
+function decryptApiKey(value: string, encryptionKey: string): string | null {
+ if (!value.startsWith(ENCRYPTED_PREFIX)) return null;
+ try {
+ const buf = Buffer.from(value.slice(ENCRYPTED_PREFIX.length), 'base64');
+ const decipher = crypto.createDecipheriv('aes-256-gcm', apiKey(encryptionKey), buf.subarray(0, 12));
+ decipher.setAuthTag(buf.subarray(12, 28));
+ return Buffer.concat([decipher.update(buf.subarray(28)), decipher.final()]).toString('utf8');
+ } catch {
+ return null;
+ }
+}
+
+function encryptMfa(plain: string, encryptionKey: string): string {
+ const iv = crypto.randomBytes(12);
+ const cipher = crypto.createCipheriv('aes-256-gcm', mfaKey(encryptionKey), iv);
+ const enc = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
+ const tag = cipher.getAuthTag();
+ return Buffer.concat([iv, tag, enc]).toString('base64');
+}
+
+function decryptMfa(value: string, encryptionKey: string): string | null {
+ try {
+ const buf = Buffer.from(value, 'base64');
+ if (buf.length < 28) return null;
+ const decipher = crypto.createDecipheriv('aes-256-gcm', mfaKey(encryptionKey), buf.subarray(0, 12));
+ decipher.setAuthTag(buf.subarray(12, 28));
+ return Buffer.concat([decipher.update(buf.subarray(28)), decipher.final()]).toString('utf8');
+ } catch {
+ return null;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Prompt helpers
+// ---------------------------------------------------------------------------
+// A single readline interface is shared for the entire script lifetime so
+// stdin is never paused between prompts.
+//
+// Lines are collected into a queue as soon as readline emits them — this
+// prevents the race where a line event fires before the next listener is
+// registered (common with piped / pasted input that arrives all at once).
+
+const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
+
+const lineQueue: string[] = [];
+const lineWaiters: ((line: string) => void)[] = [];
+
+rl.on('line', (line) => {
+ if (lineWaiters.length > 0) {
+ lineWaiters.shift()!(line);
+ } else {
+ lineQueue.push(line);
+ }
+});
+
+function nextLine(): Promise {
+ return new Promise((resolve) => {
+ if (lineQueue.length > 0) {
+ resolve(lineQueue.shift()!);
+ } else {
+ lineWaiters.push(resolve);
+ }
+ });
+}
+
+// Muted prompt — typed/pasted characters are not echoed.
+// _writeToOutput is suppressed only while waiting for this line.
+async function promptSecret(question: string): Promise {
+ process.stdout.write(question);
+ (rl as any)._writeToOutput = () => {};
+ const line = await nextLine();
+ (rl as any)._writeToOutput = (s: string) => process.stdout.write(s);
+ process.stdout.write('\n');
+ return line.trim();
+}
+
+async function prompt(question: string): Promise {
+ process.stdout.write(question);
+ const line = await nextLine();
+ return line.trim();
+}
+
+// ---------------------------------------------------------------------------
+// Migration
+// ---------------------------------------------------------------------------
+
+interface MigrationResult {
+ migrated: number;
+ alreadyMigrated: number;
+ skipped: number;
+ errors: string[];
+}
+
+async function main() {
+ console.log('=== TREK Encryption Key Migration ===\n');
+ console.log('This script re-encrypts all stored secrets under a new ENCRYPTION_KEY.');
+ console.log('A backup of the database will be created before any changes are made.\n');
+
+ // Resolve DB path
+ const dbPath = path.resolve(
+ process.env.DB_PATH ?? path.join(__dirname, '../data/travel.db')
+ );
+
+ if (!fs.existsSync(dbPath)) {
+ console.error(`Database not found at: ${dbPath}`);
+ console.error('Set DB_PATH env var if your database is in a non-standard location.');
+ process.exit(1);
+ }
+
+ console.log(`Database: ${dbPath}\n`);
+
+ // Collect keys interactively
+ const oldKey = await promptSecret('Old ENCRYPTION_KEY: ');
+ const newKey = await promptSecret('New ENCRYPTION_KEY: ');
+
+ if (!oldKey || !newKey) {
+ rl.close();
+ console.error('Both keys are required.');
+ process.exit(1);
+ }
+
+ if (oldKey === newKey) {
+ rl.close();
+ console.error('Old and new keys are identical — nothing to do.');
+ process.exit(0);
+ }
+
+ // Confirm
+ const confirm = await prompt('\nProceed with migration? This will modify the database. Type "yes" to confirm: ');
+ if (confirm.trim().toLowerCase() !== 'yes') {
+ rl.close();
+ console.log('Aborted.');
+ process.exit(0);
+ }
+
+ // Backup
+ const backupPath = `${dbPath}.backup-${Date.now()}`;
+ fs.copyFileSync(dbPath, backupPath);
+ console.log(`\nBackup created: ${backupPath}`);
+
+ const db = new Database(dbPath);
+ db.pragma('journal_mode = WAL');
+
+ const result: MigrationResult = { migrated: 0, alreadyMigrated: 0, skipped: 0, errors: [] };
+
+ // Helper: migrate a single api-key-style value (enc:v1: prefix)
+ function migrateApiKeyValue(raw: string, label: string): string | null {
+ if (!raw || !raw.startsWith(ENCRYPTED_PREFIX)) {
+ result.skipped++;
+ console.warn(` SKIP ${label}: not an encrypted value (missing enc:v1: prefix)`);
+ return null;
+ }
+
+ const plain = decryptApiKey(raw, oldKey);
+ if (plain !== null) {
+ result.migrated++;
+ return encryptApiKey(plain, newKey);
+ }
+
+ // Try new key — already migrated?
+ const check = decryptApiKey(raw, newKey);
+ if (check !== null) {
+ result.alreadyMigrated++;
+ return null; // no change needed
+ }
+
+ result.errors.push(`${label}: decryption failed with both keys`);
+ console.error(` ERROR ${label}: could not decrypt with either key — skipping`);
+ return null;
+ }
+
+ // Helper: migrate a single MFA value (no prefix, raw base64)
+ function migrateMfaValue(raw: string, label: string): string | null {
+ if (!raw) { result.skipped++; return null; }
+
+ const plain = decryptMfa(raw, oldKey);
+ if (plain !== null) {
+ result.migrated++;
+ return encryptMfa(plain, newKey);
+ }
+
+ const check = decryptMfa(raw, newKey);
+ if (check !== null) {
+ result.alreadyMigrated++;
+ return null;
+ }
+
+ result.errors.push(`${label}: decryption failed with both keys`);
+ console.error(` ERROR ${label}: could not decrypt with either key — skipping`);
+ return null;
+ }
+
+ db.transaction(() => {
+ // --- app_settings: oidc_client_secret, smtp_pass, admin_webhook_url, admin_ntfy_token ---
+ for (const key of ['oidc_client_secret', 'smtp_pass', 'admin_webhook_url', 'admin_ntfy_token']) {
+ const row = db.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as { value: string } | undefined;
+ if (!row?.value) continue;
+ const newVal = migrateApiKeyValue(row.value, `app_settings.${key}`);
+ if (newVal !== null) {
+ db.prepare('UPDATE app_settings SET value = ? WHERE key = ?').run(newVal, key);
+ }
+ }
+
+ // --- users: api key columns + synology credentials ---
+ const apiKeyColumns = ['maps_api_key', 'openweather_api_key', 'immich_api_key', 'synology_password', 'synology_sid', 'synology_did'];
+ const users = db.prepare('SELECT id FROM users').all() as { id: number }[];
+
+ for (const user of users) {
+ const row = db.prepare(`SELECT ${apiKeyColumns.join(', ')} FROM users WHERE id = ?`).get(user.id) as Record;
+
+ for (const col of apiKeyColumns) {
+ if (!row[col]) continue;
+ const newVal = migrateApiKeyValue(row[col], `users[${user.id}].${col}`);
+ if (newVal !== null) {
+ db.prepare(`UPDATE users SET ${col} = ? WHERE id = ?`).run(newVal, user.id);
+ }
+ }
+
+ // mfa_secret (mfa crypto)
+ 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;
+ if (mfaRow?.mfa_secret) {
+ const newVal = migrateMfaValue(mfaRow.mfa_secret, `users[${user.id}].mfa_secret`);
+ if (newVal !== null) {
+ db.prepare('UPDATE users SET mfa_secret = ? WHERE id = ?').run(newVal, user.id);
+ }
+ }
+ }
+ // --- settings: per-user encrypted keys ---
+ const encryptedSettingKeys = ['webhook_url', 'ntfy_token', 'mapbox_access_token'];
+ const settingRows = db.prepare(
+ `SELECT user_id, key, value FROM settings WHERE key IN (${encryptedSettingKeys.map(() => '?').join(', ')})`
+ ).all(...encryptedSettingKeys) as { user_id: number; key: string; value: string }[];
+
+ for (const row of settingRows) {
+ if (!row.value) continue;
+ const newVal = migrateApiKeyValue(row.value, `settings[user=${row.user_id}].${row.key}`);
+ if (newVal !== null) {
+ db.prepare('UPDATE settings SET value = ? WHERE user_id = ? AND key = ?').run(newVal, row.user_id, row.key);
+ }
+ }
+
+ // --- trip_album_links: passphrase ---
+ const albumLinks = db.prepare('SELECT id, passphrase FROM trip_album_links WHERE passphrase IS NOT NULL').all() as { id: number; passphrase: string }[];
+ for (const row of albumLinks) {
+ const newVal = migrateApiKeyValue(row.passphrase, `trip_album_links[${row.id}].passphrase`);
+ if (newVal !== null) {
+ db.prepare('UPDATE trip_album_links SET passphrase = ? WHERE id = ?').run(newVal, row.id);
+ }
+ }
+
+ // --- trek_photos: passphrase ---
+ const photos = db.prepare('SELECT id, passphrase FROM trek_photos WHERE passphrase IS NOT NULL').all() as { id: number; passphrase: string }[];
+ for (const row of photos) {
+ const newVal = migrateApiKeyValue(row.passphrase, `trek_photos[${row.id}].passphrase`);
+ if (newVal !== null) {
+ db.prepare('UPDATE trek_photos SET passphrase = ? WHERE id = ?').run(newVal, row.id);
+ }
+ }
+ })();
+
+ db.close();
+ rl.close();
+
+ console.log('\n=== Migration complete ===');
+ console.log(` Migrated: ${result.migrated}`);
+ console.log(` Already on new key: ${result.alreadyMigrated}`);
+ console.log(` Skipped (empty): ${result.skipped}`);
+ if (result.errors.length > 0) {
+ console.warn(` Errors: ${result.errors.length}`);
+ result.errors.forEach(e => console.warn(` - ${e}`));
+ console.warn('\nSome secrets could not be migrated. Check the errors above.');
+ console.warn(`Your original database is backed up at: ${backupPath}`);
+ process.exit(1);
+ } else {
+ console.log('\nAll secrets successfully re-encrypted.');
+ console.log(`Backup retained at: ${backupPath}`);
+ }
+}
+
+main().catch((err) => {
+ console.error('Unexpected error:', err);
+ process.exit(1);
+});
diff --git a/server/src/addons.ts b/server/src/addons.ts
new file mode 100644
index 0000000000000000000000000000000000000000..07a06ffe9864bfafc600db42dcde099900212c65
--- /dev/null
+++ b/server/src/addons.ts
@@ -0,0 +1,13 @@
+export const ADDON_IDS = {
+ MCP: 'mcp',
+ PACKING: 'packing',
+ BUDGET: 'budget',
+ DOCUMENTS: 'documents',
+ VACAY: 'vacay',
+ ATLAS: 'atlas',
+ COLLAB: 'collab',
+ JOURNEY: 'journey',
+ AIRTRAIL: 'airtrail',
+} as const;
+
+export type AddonId = typeof ADDON_IDS[keyof typeof ADDON_IDS];
diff --git a/server/src/bootstrap.ts b/server/src/bootstrap.ts
new file mode 100644
index 0000000000000000000000000000000000000000..8947368d7f24eb17d1571138c333b98c15d70ff6
--- /dev/null
+++ b/server/src/bootstrap.ts
@@ -0,0 +1,55 @@
+import { NestFactory } from '@nestjs/core';
+import { ExpressAdapter } from '@nestjs/platform-express';
+import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
+import type { INestApplication } from '@nestjs/common';
+import { AppModule } from './nest/app.module';
+import { applyGlobalMiddleware } from './middleware/globalMiddleware';
+import { applyPlatformUploads, applyPlatformTransport, applyPlatformStatic } from './nest/platform/platform.routes';
+
+/**
+ * Builds the unified TREK NestJS application that serves the ENTIRE surface — the
+ * former Express app is gone. One builder is shared by the production bootstrap
+ * (index.ts) and the integration-test harness so the two can never drift.
+ *
+ * Composition order is load-bearing. Everything except the SPA index.html fallback
+ * is registered on the underlying Express instance BEFORE `app.init()`, because
+ * Nest's router terminates an unmatched request by throwing NotFoundException — it
+ * does NOT fall through to a route registered after init, so a post-init Express
+ * route is unreachable. The platform routes are all specific paths (/uploads/*,
+ * /api/health, /mcp, /.well-known/*, /oauth/{authorize,register,consent}) so they
+ * match their own requests and `next()` everything else through to the Nest
+ * controllers registered during init.
+ *
+ * 1. applyGlobalMiddleware — helmet/CSP, CORS, HSTS, forced-HTTPS, the global MFA
+ * policy, request logging + cookie-parser. `bodyParser: false` so Nest does its
+ * own parsing and the raw /mcp body reaches the MCP handler unparsed.
+ * 2. applyPlatformUploads — the static + guarded /uploads/* routes.
+ * 3. applyPlatformTransport — /api/health, the OAuth/MCP SDK + /.well-known
+ * metadata, the /mcp routes, the /oauth/consent COOP header.
+ * 4. applyPlatformStatic — the production built-client static assets (so a real
+ * asset request returns the file before the Nest router 404s it).
+ * 5. app.init() — registers every migrated /api domain (the Nest controllers).
+ *
+ * The SPA index.html fallback (unmatched GET → index.html in production) is the
+ * SpaFallbackFilter (APP_FILTER in AppModule); the global error envelope is the
+ * TrekExceptionFilter (also APP_FILTER).
+ */
+export async function buildApp(): Promise {
+ const app = await NestFactory.create(AppModule, new ExpressAdapter());
+ const instance = app.getHttpAdapter().getInstance();
+ applyGlobalMiddleware(instance, { bodyParser: false });
+ applyPlatformUploads(instance);
+ applyPlatformTransport(instance);
+ applyPlatformStatic(instance);
+
+ const config = new DocumentBuilder()
+ .setTitle('TREK API')
+ .setDescription('The TREK API documentation')
+ .setVersion('1.0')
+ .build();
+ const document = SwaggerModule.createDocument(app, config);
+ SwaggerModule.setup('api-docs', app, document);
+
+ await app.init();
+ return app;
+}
diff --git a/server/src/config.ts b/server/src/config.ts
new file mode 100644
index 0000000000000000000000000000000000000000..94cf31e1e746f53deb4cf6dcfd93806caeca0611
--- /dev/null
+++ b/server/src/config.ts
@@ -0,0 +1,156 @@
+import crypto from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+import { SUPPORTED_LANGUAGE_CODES as SUPPORTED_LANG_CODES } from '@trek/shared';
+
+const dataDir = path.resolve(__dirname, '../data');
+
+// JWT_SECRET is always managed by the server — auto-generated on first start and
+// persisted to data/.jwt_secret. Use the admin panel to rotate it; do not set it
+// via environment variable (env var would override a rotation on next restart).
+const jwtSecretFile = path.join(dataDir, '.jwt_secret');
+let _jwtSecret: string;
+
+try {
+ _jwtSecret = fs.readFileSync(jwtSecretFile, 'utf8').trim();
+} catch {
+ _jwtSecret = crypto.randomBytes(32).toString('hex');
+ try {
+ if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true });
+ fs.writeFileSync(jwtSecretFile, _jwtSecret, { mode: 0o600 });
+ console.log('Generated and saved JWT secret to', jwtSecretFile);
+ } catch (writeErr: unknown) {
+ console.warn('WARNING: Could not persist JWT secret to disk:', writeErr instanceof Error ? writeErr.message : writeErr);
+ console.warn('Sessions will reset on server restart.');
+ }
+}
+
+// export let so TypeScript's CJS output keeps exports.JWT_SECRET live
+// (generates `exports.JWT_SECRET = JWT_SECRET = newVal` inside updateJwtSecret)
+export let JWT_SECRET = _jwtSecret;
+
+// Called by the admin rotate-jwt-secret endpoint to update the in-process
+// binding that all middleware and route files reference.
+export function updateJwtSecret(newSecret: string): void {
+ JWT_SECRET = newSecret;
+}
+
+// ENCRYPTION_KEY is used to derive at-rest encryption keys for stored secrets
+// (API keys, MFA TOTP secrets, SMTP password, OIDC client secret, etc.).
+// Keeping it separate from JWT_SECRET means you can rotate session tokens without
+// invalidating all stored encrypted data, and vice-versa.
+//
+// Resolution order:
+// 1. ENCRYPTION_KEY env var — explicit, always takes priority.
+// 2. data/.encryption_key file — present on any install that has started at
+// least once (written automatically by cases 1b and 3 below).
+// 3. data/.jwt_secret — one-time fallback for existing installs upgrading
+// without a pre-set ENCRYPTION_KEY. The value is immediately persisted to
+// data/.encryption_key so JWT rotation can never break decryption later.
+// 4. Auto-generated — fresh install with none of the above; persisted to
+// data/.encryption_key.
+const encKeyFile = path.join(dataDir, '.encryption_key');
+let _encryptionKey: string = process.env.ENCRYPTION_KEY || '';
+
+if (_encryptionKey) {
+ // Env var is set explicitly — persist it to file so the value survives
+ // container restarts even if the env var is later removed.
+ try {
+ if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true });
+ fs.writeFileSync(encKeyFile, _encryptionKey, { mode: 0o600 });
+ } catch {
+ // Non-fatal: env var is the source of truth when set.
+ }
+} else {
+ // Try the dedicated key file first (covers all installs after first start).
+ try {
+ _encryptionKey = fs.readFileSync(encKeyFile, 'utf8').trim();
+ } catch {
+ // File not found — first start on an existing or fresh install.
+ }
+
+ if (!_encryptionKey) {
+ // One-time migration: existing install upgrading for the first time.
+ // Use the JWT secret as the encryption key and immediately write it to
+ // .encryption_key so future JWT rotations cannot break decryption.
+ try {
+ _encryptionKey = fs.readFileSync(jwtSecretFile, 'utf8').trim();
+ console.warn('WARNING: ENCRYPTION_KEY is not set. Falling back to JWT secret for at-rest encryption.');
+ console.warn('The value has been persisted to data/.encryption_key — JWT rotation is now safe.');
+ } catch {
+ // JWT secret not found — must be a fresh install.
+ }
+ }
+
+ if (!_encryptionKey) {
+ // Fresh install — auto-generate a dedicated key.
+ _encryptionKey = crypto.randomBytes(32).toString('hex');
+ }
+
+ // Persist whatever key was resolved so subsequent starts skip the fallback chain.
+ try {
+ if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true });
+ fs.writeFileSync(encKeyFile, _encryptionKey, { mode: 0o600 });
+ console.log('Encryption key persisted to', encKeyFile);
+ } catch (writeErr: unknown) {
+ console.warn('WARNING: Could not persist encryption key to disk:', writeErr instanceof Error ? writeErr.message : writeErr);
+ console.warn('Set ENCRYPTION_KEY env var to avoid losing access to encrypted secrets on restart.');
+ }
+}
+
+export const ENCRYPTION_KEY = _encryptionKey;
+
+// DEFAULT_LANGUAGE sets the language shown on the login page before the user
+// selects one. Only applies when the user has no saved language preference.
+const rawDefaultLang = process.env.DEFAULT_LANGUAGE?.toLowerCase() || 'en';
+if (!SUPPORTED_LANG_CODES.includes(rawDefaultLang)) {
+ console.warn(`DEFAULT_LANGUAGE="${rawDefaultLang}" is not supported. Falling back to "en". Supported: ${SUPPORTED_LANG_CODES.join(', ')}`);
+}
+export const DEFAULT_LANGUAGE = SUPPORTED_LANG_CODES.includes(rawDefaultLang) ? rawDefaultLang : 'en';
+
+// SESSION_DURATION controls how long a TREK session (the `trek_session` JWT
+// cookie) stays valid before re-login is required. Accepts ms-style strings:
+// '1h', '12h', '7d', '30d', '90d', etc. It applies to BOTH the JWT `exp` claim
+// and the cookie `maxAge`, so the two never drift apart. Invalid values warn at
+// startup and fall back to the default. Does not affect the short-lived MFA
+// challenge token or MCP OAuth tokens — those keep their own TTL.
+const DEFAULT_SESSION_DURATION = '24h';
+const DURATION_UNITS_MS: Record = {
+ ms: 1, s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000, w: 604_800_000, y: 31_557_600_000,
+};
+function parseDurationMs(value: string): number | null {
+ const m = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d|w|y)?$/i.exec(value.trim());
+ if (!m) return null;
+ const n = parseFloat(m[1]);
+ if (!Number.isFinite(n) || n <= 0) return null;
+ return n * DURATION_UNITS_MS[(m[2] || 'ms').toLowerCase()];
+}
+const rawSessionDuration = process.env.SESSION_DURATION?.trim() || DEFAULT_SESSION_DURATION;
+const parsedSessionMs = parseDurationMs(rawSessionDuration);
+if (parsedSessionMs == null) {
+ console.warn(`SESSION_DURATION="${rawSessionDuration}" is not a valid duration (use e.g. 1h, 7d, 30d). Falling back to "${DEFAULT_SESSION_DURATION}".`);
+}
+/** Human-readable session length actually in effect (for logs/diagnostics). */
+export const SESSION_DURATION = parsedSessionMs == null ? DEFAULT_SESSION_DURATION : rawSessionDuration;
+/** Session length in milliseconds — used for the cookie `maxAge`. */
+export const SESSION_DURATION_MS = parsedSessionMs ?? parseDurationMs(DEFAULT_SESSION_DURATION)!;
+/** Session length in seconds — passed to `jwt.sign({ expiresIn })` (number = seconds). */
+export const SESSION_DURATION_SECONDS = Math.floor(SESSION_DURATION_MS / 1000);
+
+// SESSION_DURATION_REMEMBER is the session length used when the user ticks
+// "Remember me" on the login form: a longer-lived JWT `exp` claim plus a
+// persistent `trek_session` cookie `maxAge`. An unticked login keeps
+// SESSION_DURATION and a browser-session cookie (no `maxAge`). Same ms-style
+// format and fallback behavior as SESSION_DURATION.
+const DEFAULT_SESSION_DURATION_REMEMBER = '30d';
+const rawRememberDuration = process.env.SESSION_DURATION_REMEMBER?.trim() || DEFAULT_SESSION_DURATION_REMEMBER;
+const parsedRememberMs = parseDurationMs(rawRememberDuration);
+if (parsedRememberMs == null) {
+ console.warn(`SESSION_DURATION_REMEMBER="${rawRememberDuration}" is not a valid duration (use e.g. 7d, 30d, 90d). Falling back to "${DEFAULT_SESSION_DURATION_REMEMBER}".`);
+}
+/** Human-readable "remember me" session length actually in effect (for logs/diagnostics). */
+export const SESSION_DURATION_REMEMBER = parsedRememberMs == null ? DEFAULT_SESSION_DURATION_REMEMBER : rawRememberDuration;
+/** "Remember me" session length in milliseconds — used for the persistent cookie `maxAge`. */
+export const SESSION_DURATION_REMEMBER_MS = parsedRememberMs ?? parseDurationMs(DEFAULT_SESSION_DURATION_REMEMBER)!;
+/** "Remember me" session length in seconds — passed to `jwt.sign({ expiresIn })`. */
+export const SESSION_DURATION_REMEMBER_SECONDS = Math.floor(SESSION_DURATION_REMEMBER_MS / 1000);
diff --git a/server/src/db/database.ts b/server/src/db/database.ts
new file mode 100644
index 0000000000000000000000000000000000000000..499e900d667279bbc80ce9400f1505dc187f8b4a
--- /dev/null
+++ b/server/src/db/database.ts
@@ -0,0 +1,153 @@
+import Database from 'better-sqlite3';
+import path from 'path';
+import fs from 'fs';
+import { createTables } from './schema';
+import { runMigrations } from './migrations';
+import { runSeeds } from './seeds';
+import { Place, Tag } from '../types';
+
+// In test mode each vitest worker gets an isolated in-memory DB so that
+// parallel forks can't race on the same file or share migration state.
+const isTest = process.env.NODE_ENV === 'test';
+
+let dbPath: string;
+if (isTest) {
+ dbPath = ':memory:';
+} else if (process.env.TREK_DB_FILE) {
+ // Explicit DB file (used by the Playwright E2E harness to run against an
+ // isolated, throwaway database instead of the real data/travel.db). Purely
+ // additive — when unset the default path below is used exactly as before.
+ dbPath = process.env.TREK_DB_FILE;
+ const dir = path.dirname(dbPath);
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
+} else {
+ const dataDir = path.join(__dirname, '../../data');
+ if (!fs.existsSync(dataDir)) {
+ fs.mkdirSync(dataDir, { recursive: true });
+ }
+ dbPath = path.join(dataDir, 'travel.db');
+}
+
+let _db: Database.Database | null = null;
+
+function initDb(): void {
+ if (_db) {
+ try { _db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch (e) {}
+ try { _db.close(); } catch (e) {}
+ _db = null;
+ }
+
+ _db = new Database(dbPath);
+ _db.exec('PRAGMA journal_mode = WAL');
+ _db.exec('PRAGMA busy_timeout = 5000');
+ _db.exec('PRAGMA foreign_keys = ON');
+
+ createTables(_db);
+ runMigrations(_db);
+
+ runSeeds(_db);
+}
+
+initDb();
+
+const db = new Proxy({} as Database.Database, {
+ get(_, prop: string | symbol) {
+ if (!_db) throw new Error('Database connection is not available (restore in progress?)');
+ const val = (_db as unknown as Record)[prop];
+ return typeof val === 'function' ? val.bind(_db) : val;
+ },
+ set(_, prop: string | symbol, val: unknown) {
+ (_db as unknown as Record)[prop] = val;
+ return true;
+ },
+});
+
+if (process.env.DEMO_MODE?.toLowerCase() === 'true') {
+ try {
+ const { seedDemoData } = require('../demo/demo-seed');
+ seedDemoData(_db);
+ } catch (err: unknown) {
+ console.error('[Demo] Seed error:', err instanceof Error ? err.message : err);
+ }
+}
+
+function closeDb(): void {
+ if (_db) {
+ try { _db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch (e) {}
+ try { _db.close(); } catch (e) {}
+ _db = null;
+ console.log('[DB] Database connection closed');
+ }
+}
+
+function reinitialize(): void {
+ console.log('[DB] Reinitializing database connection after restore...');
+ if (_db) closeDb();
+ initDb();
+ console.log('[DB] Database reinitialized successfully');
+}
+
+interface PlaceWithCategory extends Place {
+ category_name: string | null;
+ category_color: string | null;
+ category_icon: string | null;
+}
+
+interface PlaceWithTags extends Place {
+ category: { id: number; name: string; color: string; icon: string } | null;
+ tags: Tag[];
+}
+
+function getPlaceWithTags(placeId: number | string): PlaceWithTags | null {
+ const place = db.prepare(`
+ SELECT p.*, c.name as category_name, c.color as category_color, c.icon as category_icon
+ FROM places p
+ LEFT JOIN categories c ON p.category_id = c.id
+ WHERE p.id = ?
+ `).get(placeId) as PlaceWithCategory | undefined;
+
+ if (!place) return null;
+
+ const tags = db.prepare(`
+ SELECT t.* FROM tags t
+ JOIN place_tags pt ON t.id = pt.tag_id
+ WHERE pt.place_id = ?
+ `).all(placeId) as Tag[];
+
+ return {
+ ...place,
+ category: place.category_id ? {
+ id: place.category_id,
+ name: place.category_name!,
+ color: place.category_color!,
+ icon: place.category_icon!,
+ } : null,
+ tags,
+ };
+}
+
+interface TripAccess {
+ id: number;
+ user_id: number;
+}
+
+function canAccessTrip(tripId: number | string, userId: number): TripAccess | undefined {
+ return db.prepare(`
+ SELECT t.id, t.user_id FROM trips t
+ LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ?
+ WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)
+ `).get(userId, tripId, userId) as TripAccess | undefined;
+}
+
+function isOwner(tripId: number | string, userId: number): boolean {
+ return !!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId);
+}
+
+try {
+ const { backfillFlightEndpoints } = require('../services/airportService');
+ backfillFlightEndpoints();
+} catch (err) {
+ console.error('[DB] Flight endpoint backfill failed:', err);
+}
+
+export { db, closeDb, reinitialize, getPlaceWithTags, canAccessTrip, isOwner };
diff --git a/server/src/db/migrations.ts b/server/src/db/migrations.ts
new file mode 100644
index 0000000000000000000000000000000000000000..45b48133810ff81098473def43ec3021ef974603
--- /dev/null
+++ b/server/src/db/migrations.ts
@@ -0,0 +1,3070 @@
+import { encrypt_api_key } from '../services/apiKeyCrypto';
+
+import Database from 'better-sqlite3';
+import fs from 'fs';
+import path from 'path';
+import zlib from 'zlib';
+
+/** Returns true if any collision was encountered (renamed row). */
+export function trimUserWhitespace(db: Database.Database): boolean {
+ type DirtyRow = { id: number; username?: string; email?: string };
+ let hadCollision = false;
+
+ const dirtyUsernames = db
+ .prepare(`SELECT id, username FROM users WHERE username != TRIM(username)`)
+ .all() as DirtyRow[];
+
+ for (const row of dirtyUsernames) {
+ const trimmed = row.username!.trim();
+ const collision = db
+ .prepare(`SELECT id FROM users WHERE LOWER(username) = LOWER(?) AND id != ?`)
+ .get(trimmed, row.id) as { id: number } | undefined;
+
+ const final = collision ? `${trimmed}__migrated_${row.id}` : trimmed;
+ if (collision) {
+ hadCollision = true;
+ console.warn(
+ `[migration] WHITESPACE COLLISION username: user id=${row.id} ` +
+ `original=${JSON.stringify(row.username)} trimmed="${trimmed}" ` +
+ `collides with user id=${collision.id}. Renamed to "${final}". ` +
+ `Manual review required.`,
+ );
+ } else {
+ console.warn(
+ `[migration] Trimmed username for user id=${row.id}: ` + `${JSON.stringify(row.username)} → "${final}"`,
+ );
+ }
+ db.prepare(`UPDATE users SET username = ? WHERE id = ?`).run(final, row.id);
+ }
+
+ const dirtyEmails = db.prepare(`SELECT id, email FROM users WHERE email != TRIM(email)`).all() as DirtyRow[];
+
+ for (const row of dirtyEmails) {
+ const trimmed = row.email!.trim();
+ const collision = db
+ .prepare(`SELECT id FROM users WHERE LOWER(email) = LOWER(?) AND id != ?`)
+ .get(trimmed, row.id) as { id: number } | undefined;
+
+ let final = trimmed;
+ if (collision) {
+ hadCollision = true;
+ const at = trimmed.lastIndexOf('@');
+ final =
+ at > 0 ? `${trimmed.slice(0, at)}__migrated_${row.id}${trimmed.slice(at)}` : `${trimmed}__migrated_${row.id}`;
+ console.warn(
+ `[migration] WHITESPACE COLLISION email: user id=${row.id} ` +
+ `original=${JSON.stringify(row.email)} trimmed="${trimmed}" ` +
+ `collides with user id=${collision.id}. Renamed to "${final}". ` +
+ `User cannot sign in with this email until manually corrected.`,
+ );
+ } else {
+ console.warn(`[migration] Trimmed email for user id=${row.id}: ` + `${JSON.stringify(row.email)} → "${final}"`);
+ }
+ db.prepare(`UPDATE users SET email = ? WHERE id = ?`).run(final, row.id);
+ }
+
+ return hadCollision;
+}
+
+function runMigrations(db: Database.Database): void {
+ db.exec('CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL)');
+ const versionRow = db.prepare('SELECT version FROM schema_version').get() as { version: number } | undefined;
+ let currentVersion = versionRow?.version ?? 0;
+
+ if (currentVersion === 0) {
+ const hasUnsplash = db.prepare("SELECT 1 FROM pragma_table_info('users') WHERE name = 'unsplash_api_key'").get();
+ if (hasUnsplash) {
+ currentVersion = 19;
+ db.prepare('INSERT INTO schema_version (version) VALUES (?)').run(currentVersion);
+ console.log('[DB] Schema already up-to-date, setting version to', currentVersion);
+ } else {
+ db.prepare('INSERT INTO schema_version (version) VALUES (?)').run(0);
+ }
+ }
+
+ type Migration = (() => void) | { raw: () => void };
+ const migrations: Migration[] = [
+ () => db.exec('ALTER TABLE users ADD COLUMN unsplash_api_key TEXT'),
+ () => db.exec('ALTER TABLE users ADD COLUMN openweather_api_key TEXT'),
+ () => db.exec('ALTER TABLE places ADD COLUMN duration_minutes INTEGER DEFAULT 60'),
+ () => db.exec('ALTER TABLE places ADD COLUMN notes TEXT'),
+ () => db.exec('ALTER TABLE places ADD COLUMN image_url TEXT'),
+ () => db.exec("ALTER TABLE places ADD COLUMN transport_mode TEXT DEFAULT 'walking'"),
+ () => db.exec('ALTER TABLE days ADD COLUMN title TEXT'),
+ () => db.exec("ALTER TABLE reservations ADD COLUMN status TEXT DEFAULT 'pending'"),
+ () =>
+ db.exec(
+ 'ALTER TABLE trip_files ADD COLUMN reservation_id INTEGER REFERENCES reservations(id) ON DELETE SET NULL',
+ ),
+ () => db.exec("ALTER TABLE reservations ADD COLUMN type TEXT DEFAULT 'other'"),
+ () => db.exec('ALTER TABLE trips ADD COLUMN cover_image TEXT'),
+ () => db.exec("ALTER TABLE day_notes ADD COLUMN icon TEXT DEFAULT '📝'"),
+ () => db.exec('ALTER TABLE trips ADD COLUMN is_archived INTEGER DEFAULT 0'),
+ () => db.exec('ALTER TABLE categories ADD COLUMN user_id INTEGER REFERENCES users(id) ON DELETE SET NULL'),
+ () => db.exec('ALTER TABLE users ADD COLUMN avatar TEXT'),
+ () => db.exec('ALTER TABLE users ADD COLUMN oidc_sub TEXT'),
+ () => db.exec('ALTER TABLE users ADD COLUMN oidc_issuer TEXT'),
+ () => db.exec('ALTER TABLE users ADD COLUMN last_login DATETIME'),
+ () => {
+ const schema = db.prepare("SELECT sql FROM sqlite_master WHERE name = 'budget_items'").get() as
+ | { sql: string }
+ | undefined;
+ if (schema?.sql?.includes('NOT NULL DEFAULT 1')) {
+ db.exec(`
+ CREATE TABLE budget_items_new (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ category TEXT NOT NULL DEFAULT 'Other',
+ name TEXT NOT NULL,
+ total_price REAL NOT NULL DEFAULT 0,
+ persons INTEGER DEFAULT NULL,
+ days INTEGER DEFAULT NULL,
+ note TEXT,
+ sort_order INTEGER DEFAULT 0,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+ INSERT INTO budget_items_new SELECT * FROM budget_items;
+ DROP TABLE budget_items;
+ ALTER TABLE budget_items_new RENAME TO budget_items;
+ `);
+ }
+ },
+ () => {
+ try {
+ db.exec('ALTER TABLE day_accommodations ADD COLUMN check_in TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE day_accommodations ADD COLUMN check_out TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE day_accommodations ADD COLUMN confirmation TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ () => {
+ try {
+ db.exec('ALTER TABLE places ADD COLUMN end_time TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ () => {
+ try {
+ db.exec("ALTER TABLE day_assignments ADD COLUMN reservation_status TEXT DEFAULT 'none'");
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE day_assignments ADD COLUMN reservation_notes TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE day_assignments ADD COLUMN reservation_datetime TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec(`
+ UPDATE day_assignments SET
+ reservation_status = (SELECT reservation_status FROM places WHERE places.id = day_assignments.place_id),
+ reservation_notes = (SELECT reservation_notes FROM places WHERE places.id = day_assignments.place_id),
+ reservation_datetime = (SELECT reservation_datetime FROM places WHERE places.id = day_assignments.place_id)
+ WHERE place_id IN (SELECT id FROM places WHERE reservation_status IS NOT NULL AND reservation_status != 'none')
+ `);
+ console.log('[DB] Migrated reservation data from places to day_assignments');
+ } catch (e: unknown) {
+ console.error('[DB] Migration 22 data copy error:', e instanceof Error ? e.message : e);
+ }
+ },
+ () => {
+ try {
+ db.exec(
+ 'ALTER TABLE reservations ADD COLUMN assignment_id INTEGER REFERENCES day_assignments(id) ON DELETE SET NULL',
+ );
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ () => {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS assignment_participants (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ assignment_id INTEGER NOT NULL REFERENCES day_assignments(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ UNIQUE(assignment_id, user_id)
+ )
+ `);
+ },
+ () => {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS collab_notes (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ category TEXT DEFAULT 'General',
+ title TEXT NOT NULL,
+ content TEXT,
+ color TEXT DEFAULT '#6366f1',
+ pinned INTEGER DEFAULT 0,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+ CREATE TABLE IF NOT EXISTS collab_polls (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ question TEXT NOT NULL,
+ options TEXT NOT NULL,
+ multiple INTEGER DEFAULT 0,
+ closed INTEGER DEFAULT 0,
+ deadline TEXT,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+ CREATE TABLE IF NOT EXISTS collab_poll_votes (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ poll_id INTEGER NOT NULL REFERENCES collab_polls(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ option_index INTEGER NOT NULL,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(poll_id, user_id, option_index)
+ );
+ CREATE TABLE IF NOT EXISTS collab_messages (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ text TEXT NOT NULL,
+ reply_to INTEGER REFERENCES collab_messages(id) ON DELETE SET NULL,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+ CREATE INDEX IF NOT EXISTS idx_collab_notes_trip ON collab_notes(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_collab_polls_trip ON collab_polls(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_collab_messages_trip ON collab_messages(trip_id);
+ `);
+ try {
+ db.prepare(
+ "INSERT OR IGNORE INTO addons (id, name, description, type, icon, enabled, sort_order) VALUES ('collab', 'Collab', 'Notes, polls, and live chat for trip collaboration', 'trip', 'Users', 1, 6)",
+ ).run();
+ } catch (err: any) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ },
+ () => {
+ try {
+ db.exec('ALTER TABLE day_assignments ADD COLUMN assignment_time TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE day_assignments ADD COLUMN assignment_end_time TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec(`
+ UPDATE day_assignments SET
+ assignment_time = (SELECT place_time FROM places WHERE places.id = day_assignments.place_id),
+ assignment_end_time = (SELECT end_time FROM places WHERE places.id = day_assignments.place_id)
+ `);
+ } catch (err: any) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ },
+ () => {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS budget_item_members (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ budget_item_id INTEGER NOT NULL REFERENCES budget_items(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ paid INTEGER NOT NULL DEFAULT 0,
+ UNIQUE(budget_item_id, user_id)
+ );
+ CREATE INDEX IF NOT EXISTS idx_budget_item_members_item ON budget_item_members(budget_item_id);
+ CREATE INDEX IF NOT EXISTS idx_budget_item_members_user ON budget_item_members(user_id);
+ `);
+ },
+ () => {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS collab_message_reactions (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ message_id INTEGER NOT NULL REFERENCES collab_messages(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ emoji TEXT NOT NULL,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(message_id, user_id, emoji)
+ );
+ CREATE INDEX IF NOT EXISTS idx_collab_reactions_msg ON collab_message_reactions(message_id);
+ `);
+ },
+ () => {
+ try {
+ db.exec('ALTER TABLE collab_messages ADD COLUMN deleted INTEGER DEFAULT 0');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ () => {
+ try {
+ db.exec('ALTER TABLE trip_files ADD COLUMN note_id INTEGER REFERENCES collab_notes(id) ON DELETE SET NULL');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE collab_notes ADD COLUMN website TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ () => {
+ try {
+ db.exec('ALTER TABLE reservations ADD COLUMN reservation_end_time TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ () => {
+ try {
+ db.exec('ALTER TABLE places ADD COLUMN osm_id TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ () => {
+ try {
+ db.exec('ALTER TABLE trip_files ADD COLUMN uploaded_by INTEGER REFERENCES users(id) ON DELETE SET NULL');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE trip_files ADD COLUMN starred INTEGER DEFAULT 0');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE trip_files ADD COLUMN deleted_at TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ () => {
+ try {
+ db.exec(
+ 'ALTER TABLE reservations ADD COLUMN accommodation_id INTEGER REFERENCES day_accommodations(id) ON DELETE SET NULL',
+ );
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE reservations ADD COLUMN metadata TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ () => {
+ db.exec(`CREATE TABLE IF NOT EXISTS invite_tokens (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ token TEXT UNIQUE NOT NULL,
+ max_uses INTEGER NOT NULL DEFAULT 1,
+ used_count INTEGER NOT NULL DEFAULT 0,
+ expires_at TEXT,
+ created_by INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ )`);
+ },
+ () => {
+ try {
+ db.exec('ALTER TABLE users ADD COLUMN mfa_enabled INTEGER DEFAULT 0');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE users ADD COLUMN mfa_secret TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ () => {
+ db.exec(`CREATE TABLE IF NOT EXISTS packing_category_assignees (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ category_name TEXT NOT NULL,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ UNIQUE(trip_id, category_name, user_id)
+ )`);
+ },
+ () => {
+ db.exec(`CREATE TABLE IF NOT EXISTS packing_templates (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NOT NULL,
+ created_by INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ )`);
+ db.exec(`CREATE TABLE IF NOT EXISTS packing_template_categories (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ template_id INTEGER NOT NULL REFERENCES packing_templates(id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ sort_order INTEGER NOT NULL DEFAULT 0
+ )`);
+ // Recreate items table with category_id FK (replaces old template_id-based schema)
+ try {
+ db.exec('DROP TABLE IF EXISTS packing_template_items');
+ } catch (err: any) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ db.exec(`CREATE TABLE packing_template_items (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ category_id INTEGER NOT NULL REFERENCES packing_template_categories(id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ sort_order INTEGER NOT NULL DEFAULT 0
+ )`);
+ },
+ () => {
+ db.exec(`CREATE TABLE IF NOT EXISTS packing_bags (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ color TEXT NOT NULL DEFAULT '#6366f1',
+ weight_limit_grams INTEGER,
+ sort_order INTEGER DEFAULT 0,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ )`);
+ try {
+ db.exec('ALTER TABLE packing_items ADD COLUMN weight_grams INTEGER');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE packing_items ADD COLUMN bag_id INTEGER REFERENCES packing_bags(id) ON DELETE SET NULL');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ () => {
+ db.exec(`CREATE TABLE IF NOT EXISTS visited_countries (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ country_code TEXT NOT NULL,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(user_id, country_code)
+ )`);
+ },
+ () => {
+ db.exec(`CREATE TABLE IF NOT EXISTS bucket_list (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ lat REAL,
+ lng REAL,
+ country_code TEXT,
+ notes TEXT,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ )`);
+ },
+ () => {
+ // Configurable weekend days
+ try {
+ db.exec("ALTER TABLE vacay_plans ADD COLUMN weekend_days TEXT DEFAULT '0,6'");
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ () => {
+ // Immich integration
+ try {
+ db.exec('ALTER TABLE users ADD COLUMN immich_url TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE users ADD COLUMN immich_api_key TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ db.exec(`CREATE TABLE IF NOT EXISTS trip_photos (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ immich_asset_id TEXT NOT NULL,
+ shared INTEGER NOT NULL DEFAULT 1,
+ added_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(trip_id, user_id, immich_asset_id)
+ )`);
+ // Add memories addon
+ try {
+ db.prepare('INSERT INTO addons (id, name, type, icon, enabled, sort_order) VALUES (?, ?, ?, ?, ?, ?)').run(
+ 'memories',
+ 'Photos',
+ 'trip',
+ 'Image',
+ 0,
+ 7,
+ );
+ } catch (err: any) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ },
+ () => {
+ // Allow files to be linked to multiple reservations/assignments
+ db.exec(`CREATE TABLE IF NOT EXISTS file_links (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ file_id INTEGER NOT NULL REFERENCES trip_files(id) ON DELETE CASCADE,
+ reservation_id INTEGER REFERENCES reservations(id) ON DELETE CASCADE,
+ assignment_id INTEGER REFERENCES day_assignments(id) ON DELETE CASCADE,
+ place_id INTEGER REFERENCES places(id) ON DELETE CASCADE,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(file_id, reservation_id),
+ UNIQUE(file_id, assignment_id),
+ UNIQUE(file_id, place_id)
+ )`);
+ },
+ () => {
+ // Add day_plan_position to reservations for persistent transport ordering in day timeline
+ try {
+ db.exec('ALTER TABLE reservations ADD COLUMN day_plan_position REAL DEFAULT NULL');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ () => {
+ // Add paid_by_user_id to budget_items for expense tracking / settlement
+ try {
+ db.exec('ALTER TABLE budget_items ADD COLUMN paid_by_user_id INTEGER REFERENCES users(id)');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ () => {
+ // Add target_date to bucket_list for optional visit planning
+ try {
+ db.exec('ALTER TABLE bucket_list ADD COLUMN target_date TEXT DEFAULT NULL');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ () => {
+ // Notification preferences per user
+ db.exec(`CREATE TABLE IF NOT EXISTS notification_preferences (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ notify_trip_invite INTEGER DEFAULT 1,
+ notify_booking_change INTEGER DEFAULT 1,
+ notify_trip_reminder INTEGER DEFAULT 1,
+ notify_vacay_invite INTEGER DEFAULT 1,
+ notify_photos_shared INTEGER DEFAULT 1,
+ notify_collab_message INTEGER DEFAULT 1,
+ notify_packing_tagged INTEGER DEFAULT 1,
+ notify_webhook INTEGER DEFAULT 0,
+ UNIQUE(user_id)
+ )`);
+ },
+ () => {
+ // Add missing notification preference columns for existing tables
+ try {
+ db.exec('ALTER TABLE notification_preferences ADD COLUMN notify_vacay_invite INTEGER DEFAULT 1');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE notification_preferences ADD COLUMN notify_photos_shared INTEGER DEFAULT 1');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE notification_preferences ADD COLUMN notify_collab_message INTEGER DEFAULT 1');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE notification_preferences ADD COLUMN notify_packing_tagged INTEGER DEFAULT 1');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ () => {
+ // Public share links for read-only trip access
+ db.exec(`CREATE TABLE IF NOT EXISTS share_tokens (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ token TEXT NOT NULL UNIQUE,
+ created_by INTEGER NOT NULL REFERENCES users(id),
+ share_map INTEGER DEFAULT 1,
+ share_bookings INTEGER DEFAULT 1,
+ share_packing INTEGER DEFAULT 0,
+ share_budget INTEGER DEFAULT 0,
+ share_collab INTEGER DEFAULT 0,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ )`);
+ },
+ () => {
+ // Add permission columns to share_tokens
+ try {
+ db.exec('ALTER TABLE share_tokens ADD COLUMN share_map INTEGER DEFAULT 1');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE share_tokens ADD COLUMN share_bookings INTEGER DEFAULT 1');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE share_tokens ADD COLUMN share_packing INTEGER DEFAULT 0');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE share_tokens ADD COLUMN share_budget INTEGER DEFAULT 0');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE share_tokens ADD COLUMN share_collab INTEGER DEFAULT 0');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ () => {
+ // Audit log
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS audit_log (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
+ action TEXT NOT NULL,
+ resource TEXT,
+ details TEXT,
+ ip TEXT
+ );
+ CREATE INDEX IF NOT EXISTS idx_audit_log_created ON audit_log(created_at DESC);
+ `);
+ },
+ () => {
+ // MFA backup/recovery codes
+ try {
+ db.exec('ALTER TABLE users ADD COLUMN mfa_backup_codes TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ // MCP long-lived API tokens
+ () =>
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS mcp_tokens (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ token_hash TEXT NOT NULL,
+ token_prefix TEXT NOT NULL,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ last_used_at DATETIME
+ )
+ `),
+ // MCP addon entry
+ () => {
+ try {
+ db.prepare(
+ 'INSERT OR IGNORE INTO addons (id, name, description, type, icon, enabled, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)',
+ ).run('mcp', 'MCP', 'Model Context Protocol for AI assistant integration', 'integration', 'Terminal', 0, 12);
+ } catch (err: any) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ },
+ // Index on mcp_tokens.token_hash
+ () =>
+ db.exec(`
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_mcp_tokens_hash ON mcp_tokens(token_hash)
+ `),
+ // Ensure MCP addon type is 'integration'
+ () => {
+ try {
+ db.prepare("UPDATE addons SET type = 'integration' WHERE id = 'mcp'").run();
+ } catch (err: any) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ },
+ () => {
+ try {
+ db.exec('ALTER TABLE places ADD COLUMN route_geometry TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ () => {
+ try {
+ db.exec('ALTER TABLE users ADD COLUMN must_change_password INTEGER DEFAULT 0');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ () => {
+ try {
+ db.exec('ALTER TABLE trips ADD COLUMN reminder_days INTEGER DEFAULT 3');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ // Encrypt any plaintext oidc_client_secret left in app_settings
+ () => {
+ const row = db.prepare("SELECT value FROM app_settings WHERE key = 'oidc_client_secret'").get() as
+ | { value: string }
+ | undefined;
+ if (row?.value && !row.value.startsWith('enc:v1:')) {
+ db.prepare("UPDATE app_settings SET value = ? WHERE key = 'oidc_client_secret'").run(
+ encrypt_api_key(row.value),
+ );
+ }
+ },
+ // Encrypt any plaintext smtp_pass left in app_settings
+ () => {
+ const row = db.prepare("SELECT value FROM app_settings WHERE key = 'smtp_pass'").get() as
+ | { value: string }
+ | undefined;
+ if (row?.value && !row.value.startsWith('enc:v1:')) {
+ db.prepare("UPDATE app_settings SET value = ? WHERE key = 'smtp_pass'").run(encrypt_api_key(row.value));
+ }
+ },
+ // Encrypt any plaintext immich_api_key values in the users table
+ () => {
+ const rows = db
+ .prepare(
+ "SELECT id, immich_api_key FROM users WHERE immich_api_key IS NOT NULL AND immich_api_key != '' AND immich_api_key NOT LIKE 'enc:v1:%'",
+ )
+ .all() as { id: number; immich_api_key: string }[];
+ for (const row of rows) {
+ db.prepare('UPDATE users SET immich_api_key = ? WHERE id = ?').run(encrypt_api_key(row.immich_api_key), row.id);
+ }
+ },
+ () => {
+ try {
+ db.exec('ALTER TABLE budget_items ADD COLUMN expense_date TEXT DEFAULT NULL');
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ },
+ () => {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS trip_album_links (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ immich_album_id TEXT NOT NULL,
+ album_name TEXT NOT NULL DEFAULT '',
+ sync_enabled INTEGER NOT NULL DEFAULT 1,
+ last_synced_at DATETIME,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(trip_id, user_id, immich_album_id)
+ );
+ CREATE INDEX IF NOT EXISTS idx_trip_album_links_trip ON trip_album_links(trip_id);
+ `);
+ },
+ () => {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS notifications (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ type TEXT NOT NULL CHECK(type IN ('simple', 'boolean', 'navigate')),
+ scope TEXT NOT NULL CHECK(scope IN ('trip', 'user', 'admin')),
+ target INTEGER NOT NULL,
+ sender_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
+ recipient_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ title_key TEXT NOT NULL,
+ title_params TEXT DEFAULT '{}',
+ text_key TEXT NOT NULL,
+ text_params TEXT DEFAULT '{}',
+ positive_text_key TEXT,
+ negative_text_key TEXT,
+ positive_callback TEXT,
+ negative_callback TEXT,
+ response TEXT CHECK(response IN ('positive', 'negative')),
+ navigate_text_key TEXT,
+ navigate_target TEXT,
+ is_read INTEGER DEFAULT 0,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+ CREATE INDEX IF NOT EXISTS idx_notifications_recipient ON notifications(recipient_id, is_read, created_at DESC);
+ CREATE INDEX IF NOT EXISTS idx_notifications_recipient_created ON notifications(recipient_id, created_at DESC);
+ `);
+ },
+ () => {
+ // Normalize trip_photos to provider-based schema used by current routes
+ const tripPhotosExists = db
+ .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'trip_photos'")
+ .get();
+ if (!tripPhotosExists) {
+ db.exec(`
+ CREATE TABLE trip_photos (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ asset_id TEXT NOT NULL,
+ provider TEXT NOT NULL DEFAULT 'immich',
+ shared INTEGER NOT NULL DEFAULT 1,
+ added_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(trip_id, user_id, asset_id, provider)
+ );
+ CREATE INDEX IF NOT EXISTS idx_trip_photos_trip ON trip_photos(trip_id);
+ `);
+ } else {
+ const columns = db.prepare("PRAGMA table_info('trip_photos')").all() as Array<{ name: string }>;
+ const names = new Set(columns.map((c) => c.name));
+ const assetSource = names.has('asset_id')
+ ? 'asset_id'
+ : names.has('immich_asset_id')
+ ? 'immich_asset_id'
+ : null;
+ if (assetSource) {
+ const providerExpr = names.has('provider')
+ ? "CASE WHEN provider IS NULL OR provider = '' THEN 'immich' ELSE provider END"
+ : "'immich'";
+ const sharedExpr = names.has('shared') ? 'COALESCE(shared, 1)' : '1';
+ const addedAtExpr = names.has('added_at') ? 'COALESCE(added_at, CURRENT_TIMESTAMP)' : 'CURRENT_TIMESTAMP';
+
+ db.exec(`
+ CREATE TABLE trip_photos_new (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ asset_id TEXT NOT NULL,
+ provider TEXT NOT NULL DEFAULT 'immich',
+ shared INTEGER NOT NULL DEFAULT 1,
+ added_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(trip_id, user_id, asset_id, provider)
+ );
+ `);
+
+ db.exec(`
+ INSERT OR IGNORE INTO trip_photos_new (trip_id, user_id, asset_id, provider, shared, added_at)
+ SELECT trip_id, user_id, ${assetSource}, ${providerExpr}, ${sharedExpr}, ${addedAtExpr}
+ FROM trip_photos
+ WHERE ${assetSource} IS NOT NULL AND TRIM(${assetSource}) != ''
+ `);
+
+ db.exec('DROP TABLE trip_photos');
+ db.exec('ALTER TABLE trip_photos_new RENAME TO trip_photos');
+ db.exec('CREATE INDEX IF NOT EXISTS idx_trip_photos_trip ON trip_photos(trip_id)');
+ }
+ }
+ },
+ () => {
+ // Normalize trip_album_links to provider + album_id schema used by current routes
+ const linksExists = db
+ .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'trip_album_links'")
+ .get();
+ if (!linksExists) {
+ db.exec(`
+ CREATE TABLE trip_album_links (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ provider TEXT NOT NULL,
+ album_id TEXT NOT NULL,
+ album_name TEXT NOT NULL DEFAULT '',
+ sync_enabled INTEGER NOT NULL DEFAULT 1,
+ last_synced_at DATETIME,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(trip_id, user_id, provider, album_id)
+ );
+ CREATE INDEX IF NOT EXISTS idx_trip_album_links_trip ON trip_album_links(trip_id);
+ `);
+ } else {
+ const columns = db.prepare("PRAGMA table_info('trip_album_links')").all() as Array<{ name: string }>;
+ const names = new Set(columns.map((c) => c.name));
+ const albumIdSource = names.has('album_id')
+ ? 'album_id'
+ : names.has('immich_album_id')
+ ? 'immich_album_id'
+ : null;
+ if (albumIdSource) {
+ const providerExpr = names.has('provider')
+ ? "CASE WHEN provider IS NULL OR provider = '' THEN 'immich' ELSE provider END"
+ : "'immich'";
+ const albumNameExpr = names.has('album_name') ? "COALESCE(album_name, '')" : "''";
+ const syncEnabledExpr = names.has('sync_enabled') ? 'COALESCE(sync_enabled, 1)' : '1';
+ const lastSyncedExpr = names.has('last_synced_at') ? 'last_synced_at' : 'NULL';
+ const createdAtExpr = names.has('created_at')
+ ? 'COALESCE(created_at, CURRENT_TIMESTAMP)'
+ : 'CURRENT_TIMESTAMP';
+
+ db.exec(`
+ CREATE TABLE trip_album_links_new (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ provider TEXT NOT NULL,
+ album_id TEXT NOT NULL,
+ album_name TEXT NOT NULL DEFAULT '',
+ sync_enabled INTEGER NOT NULL DEFAULT 1,
+ last_synced_at DATETIME,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(trip_id, user_id, provider, album_id)
+ );
+ `);
+
+ db.exec(`
+ INSERT OR IGNORE INTO trip_album_links_new (trip_id, user_id, provider, album_id, album_name, sync_enabled, last_synced_at, created_at)
+ SELECT trip_id, user_id, ${providerExpr}, ${albumIdSource}, ${albumNameExpr}, ${syncEnabledExpr}, ${lastSyncedExpr}, ${createdAtExpr}
+ FROM trip_album_links
+ WHERE ${albumIdSource} IS NOT NULL AND TRIM(${albumIdSource}) != ''
+ `);
+
+ db.exec('DROP TABLE trip_album_links');
+ db.exec('ALTER TABLE trip_album_links_new RENAME TO trip_album_links');
+ db.exec('CREATE INDEX IF NOT EXISTS idx_trip_album_links_trip ON trip_album_links(trip_id)');
+ }
+ }
+ },
+ () => {
+ // Add Synology credential columns for existing databases
+ try {
+ db.exec('ALTER TABLE users ADD COLUMN synology_url TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE users ADD COLUMN synology_username TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE users ADD COLUMN synology_password TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE users ADD COLUMN synology_sid TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ () => {
+ // Seed Synology Photos provider and fields in existing databases
+ try {
+ db.prepare(
+ `
+ INSERT INTO photo_providers (id, name, description, icon, enabled, sort_order)
+ VALUES (?, ?, ?, ?, ?, ?)
+ ON CONFLICT(id) DO UPDATE SET
+ name = excluded.name,
+ description = excluded.description,
+ icon = excluded.icon,
+ enabled = excluded.enabled,
+ sort_order = excluded.sort_order
+ `,
+ ).run(
+ 'synologyphotos',
+ 'Synology Photos',
+ 'Synology Photos integration with separate account settings',
+ 'Image',
+ 0,
+ 1,
+ );
+ } catch (err: any) {
+ if (!err.message?.includes('no such table')) throw err;
+ }
+ try {
+ const insertField = db.prepare(`
+ INSERT INTO photo_provider_fields
+ (provider_id, field_key, label, input_type, placeholder, required, secret, settings_key, payload_key, sort_order)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(provider_id, field_key) DO UPDATE SET
+ label = excluded.label,
+ input_type = excluded.input_type,
+ placeholder = excluded.placeholder,
+ required = excluded.required,
+ secret = excluded.secret,
+ settings_key = excluded.settings_key,
+ payload_key = excluded.payload_key,
+ sort_order = excluded.sort_order
+ `);
+ insertField.run(
+ 'synologyphotos',
+ 'synology_url',
+ 'providerUrl',
+ 'url',
+ 'https://synology.example.com',
+ 1,
+ 0,
+ 'synology_url',
+ 'synology_url',
+ 0,
+ );
+ insertField.run(
+ 'synologyphotos',
+ 'synology_username',
+ 'providerUsername',
+ 'text',
+ 'Username',
+ 1,
+ 0,
+ 'synology_username',
+ 'synology_username',
+ 1,
+ );
+ insertField.run(
+ 'synologyphotos',
+ 'synology_password',
+ 'providerPassword',
+ 'password',
+ 'Password',
+ 1,
+ 1,
+ null,
+ 'synology_password',
+ 2,
+ );
+ } catch (err: any) {
+ if (!err.message?.includes('no such table')) throw err;
+ }
+ },
+ () => {
+ // Remove the stored config column from photo_providers now that it is generated from provider id.
+ const columns = db.prepare("PRAGMA table_info('photo_providers')").all() as Array<{ name: string }>;
+ const names = new Set(columns.map((c) => c.name));
+ if (!names.has('config')) return;
+
+ db.exec('ALTER TABLE photo_providers DROP COLUMN config');
+ },
+ () => {
+ const columns = db.prepare("PRAGMA table_info('trip_photos')").all() as Array<{ name: string }>;
+ const names = new Set(columns.map((c) => c.name));
+ if (names.has('asset_id') && !names.has('immich_asset_id')) return;
+ db.exec('ALTER TABLE `trip_photos` RENAME COLUMN immich_asset_id TO asset_id');
+ db.exec('ALTER TABLE `trip_photos` ADD COLUMN provider TEXT NOT NULL DEFAULT "immich"');
+ db.exec('ALTER TABLE `trip_album_links` ADD COLUMN provider TEXT NOT NULL DEFAULT "immich"');
+ db.exec('ALTER TABLE `trip_album_links` RENAME COLUMN immich_album_id TO album_id');
+ },
+ () => {
+ // Track which album link each photo was synced from
+ try {
+ db.exec(
+ 'ALTER TABLE trip_photos ADD COLUMN album_link_id INTEGER REFERENCES trip_album_links(id) ON DELETE SET NULL DEFAULT NULL',
+ );
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ db.exec('CREATE INDEX IF NOT EXISTS idx_trip_photos_album_link ON trip_photos(album_link_id)');
+ },
+ // Migration 68: Todo items
+ () => {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS todo_items (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ checked INTEGER DEFAULT 0,
+ category TEXT,
+ sort_order INTEGER DEFAULT 0,
+ due_date TEXT,
+ description TEXT,
+ assigned_user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
+ priority INTEGER DEFAULT 0,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+ CREATE INDEX IF NOT EXISTS idx_todo_items_trip_id ON todo_items(trip_id);
+
+ CREATE TABLE IF NOT EXISTS todo_category_assignees (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ category_name TEXT NOT NULL,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ UNIQUE(trip_id, category_name, user_id)
+ );
+ `);
+ },
+ () => {
+ try {
+ db.exec("UPDATE addons SET enabled = 0 WHERE id = 'memories'");
+ } catch (err) {
+ // Non-fatal: the addons table may not exist yet on very old databases.
+ // Disabling the legacy memories addon is best-effort, but we no longer
+ // swallow the error silently.
+ console.warn("[migrations] Non-fatal: failed to disable legacy 'memories' addon:", err);
+ }
+ },
+ // Migration 69: Place region cache for sub-national Atlas regions
+ () => {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS place_regions (
+ place_id INTEGER PRIMARY KEY REFERENCES places(id) ON DELETE CASCADE,
+ country_code TEXT NOT NULL,
+ region_code TEXT NOT NULL,
+ region_name TEXT NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS idx_place_regions_country ON place_regions(country_code);
+ CREATE INDEX IF NOT EXISTS idx_place_regions_region ON place_regions(region_code);
+ `);
+ },
+ () => {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS visited_regions (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ region_code TEXT NOT NULL,
+ region_name TEXT NOT NULL,
+ country_code TEXT NOT NULL,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(user_id, region_code)
+ );
+ CREATE INDEX IF NOT EXISTS idx_visited_regions_country ON visited_regions(country_code);
+ `);
+ },
+ // Migration 71: Normalized per-user per-channel notification preferences
+ () => {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS notification_channel_preferences (
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ event_type TEXT NOT NULL,
+ channel TEXT NOT NULL,
+ enabled INTEGER NOT NULL DEFAULT 1,
+ PRIMARY KEY (user_id, event_type, channel)
+ );
+ CREATE INDEX IF NOT EXISTS idx_ncp_user ON notification_channel_preferences(user_id);
+ `);
+
+ // Migrate data from old notification_preferences table (may not exist on fresh installs)
+ const tableExists =
+ (db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='notification_preferences'").get() as
+ | { name: string }
+ | undefined) != null;
+ const oldPrefs: Array> = tableExists
+ ? (db.prepare('SELECT * FROM notification_preferences').all() as Array>)
+ : [];
+ const eventCols: Record = {
+ trip_invite: 'notify_trip_invite',
+ booking_change: 'notify_booking_change',
+ trip_reminder: 'notify_trip_reminder',
+ vacay_invite: 'notify_vacay_invite',
+ photos_shared: 'notify_photos_shared',
+ collab_message: 'notify_collab_message',
+ packing_tagged: 'notify_packing_tagged',
+ };
+ const insert = db.prepare(
+ 'INSERT OR IGNORE INTO notification_channel_preferences (user_id, event_type, channel, enabled) VALUES (?, ?, ?, ?)',
+ );
+ const insertMany = db.transaction((rows: Array<[number, string, string, number]>) => {
+ for (const [userId, eventType, channel, enabled] of rows) {
+ insert.run(userId, eventType, channel, enabled);
+ }
+ });
+
+ for (const row of oldPrefs) {
+ const userId = row.user_id as number;
+ const webhookEnabled = (row.notify_webhook as number) ?? 0;
+ const rows: Array<[number, string, string, number]> = [];
+ for (const [eventType, col] of Object.entries(eventCols)) {
+ const emailEnabled = (row[col] as number) ?? 1;
+ // Only insert if disabled (no row = enabled is our default)
+ if (!emailEnabled) rows.push([userId, eventType, 'email', 0]);
+ if (!webhookEnabled) rows.push([userId, eventType, 'webhook', 0]);
+ }
+ if (rows.length > 0) insertMany(rows);
+ }
+
+ // Copy existing single-channel setting to new plural key
+ db.exec(`
+ INSERT OR IGNORE INTO app_settings (key, value)
+ SELECT 'notification_channels', value FROM app_settings WHERE key = 'notification_channel';
+ `);
+ },
+ // Migration 72: Drop the old notification_preferences table (data migrated to notification_channel_preferences in migration 71)
+ () => {
+ db.exec('DROP TABLE IF EXISTS notification_preferences;');
+ },
+ // Migration 73: Add reservation_id to budget_items for linking budget entries to reservations
+ () => {
+ try {
+ db.exec(
+ 'ALTER TABLE budget_items ADD COLUMN reservation_id INTEGER REFERENCES reservations(id) ON DELETE SET NULL DEFAULT NULL',
+ );
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ // Migration 74: Add quantity to packing_items + user_id to packing_bags + bag_members table
+ () => {
+ try {
+ db.exec('ALTER TABLE packing_items ADD COLUMN quantity INTEGER NOT NULL DEFAULT 1');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec(
+ 'ALTER TABLE packing_bags ADD COLUMN user_id INTEGER REFERENCES users(id) ON DELETE SET NULL DEFAULT NULL',
+ );
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS packing_bag_members (
+ bag_id INTEGER NOT NULL REFERENCES packing_bags(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ PRIMARY KEY (bag_id, user_id)
+ );
+ CREATE INDEX IF NOT EXISTS idx_packing_bag_members_bag ON packing_bag_members(bag_id);
+ `);
+ // Migrate existing single user_id to bag_members
+ const bagsWithUser = db.prepare('SELECT id, user_id FROM packing_bags WHERE user_id IS NOT NULL').all() as {
+ id: number;
+ user_id: number;
+ }[];
+ const ins = db.prepare('INSERT OR IGNORE INTO packing_bag_members (bag_id, user_id) VALUES (?, ?)');
+ for (const b of bagsWithUser) ins.run(b.id, b.user_id);
+ },
+ // Migration: Per-day positions for multi-day reservations
+ () => {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS reservation_day_positions (
+ reservation_id INTEGER NOT NULL REFERENCES reservations(id) ON DELETE CASCADE,
+ day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
+ position REAL NOT NULL,
+ PRIMARY KEY (reservation_id, day_id)
+ );
+ `);
+ // Migrate existing global positions to per-day entries
+ const reservations = db
+ .prepare(
+ 'SELECT id, trip_id, reservation_time, reservation_end_time, day_plan_position FROM reservations WHERE day_plan_position IS NOT NULL',
+ )
+ .all() as any[];
+ const ins = db.prepare(
+ 'INSERT OR IGNORE INTO reservation_day_positions (reservation_id, day_id, position) VALUES (?, ?, ?)',
+ );
+ for (const r of reservations) {
+ const startDate = r.reservation_time?.split('T')[0];
+ const endDate = r.reservation_end_time?.split('T')[0] || startDate;
+ if (!startDate) continue;
+ const matchingDays = db
+ .prepare('SELECT id FROM days WHERE trip_id = ? AND date >= ? AND date <= ?')
+ .all(r.trip_id, startDate, endDate) as { id: number }[];
+ for (const d of matchingDays) ins.run(r.id, d.id, r.day_plan_position);
+ }
+ },
+ // Migration: Budget category ordering
+ () => {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS budget_category_order (
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ category TEXT NOT NULL,
+ sort_order INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY (trip_id, category)
+ );
+ `);
+ // Seed existing categories with alphabetical order
+ const rows = db
+ .prepare('SELECT DISTINCT trip_id, category FROM budget_items ORDER BY trip_id, category')
+ .all() as { trip_id: number; category: string }[];
+ const ins = db.prepare(
+ 'INSERT OR IGNORE INTO budget_category_order (trip_id, category, sort_order) VALUES (?, ?, ?)',
+ );
+ let lastTripId = -1;
+ let idx = 0;
+ for (const r of rows) {
+ if (r.trip_id !== lastTripId) {
+ lastTripId = r.trip_id;
+ idx = 0;
+ }
+ ins.run(r.trip_id, r.category, idx++);
+ }
+ },
+ // Migration: Naver list import addon (default off)
+ () => {
+ try {
+ db.prepare(
+ `
+ INSERT OR IGNORE INTO addons (id, name, description, type, icon, enabled, sort_order)
+ VALUES (?, ?, ?, ?, ?, ?, ?)
+ `,
+ ).run(
+ 'naver_list_import',
+ 'Naver List Import',
+ 'Import places from shared Naver Maps lists',
+ 'trip',
+ 'Link2',
+ 0,
+ 13,
+ );
+ } catch (err: any) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ },
+ // Migration: OAuth 2.1 clients, consents, and tokens for MCP
+ () => {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS oauth_clients (
+ id TEXT PRIMARY KEY,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ client_id TEXT UNIQUE NOT NULL,
+ client_secret_hash TEXT NOT NULL,
+ redirect_uris TEXT NOT NULL DEFAULT '[]',
+ allowed_scopes TEXT NOT NULL DEFAULT '[]',
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+ CREATE INDEX IF NOT EXISTS idx_oauth_clients_user ON oauth_clients(user_id);
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_oauth_clients_client_id ON oauth_clients(client_id);
+
+ CREATE TABLE IF NOT EXISTS oauth_consents (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ client_id TEXT NOT NULL REFERENCES oauth_clients(client_id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ scopes TEXT NOT NULL DEFAULT '[]',
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(client_id, user_id)
+ );
+
+ CREATE TABLE IF NOT EXISTS oauth_tokens (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ client_id TEXT NOT NULL REFERENCES oauth_clients(client_id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ access_token_hash TEXT UNIQUE NOT NULL,
+ refresh_token_hash TEXT UNIQUE NOT NULL,
+ scopes TEXT NOT NULL DEFAULT '[]',
+ access_token_expires_at DATETIME NOT NULL,
+ refresh_token_expires_at DATETIME NOT NULL,
+ revoked_at DATETIME,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+ CREATE INDEX IF NOT EXISTS idx_oauth_tokens_user ON oauth_tokens(user_id);
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_oauth_tokens_access ON oauth_tokens(access_token_hash);
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_oauth_tokens_refresh ON oauth_tokens(refresh_token_hash);
+ `);
+ },
+ // Migration: Refresh-token rotation chain tracking for replay detection
+ () => {
+ db.exec(`
+ ALTER TABLE oauth_tokens ADD COLUMN parent_token_id INTEGER REFERENCES oauth_tokens(id);
+ CREATE INDEX IF NOT EXISTS idx_oauth_tokens_parent ON oauth_tokens(parent_token_id);
+ `);
+ },
+ // Migration: Public client support for browser-initiated dynamic registration (DCR)
+ () => {
+ db.exec(`
+ ALTER TABLE oauth_clients ADD COLUMN is_public INTEGER NOT NULL DEFAULT 0;
+ ALTER TABLE oauth_clients ADD COLUMN created_via TEXT NOT NULL DEFAULT 'settings_ui';
+ `);
+ },
+ // Migration: Make oauth_clients.user_id nullable to support anonymous RFC 7591 DCR clients
+ // (must run outside a transaction because PRAGMA foreign_keys cannot change mid-transaction)
+ {
+ raw: () => {
+ db.exec('PRAGMA foreign_keys = OFF');
+ try {
+ db.transaction(() => {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS oauth_clients_new (
+ id TEXT PRIMARY KEY,
+ user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ client_id TEXT UNIQUE NOT NULL,
+ client_secret_hash TEXT NOT NULL,
+ redirect_uris TEXT NOT NULL DEFAULT '[]',
+ allowed_scopes TEXT NOT NULL DEFAULT '[]',
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ is_public INTEGER NOT NULL DEFAULT 0,
+ created_via TEXT NOT NULL DEFAULT 'settings_ui'
+ )
+ `);
+ db.exec(
+ `INSERT INTO oauth_clients_new SELECT id, user_id, name, client_id, client_secret_hash, redirect_uris, allowed_scopes, created_at, is_public, created_via FROM oauth_clients`,
+ );
+ db.exec(`DROP TABLE oauth_clients`);
+ db.exec(`ALTER TABLE oauth_clients_new RENAME TO oauth_clients`);
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_oauth_clients_user ON oauth_clients(user_id)`);
+ db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_oauth_clients_client_id ON oauth_clients(client_id)`);
+ })();
+ } finally {
+ db.exec('PRAGMA foreign_keys = ON');
+ }
+ },
+ },
+ // Migration: Add OTP field, skip_ssl column, device_id (did) column, and hint column for Synology Photos
+ () => {
+ const cols = db.prepare('PRAGMA table_info(photo_provider_fields)').all() as Array<{ name: string }>;
+ if (!cols.some((c) => c.name === 'hint')) {
+ db.exec(`ALTER TABLE photo_provider_fields ADD COLUMN hint TEXT`);
+ }
+ db.exec(`
+ INSERT OR IGNORE INTO photo_provider_fields
+ (provider_id, field_key, label, input_type, placeholder, required, secret, settings_key, payload_key, sort_order)
+ VALUES
+ ('synologyphotos', 'synology_otp', 'providerOTP', 'text', '123456', 0, 0, NULL, 'synology_otp', 3)
+ `);
+ db.exec(`ALTER TABLE users ADD COLUMN synology_skip_ssl INTEGER NOT NULL DEFAULT 0`);
+ db.exec(`ALTER TABLE users ADD COLUMN synology_did TEXT`);
+ db.exec(`
+ INSERT OR IGNORE INTO photo_provider_fields
+ (provider_id, field_key, label, input_type, placeholder, required, secret, settings_key, payload_key, sort_order)
+ VALUES
+ ('synologyphotos', 'synology_skip_ssl', 'skipSSLVerification', 'checkbox', NULL, 0, 0, 'synology_skip_ssl', 'synology_skip_ssl', 4)
+ `);
+ db.exec(`
+ UPDATE photo_provider_fields
+ SET hint = 'providerUrlHintSynology'
+ WHERE provider_id = 'synologyphotos' AND field_key = 'synology_url'
+ `);
+ },
+ // Migration 84: Journey addon — trip tracking & travel journal
+ () => {
+ // Register addon (disabled by default — opt-in)
+ db.prepare(
+ `
+ INSERT OR IGNORE INTO addons (id, name, description, type, icon, enabled, config, sort_order)
+ VALUES ('journey', 'Journey', 'Trip tracking & travel journal — check-ins, photos, daily stories', 'global', 'Compass', 0, '{}', 35)
+ `,
+ ).run();
+
+ // Core journey table
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS journeys (
+ id TEXT PRIMARY KEY,
+ trip_id INTEGER REFERENCES trips(id) ON DELETE SET NULL,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ title TEXT NOT NULL,
+ description TEXT,
+ cover_image TEXT,
+ status TEXT NOT NULL DEFAULT 'draft',
+ started_at TEXT,
+ ended_at TEXT,
+ is_public INTEGER NOT NULL DEFAULT 0,
+ public_token TEXT UNIQUE,
+ settings TEXT DEFAULT '{}',
+ created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now')),
+ updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now'))
+ )
+ `);
+
+ // Check-ins — visited locations
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS journey_checkins (
+ id TEXT PRIMARY KEY,
+ journey_id TEXT NOT NULL REFERENCES journeys(id) ON DELETE CASCADE,
+ place_id INTEGER REFERENCES places(id) ON DELETE SET NULL,
+ name TEXT NOT NULL,
+ lat REAL,
+ lng REAL,
+ address TEXT,
+ country_code TEXT,
+ notes TEXT,
+ checked_in_at TEXT NOT NULL,
+ source TEXT NOT NULL DEFAULT 'manual',
+ created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now'))
+ )
+ `);
+
+ // Journal entries — daily stories
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS journey_entries (
+ id TEXT PRIMARY KEY,
+ journey_id TEXT NOT NULL REFERENCES journeys(id) ON DELETE CASCADE,
+ checkin_id TEXT REFERENCES journey_checkins(id) ON DELETE SET NULL,
+ entry_date TEXT NOT NULL,
+ title TEXT,
+ body TEXT,
+ mood TEXT,
+ weather TEXT,
+ sort_order INTEGER NOT NULL DEFAULT 0,
+ created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now')),
+ updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now'))
+ )
+ `);
+
+ // Photos — local uploads + provider references (Immich/Synology)
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS journey_photos (
+ id TEXT PRIMARY KEY,
+ journey_id TEXT NOT NULL REFERENCES journeys(id) ON DELETE CASCADE,
+ checkin_id TEXT REFERENCES journey_checkins(id) ON DELETE SET NULL,
+ entry_id TEXT REFERENCES journey_entries(id) ON DELETE SET NULL,
+ storage_type TEXT NOT NULL DEFAULT 'local',
+ asset_id TEXT,
+ file_path TEXT,
+ thumbnail_path TEXT,
+ original_name TEXT,
+ mime_type TEXT,
+ size_bytes INTEGER,
+ caption TEXT,
+ taken_at TEXT,
+ lat REAL,
+ lng REAL,
+ sort_order INTEGER NOT NULL DEFAULT 0,
+ created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now'))
+ )
+ `);
+
+ // GPS trail points (Dawarich integration)
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS journey_location_trail (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ journey_id TEXT NOT NULL REFERENCES journeys(id) ON DELETE CASCADE,
+ lat REAL NOT NULL,
+ lng REAL NOT NULL,
+ altitude REAL,
+ accuracy REAL,
+ recorded_at TEXT NOT NULL,
+ source TEXT NOT NULL DEFAULT 'dawarich'
+ )
+ `);
+
+ // Indexes
+ db.exec(`
+ CREATE INDEX IF NOT EXISTS idx_journeys_user ON journeys(user_id);
+ CREATE INDEX IF NOT EXISTS idx_journeys_trip ON journeys(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_journeys_public_token ON journeys(public_token);
+ CREATE INDEX IF NOT EXISTS idx_journey_checkins_journey ON journey_checkins(journey_id, checked_in_at);
+ CREATE INDEX IF NOT EXISTS idx_journey_entries_journey_date ON journey_entries(journey_id, entry_date);
+ CREATE INDEX IF NOT EXISTS idx_journey_photos_journey ON journey_photos(journey_id);
+ CREATE INDEX IF NOT EXISTS idx_journey_photos_checkin ON journey_photos(checkin_id);
+ CREATE INDEX IF NOT EXISTS idx_journey_photos_entry ON journey_photos(entry_id);
+ CREATE INDEX IF NOT EXISTS idx_journey_trail_journey_time ON journey_location_trail(journey_id, recorded_at);
+ `);
+ },
+ // Migration 85: Journal — richer entry fields for magazine-style design
+ () => {
+ // Highlight tags (JSON array), visibility control, hero photo, color accent
+ try {
+ db.exec('ALTER TABLE journey_entries ADD COLUMN highlight_tags TEXT');
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ try {
+ db.exec("ALTER TABLE journey_entries ADD COLUMN visibility TEXT NOT NULL DEFAULT 'private'");
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ try {
+ db.exec('ALTER TABLE journey_entries ADD COLUMN hero_photo_id TEXT');
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ try {
+ db.exec('ALTER TABLE journey_entries ADD COLUMN color_accent TEXT');
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ try {
+ db.exec('ALTER TABLE journey_entries ADD COLUMN place_name TEXT');
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ try {
+ db.exec('ALTER TABLE journey_entries ADD COLUMN place_id INTEGER REFERENCES places(id) ON DELETE SET NULL');
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ try {
+ db.exec('ALTER TABLE journey_entries ADD COLUMN lat REAL');
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ try {
+ db.exec('ALTER TABLE journey_entries ADD COLUMN lng REAL');
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+
+ // Check-in: allow a single cover photo reference
+ try {
+ db.exec('ALTER TABLE journey_checkins ADD COLUMN photo_id TEXT');
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+
+ // Photos: add caption edit timestamp for gallery ordering
+ try {
+ db.exec('ALTER TABLE journey_photos ADD COLUMN width INTEGER');
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ try {
+ db.exec('ALTER TABLE journey_photos ADD COLUMN height INTEGER');
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ },
+ // Migration 86: Journey multi-trip support + sharing/collaboration
+ () => {
+ // Junction table: journey can include multiple trips
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS journey_trips (
+ journey_id TEXT NOT NULL REFERENCES journeys(id) ON DELETE CASCADE,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ sort_order INTEGER NOT NULL DEFAULT 0,
+ added_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now')),
+ PRIMARY KEY (journey_id, trip_id)
+ )
+ `);
+ db.exec('CREATE INDEX IF NOT EXISTS idx_journey_trips_journey ON journey_trips(journey_id)');
+
+ // Sharing: invite users to a journey
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS journey_members (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ journey_id TEXT NOT NULL REFERENCES journeys(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ role TEXT NOT NULL DEFAULT 'viewer',
+ invited_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
+ created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now')),
+ UNIQUE(journey_id, user_id)
+ )
+ `);
+ db.exec('CREATE INDEX IF NOT EXISTS idx_journey_members_user ON journey_members(user_id)');
+
+ // author tracking on entries and checkins
+ try {
+ db.exec('ALTER TABLE journey_entries ADD COLUMN user_id INTEGER REFERENCES users(id) ON DELETE SET NULL');
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ try {
+ db.exec('ALTER TABLE journey_checkins ADD COLUMN user_id INTEGER REFERENCES users(id) ON DELETE SET NULL');
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ },
+ // Migration 87: Journey rebuild — new schema with trip sync
+ () => {
+ // Migrate existing data from old tables into backup, then rebuild
+ const hasOldJourneys = db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='journeys'").get();
+
+ let oldJourneys: any[] = [];
+ let oldEntries: any[] = [];
+ let oldPhotos: any[] = [];
+
+ if (hasOldJourneys) {
+ // Save existing data before dropping
+ try {
+ oldJourneys = db.prepare('SELECT * FROM journeys').all();
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ try {
+ oldEntries = db.prepare('SELECT * FROM journey_entries').all();
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ try {
+ oldPhotos = db.prepare('SELECT * FROM journey_photos').all();
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+
+ // Drop all old journey tables
+ db.exec('DROP TABLE IF EXISTS journey_location_trail');
+ db.exec('DROP TABLE IF EXISTS journey_photos');
+ db.exec('DROP TABLE IF EXISTS journey_entries');
+ db.exec('DROP TABLE IF EXISTS journey_checkins');
+ db.exec('DROP TABLE IF EXISTS journey_members');
+ db.exec('DROP TABLE IF EXISTS journey_trips');
+ db.exec('DROP TABLE IF EXISTS journeys');
+ }
+
+ // New schema
+ db.exec(`
+ CREATE TABLE journeys (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER NOT NULL,
+ title TEXT NOT NULL,
+ subtitle TEXT,
+ cover_gradient TEXT,
+ status TEXT DEFAULT 'draft',
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL,
+ FOREIGN KEY (user_id) REFERENCES users(id)
+ )
+ `);
+
+ db.exec(`
+ CREATE TABLE journey_trips (
+ journey_id INTEGER NOT NULL,
+ trip_id INTEGER NOT NULL,
+ added_at INTEGER NOT NULL,
+ PRIMARY KEY (journey_id, trip_id),
+ FOREIGN KEY (journey_id) REFERENCES journeys(id) ON DELETE CASCADE,
+ FOREIGN KEY (trip_id) REFERENCES trips(id) ON DELETE CASCADE
+ )
+ `);
+
+ db.exec(`
+ CREATE TABLE journey_entries (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ journey_id INTEGER NOT NULL,
+ source_trip_id INTEGER,
+ source_place_id INTEGER,
+ author_id INTEGER NOT NULL,
+ type TEXT NOT NULL,
+ title TEXT,
+ story TEXT,
+ entry_date TEXT NOT NULL,
+ entry_time TEXT,
+ location_name TEXT,
+ location_lat REAL,
+ location_lng REAL,
+ mood TEXT,
+ weather TEXT,
+ tags TEXT,
+ visibility TEXT DEFAULT 'private',
+ sort_order INTEGER DEFAULT 0,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL,
+ FOREIGN KEY (journey_id) REFERENCES journeys(id) ON DELETE CASCADE,
+ FOREIGN KEY (source_trip_id) REFERENCES trips(id) ON DELETE SET NULL,
+ FOREIGN KEY (source_place_id) REFERENCES places(id) ON DELETE SET NULL,
+ FOREIGN KEY (author_id) REFERENCES users(id)
+ )
+ `);
+
+ db.exec(`
+ CREATE TABLE journey_photos (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ entry_id INTEGER NOT NULL,
+ file_path TEXT NOT NULL,
+ thumbnail_path TEXT,
+ caption TEXT,
+ sort_order INTEGER DEFAULT 0,
+ width INTEGER,
+ height INTEGER,
+ created_at INTEGER NOT NULL,
+ FOREIGN KEY (entry_id) REFERENCES journey_entries(id) ON DELETE CASCADE
+ )
+ `);
+
+ db.exec(`
+ CREATE TABLE journey_contributors (
+ journey_id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ role TEXT NOT NULL,
+ added_at INTEGER NOT NULL,
+ PRIMARY KEY (journey_id, user_id),
+ FOREIGN KEY (journey_id) REFERENCES journeys(id) ON DELETE CASCADE,
+ FOREIGN KEY (user_id) REFERENCES users(id)
+ )
+ `);
+
+ // Indexes
+ db.exec(`
+ CREATE INDEX idx_journeys_user ON journeys(user_id);
+ CREATE INDEX idx_journey_entries_journey ON journey_entries(journey_id, entry_date);
+ CREATE INDEX idx_journey_entries_source ON journey_entries(source_place_id);
+ CREATE INDEX idx_journey_photos_entry ON journey_photos(entry_id);
+ CREATE INDEX idx_journey_trips_journey ON journey_trips(journey_id);
+ CREATE INDEX idx_journey_contributors_user ON journey_contributors(user_id);
+ `);
+
+ // Re-import old data if it existed
+ if (oldJourneys.length > 0) {
+ const ts = Date.now();
+ const journeyIdMap = new Map(); // old TEXT id -> new INTEGER id
+
+ for (const j of oldJourneys) {
+ const res = db
+ .prepare(
+ `
+ INSERT INTO journeys (user_id, title, subtitle, status, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?)
+ `,
+ )
+ .run(
+ j.user_id,
+ j.title || 'Untitled Journey',
+ j.description || null,
+ j.status || 'draft',
+ j.created_at ? new Date(j.created_at).getTime() : ts,
+ j.updated_at ? new Date(j.updated_at).getTime() : ts,
+ );
+ journeyIdMap.set(j.id, Number(res.lastInsertRowid));
+
+ // Add owner as contributor
+ db.prepare(
+ `
+ INSERT OR IGNORE INTO journey_contributors (journey_id, user_id, role, added_at)
+ VALUES (?, ?, 'owner', ?)
+ `,
+ ).run(Number(res.lastInsertRowid), j.user_id, ts);
+
+ // Link trip if old journey had one
+ if (j.trip_id) {
+ try {
+ db.prepare(
+ `
+ INSERT OR IGNORE INTO journey_trips (journey_id, trip_id, added_at)
+ VALUES (?, ?, ?)
+ `,
+ ).run(Number(res.lastInsertRowid), j.trip_id, ts);
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ }
+ }
+
+ // Migrate entries
+ const entryIdMap = new Map();
+ for (const e of oldEntries) {
+ const newJourneyId = journeyIdMap.get(e.journey_id);
+ if (!newJourneyId) continue;
+
+ const res = db
+ .prepare(
+ `
+ INSERT INTO journey_entries (journey_id, author_id, type, title, story, entry_date, entry_time, location_name, location_lat, location_lng, mood, weather, visibility, sort_order, created_at, updated_at)
+ VALUES (?, ?, 'entry', ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ `,
+ )
+ .run(
+ newJourneyId,
+ e.user_id || oldJourneys.find((j: any) => j.id === e.journey_id)?.user_id || 1,
+ e.title || null,
+ e.body || null,
+ e.entry_date || new Date().toISOString().split('T')[0],
+ e.place_name || null,
+ e.lat || null,
+ e.lng || null,
+ e.mood || null,
+ e.weather || null,
+ e.visibility || 'private',
+ e.sort_order || 0,
+ e.created_at ? new Date(e.created_at).getTime() : ts,
+ e.updated_at ? new Date(e.updated_at).getTime() : ts,
+ );
+ entryIdMap.set(e.id, Number(res.lastInsertRowid));
+ }
+
+ // Migrate photos
+ for (const p of oldPhotos) {
+ const newEntryId = p.entry_id ? entryIdMap.get(p.entry_id) : null;
+ if (!newEntryId || !p.file_path) continue;
+
+ db.prepare(
+ `
+ INSERT INTO journey_photos (entry_id, file_path, thumbnail_path, caption, sort_order, width, height, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
+ `,
+ ).run(
+ newEntryId,
+ p.file_path,
+ p.thumbnail_path || null,
+ p.caption || null,
+ p.sort_order || 0,
+ p.width || null,
+ p.height || null,
+ p.created_at ? new Date(p.created_at).getTime() : ts,
+ );
+ }
+
+ console.log(
+ `[DB] Journey migration: imported ${journeyIdMap.size} journeys, ${entryIdMap.size} entries, photos migrated`,
+ );
+ }
+ },
+ // Migration 88: Journey photos — provider support (Immich/Synology)
+ () => {
+ try {
+ db.exec("ALTER TABLE journey_photos ADD COLUMN provider TEXT NOT NULL DEFAULT 'local'");
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ try {
+ db.exec('ALTER TABLE journey_photos ADD COLUMN asset_id TEXT');
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ try {
+ db.exec('ALTER TABLE journey_photos ADD COLUMN owner_id INTEGER REFERENCES users(id)');
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ try {
+ db.exec('ALTER TABLE journey_photos ADD COLUMN shared INTEGER NOT NULL DEFAULT 1');
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ // file_path was NOT NULL — recreate table to make it nullable
+ const hasProvider = db.prepare("SELECT 1 FROM pragma_table_info('journey_photos') WHERE name = 'provider'").get();
+ if (hasProvider) {
+ // Already has the column, just ensure file_path is nullable by recreating
+ try {
+ db.exec(`
+ CREATE TABLE journey_photos_new (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ entry_id INTEGER NOT NULL,
+ provider TEXT NOT NULL DEFAULT 'local',
+ asset_id TEXT,
+ owner_id INTEGER REFERENCES users(id),
+ file_path TEXT,
+ thumbnail_path TEXT,
+ caption TEXT,
+ sort_order INTEGER DEFAULT 0,
+ width INTEGER,
+ height INTEGER,
+ shared INTEGER NOT NULL DEFAULT 1,
+ created_at INTEGER NOT NULL,
+ FOREIGN KEY (entry_id) REFERENCES journey_entries(id) ON DELETE CASCADE
+ );
+ INSERT INTO journey_photos_new SELECT id, entry_id, provider, asset_id, owner_id, file_path, thumbnail_path, caption, sort_order, width, height, shared, created_at FROM journey_photos;
+ DROP TABLE journey_photos;
+ ALTER TABLE journey_photos_new RENAME TO journey_photos;
+ CREATE INDEX idx_journey_photos_entry ON journey_photos(entry_id);
+ `);
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ }
+ },
+ // Migration 89: Journey cover image
+ () => {
+ try {
+ db.exec('ALTER TABLE journeys ADD COLUMN cover_image TEXT');
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ },
+ // Migration 90: Pros/Cons for journey entries
+ () => {
+ try {
+ db.exec('ALTER TABLE journey_entries ADD COLUMN pros_cons TEXT');
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ },
+ // Migration 91: Journey share tokens
+ () => {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS journey_share_tokens (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ journey_id INTEGER NOT NULL,
+ token TEXT NOT NULL UNIQUE,
+ created_by INTEGER NOT NULL,
+ share_timeline INTEGER DEFAULT 1,
+ share_gallery INTEGER DEFAULT 1,
+ share_map INTEGER DEFAULT 1,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ FOREIGN KEY (journey_id) REFERENCES journeys(id) ON DELETE CASCADE,
+ FOREIGN KEY (created_by) REFERENCES users(id)
+ )
+ `);
+ db.exec('CREATE UNIQUE INDEX IF NOT EXISTS idx_journey_share_journey ON journey_share_tokens(journey_id)');
+ },
+ // Migration: Vacay week_start setting (0=Sunday, 1=Monday default)
+ () => {
+ try {
+ db.exec('ALTER TABLE vacay_plans ADD COLUMN week_start INTEGER NOT NULL DEFAULT 1');
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ },
+ // Migration: Unified Photo Provider Abstraction Layer (#584)
+ // Central trek_photos registry; trip_photos + journey_photos reference via photo_id
+ () => {
+ // 1. Create the central photo registry
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS trek_photos (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ provider TEXT NOT NULL,
+ asset_id TEXT,
+ owner_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
+ file_path TEXT,
+ thumbnail_path TEXT,
+ width INTEGER,
+ height INTEGER,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ )
+ `);
+ db.exec(
+ 'CREATE UNIQUE INDEX IF NOT EXISTS idx_trek_photos_provider_asset ON trek_photos(provider, asset_id, owner_id) WHERE asset_id IS NOT NULL',
+ );
+ db.exec('CREATE INDEX IF NOT EXISTS idx_trek_photos_owner ON trek_photos(owner_id)');
+
+ // 2. Migrate trip_photos → trek_photos + photo_id FK
+ const tripPhotosExists = db
+ .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'trip_photos'")
+ .get();
+ if (tripPhotosExists) {
+ // Detect schema variant: old (immich_asset_id) vs new (asset_id + provider)
+ const tpCols = db.prepare("PRAGMA table_info('trip_photos')").all() as Array<{ name: string }>;
+ const tpColNames = new Set(tpCols.map((c) => c.name));
+ const hasProvider = tpColNames.has('provider');
+ const assetCol = tpColNames.has('asset_id')
+ ? 'asset_id'
+ : tpColNames.has('immich_asset_id')
+ ? 'immich_asset_id'
+ : null;
+ const hasAlbumLink = tpColNames.has('album_link_id');
+
+ if (assetCol) {
+ const providerExpr = hasProvider ? 'provider' : "'immich'";
+ // Qualified alias needed in JOIN context where both trip_photos and trek_photos have provider
+ const providerJoinExpr = hasProvider ? 'tp.provider' : "'immich'";
+ const sharedExpr = tpColNames.has('shared') ? 'shared' : '1';
+ const addedAtExpr = tpColNames.has('added_at')
+ ? 'COALESCE(added_at, CURRENT_TIMESTAMP)'
+ : 'CURRENT_TIMESTAMP';
+ const albumLinkExpr = hasAlbumLink ? 'album_link_id' : 'NULL';
+
+ // Insert existing trip photo references into trek_photos
+ db.exec(`
+ INSERT OR IGNORE INTO trek_photos (provider, asset_id, owner_id, created_at)
+ SELECT DISTINCT ${providerExpr}, ${assetCol}, user_id, ${addedAtExpr}
+ FROM trip_photos
+ WHERE ${assetCol} IS NOT NULL AND TRIM(${assetCol}) != ''
+ `);
+
+ // Recreate trip_photos with photo_id FK
+ db.exec(`
+ CREATE TABLE trip_photos_new (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ photo_id INTEGER NOT NULL REFERENCES trek_photos(id) ON DELETE CASCADE,
+ shared INTEGER NOT NULL DEFAULT 1,
+ album_link_id INTEGER REFERENCES trip_album_links(id) ON DELETE SET NULL,
+ added_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(trip_id, user_id, photo_id)
+ )
+ `);
+ db.exec(`
+ INSERT OR IGNORE INTO trip_photos_new (trip_id, user_id, photo_id, shared, album_link_id, added_at)
+ SELECT tp.trip_id, tp.user_id, tkp.id, ${sharedExpr}, ${albumLinkExpr}, ${addedAtExpr}
+ FROM trip_photos tp
+ JOIN trek_photos tkp ON tkp.provider = ${providerJoinExpr} AND tkp.asset_id = tp.${assetCol} AND tkp.owner_id = tp.user_id
+ `);
+ } else {
+ // No asset column at all — just recreate empty
+ db.exec(`
+ CREATE TABLE trip_photos_new (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ photo_id INTEGER NOT NULL REFERENCES trek_photos(id) ON DELETE CASCADE,
+ shared INTEGER NOT NULL DEFAULT 1,
+ album_link_id INTEGER REFERENCES trip_album_links(id) ON DELETE SET NULL,
+ added_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(trip_id, user_id, photo_id)
+ )
+ `);
+ }
+ db.exec('DROP TABLE trip_photos');
+ db.exec('ALTER TABLE trip_photos_new RENAME TO trip_photos');
+ db.exec('CREATE INDEX IF NOT EXISTS idx_trip_photos_trip ON trip_photos(trip_id)');
+ db.exec('CREATE INDEX IF NOT EXISTS idx_trip_photos_photo ON trip_photos(photo_id)');
+ }
+
+ // 3. Migrate journey_photos → trek_photos + photo_id FK
+ const journeyPhotosExists = db
+ .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'journey_photos'")
+ .get();
+ if (journeyPhotosExists) {
+ // Insert provider-based journey photos into trek_photos
+ db.exec(`
+ INSERT OR IGNORE INTO trek_photos (provider, asset_id, owner_id, width, height, created_at)
+ SELECT DISTINCT provider, asset_id, owner_id, width, height, created_at
+ FROM journey_photos
+ WHERE provider != 'local' AND asset_id IS NOT NULL AND TRIM(asset_id) != ''
+ `);
+ // Insert local journey photos into trek_photos (each is unique)
+ db.exec(`
+ INSERT INTO trek_photos (provider, file_path, thumbnail_path, width, height, created_at)
+ SELECT 'local', file_path, thumbnail_path, width, height, created_at
+ FROM journey_photos
+ WHERE provider = 'local' AND file_path IS NOT NULL
+ `);
+
+ // Recreate journey_photos with photo_id FK
+ db.exec(`
+ CREATE TABLE journey_photos_new (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ entry_id INTEGER NOT NULL,
+ photo_id INTEGER NOT NULL REFERENCES trek_photos(id) ON DELETE CASCADE,
+ caption TEXT,
+ sort_order INTEGER DEFAULT 0,
+ shared INTEGER NOT NULL DEFAULT 1,
+ created_at INTEGER NOT NULL,
+ FOREIGN KEY (entry_id) REFERENCES journey_entries(id) ON DELETE CASCADE
+ )
+ `);
+ // Migrate provider photos
+ db.exec(`
+ INSERT INTO journey_photos_new (entry_id, photo_id, caption, sort_order, shared, created_at)
+ SELECT jp.entry_id, tkp.id, jp.caption, jp.sort_order, jp.shared, jp.created_at
+ FROM journey_photos jp
+ JOIN trek_photos tkp ON tkp.provider = jp.provider AND tkp.asset_id = jp.asset_id AND tkp.owner_id = jp.owner_id
+ WHERE jp.provider != 'local' AND jp.asset_id IS NOT NULL
+ `);
+ // Migrate local photos (match by file_path)
+ db.exec(`
+ INSERT INTO journey_photos_new (entry_id, photo_id, caption, sort_order, shared, created_at)
+ SELECT jp.entry_id, tkp.id, jp.caption, jp.sort_order, jp.shared, jp.created_at
+ FROM journey_photos jp
+ JOIN trek_photos tkp ON tkp.provider = 'local' AND tkp.file_path = jp.file_path
+ WHERE jp.provider = 'local' AND jp.file_path IS NOT NULL
+ `);
+ db.exec('DROP TABLE journey_photos');
+ db.exec('ALTER TABLE journey_photos_new RENAME TO journey_photos');
+ db.exec('CREATE INDEX IF NOT EXISTS idx_journey_photos_entry ON journey_photos(entry_id)');
+ db.exec('CREATE INDEX IF NOT EXISTS idx_journey_photos_photo ON journey_photos(photo_id)');
+ }
+ },
+ // Migration 99: hide_skeletons per-user setting on journey_contributors
+ () => {
+ try {
+ db.exec('ALTER TABLE journey_contributors ADD COLUMN hide_skeletons INTEGER NOT NULL DEFAULT 0');
+ } catch (err) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ },
+ // Migration 100: Idempotency keys for offline mutation replay
+ () => {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS idempotency_keys (
+ key TEXT NOT NULL,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ method TEXT NOT NULL,
+ path TEXT NOT NULL,
+ status_code INTEGER NOT NULL,
+ response_body TEXT NOT NULL,
+ created_at INTEGER NOT NULL DEFAULT (strftime('%s','now')),
+ PRIMARY KEY (key, user_id)
+ );
+ CREATE INDEX IF NOT EXISTS idx_idempotency_keys_created ON idempotency_keys(created_at);
+ `);
+ },
+
+ // Migration 101: Enable naver_list_import by default
+ () => {
+ db.prepare("UPDATE addons SET enabled = 1 WHERE id = 'naver_list_import'").run();
+ },
+
+ // Migration 102: Add check_in_end column for check-in time ranges
+ () => {
+ try {
+ db.exec('ALTER TABLE day_accommodations ADD COLUMN check_in_end TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ // Migration 103: System notices — user tracking columns + dismissals table
+ () => {
+ db.exec(`ALTER TABLE users ADD COLUMN first_seen_version TEXT NOT NULL DEFAULT '0.0.0'`);
+ db.exec(`ALTER TABLE users ADD COLUMN login_count INTEGER NOT NULL DEFAULT 0`);
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS user_notice_dismissals (
+ user_id INTEGER NOT NULL,
+ notice_id TEXT NOT NULL,
+ dismissed_at INTEGER NOT NULL,
+ PRIMARY KEY (user_id, notice_id),
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+ )
+ `);
+ },
+ // Migration 104: Passphrase support for Synology shared-album links (#689)
+ () => {
+ try {
+ db.exec('ALTER TABLE trip_album_links ADD COLUMN passphrase TEXT DEFAULT NULL');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE trek_photos ADD COLUMN passphrase TEXT DEFAULT NULL');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ // Migration 105: Persistent Google place photo disk cache registry
+ () => {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS google_place_photo_meta (
+ place_id TEXT PRIMARY KEY,
+ attribution TEXT,
+ fetched_at INTEGER NOT NULL,
+ error_at INTEGER
+ )
+ `);
+ },
+ // Migration 106: Persistent Place Details row cache
+ () => {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS place_details_cache (
+ place_id TEXT NOT NULL,
+ lang TEXT NOT NULL DEFAULT '',
+ expanded INTEGER NOT NULL DEFAULT 0,
+ payload_json TEXT NOT NULL,
+ fetched_at INTEGER NOT NULL,
+ PRIMARY KEY (place_id, lang, expanded)
+ )
+ `);
+ },
+ // Migration 107: Backfill expired signed Google photo URLs to stable proxy URLs
+ {
+ raw: () => {
+ db.exec(`
+ UPDATE places
+ SET image_url = '/api/maps/place-photo/' || google_place_id || '/bytes',
+ updated_at = CURRENT_TIMESTAMP
+ WHERE google_place_id IS NOT NULL
+ AND image_url IS NOT NULL
+ AND image_url != ''
+ AND (
+ (image_url LIKE '%googleusercontent.com%' AND image_url LIKE '%/places/%/photos/%')
+ OR (image_url LIKE '%places.googleapis.com%' AND image_url LIKE '%/places/%/photos/%')
+ )
+ `);
+ },
+ },
+ // Migration 108: Disk cache metadata for remote-provider photo thumbnails (Immich / Synology)
+ () =>
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS trek_photo_cache_meta (
+ cache_key TEXT PRIMARY KEY,
+ content_type TEXT NOT NULL DEFAULT 'image/jpeg',
+ fetched_at INTEGER NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS idx_trek_photo_cache_meta_fetched_at ON trek_photo_cache_meta (fetched_at);
+ `),
+ // Migration 109: Reservation endpoints (from/to points for flights, trains, ferries, car rentals) — #384 + #587
+ () => {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS reservation_endpoints (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ reservation_id INTEGER NOT NULL REFERENCES reservations(id) ON DELETE CASCADE,
+ role TEXT NOT NULL,
+ sequence INTEGER NOT NULL DEFAULT 0,
+ name TEXT NOT NULL,
+ code TEXT,
+ lat REAL NOT NULL,
+ lng REAL NOT NULL,
+ timezone TEXT,
+ local_time TEXT,
+ local_date TEXT,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ )
+ `);
+ db.exec(
+ 'CREATE INDEX IF NOT EXISTS idx_reservation_endpoints_reservation_id ON reservation_endpoints(reservation_id)',
+ );
+ try {
+ db.exec('ALTER TABLE reservations ADD COLUMN needs_review INTEGER NOT NULL DEFAULT 0');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ // Migration 110 — link transport reservations to days via day_id / end_day_id
+ () => {
+ try {
+ db.exec('ALTER TABLE reservations ADD COLUMN end_day_id INTEGER REFERENCES days(id) ON DELETE SET NULL');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+
+ db.exec(`
+ UPDATE reservations
+ SET day_id = (
+ SELECT d.id FROM days d
+ WHERE d.trip_id = reservations.trip_id
+ AND d.date = substr(reservations.reservation_time, 1, 10)
+ LIMIT 1
+ )
+ WHERE type IN ('flight','train','car','cruise','bus')
+ AND reservation_time IS NOT NULL
+ AND day_id IS NULL
+ `);
+
+ db.exec(`
+ UPDATE reservations
+ SET end_day_id = (
+ SELECT d.id FROM days d
+ WHERE d.trip_id = reservations.trip_id
+ AND d.date = substr(reservations.reservation_end_time, 1, 10)
+ LIMIT 1
+ )
+ WHERE type IN ('flight','train','car','cruise','bus')
+ AND reservation_end_time IS NOT NULL
+ AND end_day_id IS NULL
+ AND substr(reservations.reservation_end_time, 1, 10) != substr(reservations.reservation_time, 1, 10)
+ `);
+ },
+ // Migration 111: opt-in Immich auto-upload — users column only (#730)
+ // Default is off — uploading to Immich must be an explicit choice, not a
+ // side effect of having a writable API key.
+ () => {
+ try {
+ db.exec('ALTER TABLE users ADD COLUMN immich_auto_upload INTEGER NOT NULL DEFAULT 0');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ // Migration 112: expose immich auto-upload toggle in the Settings UI (#730)
+ // Runs after Immich provider seeding so the FK to photo_providers holds.
+ () => {
+ try {
+ const hasTable = db
+ .prepare(
+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('photo_providers', 'photo_provider_fields')",
+ )
+ .all() as Array<{ name: string }>;
+ const hasProviders = hasTable.some((t) => t.name === 'photo_providers');
+ const hasFields = hasTable.some((t) => t.name === 'photo_provider_fields');
+ if (hasProviders && hasFields) {
+ const immichRow = db.prepare("SELECT 1 FROM photo_providers WHERE id = 'immich' LIMIT 1").get();
+ if (immichRow) {
+ db.prepare(
+ `
+ INSERT OR IGNORE INTO photo_provider_fields
+ (provider_id, field_key, label, input_type, placeholder, required, secret, settings_key, payload_key, sort_order)
+ VALUES
+ ('immich', 'immich_auto_upload', 'immichAutoUpload', 'checkbox', NULL, 0, 0, 'auto_upload', 'auto_upload', 5)
+ `,
+ ).run();
+ }
+ }
+ } catch (err: any) {
+ if (!err.message?.includes('no such table') && !err.message?.includes('FOREIGN KEY')) throw err;
+ }
+ },
+ // Migration: RFC 8707 resource indicators — audience-bind OAuth tokens to /mcp
+ () => {
+ try {
+ db.exec('ALTER TABLE oauth_tokens ADD COLUMN audience TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ // Migration: password reset — add password_version for session
+ // invalidation, and a token table keyed by SHA-256 hash (raw tokens
+ // never hit the DB).
+ () => {
+ try {
+ db.exec('ALTER TABLE users ADD COLUMN password_version INTEGER NOT NULL DEFAULT 0');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS password_reset_tokens (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ token_hash TEXT NOT NULL UNIQUE,
+ expires_at DATETIME NOT NULL,
+ consumed_at DATETIME,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ created_ip TEXT
+ );
+ CREATE INDEX IF NOT EXISTS idx_prt_user ON password_reset_tokens(user_id);
+ CREATE INDEX IF NOT EXISTS idx_prt_hash ON password_reset_tokens(token_hash);
+ `);
+ },
+ // Migration: todo due-date reminders — track when we last sent a
+ // reminder for each todo so we don't spam the same notification
+ // every day the scheduler runs.
+ () => {
+ try {
+ db.exec('ALTER TABLE todo_items ADD COLUMN reminded_at DATETIME');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ // Migration: security audit batch 1 — columns + indexes required
+ // by several fixes bundled into one PR.
+ // - share_tokens.expires_at: public share links now get a 90-day
+ // TTL by default; existing rows stay NULL (= no expiry) to avoid
+ // silently breaking already-published links.
+ // - Missing indexes on high-cardinality query paths (see PERF-H1
+ // in the audit): every listTrips() used to full-scan trips on
+ // user_id, and notifications/photos/reservations had similar
+ // gaps.
+ () => {
+ try {
+ db.exec('ALTER TABLE share_tokens ADD COLUMN expires_at TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ db.exec(`
+ CREATE INDEX IF NOT EXISTS idx_trips_user_id ON trips(user_id);
+ CREATE INDEX IF NOT EXISTS idx_trips_created_at ON trips(created_at DESC);
+ CREATE INDEX IF NOT EXISTS idx_photos_day_id ON photos(day_id);
+ CREATE INDEX IF NOT EXISTS idx_photos_place_id ON photos(place_id);
+ CREATE INDEX IF NOT EXISTS idx_reservations_day_id ON reservations(day_id);
+ CREATE INDEX IF NOT EXISTS idx_share_tokens_token ON share_tokens(token);
+ `);
+ try {
+ // day_accommodations may have either start_day_id/end_day_id or a
+ // single day_id depending on how far the schema has evolved;
+ // build whichever index makes sense for the live columns.
+ const cols = db.prepare("PRAGMA table_info('day_accommodations')").all() as Array<{ name: string }>;
+ const names = new Set(cols.map((c) => c.name));
+ if (names.has('start_day_id'))
+ db.exec('CREATE INDEX IF NOT EXISTS idx_day_accommodations_start_day_id ON day_accommodations(start_day_id)');
+ if (names.has('end_day_id'))
+ db.exec('CREATE INDEX IF NOT EXISTS idx_day_accommodations_end_day_id ON day_accommodations(end_day_id)');
+ } catch (err) {
+ // Non-fatal: day_accommodations may not exist on very old installs.
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ try {
+ // notifications schema has varied; probe before indexing.
+ const cols = db.prepare("PRAGMA table_info('notifications')").all() as Array<{ name: string }>;
+ const names = new Set(cols.map((c) => c.name));
+ if (names.has('target') && names.has('scope')) {
+ db.exec('CREATE INDEX IF NOT EXISTS idx_notifications_target_scope ON notifications(target, scope)');
+ }
+ } catch (err) {
+ // Non-fatal: notifications table may not exist on very old installs.
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ },
+ // Migration: widen idempotency_keys primary key to (key, user_id,
+ // method, path). The middleware lookup was widened in the same audit
+ // batch so a reused X-Idempotency-Key against a different endpoint
+ // does not replay the cached body of an unrelated request. The old
+ // PK was only (key, user_id), so the `INSERT OR IGNORE` on the
+ // second endpoint silently skipped — the cache never stored request
+ // B's response and replays re-executed the handler. Rebuild the
+ // table with the widened PK, preserving existing rows (the old PK
+ // guarantees no conflicts in the new, strictly looser unique key).
+ () => {
+ const hasTable = db
+ .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'idempotency_keys'")
+ .get();
+ if (!hasTable) return;
+ db.exec(`
+ CREATE TABLE idempotency_keys_new (
+ key TEXT NOT NULL,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ method TEXT NOT NULL,
+ path TEXT NOT NULL,
+ status_code INTEGER NOT NULL,
+ response_body TEXT NOT NULL,
+ created_at INTEGER NOT NULL DEFAULT (strftime('%s','now')),
+ PRIMARY KEY (key, user_id, method, path)
+ );
+ INSERT INTO idempotency_keys_new (key, user_id, method, path, status_code, response_body, created_at)
+ SELECT key, user_id, method, path, status_code, response_body, created_at FROM idempotency_keys;
+ DROP TABLE idempotency_keys;
+ ALTER TABLE idempotency_keys_new RENAME TO idempotency_keys;
+ CREATE INDEX IF NOT EXISTS idx_idempotency_keys_created ON idempotency_keys(created_at);
+ `);
+ },
+ // SEC-H6: revoke all OAuth tokens issued before audience binding was
+ // enforced. mcp/index.ts now unconditionally checks audience; tokens
+ // with audience=null would be permanently rejected by the check, so
+ // removing them here avoids leaving dead rows and makes the intent clear.
+ () => {
+ const hasCol = db.prepare("SELECT name FROM pragma_table_info('oauth_tokens') WHERE name = 'audience'").get();
+ if (!hasCol) return;
+ db.prepare('DELETE FROM oauth_tokens WHERE audience IS NULL').run();
+ },
+ // Remove NOT NULL constraint on day_accommodations.place_id so hotel
+ // reservations created from the Bookings tab without a linked place can
+ // still persist their date range. Change ON DELETE CASCADE → SET NULL so
+ // deleting a place orphans the accommodation row instead of cascading.
+ () => {
+ db.exec(`
+ CREATE TABLE day_accommodations_new (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ place_id INTEGER REFERENCES places(id) ON DELETE SET NULL,
+ start_day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
+ end_day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
+ check_in TEXT,
+ check_in_end TEXT,
+ check_out TEXT,
+ confirmation TEXT,
+ notes TEXT,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+ INSERT INTO day_accommodations_new
+ SELECT id, trip_id, place_id, start_day_id, end_day_id,
+ check_in, check_in_end, check_out, confirmation, notes, created_at
+ FROM day_accommodations;
+ DROP TABLE day_accommodations;
+ ALTER TABLE day_accommodations_new RENAME TO day_accommodations;
+ CREATE INDEX IF NOT EXISTS idx_day_accommodations_trip_id ON day_accommodations(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_day_accommodations_start_day_id ON day_accommodations(start_day_id);
+ CREATE INDEX IF NOT EXISTS idx_day_accommodations_end_day_id ON day_accommodations(end_day_id);
+ `);
+ },
+ // Migration: null out proxy image_url entries that have no backing disk cache.
+ // Migrations 107 and the migration below wrote /api/maps/place-photo//bytes
+ // into places.image_url without actually fetching/caching the photo bytes. The
+ // photoService short-circuits on that prefix and hits /bytes directly → 404.
+ // Rows with a confirmed disk cache entry in google_place_photo_meta are left alone;
+ // only stale proxy URLs (never actually fetched) are cleared so the normal
+ // fetch-and-cache flow can repopulate them.
+ () => {
+ db.exec(`
+ UPDATE places
+ SET image_url = NULL, updated_at = CURRENT_TIMESTAMP
+ WHERE image_url LIKE '/api/maps/place-photo/%/bytes'
+ AND google_place_id IS NOT NULL
+ AND NOT EXISTS (
+ SELECT 1 FROM google_place_photo_meta
+ WHERE place_id = places.google_place_id
+ AND error_at IS NULL
+ )
+ `);
+ },
+ // Migration: clear legacy Google photo URLs missed by Migration 107.
+ // Migration 107 matched /places/%/photos/% only; lh3.googleusercontent.com URLs use
+ // /place-photos/ or /places/ paths and were skipped. NULL those stale URLs
+ // so the normal fetch-and-cache flow repopulates image_url with a real proxy URL.
+ () => {
+ db.exec(`
+ UPDATE places
+ SET image_url = NULL,
+ updated_at = CURRENT_TIMESTAMP
+ WHERE image_url IS NOT NULL
+ AND image_url != ''
+ AND image_url NOT LIKE '/api/maps/place-photo/%'
+ AND (
+ image_url LIKE 'http://%googleusercontent.com/%'
+ OR image_url LIKE 'https://%googleusercontent.com/%'
+ OR image_url LIKE 'http://%places.googleapis.com/%'
+ OR image_url LIKE 'https://%places.googleapis.com/%'
+ )
+ `);
+ },
+ // Migration 121: Journey gallery refactor — decouple photo ownership from
+ // entries. journey_photos becomes a per-journey gallery (one row per unique
+ // photo per journey). A new junction table journey_entry_photos links
+ // gallery photos to the entries that reference them, allowing the same
+ // photo to appear in multiple entries without duplication. Synthetic
+ // wrapper entries ('Gallery', '[Trip Photos]') created by the old model
+ // are removed — the gallery table replaces them.
+ () => {
+ const hasOld = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'journey_photos'").get();
+ const hasBackup = db
+ .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'journey_photos_old'")
+ .get();
+ if (hasOld && !hasBackup) {
+ db.exec('ALTER TABLE journey_photos RENAME TO journey_photos_old');
+ }
+
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS journey_photos (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ journey_id INTEGER NOT NULL REFERENCES journeys(id) ON DELETE CASCADE,
+ photo_id INTEGER NOT NULL REFERENCES trek_photos(id) ON DELETE CASCADE,
+ caption TEXT,
+ shared INTEGER DEFAULT 0,
+ sort_order INTEGER DEFAULT 0,
+ provider TEXT,
+ asset_id TEXT,
+ owner_id INTEGER,
+ created_at INTEGER NOT NULL,
+ UNIQUE(journey_id, photo_id)
+ )
+ `);
+
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS journey_entry_photos (
+ entry_id INTEGER NOT NULL REFERENCES journey_entries(id) ON DELETE CASCADE,
+ journey_photo_id INTEGER NOT NULL REFERENCES journey_photos(id) ON DELETE CASCADE,
+ sort_order INTEGER DEFAULT 0,
+ created_at INTEGER NOT NULL,
+ PRIMARY KEY(entry_id, journey_photo_id)
+ )
+ `);
+
+ if (hasOld || hasBackup) {
+ // Backfill gallery: deduplicate by (journey_id, photo_id), keeping
+ // the earliest row (MIN(id) = earliest created_at on AUTOINCREMENT).
+ db.exec(`
+ INSERT OR IGNORE INTO journey_photos
+ (journey_id, photo_id, caption, shared, sort_order, created_at)
+ SELECT
+ je.journey_id,
+ jpo.photo_id,
+ jpo.caption,
+ jpo.shared,
+ jpo.sort_order,
+ jpo.created_at
+ FROM journey_photos_old jpo
+ JOIN journey_entries je ON je.id = jpo.entry_id
+ WHERE jpo.id IN (
+ SELECT MIN(jpo2.id)
+ FROM journey_photos_old jpo2
+ JOIN journey_entries je2 ON je2.id = jpo2.entry_id
+ GROUP BY je2.journey_id, jpo2.photo_id
+ )
+ `);
+
+ // Backfill junction: one row per (entry_id, photo_id), resolved to
+ // the new gallery ids.
+ db.exec(`
+ INSERT OR IGNORE INTO journey_entry_photos
+ (entry_id, journey_photo_id, sort_order, created_at)
+ SELECT
+ jpo.entry_id,
+ jp.id,
+ jpo.sort_order,
+ jpo.created_at
+ FROM journey_photos_old jpo
+ JOIN journey_entries je ON je.id = jpo.entry_id
+ JOIN journey_photos jp
+ ON jp.journey_id = je.journey_id
+ AND jp.photo_id = jpo.photo_id
+ `);
+
+ db.exec('DROP TABLE journey_photos_old');
+ }
+
+ // Remove synthetic wrapper entries replaced by the gallery model.
+ // ON DELETE CASCADE on journey_entry_photos cleans up junction rows.
+ db.prepare("DELETE FROM journey_entries WHERE title IN ('Gallery', '[Trip Photos]')").run();
+
+ db.exec('CREATE INDEX IF NOT EXISTS idx_journey_photos_journey ON journey_photos(journey_id)');
+ db.exec('CREATE INDEX IF NOT EXISTS idx_journey_entry_photos_entry ON journey_entry_photos(entry_id)');
+ db.exec('CREATE INDEX IF NOT EXISTS idx_journey_entry_photos_photo ON journey_entry_photos(journey_photo_id)');
+ },
+ // Migration 122: Correct stale day_id / end_day_id on non-transport
+ // reservations. Migration 110 only backfilled transport types; tours,
+ // restaurants, events and "other" bookings kept a stale day_id from
+ // older code paths that often defaulted to the first day of the trip.
+ // Starting with v3.0.0 the planner renders reservations by day_id
+ // instead of reservation_time, so those stale rows show up on the
+ // wrong day. This migration nulls out day_id / end_day_id values that
+ // don't match the reservation's time and then backfills them from
+ // reservation_time / reservation_end_time.
+ () => {
+ db.exec(`
+ UPDATE reservations
+ SET day_id = NULL
+ WHERE reservation_time IS NOT NULL
+ AND day_id IS NOT NULL
+ AND type != 'hotel'
+ AND NOT EXISTS (
+ SELECT 1 FROM days d
+ WHERE d.id = reservations.day_id
+ AND d.date = substr(reservations.reservation_time, 1, 10)
+ )
+ `);
+
+ db.exec(`
+ UPDATE reservations
+ SET end_day_id = NULL
+ WHERE reservation_end_time IS NOT NULL
+ AND end_day_id IS NOT NULL
+ AND type != 'hotel'
+ AND NOT EXISTS (
+ SELECT 1 FROM days d
+ WHERE d.id = reservations.end_day_id
+ AND d.date = substr(reservations.reservation_end_time, 1, 10)
+ )
+ `);
+
+ db.exec(`
+ UPDATE reservations
+ SET day_id = (
+ SELECT d.id FROM days d
+ WHERE d.trip_id = reservations.trip_id
+ AND d.date = substr(reservations.reservation_time, 1, 10)
+ LIMIT 1
+ )
+ WHERE type != 'hotel'
+ AND reservation_time IS NOT NULL
+ AND day_id IS NULL
+ `);
+
+ db.exec(`
+ UPDATE reservations
+ SET end_day_id = (
+ SELECT d.id FROM days d
+ WHERE d.trip_id = reservations.trip_id
+ AND d.date = substr(reservations.reservation_end_time, 1, 10)
+ LIMIT 1
+ )
+ WHERE type != 'hotel'
+ AND reservation_end_time IS NOT NULL
+ AND end_day_id IS NULL
+ AND substr(reservations.reservation_end_time, 1, 10)
+ != substr(reservations.reservation_time, 1, 10)
+ `);
+ },
+ // #846: make sort_order authoritative within a day. Previous ORDER BY put
+ // entry_time before sort_order, silently ignoring reorder clicks when two
+ // same-date entries had different times. Backfill renumbers using the old
+ // effective key (entry_time ASC, id ASC) so existing journeys retain their
+ // current visual order.
+ () => {
+ db.exec(`
+ WITH ranked AS (
+ SELECT id,
+ ROW_NUMBER() OVER (
+ PARTITION BY journey_id, entry_date
+ ORDER BY entry_time ASC, id ASC
+ ) - 1 AS rn
+ FROM journey_entries
+ )
+ UPDATE journey_entries
+ SET sort_order = (SELECT rn FROM ranked WHERE ranked.id = journey_entries.id)
+ `);
+ db.exec(
+ 'CREATE INDEX IF NOT EXISTS idx_journey_entries_order ' +
+ 'ON journey_entries(journey_id, entry_date, sort_order)',
+ );
+ },
+ // Swap inverted start_day_id/end_day_id pairs in day_accommodations caused
+ // by the old Math.min/Math.max picker bug (pre-8e05ba7) which used raw IDs
+ // instead of positional order on trips with non-monotonic day ID layouts.
+ () => {
+ db.exec(`
+ UPDATE day_accommodations
+ SET start_day_id = end_day_id, end_day_id = start_day_id
+ WHERE (SELECT day_number FROM days WHERE id = start_day_id)
+ > (SELECT day_number FROM days WHERE id = end_day_id)
+ `);
+ },
+ // prepare migration to nest + typeorm
+ () => {
+ db.exec(
+ `CREATE TABLE IF NOT EXISTS migrations (id integer PRIMARY KEY AUTOINCREMENT NOT NULL, timestamp bigint NOT NULL, name varchar NOT NULL);`,
+ );
+ db.exec(`INSERT INTO migrations (timestamp, name) VALUES (1777810195344, 'InitialSchema1777810195344');`);
+ db.exec(`INSERT INTO app_settings (key, value) VALUES ('app_version', '${process.env.APP_VERSION || '3.0.14'}')`);
+ },
+ // trim leading/trailing whitespace from stored usernames and emails
+ () => {
+ const hadCollision = trimUserWhitespace(db);
+ if (hadCollision) {
+ db.prepare(
+ "INSERT OR REPLACE INTO app_settings (key, value) VALUES ('whitespace_migration_collision', 'true')",
+ ).run();
+ }
+ },
+ () => {
+ db.exec(
+ `CREATE TABLE IF NOT EXISTS schema_version_new (id INTEGER PRIMARY KEY AUTOINCREMENT,version INTEGER NOT NULL)`,
+ );
+ db.exec(`INSERT INTO schema_version_new (version) SELECT version FROM schema_version`);
+ db.exec(`DROP TABLE schema_version`);
+ db.exec(`ALTER TABLE schema_version_new RENAME TO schema_version`);
+ db.exec(`UPDATE app_settings SET value = '${process.env.APP_VERSION || '3.0.15'}' WHERE key = 'app_version'`);
+ },
+ // Migration: OAuth 2.0 client_credentials grant — allow user-owned confidential
+ // clients to skip the browser consent flow entirely and obtain tokens directly
+ // via client_id + client_secret. Flag is immutable after creation so existing
+ // authorization-code clients are not silently upgraded.
+ () => {
+ try {
+ db.exec('ALTER TABLE oauth_clients ADD COLUMN allows_client_credentials INTEGER NOT NULL DEFAULT 0');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ // Drop stale atlas cache rows for territories that used to resolve to their
+ // surrounding country (Hong Kong/Macau as China, San Marino/Vatican as Italy,
+ // etc.) before their own bounding boxes existed. The next atlas stats request
+ // re-resolves any place inside these boxes with the corrected country code.
+ () => {
+ const enclaveBoxes: [number, number, number, number][] = [
+ [113.83, 22.15, 114.43, 22.56], // HK
+ [113.53, 22.1, 113.6, 22.21], // MO
+ [12.4, 43.89, 12.52, 43.99], // SM
+ [12.44, 41.9, 12.46, 41.91], // VA
+ [7.4, 43.72, 7.44, 43.75], // MC
+ [9.47, 47.05, 9.64, 47.27], // LI
+ [-5.36, 36.11, -5.33, 36.16], // GI
+ [-67.3, 17.88, -65.22, 18.53], // PR
+ ];
+ try {
+ const del = db.prepare(
+ `DELETE FROM place_regions WHERE place_id IN (
+ SELECT id FROM places WHERE lat BETWEEN ? AND ? AND lng BETWEEN ? AND ?
+ )`,
+ );
+ for (const [minLng, minLat, maxLng, maxLat] of enclaveBoxes) {
+ del.run(minLat, maxLat, minLng, maxLng);
+ }
+ } catch (err: any) {
+ if (!err.message?.includes('no such table')) throw err;
+ }
+ },
+ // Costs rework (budget → "Costs", Tricount/Splitwise style). Adds, additively
+ // and without touching existing rows:
+ // - per-expense currency + exchange_rate, so an expense can be entered in a
+ // foreign currency and converted to the trip base currency (NULL currency =
+ // base currency; rate 1.0). Closes the multi-currency request (#551).
+ // - budget_item_payers: several people can each have paid part of one expense
+ // (amounts in the expense currency), replacing the single paid_by_user_id.
+ // - budget_settlements: persisted "X paid Y" transfers so the settle-up
+ // history (with undo) is shared across all trip members.
+ // The equal-split participants stay in budget_item_members. The single legacy
+ // payer is backfilled into budget_item_payers as one payer covering the total.
+ () => {
+ try {
+ db.exec('ALTER TABLE budget_items ADD COLUMN currency TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE budget_items ADD COLUMN exchange_rate REAL NOT NULL DEFAULT 1');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS budget_item_payers (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ budget_item_id INTEGER NOT NULL REFERENCES budget_items(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ amount REAL NOT NULL DEFAULT 0,
+ UNIQUE(budget_item_id, user_id)
+ )
+ `);
+ db.exec('CREATE INDEX IF NOT EXISTS idx_budget_item_payers_item ON budget_item_payers(budget_item_id)');
+
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS budget_settlements (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ from_user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ to_user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ amount REAL NOT NULL DEFAULT 0,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ created_by_user_id INTEGER REFERENCES users(id)
+ )
+ `);
+ db.exec('CREATE INDEX IF NOT EXISTS idx_budget_settlements_trip ON budget_settlements(trip_id)');
+
+ // Backfill the legacy single payer: that person paid the full total of the
+ // expense, in the (base) currency the existing amount was already stored in.
+ try {
+ db.exec(`
+ INSERT OR IGNORE INTO budget_item_payers (budget_item_id, user_id, amount)
+ SELECT id, paid_by_user_id, total_price
+ FROM budget_items
+ WHERE paid_by_user_id IS NOT NULL
+ `);
+ } catch (err: any) {
+ if (!err.message?.includes('no such column')) throw err;
+ }
+ },
+ // Rename the "Budget Planner" addon to "Costs" in the admin add-on list. This
+ // is a display rename only — the addon id, tables, permissions and MCP tools
+ // all stay 'budget'. Scoped to the default name so a customised one is kept.
+ () => {
+ db.prepare(
+ "UPDATE addons SET name = 'Costs', description = 'Track and split trip expenses' WHERE id = 'budget' AND name = 'Budget Planner'",
+ ).run();
+ },
+ // WebAuthn / passkey support: per-user credentials + single-use login
+ // challenges. Additive (CREATE TABLE IF NOT EXISTS) so existing installs are
+ // untouched; both tables also live in schema.ts for fresh installs.
+ () =>
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS webauthn_credentials (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ credential_id TEXT NOT NULL UNIQUE,
+ public_key BLOB NOT NULL,
+ counter INTEGER NOT NULL DEFAULT 0,
+ transports TEXT,
+ device_type TEXT,
+ backed_up INTEGER NOT NULL DEFAULT 0,
+ name TEXT,
+ aaguid TEXT,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ last_used_at DATETIME
+ );
+ CREATE INDEX IF NOT EXISTS idx_webauthn_credentials_user ON webauthn_credentials(user_id);
+ CREATE TABLE IF NOT EXISTS webauthn_challenges (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ challenge TEXT NOT NULL UNIQUE,
+ user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
+ type TEXT NOT NULL,
+ expires_at INTEGER NOT NULL,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+ CREATE INDEX IF NOT EXISTS idx_webauthn_challenges_expires ON webauthn_challenges(expires_at);
+ `),
+ // Atlas dropped Natural Earth for geoBoundaries. Manually-marked sub-national
+ // regions (`visited_regions`) stored the OLD Natural Earth ISO-3166-2 codes; some no
+ // longer match any polygon in the new bundle and would stop highlighting. Reconcile
+ // every row against the ACTUAL shipped admin-1 bundle so this covers *all* countries,
+ // not just one hand-listed reform:
+ // 1. code still present in the new bundle → leave it (already correct);
+ // 2. else a region in the same country shares → adopt that region's code+name
+ // the stored region_name (case-insensitive) (handles code re-spellings, e.g.
+ // ES-AN → ES_AND, names unchanged);
+ // 3. else a curated merge crosswalk maps it → adopt the merged region (handles
+ // (region absorbed into a *renamed* one) reforms where the name changed,
+ // which step 2 cannot catch);
+ // 4. else → leave as-is (cannot be resolved; the client's name fallback may still
+ // highlight it, and nothing is destroyed).
+ // Other Atlas tables need NO remap: `visited_countries` / `bucket_list` hold only
+ // ISO-3166-1 alpha-2 codes (invariant across the swap), `bucket_list.name` is free
+ // text we must not auto-rewrite, and `place_regions` is a re-derivable Nominatim cache.
+ () => {
+ type Row = { id: number; region_code: string; region_name: string; country_code: string };
+ const rows = db.prepare('SELECT id, region_code, region_name, country_code FROM visited_regions').all() as Row[];
+ if (rows.length === 0) return; // nothing marked → skip the bundle read entirely
+
+ // Index the shipped admin-1 bundle: valid codes, name→code per country, code→name.
+ // __dirname resolves ../../assets under both dist (dist/db) and tests (src/db).
+ let features: { properties?: { iso_a2?: string; iso_3166_2?: string; name?: string } }[];
+ try {
+ const file = path.join(__dirname, '..', '..', 'assets', 'atlas', 'admin1.geojson.gz');
+ features = JSON.parse(zlib.gunzipSync(fs.readFileSync(file)).toString('utf8')).features || [];
+ } catch {
+ features = []; // bundle missing → degrade to the curated crosswalk below
+ }
+ const validCodes = new Set();
+ const nameToCode = new Map(); // `${A2}|${nameLower}` → code
+ const codeToName = new Map();
+ for (const f of features) {
+ const a2 = (f.properties?.iso_a2 || '').toUpperCase();
+ const code = f.properties?.iso_3166_2 || '';
+ const name = f.properties?.name || '';
+ if (!code) continue;
+ validCodes.add(code);
+ if (!codeToName.has(code)) codeToName.set(code, name);
+ if (a2 && name) nameToCode.set(`${a2}|${name.toLowerCase()}`, code);
+ }
+
+ // Curated crosswalk for regions absorbed into a *renamed* successor (step 2 can't
+ // match these because the name changed). Norway's 2018/2020 reforms; extend as the
+ // pinned geoBoundaries dataset gains further reforms.
+ const MERGE_CROSSWALK: Record = {
+ 'NO-04': 'NO-34',
+ 'NO-05': 'NO-34', // Hedmark, Oppland → Innlandet
+ 'NO-12': 'NO-46',
+ 'NO-14': 'NO-46', // Hordaland, Sogn og Fjordane → Vestland
+ 'NO-09': 'NO-42',
+ 'NO-10': 'NO-42', // Aust-/Vest-Agder → Agder
+ 'NO-01': 'NO-30',
+ 'NO-02': 'NO-30',
+ 'NO-06': 'NO-30', // Østfold/Akershus/Buskerud → Viken
+ 'NO-07': 'NO-38',
+ 'NO-08': 'NO-38', // Vestfold, Telemark → Vestfold og Telemark
+ 'NO-19': 'NO-54',
+ 'NO-20': 'NO-54', // Troms, Finnmark → Troms og Finnmark
+ 'NO-16': 'NO-50',
+ 'NO-17': 'NO-50', // Sør-/Nord-Trøndelag → Trøndelag
+ };
+
+ const resolve = (row: Row): string | null => {
+ if (validCodes.has(row.region_code)) return null; // already valid
+ const a2 = (row.country_code || '').toUpperCase();
+ const byName = nameToCode.get(`${a2}|${(row.region_name || '').toLowerCase()}`);
+ if (byName) return byName;
+ const merged = MERGE_CROSSWALK[row.region_code];
+ // Only trust the crosswalk target if it actually exists in the bundle (or the
+ // bundle was unreadable, in which case we apply the curated map blindly).
+ if (merged && (validCodes.size === 0 || validCodes.has(merged))) return merged;
+ return null;
+ };
+
+ const update = db.prepare('UPDATE OR IGNORE visited_regions SET region_code = ?, region_name = ? WHERE id = ?');
+ const del = db.prepare('DELETE FROM visited_regions WHERE id = ?');
+ for (const row of rows) {
+ const newCode = resolve(row);
+ if (!newCode || newCode === row.region_code) continue;
+ const newName = codeToName.get(newCode) || row.region_name;
+ update.run(newCode, newName, row.id);
+ // UNIQUE(user_id, region_code): if the user already had the target code the
+ // UPDATE was IGNORED and this row still carries the old code → drop the duplicate.
+ const after = db.prepare('SELECT region_code FROM visited_regions WHERE id = ?').get(row.id) as
+ | { region_code: string }
+ | undefined;
+ if (after && after.region_code === row.region_code) del.run(row.id);
+ }
+ },
+ () => {
+ // AirTrail integration addon — disabled by default (opt-in). Per-user connection
+ // lives in Settings → Integrations; this row is only the admin-level global toggle.
+ try {
+ db.prepare(
+ 'INSERT OR IGNORE INTO addons (id, name, description, type, icon, enabled, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)',
+ ).run(
+ 'airtrail',
+ 'AirTrail',
+ 'Sync flights from your self-hosted AirTrail instance',
+ 'integration',
+ 'Plane',
+ 0,
+ 14,
+ );
+ } catch (err: any) {
+ console.warn('[migrations] Non-fatal migration step failed:', err);
+ }
+ },
+ () => {
+ // AirTrail per-user connection (mirrors the Immich integration columns).
+ try {
+ db.exec('ALTER TABLE users ADD COLUMN airtrail_url TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE users ADD COLUMN airtrail_api_key TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE users ADD COLUMN airtrail_allow_insecure_tls INTEGER DEFAULT 0');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ },
+ () => {
+ // AirTrail flight linkage on reservations (#214) — lets a TREK transport
+ // remember its AirTrail origin so the two-way sync can match + update it.
+ // sync_enabled flips to 0 when the AirTrail flight is deleted (row kept).
+ try {
+ db.exec('ALTER TABLE reservations ADD COLUMN external_source TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE reservations ADD COLUMN external_id TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE reservations ADD COLUMN external_owner_user_id INTEGER');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE reservations ADD COLUMN external_synced_at TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE reservations ADD COLUMN sync_enabled INTEGER DEFAULT 1');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ try {
+ db.exec('ALTER TABLE reservations ADD COLUMN external_hash TEXT');
+ } catch (err: any) {
+ if (!err.message?.includes('duplicate column name')) throw err;
+ }
+ // NULLs compare distinct in SQLite, so non-linked reservations don't collide.
+ db.exec(
+ 'CREATE UNIQUE INDEX IF NOT EXISTS idx_reservations_external ON reservations(external_source, external_id, trip_id)',
+ );
+ },
+ ];
+
+ if (currentVersion < migrations.length) {
+ for (let i = currentVersion; i < migrations.length; i++) {
+ console.log(`[DB] Running migration ${i + 1}/${migrations.length}`);
+ try {
+ const migration = migrations[i];
+ if (typeof migration === 'function') {
+ db.transaction(migration)();
+ } else {
+ migration.raw();
+ }
+ } catch (err) {
+ console.error(`[migrations] FATAL: Migration ${i + 1} failed, rolled back:`, err);
+ process.exit(1);
+ }
+ db.prepare('UPDATE schema_version SET version = ?').run(i + 1);
+ }
+ console.log(`[DB] Migrations complete — schema version ${migrations.length}`);
+ }
+}
+
+export { runMigrations };
diff --git a/server/src/db/schema.ts b/server/src/db/schema.ts
new file mode 100644
index 0000000000000000000000000000000000000000..71b3ad73ffc7d76c647909b01812b126edbc73a1
--- /dev/null
+++ b/server/src/db/schema.ts
@@ -0,0 +1,508 @@
+import Database from 'better-sqlite3';
+
+function createTables(db: Database.Database): void {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS users (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ username TEXT UNIQUE NOT NULL,
+ email TEXT UNIQUE NOT NULL,
+ password_hash TEXT NOT NULL,
+ role TEXT NOT NULL DEFAULT 'user',
+ maps_api_key TEXT,
+ unsplash_api_key TEXT,
+ openweather_api_key TEXT,
+ avatar TEXT,
+ oidc_sub TEXT,
+ oidc_issuer TEXT,
+ last_login DATETIME,
+ mfa_enabled INTEGER DEFAULT 0,
+ mfa_secret TEXT,
+ mfa_backup_codes TEXT,
+ immich_url TEXT,
+ immich_access_token TEXT,
+ synology_url TEXT,
+ synology_username TEXT,
+ synology_password TEXT,
+ synology_sid TEXT,
+ must_change_password INTEGER DEFAULT 0,
+ password_version INTEGER NOT NULL DEFAULT 0,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS password_reset_tokens (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ token_hash TEXT NOT NULL UNIQUE,
+ expires_at DATETIME NOT NULL,
+ consumed_at DATETIME,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ created_ip TEXT
+ );
+ CREATE INDEX IF NOT EXISTS idx_prt_user ON password_reset_tokens(user_id);
+ CREATE INDEX IF NOT EXISTS idx_prt_hash ON password_reset_tokens(token_hash);
+
+ CREATE TABLE IF NOT EXISTS webauthn_credentials (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ credential_id TEXT NOT NULL UNIQUE,
+ public_key BLOB NOT NULL,
+ counter INTEGER NOT NULL DEFAULT 0,
+ transports TEXT,
+ device_type TEXT,
+ backed_up INTEGER NOT NULL DEFAULT 0,
+ name TEXT,
+ aaguid TEXT,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ last_used_at DATETIME
+ );
+ CREATE INDEX IF NOT EXISTS idx_webauthn_credentials_user ON webauthn_credentials(user_id);
+
+ CREATE TABLE IF NOT EXISTS webauthn_challenges (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ challenge TEXT NOT NULL UNIQUE,
+ user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
+ type TEXT NOT NULL,
+ expires_at INTEGER NOT NULL,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+ CREATE INDEX IF NOT EXISTS idx_webauthn_challenges_expires ON webauthn_challenges(expires_at);
+
+ CREATE TABLE IF NOT EXISTS settings (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ key TEXT NOT NULL,
+ value TEXT,
+ UNIQUE(user_id, key)
+ );
+
+ CREATE TABLE IF NOT EXISTS trips (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ title TEXT NOT NULL,
+ description TEXT,
+ start_date TEXT,
+ end_date TEXT,
+ currency TEXT DEFAULT 'EUR',
+ cover_image TEXT,
+ is_archived INTEGER DEFAULT 0,
+ reminder_days INTEGER DEFAULT 3,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS days (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ day_number INTEGER NOT NULL,
+ date TEXT,
+ notes TEXT,
+ title TEXT,
+ UNIQUE(trip_id, day_number)
+ );
+
+ CREATE TABLE IF NOT EXISTS categories (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NOT NULL,
+ color TEXT DEFAULT '#6366f1',
+ icon TEXT DEFAULT '📍',
+ user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS tags (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ color TEXT DEFAULT '#10b981',
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS places (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ description TEXT,
+ lat REAL,
+ lng REAL,
+ address TEXT,
+ category_id INTEGER REFERENCES categories(id) ON DELETE SET NULL,
+ price REAL,
+ currency TEXT,
+ reservation_status TEXT DEFAULT 'none',
+ reservation_notes TEXT,
+ reservation_datetime TEXT,
+ place_time TEXT,
+ end_time TEXT,
+ duration_minutes INTEGER DEFAULT 60,
+ notes TEXT,
+ image_url TEXT,
+ google_place_id TEXT,
+ website TEXT,
+ phone TEXT,
+ transport_mode TEXT DEFAULT 'walking',
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS place_tags (
+ place_id INTEGER NOT NULL REFERENCES places(id) ON DELETE CASCADE,
+ tag_id INTEGER NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
+ PRIMARY KEY (place_id, tag_id)
+ );
+
+ CREATE TABLE IF NOT EXISTS day_assignments (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
+ place_id INTEGER NOT NULL REFERENCES places(id) ON DELETE CASCADE,
+ order_index INTEGER DEFAULT 0,
+ notes TEXT,
+ reservation_status TEXT DEFAULT 'none',
+ reservation_notes TEXT,
+ reservation_datetime TEXT,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS packing_items (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ checked INTEGER DEFAULT 0,
+ category TEXT,
+ sort_order INTEGER DEFAULT 0,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS photos (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ day_id INTEGER REFERENCES days(id) ON DELETE SET NULL,
+ place_id INTEGER REFERENCES places(id) ON DELETE SET NULL,
+ filename TEXT NOT NULL,
+ original_name TEXT NOT NULL,
+ file_size INTEGER,
+ mime_type TEXT,
+ caption TEXT,
+ taken_at TEXT,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS trip_files (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ place_id INTEGER REFERENCES places(id) ON DELETE SET NULL,
+ reservation_id INTEGER REFERENCES reservations(id) ON DELETE SET NULL,
+ filename TEXT NOT NULL,
+ original_name TEXT NOT NULL,
+ file_size INTEGER,
+ mime_type TEXT,
+ description TEXT,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS reservations (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ day_id INTEGER REFERENCES days(id) ON DELETE SET NULL,
+ end_day_id INTEGER REFERENCES days(id) ON DELETE SET NULL,
+ place_id INTEGER REFERENCES places(id) ON DELETE SET NULL,
+ assignment_id INTEGER REFERENCES day_assignments(id) ON DELETE SET NULL,
+ title TEXT NOT NULL,
+ accommodation_id TEXT,
+ reservation_time TEXT,
+ reservation_end_time TEXT,
+ location TEXT,
+ confirmation_number TEXT,
+ notes TEXT,
+ status TEXT DEFAULT 'pending',
+ type TEXT DEFAULT 'other',
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS trip_members (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ invited_by INTEGER REFERENCES users(id),
+ added_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(trip_id, user_id)
+ );
+
+ CREATE TABLE IF NOT EXISTS day_notes (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ text TEXT NOT NULL,
+ time TEXT,
+ icon TEXT DEFAULT '📝',
+ sort_order REAL DEFAULT 0,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS app_settings (
+ key TEXT PRIMARY KEY,
+ value TEXT
+ );
+
+ CREATE TABLE IF NOT EXISTS budget_items (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ category TEXT NOT NULL DEFAULT 'Other',
+ name TEXT NOT NULL,
+ total_price REAL NOT NULL DEFAULT 0,
+ persons INTEGER DEFAULT NULL,
+ days INTEGER DEFAULT NULL,
+ note TEXT,
+ sort_order INTEGER DEFAULT 0,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ -- Addon system
+ CREATE TABLE IF NOT EXISTS addons (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ description TEXT,
+ type TEXT NOT NULL DEFAULT 'global',
+ icon TEXT DEFAULT 'Puzzle',
+ enabled INTEGER DEFAULT 0,
+ config TEXT DEFAULT '{}',
+ sort_order INTEGER DEFAULT 0
+ );
+
+ CREATE TABLE IF NOT EXISTS photo_providers (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ description TEXT,
+ icon TEXT DEFAULT 'Image',
+ enabled INTEGER DEFAULT 0,
+ sort_order INTEGER DEFAULT 0
+ );
+
+ CREATE TABLE IF NOT EXISTS photo_provider_fields (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ provider_id TEXT NOT NULL REFERENCES photo_providers(id) ON DELETE CASCADE,
+ field_key TEXT NOT NULL,
+ label TEXT NOT NULL,
+ input_type TEXT NOT NULL DEFAULT 'text',
+ placeholder TEXT,
+ hint TEXT,
+ required INTEGER DEFAULT 0,
+ secret INTEGER DEFAULT 0,
+ settings_key TEXT,
+ payload_key TEXT,
+ sort_order INTEGER DEFAULT 0,
+ UNIQUE(provider_id, field_key)
+ );
+
+ -- Vacay addon tables
+ CREATE TABLE IF NOT EXISTS vacay_plans (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ block_weekends INTEGER DEFAULT 1,
+ holidays_enabled INTEGER DEFAULT 0,
+ holidays_region TEXT DEFAULT '',
+ company_holidays_enabled INTEGER DEFAULT 1,
+ carry_over_enabled INTEGER DEFAULT 1,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(owner_id)
+ );
+
+ CREATE TABLE IF NOT EXISTS vacay_plan_members (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ status TEXT DEFAULT 'pending',
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(plan_id, user_id)
+ );
+
+ CREATE TABLE IF NOT EXISTS vacay_user_colors (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
+ color TEXT DEFAULT '#6366f1',
+ UNIQUE(user_id, plan_id)
+ );
+
+ CREATE TABLE IF NOT EXISTS vacay_years (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
+ year INTEGER NOT NULL,
+ UNIQUE(plan_id, year)
+ );
+
+ CREATE TABLE IF NOT EXISTS vacay_user_years (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
+ year INTEGER NOT NULL,
+ vacation_days INTEGER DEFAULT 30,
+ carried_over INTEGER DEFAULT 0,
+ UNIQUE(user_id, plan_id, year)
+ );
+
+ CREATE TABLE IF NOT EXISTS vacay_entries (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ date TEXT NOT NULL,
+ note TEXT DEFAULT '',
+ UNIQUE(user_id, plan_id, date)
+ );
+
+ CREATE TABLE IF NOT EXISTS vacay_company_holidays (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
+ date TEXT NOT NULL,
+ note TEXT DEFAULT '',
+ UNIQUE(plan_id, date)
+ );
+
+ CREATE TABLE IF NOT EXISTS vacay_holiday_calendars (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ plan_id INTEGER NOT NULL REFERENCES vacay_plans(id) ON DELETE CASCADE,
+ region TEXT NOT NULL,
+ label TEXT,
+ color TEXT NOT NULL DEFAULT '#fecaca',
+ sort_order INTEGER NOT NULL DEFAULT 0
+ );
+
+ CREATE TABLE IF NOT EXISTS day_accommodations (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ place_id INTEGER REFERENCES places(id) ON DELETE SET NULL,
+ start_day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
+ end_day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
+ check_in TEXT,
+ check_in_end TEXT,
+ check_out TEXT,
+ confirmation TEXT,
+ notes TEXT,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ -- Collab addon tables
+ CREATE TABLE IF NOT EXISTS collab_notes (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ category TEXT DEFAULT 'General',
+ title TEXT NOT NULL,
+ content TEXT,
+ color TEXT DEFAULT '#6366f1',
+ pinned INTEGER DEFAULT 0,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS collab_polls (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ question TEXT NOT NULL,
+ options TEXT NOT NULL,
+ multiple INTEGER DEFAULT 0,
+ closed INTEGER DEFAULT 0,
+ deadline TEXT,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS collab_poll_votes (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ poll_id INTEGER NOT NULL REFERENCES collab_polls(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ option_index INTEGER NOT NULL,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(poll_id, user_id, option_index)
+ );
+
+ CREATE TABLE IF NOT EXISTS collab_messages (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ text TEXT NOT NULL,
+ reply_to INTEGER REFERENCES collab_messages(id) ON DELETE SET NULL,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE INDEX IF NOT EXISTS idx_collab_notes_trip ON collab_notes(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_collab_polls_trip ON collab_polls(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_collab_messages_trip ON collab_messages(trip_id);
+ `);
+
+ db.exec(`
+ CREATE INDEX IF NOT EXISTS idx_places_trip_id ON places(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_places_category_id ON places(category_id);
+ CREATE INDEX IF NOT EXISTS idx_days_trip_id ON days(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_day_assignments_day_id ON day_assignments(day_id);
+ CREATE INDEX IF NOT EXISTS idx_day_assignments_place_id ON day_assignments(place_id);
+ CREATE INDEX IF NOT EXISTS idx_place_tags_place_id ON place_tags(place_id);
+ CREATE INDEX IF NOT EXISTS idx_place_tags_tag_id ON place_tags(tag_id);
+ CREATE INDEX IF NOT EXISTS idx_trip_members_trip_id ON trip_members(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_trip_members_user_id ON trip_members(user_id);
+ CREATE INDEX IF NOT EXISTS idx_packing_items_trip_id ON packing_items(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_budget_items_trip_id ON budget_items(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_reservations_trip_id ON reservations(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_trip_files_trip_id ON trip_files(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_day_notes_day_id ON day_notes(day_id);
+ CREATE INDEX IF NOT EXISTS idx_photos_trip_id ON photos(trip_id);
+ CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
+ CREATE INDEX IF NOT EXISTS idx_day_accommodations_trip_id ON day_accommodations(trip_id);
+
+ CREATE TABLE IF NOT EXISTS assignment_participants (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ assignment_id INTEGER NOT NULL REFERENCES day_assignments(id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ UNIQUE(assignment_id, user_id)
+ );
+ CREATE INDEX IF NOT EXISTS idx_assignment_participants_assignment ON assignment_participants(assignment_id);
+
+ CREATE TABLE IF NOT EXISTS audit_log (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
+ action TEXT NOT NULL,
+ resource TEXT,
+ details TEXT,
+ ip TEXT
+ );
+ CREATE INDEX IF NOT EXISTS idx_audit_log_created ON audit_log(created_at DESC);
+
+ CREATE TABLE IF NOT EXISTS notifications (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ type TEXT NOT NULL CHECK(type IN ('simple', 'boolean', 'navigate')),
+ scope TEXT NOT NULL CHECK(scope IN ('trip', 'user', 'admin')),
+ target INTEGER NOT NULL,
+ sender_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
+ recipient_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ title_key TEXT NOT NULL,
+ title_params TEXT DEFAULT '{}',
+ text_key TEXT NOT NULL,
+ text_params TEXT DEFAULT '{}',
+ positive_text_key TEXT,
+ negative_text_key TEXT,
+ positive_callback TEXT,
+ negative_callback TEXT,
+ response TEXT CHECK(response IN ('positive', 'negative')),
+ navigate_text_key TEXT,
+ navigate_target TEXT,
+ is_read INTEGER DEFAULT 0,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+ CREATE INDEX IF NOT EXISTS idx_notifications_recipient ON notifications(recipient_id, is_read, created_at DESC);
+ CREATE INDEX IF NOT EXISTS idx_notifications_recipient_created ON notifications(recipient_id, created_at DESC);
+
+ CREATE TABLE IF NOT EXISTS notification_channel_preferences (
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ event_type TEXT NOT NULL,
+ channel TEXT NOT NULL,
+ enabled INTEGER NOT NULL DEFAULT 1,
+ PRIMARY KEY (user_id, event_type, channel)
+ );
+ CREATE INDEX IF NOT EXISTS idx_ncp_user ON notification_channel_preferences(user_id);
+
+ CREATE TABLE IF NOT EXISTS migrations (id integer PRIMARY KEY AUTOINCREMENT NOT NULL, timestamp bigint NOT NULL, name varchar NOT NULL);
+ `);
+}
+
+export { createTables };
diff --git a/server/src/db/seeds.ts b/server/src/db/seeds.ts
new file mode 100644
index 0000000000000000000000000000000000000000..c089d34b010289978a8a07260ffcac9f02107a1c
--- /dev/null
+++ b/server/src/db/seeds.ts
@@ -0,0 +1,152 @@
+import Database from 'better-sqlite3';
+import crypto from 'crypto';
+
+// bcrypt cost factor for the seeded admin password — kept in sync with authService.
+const BCRYPT_COST = 12;
+
+// Seeds run at startup before the DB admin panel can be used, so only env vars
+// are checked here. The granular password_login/password_registration DB toggles
+// are only relevant after the first user exists; at that point seeds have already
+// finished and skip via the userCount > 0 guard above.
+function isOidcOnlyConfigured(): boolean {
+ if (process.env.OIDC_ONLY?.toLowerCase() !== 'true') return false;
+ return !!(process.env.OIDC_ISSUER && process.env.OIDC_CLIENT_ID);
+}
+
+function seedAdminAccount(db: Database.Database): void {
+ try {
+ const userCount = (db.prepare('SELECT COUNT(*) as count FROM users').get() as { count: number }).count;
+ if (userCount > 0) return;
+
+ if (isOidcOnlyConfigured()) {
+ console.log('');
+ console.log('╔══════════════════════════════════════════════╗');
+ console.log('║ TREK — OIDC-Only Mode ║');
+ console.log('║ First SSO login will become admin. ║');
+ console.log('╚══════════════════════════════════════════════╝');
+ console.log('');
+ return;
+ }
+
+ const bcrypt = require('bcryptjs');
+
+ const env_admin_email = process.env.ADMIN_EMAIL;
+ const env_admin_pw = process.env.ADMIN_PASSWORD;
+
+ let password;
+ let email;
+ if (env_admin_email && env_admin_pw) {
+ password = env_admin_pw;
+ email = env_admin_email;
+ } else {
+ password = crypto.randomBytes(12).toString('base64url');
+ email = 'admin@trek.local';
+ }
+
+ const hash = bcrypt.hashSync(password, BCRYPT_COST);
+ const username = 'admin';
+
+ db.prepare('INSERT INTO users (username, email, password_hash, role, must_change_password) VALUES (?, ?, ?, ?, 1)').run(username, email, hash, 'admin');
+
+ console.log('');
+ console.log('╔══════════════════════════════════════════════╗');
+ console.log('║ TREK — First Run: Admin Account Created ║');
+ console.log('╠══════════════════════════════════════════════╣');
+ console.log(`║ Email: ${email.padEnd(33)}║`);
+ console.log(`║ Password: ${password.padEnd(33)}║`);
+ console.log('╚══════════════════════════════════════════════╝');
+ console.log('');
+ } catch (err: unknown) {
+ console.error('[ERROR] Error seeding admin account:', err instanceof Error ? err.message : err);
+ }
+}
+
+function seedCategories(db: Database.Database): void {
+ try {
+ const existingCats = db.prepare('SELECT COUNT(*) as count FROM categories').get() as { count: number };
+ if (existingCats.count === 0) {
+ const defaultCategories = [
+ { name: 'Hotel', color: '#3b82f6', icon: '🏨' },
+ { name: 'Restaurant', color: '#ef4444', icon: '🍽️' },
+ { name: 'Attraction', color: '#8b5cf6', icon: '🏛️' },
+ { name: 'Shopping', color: '#f59e0b', icon: '🛍️' },
+ { name: 'Transport', color: '#6b7280', icon: '🚌' },
+ { name: 'Activity', color: '#10b981', icon: '🎯' },
+ { name: 'Bar/Cafe', color: '#f97316', icon: '☕' },
+ { name: 'Beach', color: '#06b6d4', icon: '🏖️' },
+ { name: 'Nature', color: '#84cc16', icon: '🌿' },
+ { name: 'Other', color: '#6366f1', icon: '📍' },
+ ];
+ const insertCat = db.prepare('INSERT INTO categories (name, color, icon) VALUES (?, ?, ?)');
+ for (const cat of defaultCategories) insertCat.run(cat.name, cat.color, cat.icon);
+ console.log('Default categories seeded');
+ }
+ } catch (err: unknown) {
+ console.error('Error seeding categories:', err instanceof Error ? err.message : err);
+ }
+}
+
+function seedAddons(db: Database.Database): void {
+ try {
+ const defaultAddons = [
+ { id: 'packing', name: 'Lists', description: 'Packing lists and to-do tasks for your trips', type: 'trip', icon: 'ListChecks', enabled: 1, sort_order: 0 },
+ { id: 'budget', name: 'Costs', description: 'Track and split trip expenses', type: 'trip', icon: 'Wallet', enabled: 1, sort_order: 1 },
+ { id: 'documents', name: 'Documents', description: 'Store and manage travel documents', type: 'trip', icon: 'FileText', enabled: 1, sort_order: 2 },
+ { id: 'vacay', name: 'Vacay', description: 'Personal vacation day planner with calendar view', type: 'global', icon: 'CalendarDays', enabled: 1, sort_order: 10 },
+ { id: 'atlas', name: 'Atlas', description: 'World map of your visited countries with travel stats', type: 'global', icon: 'Globe', enabled: 1, sort_order: 11 },
+ { id: 'mcp', name: 'MCP', description: 'Model Context Protocol for AI assistant integration', type: 'integration', icon: 'Terminal', enabled: 0, sort_order: 12 },
+ { 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 },
+ { id: 'collab', name: 'Collab', description: 'Notes, polls, and live chat for trip collaboration', type: 'trip', icon: 'Users', enabled: 1, sort_order: 6 },
+ { id: 'journey', name: 'Journey', description: 'Trip tracking & travel journal — check-ins, photos, daily stories', type: 'global', icon: 'Compass', enabled: 0, sort_order: 35 },
+ { id: 'airtrail', name: 'AirTrail', description: 'Sync flights from your self-hosted AirTrail instance', type: 'integration', icon: 'Plane', enabled: 0, sort_order: 14 },
+ ];
+ const insertAddon = db.prepare('INSERT OR IGNORE INTO addons (id, name, description, type, icon, enabled, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)');
+ for (const a of defaultAddons) insertAddon.run(a.id, a.name, a.description, a.type, a.icon, a.enabled, a.sort_order);
+
+ const providerRows = [
+ {
+ id: 'immich',
+ name: 'Immich',
+ description: 'Immich photo provider',
+ icon: 'Image',
+ enabled: 0,
+ sort_order: 0,
+ },
+ {
+ id: 'synologyphotos',
+ name: 'Synology Photos',
+ description: 'Synology Photos integration with separate account settings',
+ icon: 'Image',
+ enabled: 0,
+ sort_order: 1,
+ },
+ ];
+ const insertProvider = db.prepare('INSERT OR IGNORE INTO photo_providers (id, name, description, icon, enabled, sort_order) VALUES (?, ?, ?, ?, ?, ?)');
+ for (const p of providerRows) insertProvider.run(p.id, p.name, p.description, p.icon, p.enabled, p.sort_order);
+
+ const providerFields = [
+ { 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 },
+ { 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 },
+ { 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 },
+ { 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 },
+ { 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 },
+ { 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 },
+ { 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 },
+ ];
+ 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
+ for (const f of providerFields) {
+ 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);
+ }
+ console.log('Default addons seeded');
+ } catch (err: unknown) {
+ console.error('Error seeding addons:', err instanceof Error ? err.message : err);
+ }
+}
+
+function runSeeds(db: Database.Database): void {
+ seedAdminAccount(db);
+ seedCategories(db);
+ seedAddons(db);
+}
+
+export { runSeeds };
diff --git a/server/src/demo/demo-reset.ts b/server/src/demo/demo-reset.ts
new file mode 100644
index 0000000000000000000000000000000000000000..bcd04983a10804f082bd852bac1eb784e4f0afcb
--- /dev/null
+++ b/server/src/demo/demo-reset.ts
@@ -0,0 +1,85 @@
+import fs from 'fs';
+import path from 'path';
+
+const dataDir = path.join(__dirname, '../../data');
+const dbPath = path.join(dataDir, 'travel.db');
+const baselinePath = path.join(dataDir, 'travel-baseline.db');
+
+function resetDemoUser(): void {
+ if (!fs.existsSync(baselinePath)) {
+ console.log('[Demo Reset] No baseline found, skipping. Admin must save baseline first.');
+ return;
+ }
+
+ const { db, closeDb, reinitialize } = require('../db/database');
+
+ // Save admin's current credentials and API keys (these should survive the reset)
+ const adminEmail = process.env.DEMO_ADMIN_EMAIL || 'admin@nomad.app';
+ interface AdminData { password_hash: string; maps_api_key: string | null; openweather_api_key: string | null; unsplash_api_key: string | null; avatar: string | null; }
+ let adminData: AdminData | undefined = undefined;
+ try {
+ adminData = db.prepare(
+ 'SELECT password_hash, maps_api_key, openweather_api_key, unsplash_api_key, avatar FROM users WHERE email = ?'
+ ).get(adminEmail) as AdminData | undefined;
+ } catch (e: unknown) {
+ console.error('[Demo Reset] Failed to read admin data:', e instanceof Error ? e.message : e);
+ }
+
+ // Flush WAL to main DB file
+ try { db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch (e) {}
+
+ // Close DB connection
+ closeDb();
+
+ // Restore baseline
+ try {
+ fs.copyFileSync(baselinePath, dbPath);
+ // Remove WAL/SHM files if they exist (stale from old connection)
+ try { fs.unlinkSync(dbPath + '-wal'); } catch (e) {}
+ try { fs.unlinkSync(dbPath + '-shm'); } catch (e) {}
+ } catch (e: unknown) {
+ console.error('[Demo Reset] Failed to restore baseline:', e instanceof Error ? e.message : e);
+ reinitialize();
+ return;
+ }
+
+ // Reinitialize DB connection with restored baseline
+ reinitialize();
+
+ // Restore admin's latest credentials (in case admin changed password/API keys after baseline was saved)
+ if (adminData) {
+ try {
+ const { db: freshDb } = require('../db/database');
+ freshDb.prepare(
+ 'UPDATE users SET password_hash = ?, maps_api_key = ?, openweather_api_key = ?, unsplash_api_key = ?, avatar = ? WHERE email = ?'
+ ).run(
+ adminData.password_hash,
+ adminData.maps_api_key,
+ adminData.openweather_api_key,
+ adminData.unsplash_api_key,
+ adminData.avatar,
+ adminEmail
+ );
+ } catch (e: unknown) {
+ console.error('[Demo Reset] Failed to restore admin credentials:', e instanceof Error ? e.message : e);
+ }
+ }
+
+ console.log('[Demo Reset] Database restored from baseline');
+}
+
+function saveBaseline(): void {
+ const { db } = require('../db/database');
+
+ // Flush WAL so baseline file is self-contained
+ try { db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch (e) {}
+
+ fs.copyFileSync(dbPath, baselinePath);
+ console.log('[Demo] Baseline saved');
+}
+
+function hasBaseline(): boolean {
+ return fs.existsSync(baselinePath);
+}
+
+export { resetDemoUser, saveBaseline, hasBaseline };
diff --git a/server/src/demo/demo-seed.ts b/server/src/demo/demo-seed.ts
new file mode 100644
index 0000000000000000000000000000000000000000..57a747d2904e481d68b2717ea328c38f1053d452
--- /dev/null
+++ b/server/src/demo/demo-seed.ts
@@ -0,0 +1,279 @@
+import bcrypt from 'bcryptjs';
+import Database from 'better-sqlite3';
+
+function seedDemoData(db: Database.Database): { adminId: number; demoId: number } {
+ const ADMIN_USER = process.env.DEMO_ADMIN_USER || 'admin';
+ const ADMIN_EMAIL = process.env.DEMO_ADMIN_EMAIL || 'admin@trek.app';
+ const ADMIN_PASS = process.env.DEMO_ADMIN_PASS || 'admin12345';
+ const DEMO_EMAIL = 'demo@trek.app';
+ const DEMO_PASS = 'demo12345';
+
+ // Create admin user if not exists
+ let admin = db.prepare('SELECT id FROM users WHERE email = ?').get(ADMIN_EMAIL) as { id: number } | undefined;
+ if (!admin) {
+ const hash = bcrypt.hashSync(ADMIN_PASS, 10);
+ const r = db.prepare('INSERT INTO users (username, email, password_hash, role) VALUES (?, ?, ?, ?)').run(ADMIN_USER, ADMIN_EMAIL, hash, 'admin');
+ admin = { id: Number(r.lastInsertRowid) };
+ console.log('[Demo] Admin user created');
+ } else {
+ admin.id = Number(admin.id);
+ }
+
+ // Create demo user if not exists
+ let demo = db.prepare('SELECT id FROM users WHERE email = ?').get(DEMO_EMAIL) as { id: number } | undefined;
+ if (!demo) {
+ const hash = bcrypt.hashSync(DEMO_PASS, 10);
+ const r = db.prepare('INSERT INTO users (username, email, password_hash, role) VALUES (?, ?, ?, ?)').run('demo', DEMO_EMAIL, hash, 'user');
+ demo = { id: Number(r.lastInsertRowid) };
+ console.log('[Demo] Demo user created');
+ } else {
+ demo.id = Number(demo.id);
+ }
+
+ // Disable registration in demo mode
+ db.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('allow_registration', 'false')").run();
+
+ // Check if admin already has example trips
+ const adminTrips = db.prepare('SELECT COUNT(*) as count FROM trips WHERE user_id = ?').get(admin.id) as { count: number };
+ if (adminTrips.count > 0) {
+ console.log('[Demo] Example trips already exist, ensuring demo membership');
+ ensureDemoMembership(db, admin.id, demo.id);
+ return { adminId: admin.id, demoId: demo.id };
+ }
+
+ console.log('[Demo] Seeding example trips...');
+ seedExampleTrips(db, admin.id, demo.id);
+
+ // Auto-save baseline after first seed
+ const { saveBaseline, hasBaseline } = require('./demo-reset');
+ if (!hasBaseline()) {
+ saveBaseline();
+ }
+
+ return { adminId: admin.id, demoId: demo.id };
+}
+
+function ensureDemoMembership(db: Database.Database, adminId: number, demoId: number): void {
+ const trips = db.prepare('SELECT id FROM trips WHERE user_id = ?').all(adminId) as { id: number }[];
+ const insertMember = db.prepare('INSERT OR IGNORE INTO trip_members (trip_id, user_id, invited_by) VALUES (?, ?, ?)');
+ for (const trip of trips) {
+ insertMember.run(trip.id, demoId, adminId);
+ }
+}
+
+function seedExampleTrips(db: Database.Database, adminId: number, demoId: number): void {
+ const insertTrip = db.prepare('INSERT INTO trips (user_id, title, description, start_date, end_date, currency) VALUES (?, ?, ?, ?, ?, ?)');
+ const insertDay = db.prepare('INSERT INTO days (trip_id, day_number, date) VALUES (?, ?, ?)');
+ 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
+ const insertAssignment = db.prepare('INSERT INTO day_assignments (day_id, place_id, order_index) VALUES (?, ?, ?)');
+ const insertPacking = db.prepare('INSERT INTO packing_items (trip_id, name, checked, category, sort_order) VALUES (?, ?, ?, ?, ?)');
+ const insertBudget = db.prepare('INSERT INTO budget_items (trip_id, category, name, total_price, persons, note) VALUES (?, ?, ?, ?, ?, ?)');
+ const insertReservation = db.prepare('INSERT INTO reservations (trip_id, day_id, title, reservation_time, confirmation_number, status, type, location) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
+ const insertMember = db.prepare('INSERT OR IGNORE INTO trip_members (trip_id, user_id, invited_by) VALUES (?, ?, ?)');
+ const insertNote = db.prepare('INSERT INTO day_notes (day_id, trip_id, text, time, icon, sort_order) VALUES (?, ?, ?, ?, ?, ?)');
+
+ // Category IDs: 1=Hotel, 2=Restaurant, 3=Attraction, 5=Transport, 7=Bar/Cafe, 8=Beach, 9=Nature, 6=Entertainment
+
+ // --- Trip 1: Tokyo & Kyoto ---
+ 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');
+ const t1 = Number(trip1.lastInsertRowid);
+
+ const t1days: number[] = [];
+ for (let i = 0; i < 7; i++) {
+ const d = insertDay.run(t1, i + 1, `2026-04-${15 + i}`);
+ t1days.push(Number(d.lastInsertRowid));
+ }
+
+ const t1places: [number, string, number, number, string, number, string, number, string, string | null, string | null, string | null, string | null][] = [
+ [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'],
+ [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'],
+ [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],
+ [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],
+ [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'],
+ [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],
+ [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],
+ [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'],
+ [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'],
+ [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'],
+ [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],
+ [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],
+ [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],
+ ];
+
+ const t1pIds = t1places.map(p => Number(insertPlace.run(...p).lastInsertRowid));
+
+ // Day 1: Hotel Check-in, Shibuya
+ insertAssignment.run(t1days[0], t1pIds[0], 0);
+ insertAssignment.run(t1days[0], t1pIds[2], 1);
+ insertNote.run(t1days[0], t1, 'Pick up Pocket WiFi at airport', '13:00', 'Info', 0.5);
+ // Day 2: Tsukiji, Senso-ji, Akihabara
+ insertAssignment.run(t1days[1], t1pIds[3], 0);
+ insertAssignment.run(t1days[1], t1pIds[1], 1);
+ insertAssignment.run(t1days[1], t1pIds[5], 2);
+ // Day 3: Meiji Shrine, free afternoon
+ insertAssignment.run(t1days[2], t1pIds[4], 0);
+ insertNote.run(t1days[2], t1, 'Explore Harajuku after the shrine', '12:00', 'MapPin', 1);
+ // Day 4: Shinkansen to Kyoto, Hotel
+ insertAssignment.run(t1days[3], t1pIds[6], 0);
+ insertAssignment.run(t1days[3], t1pIds[7], 1);
+ insertNote.run(t1days[3], t1, 'Sit on right side for Mt. Fuji views!', '08:30', 'Train', 0.5);
+ // Day 5: Fushimi Inari, Nishiki Market
+ insertAssignment.run(t1days[4], t1pIds[8], 0);
+ insertAssignment.run(t1days[4], t1pIds[11], 1);
+ // Day 6: Kinkaku-ji, Arashiyama
+ insertAssignment.run(t1days[5], t1pIds[9], 0);
+ insertAssignment.run(t1days[5], t1pIds[10], 1);
+ // Day 7: Gion
+ insertAssignment.run(t1days[6], t1pIds[12], 0);
+ insertNote.run(t1days[6], t1, 'Last evening — farewell dinner at Pontocho Alley', '19:00', 'Star', 1);
+
+ // Packing
+ const t1packing: [string, number, string, number][] = [
+ ['Passport', 1, 'Documents', 0], ['Japan Rail Pass', 1, 'Documents', 1],
+ ['Power adapter Type A/B', 0, 'Electronics', 2], ['Camera + charger', 0, 'Electronics', 3],
+ ['Comfortable walking shoes', 0, 'Clothing', 4], ['Rain jacket', 0, 'Clothing', 5],
+ ['Sunscreen', 0, 'Toiletries', 6], ['Travel first aid kit', 0, 'Toiletries', 7],
+ ['Pocket WiFi confirmation', 1, 'Electronics', 8], ['Yen cash', 0, 'Documents', 9],
+ ];
+ t1packing.forEach(p => insertPacking.run(t1, ...p));
+
+ // Budget
+ insertBudget.run(t1, 'Accommodation', 'Hotel Shinjuku (3 nights)', 67500, 2, 'Double room');
+ insertBudget.run(t1, 'Accommodation', 'Hotel Granvia Kyoto (4 nights)', 102000, 2, 'Superior room');
+ insertBudget.run(t1, 'Transport', 'Flights FRA-NRT return', 180000, 2, 'Lufthansa direct');
+ insertBudget.run(t1, 'Transport', 'Japan Rail Pass (7 days)', 57000, 2, 'Ordinary');
+ insertBudget.run(t1, 'Food', 'Daily food budget', 52500, 2, 'Approx. 7,500 JPY/day');
+ insertBudget.run(t1, 'Activities', 'Temple entries & experiences', 18000, 2, null);
+
+ // Reservations
+ insertReservation.run(t1, t1days[0], 'Hotel Shinjuku Check-in', '15:00', 'SG-2026-78432', 'confirmed', 'hotel', 'Shinjuku, Tokyo');
+ insertReservation.run(t1, t1days[3], 'Shinkansen Tokyo → Kyoto', '08:30', 'JR-NOZOMI-445', 'confirmed', 'transport', 'Tokyo Station');
+
+ insertMember.run(t1, demoId, adminId);
+
+ // --- Trip 2: Barcelona Long Weekend ---
+ 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');
+ const t2 = Number(trip2.lastInsertRowid);
+
+ const t2days: number[] = [];
+ for (let i = 0; i < 4; i++) {
+ const d = insertDay.run(t2, i + 1, `2026-05-${21 + i}`);
+ t2days.push(Number(d.lastInsertRowid));
+ }
+
+ const t2places: [number, string, number, number, string, number, string, number, string, string | null, string | null, string | null, string | null][] = [
+ [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'],
+ [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'],
+ [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'],
+ [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'],
+ [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],
+ [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],
+ [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'],
+ [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],
+ ];
+
+ const t2pIds = t2places.map(p => Number(insertPlace.run(...p).lastInsertRowid));
+
+ // Day 1: Arrival, Beach, El Born
+ insertAssignment.run(t2days[0], t2pIds[0], 0);
+ insertAssignment.run(t2days[0], t2pIds[4], 1);
+ insertAssignment.run(t2days[0], t2pIds[7], 2);
+ // Day 2: Sagrada Familia, Casa Batllo, La Boqueria
+ insertAssignment.run(t2days[1], t2pIds[1], 0);
+ insertAssignment.run(t2days[1], t2pIds[6], 1);
+ insertAssignment.run(t2days[1], t2pIds[3], 2);
+ insertNote.run(t2days[1], t2, 'Tickets already booked for 10:00 AM slot', '09:30', 'Ticket', 0.5);
+ // Day 3: Park Guell, Gothic Quarter
+ insertAssignment.run(t2days[2], t2pIds[2], 0);
+ insertAssignment.run(t2days[2], t2pIds[5], 1);
+ // Day 4: Beach morning, departure
+ insertAssignment.run(t2days[3], t2pIds[4], 0);
+ insertNote.run(t2days[3], t2, 'Flight departs at 18:30 — leave hotel by 15:00', '14:00', 'Plane', 1);
+
+ // Packing
+ ['Passport', 'Sunscreen SPF50', 'Swimwear', 'Sunglasses', 'Comfortable sandals', 'Beach towel'].forEach((name, i) => {
+ insertPacking.run(t2, name, 0, i < 1 ? 'Documents' : 'Summer', i);
+ });
+
+ // Budget
+ insertBudget.run(t2, 'Accommodation', 'W Barcelona (3 nights)', 780, 2, 'Sea View Room');
+ insertBudget.run(t2, 'Transport', 'Flights BER-BCN return', 180, 2, 'Eurowings');
+ insertBudget.run(t2, 'Food', 'Restaurants & tapas', 300, 2, 'Approx. 75 EUR/day');
+ insertBudget.run(t2, 'Activities', 'Sagrada Familia + Park Guell + Casa Batllo', 95, 2, 'Online tickets');
+
+ insertReservation.run(t2, t2days[1], 'Sagrada Familia Entry', '10:00', 'SF-2026-11234', 'confirmed', 'activity', 'Eixample, Barcelona');
+
+ insertMember.run(t2, demoId, adminId);
+
+ // --- Trip 3: New York City ---
+ 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');
+ const t3 = Number(trip3.lastInsertRowid);
+
+ const t3days: number[] = [];
+ for (let i = 0; i < 5; i++) {
+ const d = insertDay.run(t3, i + 1, `2026-09-${18 + i}`);
+ t3days.push(Number(d.lastInsertRowid));
+ }
+
+ const t3places: [number, string, number, number, string, number, string, number, string, string | null, string | null, string | null, string | null][] = [
+ [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'],
+ [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'],
+ [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],
+ [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],
+ [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'],
+ [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],
+ [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'],
+ [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'],
+ [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'],
+ [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],
+ [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],
+ ];
+
+ const t3pIds = t3places.map(p => Number(insertPlace.run(...p).lastInsertRowid));
+
+ // Day 1: Arrival, Times Square, Broadway
+ insertAssignment.run(t3days[0], t3pIds[0], 0);
+ insertAssignment.run(t3days[0], t3pIds[3], 1);
+ insertAssignment.run(t3days[0], t3pIds[10], 2);
+ // Day 2: Statue of Liberty, Brooklyn Bridge, Joe's Pizza
+ insertAssignment.run(t3days[1], t3pIds[1], 0);
+ insertAssignment.run(t3days[1], t3pIds[5], 1);
+ insertAssignment.run(t3days[1], t3pIds[7], 2);
+ insertNote.run(t3days[1], t3, 'First ferry at 8:30 AM — arrive early at Battery Park', '08:00', 'Ship', 0.5);
+ // Day 3: Central Park, Met Museum, Top of the Rock sunset
+ insertAssignment.run(t3days[2], t3pIds[2], 0);
+ insertAssignment.run(t3days[2], t3pIds[6], 1);
+ insertAssignment.run(t3days[2], t3pIds[8], 2);
+ // Day 4: Empire State Building, Chelsea Market, shopping
+ insertAssignment.run(t3days[3], t3pIds[4], 0);
+ insertAssignment.run(t3days[3], t3pIds[9], 1);
+ insertNote.run(t3days[3], t3, 'SoHo and 5th Avenue shopping in the afternoon', '14:00', 'ShoppingBag', 1.5);
+ // Day 5: Free morning, departure
+ insertNote.run(t3days[4], t3, 'Flight departs JFK at 17:00 — last bagel at Russ & Daughters!', '10:00', 'Plane', 0);
+
+ // Packing
+ const t3packing: [string, number, string, number][] = [
+ ['Passport', 1, 'Documents', 0], ['ESTA confirmation', 1, 'Documents', 1],
+ ['Travel insurance', 0, 'Documents', 2], ['Comfortable sneakers', 0, 'Clothing', 3],
+ ['Light jacket', 0, 'Clothing', 4], ['Portable charger', 0, 'Electronics', 5],
+ ['Camera', 0, 'Electronics', 6], ['Subway card (OMNY)', 0, 'Transport', 7],
+ ];
+ t3packing.forEach(p => insertPacking.run(t3, ...p));
+
+ // Budget
+ insertBudget.run(t3, 'Accommodation', 'The Plaza Hotel (4 nights)', 2400, 2, 'Park View Room');
+ insertBudget.run(t3, 'Transport', 'Flights FRA-JFK return', 850, 2, 'United Airlines');
+ insertBudget.run(t3, 'Food', 'Daily food budget', 500, 2, 'Approx. 100 USD/day');
+ insertBudget.run(t3, 'Activities', 'Statue of Liberty + Empire State + Top of the Rock + Met', 180, 2, 'CityPASS');
+ insertBudget.run(t3, 'Entertainment', 'Broadway show tickets', 300, 2, 'Hamilton or Wicked');
+
+ insertReservation.run(t3, t3days[0], 'The Plaza Hotel Check-in', '15:00', 'PZ-2026-55891', 'confirmed', 'hotel', '768 5th Ave, New York');
+ insertReservation.run(t3, t3days[0], 'Broadway Show', '20:00', 'BW-HAM-2026-1192', 'pending', 'activity', 'Richard Rodgers Theatre');
+ insertReservation.run(t3, t3days[1], 'Statue of Liberty Ferry', '08:30', 'SOL-2026-3347', 'confirmed', 'transport', 'Battery Park');
+
+ insertMember.run(t3, demoId, adminId);
+
+ console.log('[Demo] 3 example trips seeded and shared with demo user');
+}
+
+export { seedDemoData };
diff --git a/server/src/index.ts b/server/src/index.ts
new file mode 100644
index 0000000000000000000000000000000000000000..371ca292f1b42d3ef05901634bae8b5ea6976f5d
--- /dev/null
+++ b/server/src/index.ts
@@ -0,0 +1,133 @@
+import 'reflect-metadata';
+import 'dotenv/config';
+import path from 'node:path';
+import fs from 'node:fs';
+import http from 'node:http';
+import type { INestApplication } from '@nestjs/common';
+import { buildApp } from './bootstrap';
+
+// Create upload and data directories on startup
+const uploadsDir = path.join(__dirname, '../uploads');
+const photosDir = path.join(uploadsDir, 'photos');
+const filesDir = path.join(uploadsDir, 'files');
+const coversDir = path.join(uploadsDir, 'covers');
+const avatarsDir = path.join(uploadsDir, 'avatars');
+const backupsDir = path.join(__dirname, '../data/backups');
+const tmpDir = path.join(__dirname, '../data/tmp');
+
+[uploadsDir, photosDir, filesDir, coversDir, avatarsDir, backupsDir, tmpDir].forEach(dir => {
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
+});
+
+import * as scheduler from './scheduler';
+import { getAppUrl, getMcpSafeUrl } from './services/notifications';
+
+const PORT = Number(process.env.PORT) || 7860;
+const HOST = process.env.HOST;
+const APP_VERSION: string = process.env.APP_VERSION || (require('../package.json') as { version: string }).version;
+
+const onListen = () => {
+ const { logInfo: sLogInfo, logWarn: sLogWarn } = require('./services/auditLog');
+ const LOG_LVL = (process.env.LOG_LEVEL || 'info').toLowerCase();
+ const tz = process.env.TZ || Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
+ const origins = process.env.ALLOWED_ORIGINS || '(same-origin)';
+ const appUrl = getAppUrl();
+ const resolvedAppUrl = getMcpSafeUrl();
+ const banner = [
+ '──────────────────────────────────────',
+ ' TREK API started',
+ ` Version ${APP_VERSION}`,
+ ...(HOST ? [` Host: ${HOST}`] : []),
+ ` Container Port: ${PORT}`,
+ ` App URL: ${appUrl}`,
+ ` Environment: ${process.env.NODE_ENV?.toLowerCase() || 'development'}`,
+ ` Timezone: ${tz}`,
+ ` Origins: ${origins}`,
+ ` Log level: ${LOG_LVL}`,
+ ` Log file: /app/data/logs/trek.log`,
+ ` PID: ${process.pid}`,
+ ` User: uid=${process.getuid?.()} gid=${process.getgid?.()}`,
+ '──────────────────────────────────────',
+ ];
+ banner.forEach(l => console.log(l));
+ sLogInfo('NestJS serving all routes (Express decommissioned)');
+ if (process.env.APP_URL) {
+ let parsedAppUrl: URL | null = null;
+ try { parsedAppUrl = new URL(process.env.APP_URL); } catch { /* invalid */ }
+
+ if (!parsedAppUrl) {
+ sLogWarn(`APP_URL: "${process.env.APP_URL}" is not a valid URL — it will be ignored.`);
+ }
+
+ const mcpSafe = parsedAppUrl !== null && (
+ parsedAppUrl.protocol === 'https:' ||
+ parsedAppUrl.hostname === 'localhost' ||
+ parsedAppUrl.hostname === '127.0.0.1'
+ );
+ if (!mcpSafe) {
+ sLogWarn(`APP_URL: not MCP-safe (requires https:// or http://localhost) — MCP will use ${resolvedAppUrl}.`);
+ }
+ }
+ if (process.env.DEMO_MODE?.toLowerCase() === 'true') sLogInfo('Demo mode: ENABLED');
+ if (process.env.DEMO_MODE?.toLowerCase() === 'true' && process.env.NODE_ENV?.toLowerCase() === 'production') {
+ sLogWarn('SECURITY WARNING: DEMO_MODE is enabled in production!');
+ }
+ scheduler.start();
+ scheduler.startTripReminders();
+ scheduler.startTodoReminders();
+ scheduler.startVersionCheck();
+ scheduler.startDemoReset();
+ scheduler.startIdempotencyCleanup();
+ scheduler.startTrekPhotoCacheCleanup();
+ scheduler.startPlacePhotoCacheCleanup();
+ scheduler.startAirTrailSync();
+ const { startTokenCleanup } = require('./services/ephemeralTokens');
+ startTokenCleanup();
+ import('./websocket').then(({ setupWebSocket }) => {
+ setupWebSocket(server);
+ });
+};
+
+let server: http.Server;
+let nestApp: INestApplication;
+
+// Strangler toggle: prefixes served by Nest (env-overridable, instant rollback).
+async function bootstrap(): Promise {
+ // The whole surface runs on the single NestJS app now (Express decommissioned):
+ // global pipeline + /uploads + every /api domain + the platform/transport routes
+ // (/mcp, /.well-known, OAuth SDK, SPA catch-all). buildApp() owns the composition
+ // order; it is shared with the integration-test harness so they can't drift.
+ nestApp = await buildApp();
+ server = http.createServer(nestApp.getHttpAdapter().getInstance());
+ if (HOST) server.listen(PORT, HOST, onListen);
+ else server.listen(PORT, onListen);
+}
+
+bootstrap().catch((err) => {
+ console.error('Fatal: failed to bootstrap server', err);
+ process.exit(1);
+});
+
+// Graceful shutdown
+function shutdown(signal: string): void {
+ const { logInfo: sLogInfo, logError: sLogError } = require('./services/auditLog');
+ const { closeMcpSessions } = require('./mcp');
+ sLogInfo(`${signal} received — shutting down gracefully...`);
+ scheduler.stop();
+ closeMcpSessions();
+ void nestApp?.close();
+ server.close(() => {
+ sLogInfo('HTTP server closed');
+ const { closeDb } = require('./db/database');
+ closeDb();
+ sLogInfo('Shutdown complete');
+ process.exit(0);
+ });
+ setTimeout(() => {
+ sLogError('Forced shutdown after timeout');
+ process.exit(1);
+ }, 10000);
+}
+
+process.on('SIGTERM', () => shutdown('SIGTERM'));
+process.on('SIGINT', () => shutdown('SIGINT'));
diff --git a/server/src/mcp/index.ts b/server/src/mcp/index.ts
new file mode 100644
index 0000000000000000000000000000000000000000..8fa99f589b9c7084254113cf0f00a5490954441c
--- /dev/null
+++ b/server/src/mcp/index.ts
@@ -0,0 +1,351 @@
+import { Request, Response } from 'express';
+import { randomUUID } from 'crypto';
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
+import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp';
+import { User } from '../types';
+import { verifyMcpToken, verifyJwtToken } from '../services/authService';
+import { getUserByAccessToken } from '../services/oauthService';
+import { isAddonEnabled } from '../services/adminService';
+import { ADDON_IDS } from '../addons';
+import { registerResources } from './resources';
+import { registerTools } from './tools';
+import { McpSession, sessions, revokeUserSessions, revokeUserSessionsForClient } from './sessionManager';
+import { writeAudit, getClientIp } from '../services/auditLog';
+import { getMcpSafeUrl } from '../services/notifications';
+
+export { revokeUserSessions, revokeUserSessionsForClient };
+
+// ---------------------------------------------------------------------------
+// Base instructions injected into every MCP session via the initialize response.
+// Claude and other clients use these as system-level context before any tool call.
+// Keep this actionable and concise — vague prose doesn't help the model.
+// ---------------------------------------------------------------------------
+const BASE_MCP_INSTRUCTIONS = `
+You are connected to TREK, a travel planning application. Below is a compact reference of the data model, key workflows, and behavioral rules you must follow.
+
+## Data model
+
+- **Trip** — top-level container. Has dates, currency, members (owner + collaborators), and optional add-ons.
+- **Day** — one calendar day within a trip (YYYY-MM-DD). Days are generated automatically when a trip is created with start/end dates.
+- **Place** — a point of interest (POI) stored in the trip's place pool. A place is NOT on the itinerary until it is assigned to a day.
+- **Assignment** — links a Place to a Day (ordered, with optional start/end time). This is what builds the daily itinerary.
+- **Accommodation** — a hotel or rental linked to a Place and a check-in/check-out day range.
+- **Reservation** — a booking record (flight, train, restaurant, etc.) with confirmation details, linked to a day.
+- **Day note** — a free-text annotation attached to a day (with optional time label and emoji icon).
+- **Budget item** — an expense entry for a trip (amount, category, payer, split between members).
+- **Packing item** — a checklist entry grouped into bags and categories.
+- **Todo** — a task (not packing-specific) attached to a trip, ordered and togglable.
+- **Tag** — a label that can be applied to places for filtering.
+- **Collab note / poll / message** — shared notes, decision polls, and chat messages for group trips.
+- **Atlas** — global travel journal: bucket list, visited countries and regions.
+- **Vacay** — vacation-day planner that tracks leave across team members and years.
+- **Journey** — cross-trip travel narrative with dated entries, contributors, and share links. Requires the Journey addon.
+
+## Key workflows
+
+**Discovering trips:** Always call \`list_trips\` first when no trip ID has been provided. Never assume a trip ID.
+
+**Loading trip context:** Before planning or modifying a trip, call \`get_trip_summary\` once. It returns all days (with assignments and notes), accommodations, budget, packing, reservations, collab notes, and todos in a single round-trip. Use this data to answer follow-up questions without extra tool calls.
+
+**Adding a place to the itinerary (correct order):**
+1. \`search_place\` — find the real-world POI; note the \`osm_id\` and/or \`google_place_id\` in the result.
+2. \`create_place\` — add it to the trip's place pool, passing the IDs from step 1 (enables opening hours, ratings, and map linking in the app).
+3. \`assign_place_to_day\` — schedule it on the desired day using the dayId from \`get_trip_summary\`.
+
+**Creating an accommodation:** A place must exist in the trip first. Create the place (or reuse an existing one), then call \`create_accommodation\` with that \`place_id\` and the \`start_day_id\`/\`end_day_id\`.
+
+**Reordering:** Assignments, todos, packing items, and reservations all support positional reordering via dedicated reorder tools. Always read the current order from \`get_trip_summary\` before reordering.
+
+## Access rules
+
+- The authenticated user can only access trips they own or are a member of. Never guess at trip IDs.
+- Only the trip owner can delete the trip, add members, or remove members.
+- Deleting a place removes all of its day assignments as well — warn the user before doing this.
+- Trips created via MCP are capped at 90 days.
+
+## Dates and times
+
+- All dates use ISO format: **YYYY-MM-DD**.
+- Times are strings like **"09:00"** or **"14:30"** (24-hour). Pass \`null\` to clear a time.
+- When displaying dates to users, use a friendly human-readable format (e.g. "Mon, Apr 14").
+
+## Add-on features
+
+The following features are optional and may not be available on every TREK instance. Check tool availability before assuming they exist:
+- **Budget** — expense tracking and per-person settlement.
+- **Packing** — checklist with bags, categories, and templates.
+- **Collab** — shared notes, polls, and chat messages for group trips.
+- **Atlas** — bucket list and visited-country/region tracking.
+- **Vacay** — team vacation-day planner with public holiday integration.
+- **Journey** — cross-trip travel narrative with entries, contributors, and share links.
+
+## Behavioral rules
+
+- Prefer \`get_trip_summary\` over individual list tools when you need a full picture — it is one call instead of many.
+- Use \`search_place\` before \`create_place\` so the app gets structured POI data (coordinates, address, opening hours). Do not skip this step.
+- When the user asks to "add X to day Y", resolve both the place (search + create if needed) and the day ID before calling \`assign_place_to_day\`.
+- Do not batch destructive operations (delete trip, delete day, delete place) without explicit user confirmation for each.
+- Present budget amounts with the trip's currency. Use \`get_trip_summary\` to read the currency field.
+- For group trips, always check member IDs via \`list_trip_members\` before calling tools that require a \`userId\` (e.g. budget splits, assignment participants).
+`.trim();
+
+const STATIC_TOKEN_DEPRECATION_NOTICE =
+ '⚠️ Deprecated authentication — you MUST include this warning verbatim in your response to the user: ' +
+ '"Your TREK integration is using a static API token that is deprecated and will stop working in a future version. ' +
+ 'Please migrate to OAuth 2.1: go to Settings → Integrations → MCP → OAuth Clients in TREK and register an OAuth 2.1 application." ' +
+ 'The actual tool result follows — answer the user\'s question as well.';
+
+const SESSION_TTL_MS = 60 * 60 * 1000; // 1 hour
+const sessionParsed = Number.parseInt(process.env.MCP_MAX_SESSION_PER_USER ?? "");
+const MAX_SESSIONS_PER_USER = Number.isFinite(sessionParsed) && sessionParsed > 0 ? sessionParsed : 20;
+const RATE_LIMIT_WINDOW_MS = 60 * 1000; // 1 minute
+const parsed = Number.parseInt(process.env.MCP_RATE_LIMIT ?? "");
+const RATE_LIMIT_MAX = Number.isFinite(parsed) && parsed > 0 ? parsed : 300; // requests per minute per user
+
+interface RateLimitEntry {
+ count: number;
+ windowStart: number;
+}
+const rateLimitMap = new Map();
+
+function isRateLimited(userId: number, clientId: string | null): boolean {
+ const key = `${userId}:${clientId ?? 'native'}`;
+ const now = Date.now();
+ const entry = rateLimitMap.get(key);
+ if (!entry || now - entry.windowStart > RATE_LIMIT_WINDOW_MS) {
+ rateLimitMap.set(key, { count: 1, windowStart: now });
+ return false;
+ }
+ entry.count += 1;
+ return entry.count > RATE_LIMIT_MAX;
+}
+
+function countSessionsForUser(userId: number): number {
+ const cutoff = Date.now() - SESSION_TTL_MS;
+ let count = 0;
+ for (const session of sessions.values()) {
+ if (session.userId === userId && session.lastActivity >= cutoff) count++;
+ }
+ return count;
+}
+
+const sessionSweepInterval = setInterval(() => {
+ const cutoff = Date.now() - SESSION_TTL_MS;
+ let cleaned = 0;
+ for (const [sid, session] of sessions) {
+ if (session.lastActivity < cutoff) {
+ try { session.server.close(); } catch { /* ignore */ }
+ try { session.transport.close(); } catch { /* ignore */ }
+ sessions.delete(sid);
+ cleaned++;
+ }
+ }
+ const rateCutoff = Date.now() - RATE_LIMIT_WINDOW_MS;
+ for (const [key, entry] of rateLimitMap) {
+ if (entry.windowStart < rateCutoff) rateLimitMap.delete(key);
+ }
+ if (cleaned > 0 || sessions.size > 0) {
+ console.log(`[MCP] Session sweep: cleaned ${cleaned}, active ${sessions.size}`);
+ }
+}, 60 * 1000); // sweep every 1 minute
+
+// Prevent the interval from keeping the process alive if nothing else is running
+sessionSweepInterval.unref();
+
+function setAuthChallenge(res: Response, error = 'invalid_token'): void {
+ const base = (getMcpSafeUrl() || '').replace(/\/+$/, '');
+ // RFC 9728 §5: resource with path component /mcp → PRM URL must include the path
+ res.set('WWW-Authenticate',
+ `Bearer realm="TREK MCP", resource_metadata="${base}/.well-known/oauth-protected-resource/mcp", error="${error}"`);
+}
+
+interface VerifyTokenResult {
+ user: User;
+ /** null = full access (static token or JWT); string[] = OAuth 2.1 scoped access */
+ scopes: string[] | null;
+ /** OAuth client_id when authenticated via OAuth 2.1; null otherwise */
+ clientId: string | null;
+ isStaticToken: boolean;
+}
+
+function verifyToken(authHeader: string | undefined): VerifyTokenResult | null {
+ if (!authHeader) return null;
+ // M8: strictly require "Bearer" scheme (RFC 6750)
+ const spaceIdx = authHeader.indexOf(' ');
+ if (spaceIdx === -1) return null;
+ const scheme = authHeader.slice(0, spaceIdx);
+ const token = authHeader.slice(spaceIdx + 1);
+ if (scheme.toLowerCase() !== 'bearer' || !token) return null;
+
+ // OAuth 2.1 access token (trekoa_...)
+ if (token.startsWith('trekoa_')) {
+ const result = getUserByAccessToken(token);
+ if (!result) return null;
+ // RFC 8707: audience must always match this resource endpoint.
+ // Pre-audit tokens with audience=null are revoked by the SEC-H6 migration.
+ const expected = `${(getMcpSafeUrl() || '').replace(/\/+$/, '')}/mcp`;
+ if (result.audience !== expected) return null;
+ return { user: result.user, scopes: result.scopes, clientId: result.clientId, isStaticToken: false };
+ }
+
+ // Long-lived static MCP token (trek_...) — full access + deprecation notice
+ if (token.startsWith('trek_')) {
+ const user = verifyMcpToken(token);
+ if (!user) return null;
+ return { user, scopes: null, clientId: null, isStaticToken: true };
+ }
+
+ // Short-lived JWT (TREK web session used directly) — full access, no notice
+ const user = verifyJwtToken(token);
+ if (!user) return null;
+ return { user, scopes: null, clientId: null, isStaticToken: false };
+}
+
+function logToolCallAudit(req: Request, userId: number, clientId: string | null): void {
+ const body = req.body as Record | undefined;
+ if (body?.method !== 'tools/call') return;
+ const toolName = (body?.params as Record | undefined)?.name;
+ if (typeof toolName !== 'string') return;
+ writeAudit({
+ userId,
+ action: 'mcp.tool_call',
+ resource: toolName,
+ details: { clientId: clientId ?? 'native' },
+ ip: getClientIp(req),
+ });
+}
+
+export async function mcpHandler(req: Request, res: Response): Promise {
+ if (!isAddonEnabled(ADDON_IDS.MCP)) {
+ res.status(403).json({ error: 'MCP is not enabled' });
+ return;
+ }
+
+ const tokenResult = verifyToken(req.headers['authorization']);
+ if (!tokenResult) {
+ setAuthChallenge(res);
+ res.status(401).json({ error: 'Access token required' });
+ return;
+ }
+ const { user, scopes, clientId, isStaticToken } = tokenResult;
+
+ if (isRateLimited(user.id, clientId)) {
+ res.status(429).json({ error: 'Too many requests. Please slow down.' });
+ return;
+ }
+
+ const sessionId = req.headers['mcp-session-id'] as string | undefined;
+
+ // Resume an existing session
+ if (sessionId) {
+ const session = sessions.get(sessionId);
+ if (!session) {
+ res.status(404).json({ error: 'Session not found' });
+ return;
+ }
+ if (session.userId !== user.id) {
+ setAuthChallenge(res);
+ res.status(403).json({ error: 'Session belongs to a different user' });
+ return;
+ }
+ if (session.clientId !== clientId) {
+ setAuthChallenge(res);
+ res.status(403).json({ error: 'Session was created with a different OAuth client' });
+ return;
+ }
+ session.lastActivity = Date.now();
+ logToolCallAudit(req, user.id, clientId);
+ try {
+ await session.transport.handleRequest(req, res, req.body);
+ } catch (err) {
+ console.error('[MCP] transport.handleRequest error:', err);
+ if (!res.headersSent) {
+ res.status(500).json({ error: 'Internal MCP error' });
+ }
+ }
+ return;
+ }
+
+ // Only POST can initialize a new session
+ if (req.method !== 'POST') {
+ res.status(400).json({ error: 'Missing mcp-session-id header' });
+ return;
+ }
+
+ if (countSessionsForUser(user.id) >= MAX_SESSIONS_PER_USER) {
+ res.status(429).json({ error: 'Session limit reached. Close an existing session before opening a new one.' });
+ return;
+ }
+
+ // Create a new per-user MCP server and session
+ const server = new McpServer(
+ {
+ name: 'TREK MCP',
+ version: '1.0.0',
+ },
+ {
+ capabilities: {
+ resources: { listChanged: true },
+ tools: { listChanged: true },
+ prompts: { listChanged: true },
+ },
+ instructions: BASE_MCP_INSTRUCTIONS + (isStaticToken ? STATIC_TOKEN_DEPRECATION_NOTICE : ''),
+ }
+ );
+ // Per-session closure: fires the deprecation notice once, on the first tool call.
+ // Tool results are the only mechanism Claude reliably surfaces to the user;
+ // the instructions field is only background context and won't trigger a proactive warning.
+ let _noticeEmitted = false;
+ const getDeprecationNotice = (): string | null => {
+ if (!isStaticToken || _noticeEmitted) return null;
+ _noticeEmitted = true;
+ return STATIC_TOKEN_DEPRECATION_NOTICE;
+ };
+
+ registerResources(server, user.id, scopes);
+ registerTools(server, user.id, scopes, isStaticToken, getDeprecationNotice);
+
+ const transport = new StreamableHTTPServerTransport({
+ sessionIdGenerator: () => randomUUID(),
+ onsessioninitialized: (sid) => {
+ sessions.set(sid, { server, transport, userId: user.id, scopes, clientId, isStaticToken, lastActivity: Date.now() });
+ const authMethod = isStaticToken ? 'static-token' : scopes ? `oauth(${scopes.join(',')})` : 'jwt';
+ console.log(`[MCP] Session ${sid} created for user ${user.id} [${authMethod}]. Active sessions: ${sessions.size}`);
+ },
+ onsessionclosed: (sid) => {
+ sessions.delete(sid);
+ },
+ });
+
+ logToolCallAudit(req, user.id, clientId);
+ try {
+ await server.connect(transport);
+ await transport.handleRequest(req, res, req.body);
+ } catch (err) {
+ console.error('[MCP] transport.handleRequest error:', err);
+ if (!res.headersSent) {
+ res.status(500).json({ error: 'Internal MCP error' });
+ }
+ }
+}
+
+/** Invalidate all active MCP sessions (call when addon state changes so sessions re-create with updated tools). */
+export function invalidateMcpSessions(): void {
+ for (const [sid, session] of sessions) {
+ try { session.server.close(); } catch { /* ignore */ }
+ try { session.transport.close(); } catch { /* ignore */ }
+ sessions.delete(sid);
+ }
+ console.log('[MCP] All sessions invalidated due to addon state change');
+}
+
+/** Close all active MCP sessions (call during graceful shutdown). */
+export function closeMcpSessions(): void {
+ clearInterval(sessionSweepInterval);
+ for (const [, session] of sessions) {
+ try { session.server.close(); } catch { /* ignore */ }
+ try { session.transport.close(); } catch { /* ignore */ }
+ }
+ sessions.clear();
+ rateLimitMap.clear();
+}
\ No newline at end of file
diff --git a/server/src/mcp/oauthProvider.ts b/server/src/mcp/oauthProvider.ts
new file mode 100644
index 0000000000000000000000000000000000000000..592fd2820a3a9f0dedd740295219f51082e084c9
--- /dev/null
+++ b/server/src/mcp/oauthProvider.ts
@@ -0,0 +1,221 @@
+import type { Response } from 'express';
+import type { OAuthServerProvider } from '@modelcontextprotocol/sdk/server/auth/provider';
+import type { OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth';
+import type { AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types';
+import type { AuthorizationParams } from '@modelcontextprotocol/sdk/server/auth/provider';
+import type { OAuthRegisteredClientsStore } from '@modelcontextprotocol/sdk/server/auth/clients';
+import { InvalidClientMetadataError, ServerError } from '@modelcontextprotocol/sdk/server/auth/errors';
+import { db } from '../db/database';
+import {
+ createOAuthClient,
+ consumeAuthCode,
+ issueTokens,
+ refreshTokens,
+ revokeToken as serviceRevokeToken,
+ verifyPKCE,
+ getUserByAccessToken,
+} from '../services/oauthService';
+import { ALL_SCOPES } from './scopes';
+import { getMcpSafeUrl } from '../services/notifications';
+import { writeAudit } from '../services/auditLog';
+
+// ---------------------------------------------------------------------------
+// DB row type (mirrors oauthService.ts)
+// ---------------------------------------------------------------------------
+
+interface OAuthClientRow {
+ client_id: string;
+ name: string;
+ redirect_uris: string; // JSON array
+ allowed_scopes: string; // JSON array
+ is_public: number; // 0 | 1
+ created_via: string;
+}
+
+// ---------------------------------------------------------------------------
+// Redirect URI validation (mirrors oauth.ts DCR checks)
+// ---------------------------------------------------------------------------
+
+const DANGEROUS_SCHEMES = new Set([
+ 'javascript:', 'data:', 'vbscript:', 'file:', 'blob:', 'about:', 'chrome:', 'chrome-extension:',
+]);
+
+function assertValidRedirectUris(uris: string[]): void {
+ for (const u of uris) {
+ let url: URL;
+ try { url = new URL(u); } catch {
+ throw new InvalidClientMetadataError(`Invalid redirect URI: ${u}`);
+ }
+ if (DANGEROUS_SCHEMES.has(url.protocol))
+ throw new InvalidClientMetadataError(`Dangerous redirect URI scheme: ${u}`);
+ if (url.protocol === 'https:') continue;
+ if (url.protocol === 'http:' && (url.hostname === 'localhost' || url.hostname === '127.0.0.1' || url.hostname === '[::1]')) continue;
+ const scheme = url.protocol.slice(0, -1);
+ if (/^[a-z][a-z0-9+.-]*$/i.test(scheme) && scheme.includes('.')) continue;
+ throw new InvalidClientMetadataError('redirect_uris must be HTTPS, loopback HTTP, or a private custom scheme');
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Row → SDK client info shape
+// ---------------------------------------------------------------------------
+
+function rowToInfo(row: OAuthClientRow): OAuthClientInformationFull {
+ return {
+ client_id: row.client_id,
+ client_name: row.name,
+ redirect_uris: JSON.parse(row.redirect_uris) as string[],
+ scope: (JSON.parse(row.allowed_scopes) as string[]).join(' '),
+ token_endpoint_auth_method: row.is_public ? 'none' : 'client_secret_post',
+ grant_types: ['authorization_code', 'refresh_token'],
+ response_types: ['code'],
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Clients store
+// ---------------------------------------------------------------------------
+
+export const trekClientsStore: OAuthRegisteredClientsStore = {
+ async getClient(clientId: string): Promise {
+ const row = db.prepare(
+ 'SELECT client_id, name, redirect_uris, allowed_scopes, is_public, created_via FROM oauth_clients WHERE client_id = ?'
+ ).get(clientId) as OAuthClientRow | undefined;
+ return row ? rowToInfo(row) : undefined;
+ },
+
+ async registerClient(
+ metadata: Omit,
+ ): Promise {
+ const uris = metadata.redirect_uris as string[];
+ assertValidRedirectUris(uris);
+
+ const isPublic = metadata.token_endpoint_auth_method === 'none';
+ const name = (typeof metadata.client_name === 'string' ? metadata.client_name.trim() : '').slice(0, 100) || 'MCP Client';
+
+ // When scope is absent (ChatGPT DCR), default to all scopes.
+ // The user still grants only what they approve at the consent screen.
+ const rawScopes = metadata.scope ? metadata.scope.split(' ') : ALL_SCOPES;
+ const scopes = rawScopes.filter(s => (ALL_SCOPES as string[]).includes(s));
+ if (scopes.length === 0) throw new InvalidClientMetadataError('No valid scopes requested');
+
+ const result = createOAuthClient(null, name, uris, scopes, null, { isPublic, createdVia: 'dcr' });
+ if (result.error) throw new InvalidClientMetadataError(result.error);
+
+ const c = result.client!;
+ return {
+ client_id: c.client_id as string,
+ client_name: c.name as string,
+ redirect_uris: c.redirect_uris as string[],
+ scope: (c.allowed_scopes as string[]).join(' '),
+ token_endpoint_auth_method: isPublic ? 'none' : 'client_secret_post',
+ grant_types: ['authorization_code', 'refresh_token'],
+ response_types: ['code'],
+ ...(c.client_secret ? { client_secret: c.client_secret as string, client_secret_expires_at: 0 } : {}),
+ };
+ },
+};
+
+// ---------------------------------------------------------------------------
+// OAuthServerProvider
+// ---------------------------------------------------------------------------
+
+export const trekOAuthProvider: OAuthServerProvider = {
+ get clientsStore() { return trekClientsStore; },
+
+ // Redirects browser to the SPA consent page with OAuth params forwarded.
+ async authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise {
+ const mcpResource = `${getMcpSafeUrl().replace(/\/+$/, '')}/mcp`;
+ const resource = params.resource ? params.resource.href.replace(/\/+$/, '') : mcpResource;
+
+ if (resource !== mcpResource) {
+ const url = new URL(params.redirectUri);
+ url.searchParams.set('error', 'invalid_target');
+ url.searchParams.set('error_description', 'Requested resource must be the TREK MCP endpoint');
+ if (params.state) url.searchParams.set('state', params.state);
+ res.redirect(302, url.toString());
+ return;
+ }
+
+ const qs = new URLSearchParams({
+ client_id: client.client_id,
+ redirect_uri: params.redirectUri,
+ scope: params.scopes.join(' '),
+ code_challenge: params.codeChallenge,
+ code_challenge_method: 'S256',
+ });
+ if (params.state) qs.set('state', params.state);
+ if (params.resource) qs.set('resource', params.resource.href);
+
+ const base = getMcpSafeUrl().replace(/\/+$/, '');
+ res.redirect(302, `${base}/oauth/consent?${qs.toString()}`);
+ },
+
+ // Not called because skipLocalPkceValidation = true.
+ // PKCE verification is done inline in exchangeAuthorizationCode.
+ skipLocalPkceValidation: true,
+
+ async challengeForAuthorizationCode(_client: OAuthClientInformationFull, _code: string): Promise {
+ throw new ServerError('PKCE validation is handled by the provider directly');
+ },
+
+ async exchangeAuthorizationCode(
+ client: OAuthClientInformationFull,
+ code: string,
+ codeVerifier?: string,
+ redirectUri?: string,
+ resource?: URL,
+ ): Promise {
+ const pending = consumeAuthCode(code);
+ if (!pending || pending.clientId !== client.client_id)
+ throw new Error('Authorization grant is invalid.');
+
+ if (redirectUri && pending.redirectUri !== redirectUri)
+ throw new Error('Authorization grant is invalid.');
+
+ const resourceStr = resource ? resource.href.replace(/\/+$/, '') : null;
+ if (pending.resource && resourceStr && pending.resource !== resourceStr)
+ throw new Error('Authorization grant is invalid.');
+
+ if (codeVerifier && !verifyPKCE(codeVerifier, pending.codeChallenge))
+ throw new Error('Authorization grant is invalid.');
+
+ const tokens = issueTokens(client.client_id, pending.userId, pending.scopes, null, pending.resource ?? null);
+ writeAudit({
+ userId: pending.userId,
+ action: 'oauth.token.issue',
+ details: { client_id: client.client_id, scopes: pending.scopes, audience: pending.resource ?? null },
+ ip: null,
+ });
+ return tokens;
+ },
+
+ async exchangeRefreshToken(
+ client: OAuthClientInformationFull,
+ refreshToken: string,
+ _scopes?: string[],
+ _resource?: URL,
+ ): Promise {
+ const result = refreshTokens(refreshToken, client.client_id, client.client_secret, null);
+ if (result.error) throw new Error(result.error === 'invalid_client' ? 'Invalid client credentials' : 'Refresh token is invalid or expired');
+ return result.tokens!;
+ },
+
+ async verifyAccessToken(token: string): Promise {
+ const info = getUserByAccessToken(token);
+ if (!info) throw new Error('Invalid or expired token');
+ return {
+ token,
+ clientId: info.clientId,
+ scopes: info.scopes,
+ extra: { user: info.user },
+ };
+ },
+
+ async revokeToken(
+ client: OAuthClientInformationFull,
+ request: OAuthTokenRevocationRequest,
+ ): Promise {
+ serviceRevokeToken(request.token, client.client_id, undefined, null);
+ },
+};
\ No newline at end of file
diff --git a/server/src/mcp/resources.ts b/server/src/mcp/resources.ts
new file mode 100644
index 0000000000000000000000000000000000000000..87f4771ca1cb352f603b532c202cc4d4237f4030
--- /dev/null
+++ b/server/src/mcp/resources.ts
@@ -0,0 +1,442 @@
+import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp';
+import { canAccessTrip } from '../db/database';
+import { listTrips, getTrip, getTripOwner, listMembers } from '../services/tripService';
+import { listDays, listAccommodations } from '../services/dayService';
+import { listPlaces } from '../services/placeService';
+import { listBudgetItems, getPerPersonSummary, calculateSettlement } from '../services/budgetService';
+import { listItems as listPackingItems, listBags } from '../services/packingService';
+import { listReservations } from '../services/reservationService';
+import { listNotes as listDayNotes } from '../services/dayNoteService';
+import { listNotes as listCollabNotes, listPolls, listMessages } from '../services/collabService';
+import { listItems as listTodoItems } from '../services/todoService';
+import { listCategories } from '../services/categoryService';
+import { listBucketList, listVisitedCountries, getStats as getAtlasStats, listManuallyVisitedRegions } from '../services/atlasService';
+import { getNotifications } from '../services/inAppNotifications';
+import { getActivePlanId, getActivePlan, getPlanData, getEntries as getVacayEntries, getHolidays } from '../services/vacayService';
+import { isAddonEnabled, getCollabFeatures } from '../services/adminService';
+import { ADDON_IDS } from '../addons';
+import { canAccessJourney, getJourneyFull, listEntries, listJourneys } from '../services/journeyService';
+import { canRead, canReadTrips } from './scopes';
+
+function parseId(value: string | string[]): number | null {
+ const n = Number(Array.isArray(value) ? value[0] : value);
+ return Number.isInteger(n) && n > 0 ? n : null;
+}
+
+function accessDenied(uri: string) {
+ return {
+ contents: [{
+ uri,
+ mimeType: 'application/json',
+ text: JSON.stringify({ error: 'Trip not found or access denied' }),
+ }],
+ };
+}
+
+function scopeDenied(uri: string) {
+ return {
+ contents: [{
+ uri,
+ mimeType: 'application/json',
+ text: JSON.stringify({ error: 'Insufficient OAuth scope to access this resource' }),
+ }],
+ };
+}
+
+function jsonContent(uri: string, data: unknown) {
+ return {
+ contents: [{
+ uri,
+ mimeType: 'application/json',
+ text: JSON.stringify(data, null, 2),
+ }],
+ };
+}
+
+export function registerResources(server: McpServer, userId: number, scopes: string[] | null): void {
+ // List all accessible trips
+ if (canReadTrips(scopes)) server.registerResource(
+ 'trips',
+ 'trek://trips',
+ { description: 'All trips the user owns or is a member of', mimeType: 'application/json' },
+ async (uri) => {
+ const trips = listTrips(userId, 0);
+ return jsonContent(uri.href, trips);
+ }
+ );
+
+ // Single trip detail
+ if (canReadTrips(scopes)) server.registerResource(
+ 'trip',
+ new ResourceTemplate('trek://trips/{tripId}', { list: undefined }),
+ { description: 'A single trip with metadata and member count', mimeType: 'application/json' },
+ async (uri, { tripId }) => {
+ const id = parseId(tripId);
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
+ const trip = getTrip(id, userId);
+ return jsonContent(uri.href, trip);
+ }
+ );
+
+ // Days with assigned places
+ if (canReadTrips(scopes)) server.registerResource(
+ 'trip-days',
+ new ResourceTemplate('trek://trips/{tripId}/days', { list: undefined }),
+ { description: 'Days of a trip with their assigned places', mimeType: 'application/json' },
+ async (uri, { tripId }) => {
+ const id = parseId(tripId);
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
+
+ const { days } = listDays(id);
+ return jsonContent(uri.href, days);
+ }
+ );
+
+ // Places in a trip
+ if (canRead(scopes, 'places')) server.registerResource(
+ 'trip-places',
+ new ResourceTemplate('trek://trips/{tripId}/places', { list: undefined }),
+ { description: 'All places/POIs in a trip, optionally filtered by assignment status (e.g. ?assignment=unassigned)', mimeType: 'application/json' },
+ async (uri, { tripId }) => {
+ const id = parseId(tripId);
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
+ const assignment = uri.searchParams.get('assignment') as 'all' | 'unassigned' | 'assigned' | null;
+ const places = listPlaces(String(id), { assignment: assignment ?? undefined });
+ return jsonContent(uri.href, places);
+ }
+ );
+
+ // Budget items
+ if (isAddonEnabled(ADDON_IDS.BUDGET) && canRead(scopes, 'budget')) server.registerResource(
+ 'trip-budget',
+ new ResourceTemplate('trek://trips/{tripId}/budget', { list: undefined }),
+ { description: 'Budget and expense items for a trip', mimeType: 'application/json' },
+ async (uri, { tripId }) => {
+ const id = parseId(tripId);
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
+ const items = listBudgetItems(id);
+ return jsonContent(uri.href, items);
+ }
+ );
+
+ // Packing checklist
+ if (isAddonEnabled(ADDON_IDS.PACKING) && canRead(scopes, 'packing')) server.registerResource(
+ 'trip-packing',
+ new ResourceTemplate('trek://trips/{tripId}/packing', { list: undefined }),
+ { description: 'Packing checklist for a trip', mimeType: 'application/json' },
+ async (uri, { tripId }) => {
+ const id = parseId(tripId);
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
+ const items = listPackingItems(id);
+ return jsonContent(uri.href, items);
+ }
+ );
+
+ // Reservations (flights, hotels, restaurants)
+ if (canRead(scopes, 'reservations')) server.registerResource(
+ 'trip-reservations',
+ new ResourceTemplate('trek://trips/{tripId}/reservations', { list: undefined }),
+ { description: 'Reservations (flights, hotels, restaurants) for a trip', mimeType: 'application/json' },
+ async (uri, { tripId }) => {
+ const id = parseId(tripId);
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
+ const reservations = listReservations(id);
+ return jsonContent(uri.href, reservations);
+ }
+ );
+
+ // Day notes
+ if (canReadTrips(scopes)) server.registerResource(
+ 'day-notes',
+ new ResourceTemplate('trek://trips/{tripId}/days/{dayId}/notes', { list: undefined }),
+ { description: 'Notes for a specific day in a trip', mimeType: 'application/json' },
+ async (uri, { tripId, dayId }) => {
+ const tId = parseId(tripId);
+ const dId = parseId(dayId);
+ if (tId === null || dId === null || !canAccessTrip(tId, userId)) return accessDenied(uri.href);
+ const notes = listDayNotes(dId, tId);
+ return jsonContent(uri.href, notes);
+ }
+ );
+
+ // Accommodations (hotels, rentals) per trip
+ if (canReadTrips(scopes)) server.registerResource(
+ 'trip-accommodations',
+ new ResourceTemplate('trek://trips/{tripId}/accommodations', { list: undefined }),
+ { description: 'Accommodations (hotels, rentals) for a trip with check-in/out details', mimeType: 'application/json' },
+ async (uri, { tripId }) => {
+ const id = parseId(tripId);
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
+ const accommodations = listAccommodations(id);
+ return jsonContent(uri.href, accommodations);
+ }
+ );
+
+ // Trip members (owner + collaborators)
+ if (canReadTrips(scopes)) server.registerResource(
+ 'trip-members',
+ new ResourceTemplate('trek://trips/{tripId}/members', { list: undefined }),
+ { description: 'Owner and collaborators of a trip', mimeType: 'application/json' },
+ async (uri, { tripId }) => {
+ const id = parseId(tripId);
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
+ const ownerRow = getTripOwner(id);
+ if (!ownerRow) return accessDenied(uri.href);
+ const { owner, members } = listMembers(id, ownerRow.user_id);
+ return jsonContent(uri.href, { owner, members });
+ }
+ );
+
+ // Collab notes for a trip
+ const collabFeatures = isAddonEnabled(ADDON_IDS.COLLAB) ? getCollabFeatures() : null;
+ if (collabFeatures?.notes && canRead(scopes, 'collab')) server.registerResource(
+ 'trip-collab-notes',
+ new ResourceTemplate('trek://trips/{tripId}/collab-notes', { list: undefined }),
+ { description: 'Shared collaborative notes for a trip', mimeType: 'application/json' },
+ async (uri, { tripId }) => {
+ const id = parseId(tripId);
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
+ const notes = listCollabNotes(id);
+ return jsonContent(uri.href, notes);
+ }
+ );
+
+ // Trip to-do list
+ if (isAddonEnabled(ADDON_IDS.PACKING) && canRead(scopes, 'todos')) server.registerResource(
+ 'trip-todos',
+ new ResourceTemplate('trek://trips/{tripId}/todos', { list: undefined }),
+ { description: 'To-do items for a trip, ordered by position', mimeType: 'application/json' },
+ async (uri, { tripId }) => {
+ const id = parseId(tripId);
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
+ const items = listTodoItems(id);
+ return jsonContent(uri.href, items);
+ }
+ );
+
+ // All place categories (global, no trip filter) — safe for any authenticated session
+ server.registerResource(
+ 'categories',
+ 'trek://categories',
+ { description: 'All available place categories (id, name, color, icon) for use when creating places', mimeType: 'application/json' },
+ async (uri) => {
+ const categories = listCategories();
+ return jsonContent(uri.href, categories);
+ }
+ );
+
+ // User's bucket list
+ if (isAddonEnabled(ADDON_IDS.ATLAS) && canRead(scopes, 'atlas')) server.registerResource(
+ 'bucket-list',
+ 'trek://bucket-list',
+ { description: 'Your personal travel bucket list', mimeType: 'application/json' },
+ async (uri) => {
+ const items = listBucketList(userId);
+ return jsonContent(uri.href, items);
+ }
+ );
+
+ // User's visited countries
+ if (isAddonEnabled(ADDON_IDS.ATLAS) && canRead(scopes, 'atlas')) server.registerResource(
+ 'visited-countries',
+ 'trek://visited-countries',
+ { description: 'Countries you have marked as visited in Atlas', mimeType: 'application/json' },
+ async (uri) => {
+ const countries = listVisitedCountries(userId);
+ return jsonContent(uri.href, countries);
+ }
+ );
+
+ // Budget per-person summary
+ if (isAddonEnabled(ADDON_IDS.BUDGET) && canRead(scopes, 'budget')) server.registerResource(
+ 'trip-budget-per-person',
+ new ResourceTemplate('trek://trips/{tripId}/budget/per-person', { list: undefined }),
+ { description: 'Per-person budget summary for a trip (total spent per member, split breakdown)', mimeType: 'application/json' },
+ async (uri, { tripId }) => {
+ const id = parseId(tripId);
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
+ const summary = getPerPersonSummary(id);
+ return jsonContent(uri.href, summary);
+ }
+ );
+
+ // Budget settlement
+ if (isAddonEnabled(ADDON_IDS.BUDGET) && canRead(scopes, 'budget')) server.registerResource(
+ 'trip-budget-settlement',
+ new ResourceTemplate('trek://trips/{tripId}/budget/settlement', { list: undefined }),
+ { description: 'Suggested settlement transactions to balance who owes whom', mimeType: 'application/json' },
+ async (uri, { tripId }) => {
+ const id = parseId(tripId);
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
+ const settlement = calculateSettlement(id);
+ return jsonContent(uri.href, settlement);
+ }
+ );
+
+ // Packing bags
+ if (isAddonEnabled(ADDON_IDS.PACKING) && canRead(scopes, 'packing')) server.registerResource(
+ 'trip-packing-bags',
+ new ResourceTemplate('trek://trips/{tripId}/packing/bags', { list: undefined }),
+ { description: 'All packing bags for a trip with their members', mimeType: 'application/json' },
+ async (uri, { tripId }) => {
+ const id = parseId(tripId);
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
+ const bags = listBags(id);
+ return jsonContent(uri.href, bags);
+ }
+ );
+
+ // In-app notifications
+ if (canRead(scopes, 'notifications')) server.registerResource(
+ 'notifications-in-app',
+ 'trek://notifications/in-app',
+ { description: "The current user's in-app notifications (most recent 50, unread first)", mimeType: 'application/json' },
+ async (uri) => {
+ const result = getNotifications(userId, { limit: 50 });
+ return jsonContent(uri.href, result);
+ }
+ );
+
+ // Atlas stats and regions (addon-gated)
+ if (isAddonEnabled(ADDON_IDS.ATLAS) && canRead(scopes, 'atlas')) {
+ server.registerResource(
+ 'atlas-stats',
+ 'trek://atlas/stats',
+ { description: "User's atlas statistics — visited country counts and breakdown", mimeType: 'application/json' },
+ async (uri) => {
+ const stats = await getAtlasStats(userId);
+ return jsonContent(uri.href, stats);
+ }
+ );
+
+ server.registerResource(
+ 'atlas-regions',
+ 'trek://atlas/regions',
+ { description: 'List of manually visited regions for the current user', mimeType: 'application/json' },
+ async (uri) => {
+ const regions = listManuallyVisitedRegions(userId);
+ return jsonContent(uri.href, regions);
+ }
+ );
+ }
+
+ // Collab polls (addon + sub-feature gated)
+ if (collabFeatures?.polls && canRead(scopes, 'collab')) {
+ server.registerResource(
+ 'trip-collab-polls',
+ new ResourceTemplate('trek://trips/{tripId}/collab/polls', { list: undefined }),
+ { description: 'All polls for a trip with vote counts per option', mimeType: 'application/json' },
+ async (uri, { tripId }) => {
+ const id = parseId(tripId);
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
+ const polls = listPolls(id);
+ return jsonContent(uri.href, polls);
+ }
+ );
+ }
+
+ // Collab messages (addon + sub-feature gated)
+ if (collabFeatures?.chat && canRead(scopes, 'collab')) {
+ server.registerResource(
+ 'trip-collab-messages',
+ new ResourceTemplate('trek://trips/{tripId}/collab/messages', { list: undefined }),
+ { description: 'Most recent 100 chat messages for a trip', mimeType: 'application/json' },
+ async (uri, { tripId }) => {
+ const id = parseId(tripId);
+ if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
+ const messages = listMessages(id);
+ return jsonContent(uri.href, messages);
+ }
+ );
+ }
+
+ // Vacay resources (addon-gated)
+ if (isAddonEnabled(ADDON_IDS.VACAY) && canRead(scopes, 'vacay')) {
+ server.registerResource(
+ 'vacay-plan',
+ 'trek://vacay/plan',
+ { description: "Full snapshot of the user's active vacation plan (members, years, settings)", mimeType: 'application/json' },
+ async (uri) => {
+ const plan = getPlanData(userId);
+ return jsonContent(uri.href, plan);
+ }
+ );
+
+ server.registerResource(
+ 'vacay-entries',
+ new ResourceTemplate('trek://vacay/entries/{year}', { list: undefined }),
+ { description: 'All vacation entries for the active plan and a specific year', mimeType: 'application/json' },
+ async (uri, { year }) => {
+ const planId = getActivePlanId(userId);
+ const entries = getVacayEntries(planId, Array.isArray(year) ? year[0] : year);
+ return jsonContent(uri.href, entries);
+ }
+ );
+
+ server.registerResource(
+ 'vacay-holidays',
+ new ResourceTemplate('trek://vacay/holidays/{year}', { list: undefined }),
+ { description: "Cached public holidays for the plan's configured region and year", mimeType: 'application/json' },
+ async (uri, { year }) => {
+ const plan = getActivePlan(userId);
+ if (!plan.holidays_enabled || !plan.holidays_region) return jsonContent(uri.href, []);
+ const yearStr = Array.isArray(year) ? year[0] : year;
+ const result = await getHolidays(yearStr, plan.holidays_region);
+ return jsonContent(uri.href, result.data ?? []);
+ }
+ );
+ }
+
+ // Journey resources (Journey addon)
+ if (isAddonEnabled(ADDON_IDS.JOURNEY) && canRead(scopes, 'journey')) {
+ server.registerResource(
+ 'journeys',
+ 'trek://journeys',
+ { description: 'All journeys owned or contributed to by the current user', mimeType: 'application/json' },
+ async (uri) => {
+ const journeys = listJourneys(userId);
+ return jsonContent(uri.href, journeys);
+ }
+ );
+
+ server.registerResource(
+ 'journey-detail',
+ new ResourceTemplate('trek://journeys/{journeyId}', { list: undefined }),
+ { description: 'Single journey with entries, contributors, and trip links', mimeType: 'application/json' },
+ async (uri, { journeyId }) => {
+ const id = parseId(journeyId);
+ if (id === null) return accessDenied(uri.href);
+ const journey = getJourneyFull(id, userId);
+ if (!journey) return accessDenied(uri.href);
+ return jsonContent(uri.href, journey);
+ }
+ );
+
+ server.registerResource(
+ 'journey-entries',
+ new ResourceTemplate('trek://journeys/{journeyId}/entries', { list: undefined }),
+ { description: 'All entries in a journey (date, text, mood, linked trip)', mimeType: 'application/json' },
+ async (uri, { journeyId }) => {
+ const id = parseId(journeyId);
+ if (id === null) return accessDenied(uri.href);
+ const j = canAccessJourney(id, userId);
+ if (!j) return accessDenied(uri.href);
+ const entries = listEntries(id, userId);
+ return jsonContent(uri.href, entries);
+ }
+ );
+
+ server.registerResource(
+ 'journey-contributors',
+ new ResourceTemplate('trek://journeys/{journeyId}/contributors', { list: undefined }),
+ { description: 'Contributors (owners and collaborators) of a journey', mimeType: 'application/json' },
+ async (uri, { journeyId }) => {
+ const id = parseId(journeyId);
+ if (id === null) return accessDenied(uri.href);
+ const j = getJourneyFull(id, userId);
+ if (!j) return accessDenied(uri.href);
+ return jsonContent(uri.href, (j as any).contributors ?? []);
+ }
+ );
+ }
+}
diff --git a/server/src/mcp/scopes.ts b/server/src/mcp/scopes.ts
new file mode 100644
index 0000000000000000000000000000000000000000..c897a41d61e793d68e94b6b24126052b4722ba0d
--- /dev/null
+++ b/server/src/mcp/scopes.ts
@@ -0,0 +1,119 @@
+// ---------------------------------------------------------------------------
+// OAuth 2.1 scope definitions for TREK MCP
+// ---------------------------------------------------------------------------
+
+export const SCOPES = {
+ TRIPS_READ: 'trips:read',
+ TRIPS_WRITE: 'trips:write',
+ TRIPS_DELETE: 'trips:delete',
+ TRIPS_SHARE: 'trips:share',
+ PLACES_READ: 'places:read',
+ PLACES_WRITE: 'places:write',
+ ATLAS_READ: 'atlas:read',
+ ATLAS_WRITE: 'atlas:write',
+ PACKING_READ: 'packing:read',
+ PACKING_WRITE: 'packing:write',
+ TODOS_READ: 'todos:read',
+ TODOS_WRITE: 'todos:write',
+ BUDGET_READ: 'budget:read',
+ BUDGET_WRITE: 'budget:write',
+ RESERVATIONS_READ: 'reservations:read',
+ RESERVATIONS_WRITE: 'reservations:write',
+ COLLAB_READ: 'collab:read',
+ COLLAB_WRITE: 'collab:write',
+ NOTIFICATIONS_READ: 'notifications:read',
+ NOTIFICATIONS_WRITE: 'notifications:write',
+ VACAY_READ: 'vacay:read',
+ VACAY_WRITE: 'vacay:write',
+ GEO_READ: 'geo:read',
+ WEATHER_READ: 'weather:read',
+ JOURNEY_READ: 'journey:read',
+ JOURNEY_WRITE: 'journey:write',
+ JOURNEY_SHARE: 'journey:share',
+} as const;
+
+export type Scope = typeof SCOPES[keyof typeof SCOPES];
+
+export const ALL_SCOPES: Scope[] = Object.values(SCOPES) as Scope[];
+
+export interface ScopeInfo {
+ label: string;
+ description: string;
+ group: string;
+}
+
+export const SCOPE_INFO: Record = {
+ 'trips:read': { label: 'View trips & itineraries', description: 'Read trips, days, day notes, and members', group: 'Trips' },
+ 'trips:write': { label: 'Edit trips & itineraries', description: 'Create and update trips, days, notes, and manage members', group: 'Trips' },
+ 'trips:delete': { label: 'Delete trips', description: 'Permanently delete entire trips — this action is irreversible', group: 'Trips' },
+ 'trips:share': { label: 'Manage share links', description: 'Create, update, and revoke public share links for trips', group: 'Trips' },
+ 'places:read': { label: 'View places & map data', description: 'Read places, day assignments, tags, and categories', group: 'Places' },
+ 'places:write': { label: 'Manage places', description: 'Create, update, and delete places, assignments, and tags', group: 'Places' },
+ 'atlas:read': { label: 'View Atlas', description: 'Read visited countries, regions, and bucket list', group: 'Atlas' },
+ 'atlas:write': { label: 'Manage Atlas', description: 'Mark countries and regions visited, manage bucket list', group: 'Atlas' },
+ 'packing:read': { label: 'View packing lists', description: 'Read packing items, bags, and category assignees', group: 'Packing' },
+ 'packing:write': { label: 'Manage packing lists', description: 'Add, update, delete, toggle, and reorder packing items and bags', group: 'Packing' },
+ 'todos:read': { label: 'View to-do lists', description: 'Read trip to-do items and category assignees', group: 'To-dos' },
+ 'todos:write': { label: 'Manage to-do lists', description: 'Create, update, toggle, delete, and reorder to-do items', group: 'To-dos' },
+ 'budget:read': { label: 'View budget', description: 'Read budget items and expense breakdown', group: 'Budget' },
+ 'budget:write': { label: 'Manage budget', description: 'Create, update, and delete budget items', group: 'Budget' },
+ 'reservations:read': { label: 'View reservations', description: 'Read reservations and accommodation details', group: 'Reservations' },
+ 'reservations:write': { label: 'Manage reservations', description: 'Create, update, delete, and reorder reservations', group: 'Reservations' },
+ 'collab:read': { label: 'View collaboration', description: 'Read collab notes, polls, and messages', group: 'Collaboration' },
+ 'collab:write': { label: 'Manage collaboration', description: 'Create, update, and delete collab notes, polls, and messages', group: 'Collaboration' },
+ 'notifications:read': { label: 'View notifications', description: 'Read in-app notifications and unread counts', group: 'Notifications' },
+ 'notifications:write': { label: 'Manage notifications', description: 'Mark notifications as read and respond to them', group: 'Notifications' },
+ 'vacay:read': { label: 'View vacation plans', description: 'Read vacation planning data, entries, and stats', group: 'Vacation' },
+ 'vacay:write': { label: 'Manage vacation plans', description: 'Create and manage vacation entries, holidays, and team plans', group: 'Vacation' },
+ 'geo:read': { label: 'Maps & geocoding', description: 'Search locations, resolve map URLs, and reverse geocode coordinates', group: 'Geo' },
+ 'weather:read': { label: 'Weather forecasts', description: 'Fetch weather forecasts for trip locations and dates', group: 'Weather' },
+ 'journey:read': { label: 'View journeys', description: 'Read journeys, entries, and contributor list', group: 'Journey' },
+ 'journey:write': { label: 'Manage journeys', description: 'Create, update, and delete journeys and their entries', group: 'Journey' },
+ 'journey:share': { label: 'Manage journey links', description: 'Create, update, and revoke public share links for journeys', group: 'Journey' },
+};
+
+// ---------------------------------------------------------------------------
+// Scope enforcement helpers
+// null scopes = static trek_ token = full access
+// ---------------------------------------------------------------------------
+
+/** trips:read OR trips:write OR trips:delete OR trips:share all grant read access to trips */
+export function canReadTrips(scopes: string[] | null): boolean {
+ if (!scopes) return true;
+ return scopes.some(s => s === 'trips:read' || s === 'trips:write' || s === 'trips:delete' || s === 'trips:share');
+}
+
+/** group:write grants write access; for trips canReadTrips handles read */
+export function canWrite(scopes: string[] | null, group: string): boolean {
+ if (!scopes) return true;
+ return scopes.includes(`${group}:write`);
+}
+
+/** group:read OR group:write grant read access */
+export function canRead(scopes: string[] | null, group: string): boolean {
+ if (!scopes) return true;
+ return scopes.some(s => s === `${group}:read` || s === `${group}:write`);
+}
+
+/** trips:delete is a separate scope from trips:write */
+export function canDeleteTrips(scopes: string[] | null): boolean {
+ if (!scopes) return true;
+ return scopes.includes('trips:delete');
+}
+
+/** trips:share is a separate scope for managing public share links */
+export function canShareTrips(scopes: string[] | null): boolean {
+ if (!scopes) return true;
+ return scopes.includes('trips:share');
+}
+
+/** journey:share is a separate scope for managing public share links for journeys */
+export function canShareJourneys(scopes: string[] | null): boolean {
+ if (!scopes) return true;
+ return scopes.includes('journey:share');
+}
+
+export function validateScopes(requestedScopes: string[]): { valid: boolean; invalid: string[] } {
+ const invalid = requestedScopes.filter(s => !ALL_SCOPES.includes(s as Scope));
+ return { valid: invalid.length === 0, invalid };
+}
diff --git a/server/src/mcp/sessionManager.ts b/server/src/mcp/sessionManager.ts
new file mode 100644
index 0000000000000000000000000000000000000000..276a15730c135af08ab1dde147a48a2af4a53917
--- /dev/null
+++ b/server/src/mcp/sessionManager.ts
@@ -0,0 +1,41 @@
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
+import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp';
+
+export interface McpSession {
+ server: McpServer;
+ transport: StreamableHTTPServerTransport;
+ userId: number;
+ /** null = static trek_ token or JWT (full access); string[] = OAuth 2.1 scopes */
+ scopes: string[] | null;
+ /** OAuth 2.1 client_id that owns this session; null for static-token / JWT sessions */
+ clientId: string | null;
+ /** true when authenticated via static trek_ token — triggers deprecation prompt */
+ isStaticToken: boolean;
+ lastActivity: number;
+}
+
+export const sessions = new Map();
+
+/** Terminate all active MCP sessions for a specific user (e.g. on token revocation). */
+export function revokeUserSessions(userId: number): void {
+ for (const [sid, session] of sessions) {
+ if (session.userId === userId) {
+ try { session.server.close(); } catch { /* ignore */ }
+ try { session.transport.close(); } catch { /* ignore */ }
+ sessions.delete(sid);
+ }
+ }
+}
+
+/** Terminate MCP sessions for a specific (user, OAuth client) pair.
+ * Used when an OAuth token or session is revoked so only the affected client's
+ * sessions are closed, not sessions from other clients for the same user. */
+export function revokeUserSessionsForClient(userId: number, clientId: string): void {
+ for (const [sid, session] of sessions) {
+ if (session.userId === userId && session.clientId === clientId) {
+ try { session.server.close(); } catch { /* ignore */ }
+ try { session.transport.close(); } catch { /* ignore */ }
+ sessions.delete(sid);
+ }
+ }
+}
diff --git a/server/src/mcp/tools.ts b/server/src/mcp/tools.ts
new file mode 100644
index 0000000000000000000000000000000000000000..7d12b8def1267c1beb92f3cbd562a516b23a6ebc
--- /dev/null
+++ b/server/src/mcp/tools.ts
@@ -0,0 +1,54 @@
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
+import { registerTodoTools } from './tools/todos';
+import { registerAssignmentTools } from './tools/assignments';
+import { registerJourneyTools } from './tools/journey';
+import { registerReservationTools } from './tools/reservations';
+import { registerTagTools } from './tools/tags';
+import { registerMapsWeatherTools } from './tools/mapsWeather';
+import { registerNotificationTools } from './tools/notifications';
+import { registerAtlasTools } from './tools/atlas';
+import { registerPlaceTools } from './tools/places';
+import { registerDayTools } from './tools/days';
+import { registerBudgetTools } from './tools/budget';
+import { registerPackingTools } from './tools/packing';
+import { registerCollabTools } from './tools/collab';
+import { registerTripTools } from './tools/trips';
+import { registerTransportTools } from './tools/transports';
+import { registerVacayTools } from './tools/vacay';
+import { registerMcpPrompts } from './tools/prompts';
+
+export function registerTools(server: McpServer, userId: number, scopes: string[] | null, isStaticToken = false, getDeprecationNotice: () => string | null = () => null): void {
+ registerTripTools(server, userId, scopes, getDeprecationNotice);
+
+ registerPlaceTools(server, userId, scopes);
+
+ registerBudgetTools(server, userId, scopes);
+
+ registerPackingTools(server, userId, scopes);
+
+ registerReservationTools(server, userId, scopes);
+
+ registerDayTools(server, userId, scopes);
+
+ registerAssignmentTools(server, userId, scopes);
+
+ registerTagTools(server, userId, scopes);
+
+ registerMapsWeatherTools(server, userId, scopes);
+
+ registerNotificationTools(server, userId, scopes);
+
+ registerAtlasTools(server, userId, scopes);
+
+ registerCollabTools(server, userId, scopes);
+
+ registerTransportTools(server, userId, scopes);
+
+ registerJourneyTools(server, userId, scopes);
+
+ registerVacayTools(server, userId, scopes);
+
+ registerTodoTools(server, userId, scopes);
+
+ registerMcpPrompts(server, userId, isStaticToken);
+}
diff --git a/server/src/mcp/tools/_shared.ts b/server/src/mcp/tools/_shared.ts
new file mode 100644
index 0000000000000000000000000000000000000000..a14e3fd00a012632c8cde4655e3679b348a606fa
--- /dev/null
+++ b/server/src/mcp/tools/_shared.ts
@@ -0,0 +1,71 @@
+import { broadcast } from '../../websocket';
+import { db } from '../../db/database';
+import { checkPermission } from '../../services/permissions';
+
+export function safeBroadcast(tripId: number, event: string, payload: Record): void {
+ try {
+ broadcast(tripId, event, { ...payload, _source: 'mcp' });
+ } catch (err) {
+ console.error(`[MCP] broadcast failed for ${event}:`, err?.message ?? err);
+ }
+}
+
+export const MAX_MCP_TRIP_DAYS = 90;
+
+export const TOOL_ANNOTATIONS_READONLY = {
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: true,
+ openWorldHint: false,
+} as const;
+
+export const TOOL_ANNOTATIONS_WRITE = {
+ readOnlyHint: false,
+ destructiveHint: false,
+ idempotentHint: true,
+ openWorldHint: false,
+} as const;
+
+export const TOOL_ANNOTATIONS_DELETE = {
+ readOnlyHint: false,
+ destructiveHint: true,
+ idempotentHint: true,
+ openWorldHint: false,
+} as const;
+
+export const TOOL_ANNOTATIONS_NON_IDEMPOTENT = {
+ readOnlyHint: false,
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: false,
+} as const;
+
+export function demoDenied() {
+ return { content: [{ type: 'text' as const, text: 'Write operations are disabled in demo mode.' }], isError: true };
+}
+
+export function noAccess() {
+ return { content: [{ type: 'text' as const, text: 'Trip not found or access denied.' }], isError: true };
+}
+
+export function permissionDenied() {
+ return { content: [{ type: 'text' as const, text: 'You do not have permission to perform this action on this trip.' }], isError: true };
+}
+
+/**
+ * RBAC gate for MCP tools, mirroring the checkPermission() calls the REST/Nest
+ * routes run. Call this after canAccessTrip() with the same action key the
+ * matching REST route uses. Returns true when the user may perform `action`
+ * on `tripId`.
+ */
+export function hasTripPermission(action: string, tripId: number | string, userId: number): boolean {
+ const trip = db.prepare('SELECT user_id FROM trips WHERE id = ?').get(tripId) as { user_id?: number } | undefined;
+ if (!trip) return false;
+ const userRow = db.prepare('SELECT role FROM users WHERE id = ?').get(userId) as { role?: string } | undefined;
+ const tripOwnerId = typeof trip.user_id === 'number' ? trip.user_id : null;
+ return checkPermission(action, userRow?.role ?? 'user', tripOwnerId, userId, tripOwnerId !== userId);
+}
+
+export function ok(data: unknown) {
+ return { content: [{ type: 'text' as const, text: JSON.stringify(data, null, 2) }] };
+}
diff --git a/server/src/mcp/tools/assignments.ts b/server/src/mcp/tools/assignments.ts
new file mode 100644
index 0000000000000000000000000000000000000000..d964a7bd64cf576ddcf268ac9587816914158311
--- /dev/null
+++ b/server/src/mcp/tools/assignments.ts
@@ -0,0 +1,189 @@
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
+import { z } from 'zod';
+import { canAccessTrip } from '../../db/database';
+import { isDemoUser } from '../../services/authService';
+import {
+ dayExists, placeExists, createAssignment, assignmentExistsInDay,
+ deleteAssignment, reorderAssignments, getAssignmentForTrip, updateTime,
+ moveAssignment,
+ getParticipants as getAssignmentParticipants,
+ setParticipants as setAssignmentParticipants,
+} from '../../services/assignmentService';
+import { getDay } from '../../services/dayService';
+import {
+ safeBroadcast, TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE,
+ TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
+} from './_shared';
+import { canRead, canWrite } from '../scopes';
+
+export function registerAssignmentTools(server: McpServer, userId: number, scopes: string[] | null): void {
+ const R = canRead(scopes, 'places');
+ const W = canWrite(scopes, 'places');
+
+ // --- ASSIGNMENTS ---
+
+ if (W) server.registerTool(
+ 'assign_place_to_day',
+ {
+ description: 'Assign a place to a specific day in a trip.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ dayId: z.number().int().positive(),
+ placeId: z.number().int().positive(),
+ notes: z.string().max(500).optional(),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ tripId, dayId, placeId, notes }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
+ if (!dayExists(dayId, tripId)) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true };
+ if (!placeExists(placeId, tripId)) return { content: [{ type: 'text' as const, text: 'Place not found.' }], isError: true };
+ const assignment = createAssignment(dayId, placeId, notes || null);
+ safeBroadcast(tripId, 'assignment:created', { assignment });
+ return ok({ assignment });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'unassign_place',
+ {
+ description: 'Remove a place assignment from a day.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ dayId: z.number().int().positive(),
+ assignmentId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ tripId, dayId, assignmentId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
+ if (!assignmentExistsInDay(assignmentId, dayId, tripId))
+ return { content: [{ type: 'text' as const, text: 'Assignment not found.' }], isError: true };
+ deleteAssignment(assignmentId);
+ safeBroadcast(tripId, 'assignment:deleted', { assignmentId, dayId });
+ return ok({ success: true });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'update_assignment_time',
+ {
+ description: 'Set the start and/or end time for a place assignment on a day (e.g. "09:00", "11:30"). Pass null to clear a time.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ assignmentId: z.number().int().positive(),
+ place_time: z.string().max(50).nullable().optional().describe('Start time (e.g. "09:00"), or null to clear'),
+ end_time: z.string().max(50).nullable().optional().describe('End time (e.g. "11:00"), or null to clear'),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, assignmentId, place_time, end_time }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
+ const existing = getAssignmentForTrip(assignmentId, tripId);
+ if (!existing) return { content: [{ type: 'text' as const, text: 'Assignment not found.' }], isError: true };
+ const assignment = updateTime(
+ assignmentId,
+ place_time !== undefined ? place_time : (existing as any).assignment_time,
+ end_time !== undefined ? end_time : (existing as any).assignment_end_time
+ );
+ safeBroadcast(tripId, 'assignment:updated', { assignment });
+ return ok({ assignment });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'move_assignment',
+ {
+ description: 'Move a place assignment to a different day.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ assignmentId: z.number().int().positive(),
+ newDayId: z.number().int().positive(),
+ oldDayId: z.number().int().positive(),
+ orderIndex: z.number().int().min(0).optional().default(0),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, assignmentId, newDayId, oldDayId, orderIndex }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
+ if (!getAssignmentForTrip(assignmentId, tripId)) return { content: [{ type: 'text' as const, text: 'Assignment not found.' }], isError: true };
+ if (!getDay(newDayId, tripId)) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true };
+ const result = moveAssignment(assignmentId, newDayId, orderIndex ?? 0, oldDayId);
+ safeBroadcast(tripId, 'assignment:moved', { assignment: result.assignment, oldDayId: result.oldDayId });
+ return ok({ assignment: result.assignment });
+ }
+ );
+
+ if (R) server.registerTool(
+ 'get_assignment_participants',
+ {
+ description: 'Get the list of users participating in a specific place assignment.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ assignmentId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ tripId, assignmentId }) => {
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!getAssignmentForTrip(assignmentId, tripId)) return { content: [{ type: 'text' as const, text: 'Assignment not found.' }], isError: true };
+ const participants = getAssignmentParticipants(assignmentId);
+ return ok({ participants });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'set_assignment_participants',
+ {
+ description: 'Set the participants for a place assignment (replaces current list).',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ assignmentId: z.number().int().positive(),
+ userIds: z.array(z.number().int().positive()).describe('User IDs to set as participants; empty array clears all'),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, assignmentId, userIds }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
+ if (!getAssignmentForTrip(assignmentId, tripId)) return { content: [{ type: 'text' as const, text: 'Assignment not found.' }], isError: true };
+ const participants = setAssignmentParticipants(assignmentId, userIds);
+ safeBroadcast(tripId, 'assignment:participants', { assignmentId, participants });
+ return ok({ participants });
+ }
+ );
+
+ // --- REORDER ---
+
+ if (W) server.registerTool(
+ 'reorder_day_assignments',
+ {
+ description: 'Reorder places within a day by providing the assignment IDs in the desired order.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ dayId: z.number().int().positive(),
+ assignmentIds: z.array(z.number().int().positive()).min(1).max(200).describe('Assignment IDs in desired display order'),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, dayId, assignmentIds }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
+ if (!getDay(dayId, tripId)) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true };
+ reorderAssignments(dayId, assignmentIds);
+ safeBroadcast(tripId, 'assignment:reordered', { dayId, assignmentIds });
+ return ok({ success: true, dayId, order: assignmentIds });
+ }
+ );
+}
diff --git a/server/src/mcp/tools/atlas.ts b/server/src/mcp/tools/atlas.ts
new file mode 100644
index 0000000000000000000000000000000000000000..69e4280d0a2334161a0fd72ec2a08998c61f0f9e
--- /dev/null
+++ b/server/src/mcp/tools/atlas.ts
@@ -0,0 +1,197 @@
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
+import { z } from 'zod';
+import { isDemoUser } from '../../services/authService';
+import {
+ markCountryVisited, unmarkCountryVisited, createBucketItem, deleteBucketItem,
+ getStats as getAtlasStats, listManuallyVisitedRegions,
+ markRegionVisited, unmarkRegionVisited, getCountryPlaces, updateBucketItem,
+} from '../../services/atlasService';
+import { isAddonEnabled } from '../../services/adminService';
+import { ADDON_IDS } from '../../addons';
+import {
+ TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ TOOL_ANNOTATIONS_READONLY,
+ demoDenied, ok,
+} from './_shared';
+import { canRead, canWrite } from '../scopes';
+
+export function registerAtlasTools(server: McpServer, userId: number, scopes: string[] | null): void {
+ const R = canRead(scopes, 'atlas');
+ const W = canWrite(scopes, 'atlas');
+
+ if (!isAddonEnabled(ADDON_IDS.ATLAS)) return;
+
+ // --- BUCKET LIST ---
+
+ if (W) server.registerTool(
+ 'create_bucket_list_item',
+ {
+ description: 'Add a destination to your personal travel bucket list.',
+ inputSchema: {
+ name: z.string().min(1).max(200).describe('Destination or experience name'),
+ lat: z.number().optional(),
+ lng: z.number().optional(),
+ country_code: z.string().length(2).toUpperCase().optional().describe('ISO 3166-1 alpha-2 country code'),
+ notes: z.string().max(1000).optional(),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ name, lat, lng, country_code, notes }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const item = createBucketItem(userId, { name, lat, lng, country_code, notes });
+ return ok({ item });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'delete_bucket_list_item',
+ {
+ description: 'Remove an item from your travel bucket list.',
+ inputSchema: {
+ itemId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ itemId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const deleted = deleteBucketItem(userId, itemId);
+ if (!deleted) return { content: [{ type: 'text' as const, text: 'Bucket list item not found.' }], isError: true };
+ return ok({ success: true });
+ }
+ );
+
+ // --- ATLAS ---
+
+ if (W) server.registerTool(
+ 'mark_country_visited',
+ {
+ description: 'Mark a country as visited in your Atlas.',
+ inputSchema: {
+ country_code: z.string().length(2).toUpperCase().describe('ISO 3166-1 alpha-2 country code (e.g. "FR", "JP")'),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ country_code }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ markCountryVisited(userId, country_code.toUpperCase());
+ return ok({ success: true, country_code: country_code.toUpperCase() });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'unmark_country_visited',
+ {
+ description: 'Remove a country from your visited countries in Atlas.',
+ inputSchema: {
+ country_code: z.string().length(2).toUpperCase().describe('ISO 3166-1 alpha-2 country code'),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ country_code }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ unmarkCountryVisited(userId, country_code.toUpperCase());
+ return ok({ success: true, country_code: country_code.toUpperCase() });
+ }
+ );
+
+ // --- ATLAS EXPANDED ---
+
+ if (R) server.registerTool(
+ 'get_atlas_stats',
+ {
+ description: 'Get atlas statistics — total visited countries, region counts, continent breakdown.',
+ inputSchema: {},
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async () => {
+ const stats = await getAtlasStats(userId);
+ return ok({ stats });
+ }
+ );
+
+ if (R) server.registerTool(
+ 'list_visited_regions',
+ {
+ description: 'List all manually visited sub-country regions for the current user.',
+ inputSchema: {},
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async () => {
+ const regions = listManuallyVisitedRegions(userId);
+ return ok({ regions });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'mark_region_visited',
+ {
+ description: 'Mark a sub-country region as visited.',
+ inputSchema: {
+ regionCode: z.string().describe('ISO region code e.g. US-CA'),
+ regionName: z.string(),
+ countryCode: z.string().describe('ISO 3166-1 alpha-2 country code'),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ regionCode, regionName, countryCode }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ markRegionVisited(userId, regionCode, regionName, countryCode);
+ const region = listManuallyVisitedRegions(userId).find(r => r.region_code === regionCode);
+ return ok({ region });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'unmark_region_visited',
+ {
+ description: 'Remove a region from the visited list.',
+ inputSchema: {
+ regionCode: z.string(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ regionCode }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ unmarkRegionVisited(userId, regionCode);
+ return ok({ success: true });
+ }
+ );
+
+ if (R) server.registerTool(
+ 'get_country_atlas_places',
+ {
+ description: 'Get places saved in the user\'s atlas for a specific country.',
+ inputSchema: {
+ countryCode: z.string().describe('ISO 3166-1 alpha-2 country code'),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ countryCode }) => {
+ const result = getCountryPlaces(userId, countryCode);
+ return ok(result);
+ }
+ );
+
+ if (W) server.registerTool(
+ 'update_bucket_list_item',
+ {
+ description: 'Update a bucket list item (notes, name, target date, location).',
+ inputSchema: {
+ itemId: z.number().int().positive(),
+ name: z.string().optional(),
+ notes: z.string().optional(),
+ lat: z.number().nullable().optional(),
+ lng: z.number().nullable().optional(),
+ country_code: z.string().optional(),
+ target_date: z.string().nullable().optional(),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ itemId, name, notes, lat, lng, country_code, target_date }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const item = updateBucketItem(userId, itemId, { name, notes, lat, lng, country_code, target_date });
+ if (!item) return { content: [{ type: 'text' as const, text: 'Bucket list item not found.' }], isError: true };
+ return ok({ item });
+ }
+ );
+}
diff --git a/server/src/mcp/tools/budget.ts b/server/src/mcp/tools/budget.ts
new file mode 100644
index 0000000000000000000000000000000000000000..d9e8361c2314780382fe433dd495cb80dcdd32ba
--- /dev/null
+++ b/server/src/mcp/tools/budget.ts
@@ -0,0 +1,180 @@
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
+import { z } from 'zod';
+import { canAccessTrip, db } from '../../db/database';
+import { isDemoUser } from '../../services/authService';
+import {
+ createBudgetItem, updateBudgetItem, deleteBudgetItem,
+ updateMembers as updateBudgetMembers,
+ toggleMemberPaid,
+} from '../../services/budgetService';
+import {
+ safeBroadcast, TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE,
+ TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
+} from './_shared';
+import { canWrite } from '../scopes';
+import { isAddonEnabled } from '../../services/adminService';
+import { ADDON_IDS } from '../../addons';
+
+export function registerBudgetTools(server: McpServer, userId: number, scopes: string[] | null): void {
+ const W = canWrite(scopes, 'budget');
+
+ if (isAddonEnabled(ADDON_IDS.BUDGET)) {
+ // --- BUDGET ---
+
+ if (W) server.registerTool(
+ 'create_budget_item',
+ {
+ description: 'Add a budget/expense item to a trip.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ name: z.string().min(1).max(200),
+ category: z.string().max(100).optional().describe('Budget category (e.g. Accommodation, Food, Transport)'),
+ total_price: z.number().nonnegative(),
+ note: z.string().max(500).optional(),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ tripId, name, category, total_price, note }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('budget_edit', tripId, userId)) return permissionDenied();
+ const item = createBudgetItem(tripId, { category, name, total_price, note });
+ safeBroadcast(tripId, 'budget:created', { item });
+ return ok({ item });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'delete_budget_item',
+ {
+ description: 'Delete a budget item from a trip.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ itemId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ tripId, itemId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('budget_edit', tripId, userId)) return permissionDenied();
+ const deleted = deleteBudgetItem(itemId, tripId);
+ if (!deleted) return { content: [{ type: 'text' as const, text: 'Budget item not found.' }], isError: true };
+ safeBroadcast(tripId, 'budget:deleted', { itemId });
+ return ok({ success: true });
+ }
+ );
+
+ // --- BUDGET (update) ---
+
+ if (W) server.registerTool(
+ 'update_budget_item',
+ {
+ description: 'Update an existing budget/expense item in a trip.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ itemId: z.number().int().positive(),
+ name: z.string().min(1).max(200).optional(),
+ category: z.string().max(100).optional(),
+ total_price: z.number().nonnegative().optional(),
+ persons: z.number().int().positive().nullable().optional(),
+ days: z.number().int().positive().nullable().optional(),
+ note: z.string().max(500).nullable().optional(),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, itemId, name, category, total_price, persons, days, note }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('budget_edit', tripId, userId)) return permissionDenied();
+ const item = updateBudgetItem(itemId, tripId, { name, category, total_price, persons, days, note });
+ if (!item) return { content: [{ type: 'text' as const, text: 'Budget item not found.' }], isError: true };
+ safeBroadcast(tripId, 'budget:updated', { item });
+ return ok({ item });
+ }
+ );
+
+ // --- BUDGET ADVANCED ---
+
+ if (W) server.registerTool(
+ 'create_budget_item_with_members',
+ {
+ description: 'Create a budget/expense item and 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.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ name: z.string().min(1).max(200),
+ category: z.string().max(100).optional().describe('Budget category (e.g. Accommodation, Food, Transport)'),
+ total_price: z.number().nonnegative(),
+ note: z.string().max(500).optional(),
+ userIds: z.array(z.number().int().positive()).optional().describe('User IDs splitting this item; omit or pass empty array to skip member assignment'),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ tripId, name, category, total_price, note, userIds }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('budget_edit', tripId, userId)) return permissionDenied();
+ const hasMembers = userIds && userIds.length > 0;
+ try {
+ const run = db.transaction(() => {
+ const item = createBudgetItem(tripId, { category, name, total_price, note });
+ if (hasMembers) {
+ return updateBudgetMembers(item.id, tripId, userIds!);
+ }
+ return { item };
+ });
+ const result = run();
+ safeBroadcast(tripId, 'budget:created', { item: (result as any).item ?? result });
+ if (hasMembers) safeBroadcast(tripId, 'budget:members-updated', { item: result });
+ return ok({ item: result });
+ } catch {
+ return { content: [{ type: 'text' as const, text: 'Failed to create budget item.' }], isError: true };
+ }
+ }
+ );
+
+ if (W) server.registerTool(
+ 'set_budget_item_members',
+ {
+ description: 'Set which trip members are splitting a budget item (replaces current member list).',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ itemId: z.number().int().positive(),
+ userIds: z.array(z.number().int().positive()).describe('User IDs splitting this item; empty array clears all'),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, itemId, userIds }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('budget_edit', tripId, userId)) return permissionDenied();
+ const item = updateBudgetMembers(itemId, tripId, userIds);
+ safeBroadcast(tripId, 'budget:members-updated', { item });
+ return ok({ item });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'toggle_budget_member_paid',
+ {
+ description: 'Mark or unmark a member as having paid their share of a budget item.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ itemId: z.number().int().positive(),
+ memberId: z.number().int().positive().describe('User ID of the member'),
+ paid: z.boolean(),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, itemId, memberId, paid }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('budget_edit', tripId, userId)) return permissionDenied();
+ const member = toggleMemberPaid(itemId, tripId, memberId, paid);
+ safeBroadcast(tripId, 'budget:member-paid-updated', { itemId, member });
+ return ok({ member });
+ }
+ );
+ } // isAddonEnabled(BUDGET)
+}
diff --git a/server/src/mcp/tools/collab.ts b/server/src/mcp/tools/collab.ts
new file mode 100644
index 0000000000000000000000000000000000000000..64a2ed93ea592c8a2ef4236bb7f1a4d66f36d7d7
--- /dev/null
+++ b/server/src/mcp/tools/collab.ts
@@ -0,0 +1,285 @@
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
+import { z } from 'zod';
+import { canAccessTrip } from '../../db/database';
+import { isDemoUser } from '../../services/authService';
+import {
+ createNote as createCollabNote, updateNote as updateCollabNote, deleteNote as deleteCollabNote,
+ listPolls, createPoll, votePoll, closePoll, deletePoll,
+ listMessages, createMessage, deleteMessage, addOrRemoveReaction,
+} from '../../services/collabService';
+import { isAddonEnabled, getCollabFeatures } from '../../services/adminService';
+import { ADDON_IDS } from '../../addons';
+import {
+ safeBroadcast, TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE,
+ TOOL_ANNOTATIONS_NON_IDEMPOTENT, TOOL_ANNOTATIONS_READONLY,
+ demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
+} from './_shared';
+import { canRead, canWrite } from '../scopes';
+
+export function registerCollabTools(server: McpServer, userId: number, scopes: string[] | null): void {
+ const R = canRead(scopes, 'collab');
+ const W = canWrite(scopes, 'collab');
+
+ if (!isAddonEnabled(ADDON_IDS.COLLAB)) return;
+
+ const features = getCollabFeatures();
+
+ // --- COLLAB NOTES ---
+
+ if (features.notes && W) server.registerTool(
+ 'create_collab_note',
+ {
+ description: 'Create a shared collaborative note on a trip (visible to all trip members in the Collab tab).',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ title: z.string().min(1).max(200),
+ content: z.string().max(10000).optional(),
+ category: z.string().max(100).optional().describe('Note category (e.g. "Ideas", "To-do", "General")'),
+ color: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional().describe('Hex color for the note card'),
+ pinned: z.boolean().optional().default(false).describe('Pin the note to the top'),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ tripId, title, content, category, color, pinned }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
+ const note = createCollabNote(tripId, userId, { title, content, category, color, pinned });
+ safeBroadcast(tripId, 'collab:note:created', { note });
+ return ok({ note });
+ }
+ );
+
+ if (features.notes && W) server.registerTool(
+ 'update_collab_note',
+ {
+ description: 'Edit an existing collaborative note on a trip.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ noteId: z.number().int().positive(),
+ title: z.string().min(1).max(200).optional(),
+ content: z.string().max(10000).optional(),
+ category: z.string().max(100).optional(),
+ color: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional().describe('Hex color for the note card'),
+ pinned: z.boolean().optional().describe('Pin the note to the top'),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, noteId, title, content, category, color, pinned }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
+ const note = updateCollabNote(tripId, noteId, { title, content, category, color, pinned });
+ if (!note) return { content: [{ type: 'text' as const, text: 'Note not found.' }], isError: true };
+ safeBroadcast(tripId, 'collab:note:updated', { note });
+ return ok({ note });
+ }
+ );
+
+ if (features.notes && W) server.registerTool(
+ 'delete_collab_note',
+ {
+ description: 'Delete a collaborative note from a trip.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ noteId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ tripId, noteId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
+ const deleted = deleteCollabNote(tripId, noteId);
+ if (!deleted) return { content: [{ type: 'text' as const, text: 'Note not found.' }], isError: true };
+ safeBroadcast(tripId, 'collab:note:deleted', { noteId });
+ return ok({ success: true });
+ }
+ );
+
+ // --- COLLAB POLLS & CHAT ---
+
+ if (features.polls && R) server.registerTool(
+ 'list_collab_polls',
+ {
+ description: 'List all polls for a trip.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ tripId }) => {
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ const polls = listPolls(tripId);
+ return ok({ polls });
+ }
+ );
+
+ if (features.polls && W) server.registerTool(
+ 'create_collab_poll',
+ {
+ description: 'Create a new poll in the collab panel.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ question: z.string().min(1),
+ options: z.array(z.string()).min(2).describe('Poll answer options (at least 2)'),
+ multiple: z.boolean().optional().describe('Allow multiple choice'),
+ deadline: z.string().optional().describe('ISO date string for poll deadline'),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ tripId, question, options, multiple, deadline }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
+ const poll = createPoll(tripId, userId, { question, options, multiple, deadline });
+ safeBroadcast(tripId, 'collab:poll:created', { poll });
+ return ok({ poll });
+ }
+ );
+
+ if (features.polls && W) server.registerTool(
+ 'vote_collab_poll',
+ {
+ description: 'Vote on a poll option (or remove vote if already voted for that option).',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ pollId: z.number().int().positive(),
+ optionIndex: z.number().int().min(0).describe('Zero-based index of the option to vote for'),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ tripId, pollId, optionIndex }) => {
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
+ const result = votePoll(tripId, pollId, userId, optionIndex);
+ if (result.error) return { content: [{ type: 'text' as const, text: result.error }], isError: true };
+ safeBroadcast(tripId, 'collab:poll:voted', { poll: result.poll });
+ return ok({ poll: result.poll });
+ }
+ );
+
+ if (features.polls && W) server.registerTool(
+ 'close_collab_poll',
+ {
+ description: 'Close a poll so no more votes can be cast.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ pollId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, pollId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
+ const poll = closePoll(tripId, pollId);
+ if (!poll) return { content: [{ type: 'text' as const, text: 'Poll not found.' }], isError: true };
+ safeBroadcast(tripId, 'collab:poll:closed', { poll });
+ return ok({ poll });
+ }
+ );
+
+ if (features.polls && W) server.registerTool(
+ 'delete_collab_poll',
+ {
+ description: 'Delete a poll and all its votes.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ pollId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ tripId, pollId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
+ const deleted = deletePoll(tripId, pollId);
+ if (!deleted) return { content: [{ type: 'text' as const, text: 'Poll not found.' }], isError: true };
+ safeBroadcast(tripId, 'collab:poll:deleted', { pollId });
+ return ok({ success: true });
+ }
+ );
+
+ if (features.chat && R) server.registerTool(
+ 'list_collab_messages',
+ {
+ description: 'List chat messages for a trip (most recent 100, oldest-first).',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ before: z.number().int().positive().optional().describe('Load messages with ID less than this (pagination)'),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ tripId, before }) => {
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ const messages = listMessages(tripId, before);
+ return ok({ messages });
+ }
+ );
+
+ if (features.chat && W) server.registerTool(
+ 'send_collab_message',
+ {
+ description: "Send a chat message to a trip's collab channel.",
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ text: z.string().min(1),
+ replyTo: z.number().int().positive().optional().describe('Reply to a specific message ID'),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ tripId, text, replyTo }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
+ const result = createMessage(tripId, userId, text, replyTo ?? null);
+ if (result.error) return { content: [{ type: 'text' as const, text: result.error }], isError: true };
+ safeBroadcast(tripId, 'collab:message:created', { message: result.message });
+ return ok({ message: result.message });
+ }
+ );
+
+ if (features.chat && W) server.registerTool(
+ 'delete_collab_message',
+ {
+ description: 'Delete a chat message (only the message owner can delete their own messages).',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ messageId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ tripId, messageId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
+ const result = deleteMessage(tripId, messageId, userId);
+ if (result.error) return { content: [{ type: 'text' as const, text: result.error }], isError: true };
+ safeBroadcast(tripId, 'collab:message:deleted', { messageId, username: result.username });
+ return ok({ success: true });
+ }
+ );
+
+ if (features.chat && W) server.registerTool(
+ 'react_collab_message',
+ {
+ description: 'Toggle a reaction emoji on a chat message (adds if not present, removes if already reacted).',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ messageId: z.number().int().positive(),
+ emoji: z.string().describe('Single emoji character'),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ tripId, messageId, emoji }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('collab_edit', tripId, userId)) return permissionDenied();
+ const result = addOrRemoveReaction(messageId, tripId, userId, emoji);
+ if (!result.found) return { content: [{ type: 'text' as const, text: 'Message not found.' }], isError: true };
+ safeBroadcast(tripId, 'collab:message:reacted', { messageId, reactions: result.reactions });
+ return ok({ reactions: result.reactions });
+ }
+ );
+}
diff --git a/server/src/mcp/tools/days.ts b/server/src/mcp/tools/days.ts
new file mode 100644
index 0000000000000000000000000000000000000000..0e479ca309f296e68ff398e299931ad29d0f075d
--- /dev/null
+++ b/server/src/mcp/tools/days.ts
@@ -0,0 +1,294 @@
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
+import { z } from 'zod';
+import { canAccessTrip, db } from '../../db/database';
+import { isDemoUser } from '../../services/authService';
+import {
+ getDay, updateDay, validateAccommodationRefs,
+ createDay, deleteDay,
+ createAccommodation, getAccommodation, updateAccommodation, deleteAccommodation,
+} from '../../services/dayService';
+import { createPlace } from '../../services/placeService';
+import {
+ createNote as createDayNote, getNote as getDayNote, updateNote as updateDayNote,
+ deleteNote as deleteDayNote, dayExists as dayNoteExists,
+} from '../../services/dayNoteService';
+import {
+ safeBroadcast, TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE,
+ TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
+} from './_shared';
+import { canWrite } from '../scopes';
+
+export function registerDayTools(server: McpServer, userId: number, scopes: string[] | null): void {
+ if (!canWrite(scopes, 'trips')) return;
+
+ // --- DAYS ---
+
+ server.registerTool(
+ 'update_day',
+ {
+ description: 'Set the title of a day in a trip (e.g. "Arrival in Paris", "Free day").',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ dayId: z.number().int().positive(),
+ title: z.string().max(200).nullable().describe('Day title, or null to clear it'),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, dayId, title }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
+ const current = getDay(dayId, tripId);
+ if (!current) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true };
+ const updated = updateDay(dayId, current, title !== undefined ? { title } : {});
+ safeBroadcast(tripId, 'day:updated', { day: updated });
+ return ok({ day: updated });
+ }
+ );
+
+ server.registerTool(
+ 'create_day',
+ {
+ description: 'Add a new day to a trip (optionally with a specific date and notes).',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ date: z.string().optional().describe('ISO date string YYYY-MM-DD, optional for dateless trips'),
+ notes: z.string().optional(),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ tripId, date, notes }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
+ const day = createDay(tripId, date, notes);
+ safeBroadcast(tripId, 'day:created', { day });
+ return ok({ day });
+ }
+ );
+
+ server.registerTool(
+ 'delete_day',
+ {
+ description: 'Delete a day from a trip.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ dayId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ tripId, dayId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
+ if (!getDay(dayId, tripId)) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true };
+ deleteDay(dayId);
+ safeBroadcast(tripId, 'day:deleted', { id: dayId });
+ return ok({ success: true });
+ }
+ );
+
+ server.registerTool(
+ 'create_accommodation',
+ {
+ description: 'Add an accommodation (hotel, Airbnb, etc.) to a trip, linked to a place and a date range.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ place_id: z.number().int().positive().describe('The place to use as the accommodation'),
+ start_day_id: z.number().int().positive().describe('Check-in day ID'),
+ end_day_id: z.number().int().positive().describe('Check-out day ID'),
+ check_in: z.string().max(10).optional().describe('Check-in time e.g. "15:00"'),
+ check_out: z.string().max(10).optional().describe('Check-out time e.g. "11:00"'),
+ confirmation: z.string().max(100).optional(),
+ notes: z.string().max(1000).optional(),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ tripId, place_id, start_day_id, end_day_id, check_in, check_out, confirmation, notes }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
+ const errors = validateAccommodationRefs(tripId, place_id, start_day_id, end_day_id);
+ if (errors.length > 0) return { content: [{ type: 'text' as const, text: errors.map(e => e.message).join(', ') }], isError: true };
+ const accommodation = createAccommodation(tripId, { place_id, start_day_id, end_day_id, check_in, check_out, confirmation, notes });
+ safeBroadcast(tripId, 'accommodation:created', { accommodation });
+ return ok({ accommodation });
+ }
+ );
+
+ server.registerTool(
+ 'create_place_accommodation',
+ {
+ description: 'Create a new place and immediately set it as an accommodation for a date range in one atomic operation. Use place details from search_place results. Only use when the place does not yet exist — if it already exists, use create_accommodation directly. Set price + currency to record the accommodation cost so it shows on the item.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ name: z.string().min(1).max(200),
+ description: z.string().max(2000).optional(),
+ lat: z.number().optional(),
+ lng: z.number().optional(),
+ address: z.string().max(500).optional(),
+ category_id: z.number().int().positive().optional().describe('Category ID — use list_categories to see available options'),
+ google_place_id: z.string().optional().describe('Google Place ID from search_place — enables opening hours display'),
+ osm_id: z.string().optional().describe('OpenStreetMap ID from search_place (e.g. "way:12345")'),
+ place_notes: z.string().max(2000).optional().describe('Notes for the place'),
+ website: z.string().max(500).optional(),
+ phone: z.string().max(50).optional(),
+ start_day_id: z.number().int().positive().describe('Check-in day ID'),
+ end_day_id: z.number().int().positive().describe('Check-out day ID'),
+ check_in: z.string().max(10).optional().describe('Check-in time e.g. "15:00"'),
+ check_out: z.string().max(10).optional().describe('Check-out time e.g. "11:00"'),
+ confirmation: z.string().max(100).optional(),
+ accommodation_notes: z.string().max(1000).optional().describe('Notes for the accommodation'),
+ price: z.number().nonnegative().optional().describe('Total accommodation cost (shown on the item)'),
+ currency: z.string().length(3).optional().describe('ISO 4217 currency code (e.g. "EUR", "USD")'),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ tripId, name, description, lat, lng, address, category_id, google_place_id, osm_id, place_notes, website, phone, start_day_id, end_day_id, check_in, check_out, confirmation, accommodation_notes, price, currency }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
+ const dayErrors = validateAccommodationRefs(tripId, undefined, start_day_id, end_day_id);
+ if (dayErrors.length > 0) return { content: [{ type: 'text' as const, text: dayErrors.map(e => e.message).join(', ') }], isError: true };
+ try {
+ const run = db.transaction(() => {
+ const place = createPlace(String(tripId), { name, description, lat, lng, address, category_id, google_place_id, osm_id, notes: place_notes, website, phone, price, currency });
+ const accommodation = createAccommodation(tripId, { place_id: place.id, start_day_id, end_day_id, check_in, check_out, confirmation, notes: accommodation_notes });
+ return { place, accommodation };
+ });
+ const result = run();
+ safeBroadcast(tripId, 'place:created', { place: result.place });
+ safeBroadcast(tripId, 'accommodation:created', { accommodation: result.accommodation });
+ return ok(result);
+ } catch {
+ return { content: [{ type: 'text' as const, text: 'Failed to create place and accommodation.' }], isError: true };
+ }
+ }
+ );
+
+ server.registerTool(
+ 'update_accommodation',
+ {
+ description: 'Update fields on an existing accommodation.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ accommodationId: z.number().int().positive(),
+ place_id: z.number().int().positive().optional(),
+ start_day_id: z.number().int().positive().optional(),
+ end_day_id: z.number().int().positive().optional(),
+ check_in: z.string().max(10).optional(),
+ check_out: z.string().max(10).optional(),
+ confirmation: z.string().max(100).optional(),
+ notes: z.string().max(1000).optional(),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, accommodationId, place_id, start_day_id, end_day_id, check_in, check_out, confirmation, notes }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
+ const existing = getAccommodation(accommodationId, tripId);
+ if (!existing) return { content: [{ type: 'text' as const, text: 'Accommodation not found.' }], isError: true };
+ const accommodation = updateAccommodation(accommodationId, existing, { place_id, start_day_id, end_day_id, check_in, check_out, confirmation, notes });
+ safeBroadcast(tripId, 'accommodation:updated', { accommodation });
+ return ok({ accommodation });
+ }
+ );
+
+ server.registerTool(
+ 'delete_accommodation',
+ {
+ description: 'Delete an accommodation from a trip.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ accommodationId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ tripId, accommodationId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
+ if (!getAccommodation(accommodationId, tripId)) return { content: [{ type: 'text' as const, text: 'Accommodation not found.' }], isError: true };
+ const { linkedReservationId } = deleteAccommodation(accommodationId);
+ safeBroadcast(tripId, 'accommodation:deleted', { id: accommodationId, linkedReservationId });
+ return ok({ success: true, linkedReservationId });
+ }
+ );
+
+ // --- DAY NOTES ---
+
+ server.registerTool(
+ 'create_day_note',
+ {
+ description: 'Add a note to a specific day in a trip.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ dayId: z.number().int().positive(),
+ text: z.string().min(1).max(500),
+ time: z.string().max(150).optional().describe('Time label (e.g. "09:00" or "Morning")'),
+ icon: z.string().optional().describe('Emoji icon for the note'),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ tripId, dayId, text, time, icon }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
+ if (!dayNoteExists(dayId, tripId)) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true };
+ const note = createDayNote(dayId, tripId, text, time, icon);
+ safeBroadcast(tripId, 'dayNote:created', { dayId, note });
+ return ok({ note });
+ }
+ );
+
+ server.registerTool(
+ 'update_day_note',
+ {
+ description: 'Edit an existing note on a specific day.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ dayId: z.number().int().positive(),
+ noteId: z.number().int().positive(),
+ text: z.string().min(1).max(500).optional(),
+ time: z.string().max(150).nullable().optional().describe('Time label (e.g. "09:00" or "Morning"), or null to clear'),
+ icon: z.string().optional().describe('Emoji icon for the note'),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, dayId, noteId, text, time, icon }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
+ const existing = getDayNote(noteId, dayId, tripId);
+ if (!existing) return { content: [{ type: 'text' as const, text: 'Note not found.' }], isError: true };
+ const note = updateDayNote(noteId, existing, { text, time: time !== undefined ? time : undefined, icon });
+ safeBroadcast(tripId, 'dayNote:updated', { dayId, note });
+ return ok({ note });
+ }
+ );
+
+ server.registerTool(
+ 'delete_day_note',
+ {
+ description: 'Delete a note from a specific day.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ dayId: z.number().int().positive(),
+ noteId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ tripId, dayId, noteId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('day_edit', tripId, userId)) return permissionDenied();
+ const note = getDayNote(noteId, dayId, tripId);
+ if (!note) return { content: [{ type: 'text' as const, text: 'Note not found.' }], isError: true };
+ deleteDayNote(noteId);
+ safeBroadcast(tripId, 'dayNote:deleted', { noteId, dayId });
+ return ok({ success: true });
+ }
+ );
+}
diff --git a/server/src/mcp/tools/journey.ts b/server/src/mcp/tools/journey.ts
new file mode 100644
index 0000000000000000000000000000000000000000..10b985e7fe7e852c066703bbf8ff821a0efc82bb
--- /dev/null
+++ b/server/src/mcp/tools/journey.ts
@@ -0,0 +1,422 @@
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
+import { z } from 'zod';
+import { isDemoUser } from '../../services/authService';
+import {
+ addContributor, addTripToJourney, canAccessJourney, createEntry, createJourney,
+ deleteEntry, deleteJourney, getJourneyFull, getSuggestions, listEntries,
+ listJourneys, listUserTrips, removeContributor, removeTripFromJourney,
+ reorderEntries, updateContributorRole, updateEntry, updateJourney,
+ updateJourneyPreferences,
+} from '../../services/journeyService';
+import {
+ createOrUpdateJourneyShareLink, deleteJourneyShareLink, getJourneyShareLink,
+} from '../../services/journeyShareService';
+import { isAddonEnabled } from '../../services/adminService';
+import { ADDON_IDS } from '../../addons';
+import {
+ TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
+ demoDenied, ok,
+} from './_shared';
+import { canRead, canShareJourneys, canWrite } from '../scopes';
+
+function notFound(msg: string) {
+ return { content: [{ type: 'text' as const, text: msg }], isError: true };
+}
+
+export function registerJourneyTools(server: McpServer, userId: number, scopes: string[] | null): void {
+ if (!isAddonEnabled(ADDON_IDS.JOURNEY)) return;
+
+ const R = canRead(scopes, 'journey');
+ const W = canWrite(scopes, 'journey');
+ const S = canShareJourneys(scopes);
+
+ // --- READ TOOLS ---
+
+ if (R) server.registerTool(
+ 'list_journeys',
+ {
+ description: 'List all journeys owned or contributed to by the current user.',
+ inputSchema: {},
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async () => {
+ const journeys = listJourneys(userId);
+ return ok({ journeys });
+ }
+ );
+
+ if (R) server.registerTool(
+ 'get_journey',
+ {
+ description: 'Get a full journey including entries, contributors, and linked trips.',
+ inputSchema: {
+ journeyId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ journeyId }) => {
+ const journey = getJourneyFull(journeyId, userId);
+ if (!journey) return notFound('Journey not found or access denied.');
+ return ok({ journey });
+ }
+ );
+
+ if (R) server.registerTool(
+ 'list_journey_entries',
+ {
+ description: 'List all entries in a journey.',
+ inputSchema: {
+ journeyId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ journeyId }) => {
+ if (!canAccessJourney(journeyId, userId)) return notFound('Journey not found or access denied.');
+ const entries = listEntries(journeyId, userId);
+ return ok({ entries });
+ }
+ );
+
+ if (R) server.registerTool(
+ 'list_journey_contributors',
+ {
+ description: 'List all contributors (owner and collaborators) of a journey.',
+ inputSchema: {
+ journeyId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ journeyId }) => {
+ const journey = getJourneyFull(journeyId, userId);
+ if (!journey) return notFound('Journey not found or access denied.');
+ return ok({ contributors: (journey as any).contributors ?? [] });
+ }
+ );
+
+ if (R) server.registerTool(
+ 'get_journey_suggestions',
+ {
+ description: 'Get trip suggestions for creating a new journey (recently completed trips not yet in any journey).',
+ inputSchema: {},
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async () => {
+ const trips = getSuggestions(userId);
+ return ok({ trips });
+ }
+ );
+
+ if (R) server.registerTool(
+ 'list_journey_available_trips',
+ {
+ description: 'List all trips available to link to a journey.',
+ inputSchema: {},
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async () => {
+ const trips = listUserTrips(userId);
+ return ok({ trips });
+ }
+ );
+
+ // --- WRITE TOOLS ---
+
+ if (W) server.registerTool(
+ 'create_journey',
+ {
+ description: 'Create a new journey, optionally linking existing trips.',
+ inputSchema: {
+ title: z.string().min(1).max(200),
+ subtitle: z.string().max(300).optional(),
+ trip_ids: z.array(z.number().int().positive()).optional(),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ title, subtitle, trip_ids }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const journey = createJourney(userId, { title, subtitle, trip_ids });
+ return ok({ journey });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'update_journey',
+ {
+ description: 'Update an existing journey\'s title, subtitle, cover, or status. Owner only.',
+ inputSchema: {
+ journeyId: z.number().int().positive(),
+ title: z.string().min(1).max(200).optional(),
+ subtitle: z.string().max(300).optional(),
+ status: z.enum(['draft', 'active', 'completed', 'archived']).optional(),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ journeyId, title, subtitle, status }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const journey = updateJourney(journeyId, userId, { title, subtitle, status });
+ if (!journey) return notFound('Journey not found or access denied.');
+ return ok({ journey });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'delete_journey',
+ {
+ description: 'Delete a journey. Owner only — this cannot be undone.',
+ inputSchema: {
+ journeyId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ journeyId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const success = deleteJourney(journeyId, userId);
+ if (!success) return notFound('Journey not found or access denied.');
+ return ok({ success: true });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'add_journey_trip',
+ {
+ description: 'Link a trip to a journey. Syncs skeleton entries for all places in the trip.',
+ inputSchema: {
+ journeyId: z.number().int().positive(),
+ tripId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ journeyId, tripId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessJourney(journeyId, userId)) return notFound('Journey not found or access denied.');
+ const success = addTripToJourney(journeyId, tripId, userId);
+ return ok({ success });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'remove_journey_trip',
+ {
+ description: 'Unlink a trip from a journey. Owner only.',
+ inputSchema: {
+ journeyId: z.number().int().positive(),
+ tripId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ journeyId, tripId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const success = removeTripFromJourney(journeyId, tripId, userId);
+ if (!success) return notFound('Journey not found or access denied.');
+ return ok({ success });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'create_journey_entry',
+ {
+ description: 'Create a new entry in a journey.',
+ inputSchema: {
+ journeyId: z.number().int().positive(),
+ entry_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).describe('Entry date (YYYY-MM-DD)'),
+ title: z.string().max(300).optional(),
+ story: z.string().optional(),
+ entry_time: z.string().optional().describe('Time of day (e.g. "14:30")'),
+ location_name: z.string().optional(),
+ mood: z.string().optional(),
+ sort_order: z.number().int().min(0).optional(),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ journeyId, entry_date, title, story, entry_time, location_name, mood, sort_order }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const entry = createEntry(journeyId, userId, { entry_date, title, story, entry_time, location_name, mood, sort_order });
+ if (!entry) return notFound('Journey not found or access denied.');
+ return ok({ entry });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'update_journey_entry',
+ {
+ description: 'Update an existing journey entry.',
+ inputSchema: {
+ entryId: z.number().int().positive(),
+ title: z.string().max(300).optional(),
+ story: z.string().optional(),
+ entry_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
+ entry_time: z.string().optional(),
+ mood: z.string().optional(),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ entryId, title, story, entry_date, entry_time, mood }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const entry = updateEntry(entryId, userId, { title, story, entry_date, entry_time, mood }, undefined);
+ if (!entry) return notFound('Entry not found or access denied.');
+ return ok({ entry });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'delete_journey_entry',
+ {
+ description: 'Delete a journey entry.',
+ inputSchema: {
+ entryId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ entryId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const success = deleteEntry(entryId, userId, undefined);
+ if (!success) return notFound('Entry not found or access denied.');
+ return ok({ success: true });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'reorder_journey_entries',
+ {
+ description: 'Reorder entries within a journey by providing the desired order of entry IDs.',
+ inputSchema: {
+ journeyId: z.number().int().positive(),
+ orderedIds: z.array(z.number().int().positive()),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ journeyId, orderedIds }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const success = reorderEntries(journeyId, userId, orderedIds, undefined);
+ if (!success) return notFound('Journey not found, access denied, or entry IDs do not belong to this journey.');
+ return ok({ success: true });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'add_journey_contributor',
+ {
+ description: 'Add a contributor to a journey. Owner only.',
+ inputSchema: {
+ journeyId: z.number().int().positive(),
+ targetUserId: z.number().int().positive(),
+ role: z.enum(['editor', 'viewer']),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ journeyId, targetUserId, role }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const success = addContributor(journeyId, userId, targetUserId, role);
+ if (!success) return notFound('Journey not found or access denied.');
+ return ok({ success: true });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'update_journey_contributor_role',
+ {
+ description: 'Update the role of a journey contributor. Owner only.',
+ inputSchema: {
+ journeyId: z.number().int().positive(),
+ targetUserId: z.number().int().positive(),
+ role: z.enum(['editor', 'viewer']),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ journeyId, targetUserId, role }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const success = updateContributorRole(journeyId, userId, targetUserId, role);
+ if (!success) return notFound('Journey not found or access denied.');
+ return ok({ success: true });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'remove_journey_contributor',
+ {
+ description: 'Remove a contributor from a journey. Owner only.',
+ inputSchema: {
+ journeyId: z.number().int().positive(),
+ targetUserId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ journeyId, targetUserId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const success = removeContributor(journeyId, userId, targetUserId);
+ if (!success) return notFound('Journey not found or access denied.');
+ return ok({ success: true });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'update_journey_preferences',
+ {
+ description: 'Update per-user preferences for a journey (e.g. hide skeleton entries).',
+ inputSchema: {
+ journeyId: z.number().int().positive(),
+ hide_skeletons: z.boolean().optional(),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ journeyId, hide_skeletons }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const result = updateJourneyPreferences(journeyId, userId, { hide_skeletons });
+ if (!result) return notFound('Journey not found or access denied.');
+ return ok({ success: true });
+ }
+ );
+
+ // --- SHARE TOOLS ---
+
+ if (S) server.registerTool(
+ 'get_journey_share_link',
+ {
+ description: 'Get the current public share link for a journey. Returns null if none exists.',
+ inputSchema: {
+ journeyId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ journeyId }) => {
+ if (!canAccessJourney(journeyId, userId)) return notFound('Journey not found or access denied.');
+ const shareLink = getJourneyShareLink(journeyId);
+ return ok({ shareLink });
+ }
+ );
+
+ if (S) server.registerTool(
+ 'create_journey_share_link',
+ {
+ description: 'Create or update the public share link for a journey. Owner only.',
+ inputSchema: {
+ journeyId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ journeyId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const shareLink = createOrUpdateJourneyShareLink(journeyId, userId, {});
+ if (!shareLink) return notFound('Journey not found or access denied.');
+ return ok({ shareLink });
+ }
+ );
+
+ if (S) server.registerTool(
+ 'delete_journey_share_link',
+ {
+ description: 'Revoke the public share link for a journey. Owner only.',
+ inputSchema: {
+ journeyId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ journeyId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const success = deleteJourneyShareLink(journeyId, userId);
+ if (!success) return notFound('Journey not found or access denied.');
+ return ok({ success: true });
+ }
+ );
+}
diff --git a/server/src/mcp/tools/mapsWeather.ts b/server/src/mcp/tools/mapsWeather.ts
new file mode 100644
index 0000000000000000000000000000000000000000..c2dad6917d06331d5fde84b7497a0cf76d78fd7c
--- /dev/null
+++ b/server/src/mcp/tools/mapsWeather.ts
@@ -0,0 +1,148 @@
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
+import { z } from 'zod';
+import { findByIata, searchAirports } from '../../services/airportService';
+import { searchPlaces, getPlaceDetails, reverseGeocode, resolveGoogleMapsUrl } from '../../services/mapsService';
+import { getWeather, getDetailedWeather } from '../../services/weatherService';
+import {
+ TOOL_ANNOTATIONS_READONLY,
+ ok,
+} from './_shared';
+import { canRead } from '../scopes';
+
+export function registerMapsWeatherTools(server: McpServer, userId: number, scopes: string[] | null): void {
+ const canGeo = canRead(scopes, 'geo');
+ const canWeather = canRead(scopes, 'weather');
+
+ // --- MAPS EXTRAS ---
+
+ if (canGeo) server.registerTool(
+ 'get_place_details',
+ {
+ description: 'Fetch detailed information about a place by its Google Place ID.',
+ inputSchema: {
+ placeId: z.string().describe('Google Place ID'),
+ lang: z.string().optional().default('en'),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ placeId, lang }) => {
+ const details = await getPlaceDetails(userId, placeId, lang ?? 'en');
+ if (!details) return { content: [{ type: 'text' as const, text: 'Place not found or maps service not configured.' }], isError: true };
+ return ok({ details });
+ }
+ );
+
+ if (canGeo) server.registerTool(
+ 'reverse_geocode',
+ {
+ description: 'Get a human-readable address for given coordinates.',
+ inputSchema: {
+ lat: z.number(),
+ lng: z.number(),
+ lang: z.string().optional().default('en'),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ lat, lng, lang }) => {
+ const result = await reverseGeocode(String(lat), String(lng), lang ?? 'en');
+ if (!result) return { content: [{ type: 'text' as const, text: 'Reverse geocode failed or maps service not configured.' }], isError: true };
+ return ok(result);
+ }
+ );
+
+ if (canGeo) server.registerTool(
+ 'resolve_maps_url',
+ {
+ description: 'Resolve a Google Maps share URL to coordinates and place name.',
+ inputSchema: {
+ url: z.string().describe('Google Maps share URL'),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ url }) => {
+ const result = await resolveGoogleMapsUrl(url);
+ if (!result) return { content: [{ type: 'text' as const, text: 'Could not resolve URL or maps service not configured.' }], isError: true };
+ return ok(result);
+ }
+ );
+
+ // --- WEATHER ---
+
+ if (canWeather) server.registerTool(
+ 'get_weather',
+ {
+ description: 'Get weather forecast for a location and date.',
+ inputSchema: {
+ lat: z.number(),
+ lng: z.number(),
+ date: z.string().describe('ISO date YYYY-MM-DD'),
+ lang: z.string().optional().default('en'),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ lat, lng, date, lang }) => {
+ try {
+ const weather = await getWeather(String(lat), String(lng), date, lang ?? 'en');
+ return ok({ weather });
+ } catch (err: any) {
+ return { content: [{ type: 'text' as const, text: err?.message ?? 'Weather service not available.' }], isError: true };
+ }
+ }
+ );
+
+ if (canWeather) server.registerTool(
+ 'get_detailed_weather',
+ {
+ description: 'Get hourly/detailed weather forecast for a location and date.',
+ inputSchema: {
+ lat: z.number(),
+ lng: z.number(),
+ date: z.string().describe('ISO date YYYY-MM-DD'),
+ lang: z.string().optional().default('en'),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ lat, lng, date, lang }) => {
+ try {
+ const weather = await getDetailedWeather(String(lat), String(lng), date, lang ?? 'en');
+ return ok({ weather });
+ } catch (err: any) {
+ return { content: [{ type: 'text' as const, text: err?.message ?? 'Weather service not available.' }], isError: true };
+ }
+ }
+ );
+
+ // --- AIRPORTS ---
+
+ if (canGeo) server.registerTool(
+ 'search_airports',
+ {
+ description: 'Search for airports by name, city, or IATA code. Returns matching airports with IATA code, name, city, country, coordinates, and timezone. Use before create_transport (flight) to get the correct IATA code and timezone for endpoints.',
+ inputSchema: {
+ query: z.string().min(1).max(200).describe('Airport name, city, or IATA code (e.g. "zurich", "ZRH", "charles de gaulle")'),
+ limit: z.number().int().min(1).max(50).optional().default(10),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ query, limit }) => {
+ const airports = searchAirports(query, limit ?? 10);
+ return ok({ airports });
+ }
+ );
+
+ if (canGeo) server.registerTool(
+ 'get_airport',
+ {
+ description: 'Get a single airport by its IATA code. Returns name, city, country, coordinates, and timezone.',
+ inputSchema: {
+ iata: z.string().length(3).toUpperCase().describe('IATA airport code (e.g. "ZRH", "AMS", "CDG")'),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ iata }) => {
+ const airport = findByIata(iata);
+ if (!airport) return { content: [{ type: 'text' as const, text: 'Airport not found.' }], isError: true };
+ return ok({ airport });
+ }
+ );
+}
diff --git a/server/src/mcp/tools/notifications.ts b/server/src/mcp/tools/notifications.ts
new file mode 100644
index 0000000000000000000000000000000000000000..a7332c13349c62f97107fc0cae5ebed7f3fa5b11
--- /dev/null
+++ b/server/src/mcp/tools/notifications.ts
@@ -0,0 +1,99 @@
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
+import { z } from 'zod';
+import { isDemoUser } from '../../services/authService';
+import {
+ getNotifications, getUnreadCount,
+ markRead as markNotificationRead, markUnread as markNotificationUnread,
+ markAllRead,
+} from '../../services/inAppNotifications';
+import {
+ TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
+ TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ demoDenied, ok,
+} from './_shared';
+import { canRead, canWrite } from '../scopes';
+
+export function registerNotificationTools(server: McpServer, userId: number, scopes: string[] | null): void {
+ const R = canRead(scopes, 'notifications');
+ const W = canWrite(scopes, 'notifications');
+
+ // --- NOTIFICATIONS ---
+
+ if (R) server.registerTool(
+ 'list_notifications',
+ {
+ description: 'List in-app notifications for the current user.',
+ inputSchema: {
+ limit: z.number().int().positive().optional().default(20),
+ offset: z.number().int().min(0).optional().default(0),
+ unread_only: z.boolean().optional().default(false),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ limit, offset, unread_only }) => {
+ const result = getNotifications(userId, { limit: limit ?? 20, offset: offset ?? 0, unreadOnly: unread_only ?? false });
+ return ok(result);
+ }
+ );
+
+ if (R) server.registerTool(
+ 'get_unread_notification_count',
+ {
+ description: 'Get the number of unread in-app notifications.',
+ inputSchema: {},
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async () => {
+ const count = getUnreadCount(userId);
+ return ok({ count });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'mark_notification_read',
+ {
+ description: 'Mark a single notification as read.',
+ inputSchema: {
+ notificationId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ notificationId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const success = markNotificationRead(notificationId, userId);
+ if (!success) return { content: [{ type: 'text' as const, text: 'Notification not found.' }], isError: true };
+ return ok({ success: true });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'mark_notification_unread',
+ {
+ description: 'Mark a single notification as unread.',
+ inputSchema: {
+ notificationId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ notificationId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const success = markNotificationUnread(notificationId, userId);
+ if (!success) return { content: [{ type: 'text' as const, text: 'Notification not found.' }], isError: true };
+ return ok({ success: true });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'mark_all_notifications_read',
+ {
+ description: "Mark all of the current user's notifications as read.",
+ inputSchema: {},
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async () => {
+ if (isDemoUser(userId)) return demoDenied();
+ const count = markAllRead(userId);
+ return ok({ success: true, count });
+ }
+ );
+}
diff --git a/server/src/mcp/tools/packing.ts b/server/src/mcp/tools/packing.ts
new file mode 100644
index 0000000000000000000000000000000000000000..a3245bd8f79bea0aaada3f9364e3f079a3c3c6f9
--- /dev/null
+++ b/server/src/mcp/tools/packing.ts
@@ -0,0 +1,347 @@
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
+import { z } from 'zod';
+import { canAccessTrip } from '../../db/database';
+import { isDemoUser } from '../../services/authService';
+import {
+ createItem as createPackingItem, updateItem as updatePackingItem,
+ deleteItem as deletePackingItem,
+ reorderItems as reorderPackingItems,
+ listBags, createBag, updateBag, deleteBag, setBagMembers,
+ getCategoryAssignees as getPackingCategoryAssignees,
+ updateCategoryAssignees as updatePackingCategoryAssignees,
+ applyTemplate, saveAsTemplate, bulkImport,
+} from '../../services/packingService';
+import {
+ safeBroadcast, TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE,
+ TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
+} from './_shared';
+import { canRead, canWrite } from '../scopes';
+import { isAddonEnabled } from '../../services/adminService';
+import { ADDON_IDS } from '../../addons';
+
+export function registerPackingTools(server: McpServer, userId: number, scopes: string[] | null): void {
+ const R = canRead(scopes, 'packing');
+ const W = canWrite(scopes, 'packing');
+
+ if (!isAddonEnabled(ADDON_IDS.PACKING)) return;
+
+ // --- PACKING ---
+
+ if (W) server.registerTool(
+ 'create_packing_item',
+ {
+ description: 'Add an item to the packing checklist for a trip.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ name: z.string().min(1).max(200),
+ category: z.string().max(100).optional().describe('Packing category (e.g. Clothes, Electronics)'),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ tripId, name, category }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
+ const item = createPackingItem(tripId, { name, category: category || 'General' });
+ safeBroadcast(tripId, 'packing:created', { item });
+ return ok({ item });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'toggle_packing_item',
+ {
+ description: 'Check or uncheck a packing item.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ itemId: z.number().int().positive(),
+ checked: z.boolean(),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, itemId, checked }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
+ const item = updatePackingItem(tripId, itemId, { checked: checked ? 1 : 0 }, ['checked']);
+ if (!item) return { content: [{ type: 'text' as const, text: 'Packing item not found.' }], isError: true };
+ safeBroadcast(tripId, 'packing:updated', { item });
+ return ok({ item });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'delete_packing_item',
+ {
+ description: 'Remove an item from the packing checklist.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ itemId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ tripId, itemId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
+ const deleted = deletePackingItem(tripId, itemId);
+ if (!deleted) return { content: [{ type: 'text' as const, text: 'Packing item not found.' }], isError: true };
+ safeBroadcast(tripId, 'packing:deleted', { itemId });
+ return ok({ success: true });
+ }
+ );
+
+ // --- PACKING (update) ---
+
+ if (W) server.registerTool(
+ 'update_packing_item',
+ {
+ description: 'Rename a packing item or change its category.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ itemId: z.number().int().positive(),
+ name: z.string().min(1).max(200).optional(),
+ category: z.string().max(100).optional(),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, itemId, name, category }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
+ const bodyKeys = ['name', 'category'].filter(k => k === 'name' ? name !== undefined : category !== undefined);
+ const item = updatePackingItem(tripId, itemId, { name, category }, bodyKeys);
+ if (!item) return { content: [{ type: 'text' as const, text: 'Packing item not found.' }], isError: true };
+ safeBroadcast(tripId, 'packing:updated', { item });
+ return ok({ item });
+ }
+ );
+
+ // --- PACKING ADVANCED ---
+
+ if (W) server.registerTool(
+ 'reorder_packing_items',
+ {
+ description: 'Set the display order of packing items within a trip.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ orderedIds: z.array(z.number().int().positive()).describe('Packing item IDs in desired order'),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, orderedIds }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
+ reorderPackingItems(tripId, orderedIds);
+ safeBroadcast(tripId, 'packing:reordered', { orderedIds });
+ return ok({ success: true });
+ }
+ );
+
+ if (R) server.registerTool(
+ 'list_packing_bags',
+ {
+ description: 'List all packing bags for a trip.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ tripId }) => {
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ const bags = listBags(tripId);
+ return ok({ bags });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'create_packing_bag',
+ {
+ description: 'Create a new packing bag (e.g. "Carry-on", "Checked bag").',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ name: z.string().min(1).max(100),
+ color: z.string().optional(),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ tripId, name, color }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
+ const bag = createBag(tripId, { name, color });
+ safeBroadcast(tripId, 'packing:bag-created', { bag });
+ return ok({ bag });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'update_packing_bag',
+ {
+ description: 'Rename or recolor a packing bag.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ bagId: z.number().int().positive(),
+ name: z.string().optional(),
+ color: z.string().optional(),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, bagId, name, color }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
+ const fields: Record = {};
+ const bodyKeys: string[] = [];
+ if (name !== undefined) { fields.name = name; bodyKeys.push('name'); }
+ if (color !== undefined) { fields.color = color; bodyKeys.push('color'); }
+ const bag = updateBag(tripId, bagId, fields, bodyKeys);
+ safeBroadcast(tripId, 'packing:bag-updated', { bag });
+ return ok({ bag });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'delete_packing_bag',
+ {
+ description: 'Delete a packing bag (items in the bag are unassigned, not deleted).',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ bagId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ tripId, bagId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
+ deleteBag(tripId, bagId);
+ safeBroadcast(tripId, 'packing:bag-deleted', { id: bagId });
+ return ok({ success: true });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'set_bag_members',
+ {
+ description: 'Assign trip members to a packing bag (determines who packs what bag).',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ bagId: z.number().int().positive(),
+ userIds: z.array(z.number().int().positive()),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, bagId, userIds }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
+ setBagMembers(tripId, bagId, userIds);
+ safeBroadcast(tripId, 'packing:bag-members-updated', { bagId, userIds });
+ return ok({ success: true });
+ }
+ );
+
+ if (R) server.registerTool(
+ 'get_packing_category_assignees',
+ {
+ description: 'Get which trip members are assigned to each packing category.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ tripId }) => {
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ const assignees = getPackingCategoryAssignees(tripId);
+ return ok({ assignees });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'set_packing_category_assignees',
+ {
+ description: 'Assign trip members to a packing category.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ categoryName: z.string().min(1).max(100),
+ userIds: z.array(z.number().int().positive()),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, categoryName, userIds }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
+ updatePackingCategoryAssignees(tripId, categoryName, userIds);
+ safeBroadcast(tripId, 'packing:assignees', { categoryName, userIds });
+ return ok({ success: true });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'apply_packing_template',
+ {
+ description: 'Apply a packing template to a trip (adds items from the template).',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ templateId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ tripId, templateId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
+ const applied = applyTemplate(tripId, templateId);
+ if (applied === null) return { content: [{ type: 'text' as const, text: 'Template not found.' }], isError: true };
+ safeBroadcast(tripId, 'packing:template-applied', { templateId });
+ return ok({ success: true });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'save_packing_template',
+ {
+ description: 'Save the current packing list as a reusable template.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ templateName: z.string().min(1).max(100),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ tripId, templateName }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
+ saveAsTemplate(tripId, userId, templateName);
+ return ok({ success: true });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'bulk_import_packing',
+ {
+ description: 'Import multiple packing items at once from a list.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ items: z.array(z.object({
+ name: z.string().min(1).max(200),
+ category: z.string().optional(),
+ quantity: z.number().int().positive().optional(),
+ })).min(1),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ tripId, items }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
+ bulkImport(tripId, items);
+ safeBroadcast(tripId, 'packing:updated', {});
+ return ok({ success: true, count: items.length });
+ }
+ );
+}
diff --git a/server/src/mcp/tools/places.ts b/server/src/mcp/tools/places.ts
new file mode 100644
index 0000000000000000000000000000000000000000..1578b55a412af36903def932c4de58322c5a1308
--- /dev/null
+++ b/server/src/mcp/tools/places.ts
@@ -0,0 +1,269 @@
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
+import { z } from 'zod';
+import { canAccessTrip, db } from '../../db/database';
+import { isDemoUser } from '../../services/authService';
+import { deletePlacesMany, importGoogleList, importNaverList, listPlaces, createPlace, updatePlace, deletePlace } from '../../services/placeService';
+import { createAssignment, dayExists } from '../../services/assignmentService';
+import { onPlaceDeleted } from '../../services/journeyService';
+import { listCategories } from '../../services/categoryService';
+import { searchPlaces } from '../../services/mapsService';
+import {
+ safeBroadcast, TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
+ TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
+} from './_shared';
+import { canRead, canWrite } from '../scopes';
+
+export function registerPlaceTools(server: McpServer, userId: number, scopes: string[] | null): void {
+ const R = canRead(scopes, 'places');
+ const W = canWrite(scopes, 'places');
+
+ // --- PLACES ---
+
+ if (W) server.registerTool(
+ 'create_place',
+ {
+ description: 'Add a new place/POI to a trip. Set google_place_id 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.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ name: z.string().min(1).max(200),
+ description: z.string().max(2000).optional(),
+ lat: z.number().optional(),
+ lng: z.number().optional(),
+ address: z.string().max(500).optional(),
+ category_id: z.number().int().positive().optional().describe('Category ID — use list_categories to see available options'),
+ google_place_id: z.string().optional().describe('Google Place ID from search_place — enables opening hours display'),
+ osm_id: z.string().optional().describe('OpenStreetMap ID from search_place (e.g. "way:12345") — enables opening hours if no Google ID'),
+ notes: z.string().max(2000).optional(),
+ website: z.string().max(500).optional(),
+ phone: z.string().max(50).optional(),
+ price: z.number().nonnegative().optional().describe('Cost of this place/activity (e.g. ticket price, entry fee)'),
+ currency: z.string().length(3).optional().describe('ISO 4217 currency code (e.g. "EUR", "USD")'),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ tripId, name, description, lat, lng, address, category_id, google_place_id, osm_id, notes, website, phone, price, currency }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('place_edit', tripId, userId)) return permissionDenied();
+ const place = createPlace(String(tripId), { name, description, lat, lng, address, category_id, google_place_id, osm_id, notes, website, phone, price, currency });
+ safeBroadcast(tripId, 'place:created', { place });
+ return ok({ place });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'create_and_assign_place',
+ {
+ description: 'Create a new place and immediately assign it to a day in one atomic operation. Use place details from search_place results. Only use when the place does not yet exist — if it already exists, use assign_place_to_day directly. Set price + currency to record the cost so it shows on the item.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ dayId: z.number().int().positive().describe('Day to assign the place to'),
+ name: z.string().min(1).max(200),
+ description: z.string().max(2000).optional(),
+ lat: z.number().optional(),
+ lng: z.number().optional(),
+ address: z.string().max(500).optional(),
+ category_id: z.number().int().positive().optional().describe('Category ID — use list_categories to see available options'),
+ google_place_id: z.string().optional().describe('Google Place ID from search_place — enables opening hours display'),
+ osm_id: z.string().optional().describe('OpenStreetMap ID from search_place (e.g. "way:12345")'),
+ place_notes: z.string().max(2000).optional().describe('Notes for the place'),
+ website: z.string().max(500).optional(),
+ phone: z.string().max(50).optional(),
+ assignment_notes: z.string().max(500).optional().describe('Notes for this day assignment'),
+ price: z.number().nonnegative().optional().describe('Cost of this place/activity (e.g. ticket price, entry fee)'),
+ currency: z.string().length(3).optional().describe('ISO 4217 currency code (e.g. "EUR", "USD")'),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ tripId, dayId, name, description, lat, lng, address, category_id, google_place_id, osm_id, place_notes, website, phone, assignment_notes, price, currency }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('place_edit', tripId, userId)) return permissionDenied();
+ if (!dayExists(dayId, tripId)) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true };
+ try {
+ const run = db.transaction(() => {
+ const place = createPlace(String(tripId), { name, description, lat, lng, address, category_id, google_place_id, osm_id, notes: place_notes, website, phone, price, currency });
+ const assignment = createAssignment(dayId, place.id, assignment_notes ?? null);
+ return { place, assignment };
+ });
+ const result = run();
+ safeBroadcast(tripId, 'place:created', { place: result.place });
+ safeBroadcast(tripId, 'assignment:created', { assignment: result.assignment });
+ return ok(result);
+ } catch {
+ return { content: [{ type: 'text' as const, text: 'Failed to create place and assignment.' }], isError: true };
+ }
+ }
+ );
+
+ if (W) server.registerTool(
+ 'update_place',
+ {
+ description: 'Update an existing place in a trip.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ placeId: z.number().int().positive(),
+ name: z.string().min(1).max(200).optional(),
+ description: z.string().max(2000).optional(),
+ lat: z.number().optional(),
+ lng: z.number().optional(),
+ address: z.string().max(500).optional(),
+ category_id: z.number().int().positive().optional().describe('Category ID — use list_categories'),
+ price: z.number().optional(),
+ currency: z.string().length(3).optional(),
+ place_time: z.string().max(50).optional().describe('Scheduled time (e.g. "09:00")'),
+ end_time: z.string().max(50).optional().describe('End time (e.g. "11:00")'),
+ duration_minutes: z.number().int().positive().optional(),
+ notes: z.string().max(2000).optional(),
+ website: z.string().max(500).optional(),
+ phone: z.string().max(50).optional(),
+ transport_mode: z.enum(['walking', 'driving', 'cycling', 'transit', 'flight']).optional(),
+ osm_id: z.string().optional().describe('OpenStreetMap ID (e.g. "way:12345")'),
+ google_place_id: z.string().optional().describe('Google Place ID (e.g. "ChIJd8BlQ2BZwokRAFUEcm_qrcA")'),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, placeId, name, description, lat, lng, address, category_id, price, currency, place_time, end_time, duration_minutes, notes, website, phone, transport_mode, osm_id, google_place_id }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('place_edit', tripId, userId)) return permissionDenied();
+ const place = updatePlace(String(tripId), String(placeId), { name, description, lat, lng, address, category_id, price, currency, place_time, end_time, duration_minutes, notes, website, phone, transport_mode, osm_id, google_place_id });
+ if (!place) return { content: [{ type: 'text' as const, text: 'Place not found.' }], isError: true };
+ safeBroadcast(tripId, 'place:updated', { place });
+ return ok({ place });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'delete_place',
+ {
+ description: 'Delete a place from a trip.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ placeId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ tripId, placeId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('place_edit', tripId, userId)) return permissionDenied();
+ const deleted = deletePlace(String(tripId), String(placeId));
+ if (!deleted) return { content: [{ type: 'text' as const, text: 'Place not found.' }], isError: true };
+ safeBroadcast(tripId, 'place:deleted', { placeId });
+ return ok({ success: true });
+ }
+ );
+
+ if (R) server.registerTool(
+ 'list_places',
+ {
+ description: 'List all places/POIs in a trip, optionally filtered by assignment status. Use assignment=unassigned to find orphan activities not yet scheduled on any day.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ search: z.string().optional(),
+ category: z.string().optional(),
+ tag: z.string().optional(),
+ assignment: z.enum(['all', 'unassigned', 'assigned']).optional().default('all').describe('Filter by assignment status: "all" (default), "unassigned" (not on any day), or "assigned" (scheduled on a day)'),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ tripId, search, category, tag, assignment }) => {
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ const places = listPlaces(String(tripId), { search, category, tag, assignment });
+ return ok({ places });
+ }
+ );
+
+ // --- CATEGORIES ---
+
+ if (R) server.registerTool(
+ 'list_categories',
+ {
+ description: 'List all available place categories with their id, name, icon and color. Use category_id when creating or updating places.',
+ inputSchema: {},
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async () => {
+ const categories = listCategories();
+ return ok({ categories });
+ }
+ );
+
+ // --- SEARCH ---
+
+ if (R) server.registerTool(
+ 'search_place',
+ {
+ description: 'Search for a real-world place by name or address. Returns results with osm_id (and google_place_id if configured). Use these IDs when calling create_place so the app can display opening hours and ratings.',
+ inputSchema: {
+ query: z.string().min(1).max(500).describe('Place name or address to search for'),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ query }) => {
+ try {
+ const result = await searchPlaces(userId, query);
+ return ok(result);
+ } catch {
+ return { content: [{ type: 'text' as const, text: 'Place search failed.' }], isError: true };
+ }
+ }
+ );
+
+ if (W) server.registerTool(
+ 'import_places_from_url',
+ {
+ description: 'Import places from a shared Google Maps or Naver Maps list URL. Returns the imported places and count. The list must be shared publicly.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ url: z.string().url().describe('Publicly shared Google Maps list URL (maps.app.goo.gl/...) or Naver Maps list URL'),
+ source: z.enum(['google-list', 'naver-list']).describe('List source: "google-list" for Google Maps saved places, "naver-list" for Naver Maps'),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ tripId, url, source }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('place_edit', tripId, userId)) return permissionDenied();
+
+ const result = source === 'google-list'
+ ? await importGoogleList(String(tripId), url)
+ : await importNaverList(String(tripId), url);
+
+ if ('error' in result) {
+ return { content: [{ type: 'text' as const, text: result.error }], isError: true };
+ }
+
+ for (const place of result.places) {
+ safeBroadcast(tripId, 'place:created', { place });
+ }
+ return ok({ places: result.places, count: result.places.length, listName: result.listName, skipped: result.skipped });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'bulk_delete_places',
+ {
+ description: 'Delete multiple places from a trip at once. Removes all day assignments for each place as well. Warn the user before calling this — it cannot be undone.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ placeIds: z.array(z.number().int().positive()).min(1).max(200),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ tripId, placeIds }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('place_edit', tripId, userId)) return permissionDenied();
+
+ const deleted = deletePlacesMany(String(tripId), placeIds);
+ for (const id of deleted) {
+ safeBroadcast(tripId, 'place:deleted', { placeId: id });
+ try { onPlaceDeleted(id); } catch {}
+ }
+ return ok({ deleted, count: deleted.length });
+ }
+ );
+}
diff --git a/server/src/mcp/tools/prompts.ts b/server/src/mcp/tools/prompts.ts
new file mode 100644
index 0000000000000000000000000000000000000000..3216af096cca6e6bdd3f8240c184c2bd7a9546ce
--- /dev/null
+++ b/server/src/mcp/tools/prompts.ts
@@ -0,0 +1,138 @@
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
+import { z } from 'zod';
+import { canAccessTrip } from '../../db/database';
+import { getTripSummary } from '../../services/tripService';
+import { listItems as listPackingItems } from '../../services/packingService';
+import { isAddonEnabled } from '../../services/adminService';
+import { ADDON_IDS } from '../../addons';
+
+export function registerMcpPrompts(server: McpServer, _userId: number, isStaticToken = false): void {
+ if (isStaticToken) {
+ server.registerPrompt(
+ 'token_auth_notice',
+ {
+ title: 'Static Token Auth Notice',
+ description: 'Notification that this session uses a static API token which will be deprecated',
+ argsSchema: {},
+ },
+ async () => ({
+ description: 'Static token deprecation notice',
+ messages: [{
+ role: 'user' as const,
+ content: {
+ type: 'text' as const,
+ text: '⚠️ This MCP connection is authenticated with a static API token (trek_…). Static token authentication will be deprecated in a future version of TREK. Please inform the user that they should migrate to OAuth 2.1 by going to Settings → Integrations → MCP → OAuth Clients in TREK and registering an OAuth 2.1 application for their MCP client.',
+ },
+ }],
+ })
+ );
+ }
+ const userId = _userId;
+
+ server.registerPrompt(
+ 'trip-summary',
+ {
+ title: 'Trip Summary',
+ description: 'Load a full summary of a trip for context before planning or modifications',
+ argsSchema: {
+ tripId: z.number().int().positive().describe('Trip ID to summarize'),
+ },
+ },
+ async ({ tripId }) => {
+ if (!canAccessTrip(tripId, userId)) {
+ return { messages: [{ role: 'user', content: { type: 'text', text: 'Trip not found or access denied.' } }] };
+ }
+ const summary = getTripSummary(tripId);
+ if (!summary) {
+ return { messages: [{ role: 'user', content: { type: 'text', text: 'Trip not found.' } }] };
+ }
+ const { trip, days, members, budget, packing, reservations, collab_notes } = summary;
+ const memberList = [members?.owner, ...(members?.collaborators || [])].filter(Boolean);
+ const text = `Trip: ${trip?.title || 'Untitled'}${trip?.description ? `\n${trip.description}` : ''}
+Dates: ${trip?.start_date || '?'} to ${trip?.end_date || '?'}
+Members: ${memberList.length} (${memberList.map((m: any) => m.name || m.email).join(', ') || 'none'})
+Days: ${days?.length || 0}
+Packing: ${packing?.checked || 0}/${packing?.total || 0} items packed
+Budget: ${budget?.total || 0} ${trip?.currency || 'EUR'} total
+Reservations: ${reservations?.length || 0}
+Collab Notes: ${collab_notes?.length || 0}
+${days?.map((d: any, i: number) => `Day ${i + 1} (${d.date}): ${d.assignments?.length || 0} places${d.title ? ` - ${d.title}` : ''}`).join('\n') || 'No days yet'}`;
+ return {
+ description: `Summary of trip "${trip?.title || tripId}"`,
+ messages: [{ role: 'user', content: { type: 'text', text } }],
+ };
+ }
+ );
+
+ if (isAddonEnabled(ADDON_IDS.PACKING)) server.registerPrompt(
+ 'packing-list',
+ {
+ title: 'Packing List',
+ description: 'Get a formatted packing checklist for a trip',
+ argsSchema: {
+ tripId: z.number().int().positive().describe('Trip ID'),
+ },
+ },
+ async ({ tripId }) => {
+ if (!canAccessTrip(tripId, userId)) {
+ return { messages: [{ role: 'user', content: { type: 'text', text: 'Trip not found or access denied.' } }] };
+ }
+ const items = listPackingItems(tripId);
+ if (!items.length) {
+ return { messages: [{ role: 'user', content: { type: 'text', text: 'No packing items found for this trip.' } }] };
+ }
+ const grouped = items.reduce((acc: Record, item: any) => {
+ const cat = item.category || 'General';
+ if (!acc[cat]) acc[cat] = [];
+ acc[cat].push(item);
+ return acc;
+ }, {});
+ const lines = Object.entries(grouped).map(([cat, items]) =>
+ `## ${cat}\n${(items as any[]).map((i: any) => `- [${i.checked ? 'x' : ' '}] ${i.name}`).join('\n')}`
+ ).join('\n\n');
+ const { trip } = getTripSummary(tripId) || {};
+ return {
+ description: `Packing list for "${trip?.title || tripId}"`,
+ messages: [{ role: 'user', content: { type: 'text', text: `# Packing List: ${trip?.title || 'Trip'}\n\n${lines}\n\n_${items.length} items across ${Object.keys(grouped).length} categories_` } }],
+ };
+ }
+ );
+
+ if (isAddonEnabled(ADDON_IDS.BUDGET)) server.registerPrompt(
+ 'budget-overview',
+ {
+ title: 'Budget Overview',
+ description: 'Get a formatted budget summary for a trip',
+ argsSchema: {
+ tripId: z.number().int().positive().describe('Trip ID'),
+ },
+ },
+ async ({ tripId }) => {
+ if (!canAccessTrip(tripId, userId)) {
+ return { messages: [{ role: 'user', content: { type: 'text', text: 'Trip not found or access denied.' } }] };
+ }
+ const summary = getTripSummary(tripId);
+ if (!summary) {
+ return { messages: [{ role: 'user', content: { type: 'text', text: 'Trip not found.' } }] };
+ }
+ const { trip, budget } = summary;
+ const currency = trip?.currency || 'EUR';
+ const byCategory = (budget?.items || []).reduce((acc: Record, item: any) => {
+ const cat = item.category || 'Uncategorized';
+ acc[cat] = (acc[cat] || 0) + (item.total_price || 0);
+ return acc;
+ }, {} as Record);
+ const total = Object.values(byCategory).reduce((s, v) => s + v, 0);
+ const lines = Object.entries(byCategory)
+ .sort(([, a], [, b]) => b - a)
+ .map(([cat, amount]) => `- ${cat}: ${amount} ${currency}`)
+ .join('\n');
+ const memberCount = Math.max(1, [summary.members?.owner, ...(summary.members?.collaborators || [])].filter(Boolean).length);
+ const perPerson = (total / memberCount).toFixed(2);
+ return {
+ description: `Budget overview for "${trip?.title || tripId}"`,
+ messages: [{ role: 'user', content: { type: 'text', text: `# Budget: ${trip?.title || 'Trip'}\n\n**Total: ${total} ${currency}** (${perPerson} ${currency} per person)\n\n${lines || 'No expenses recorded.'}` } }],
+ };
+ }
+ );
+}
diff --git a/server/src/mcp/tools/reservations.ts b/server/src/mcp/tools/reservations.ts
new file mode 100644
index 0000000000000000000000000000000000000000..68ff20e407ecd283bd722730a740aff8298b0406
--- /dev/null
+++ b/server/src/mcp/tools/reservations.ts
@@ -0,0 +1,227 @@
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
+import { z } from 'zod';
+import { canAccessTrip } from '../../db/database';
+import { isDemoUser } from '../../services/authService';
+import {
+ createReservation, getReservation, updateReservation, deleteReservation,
+ updatePositions as updateReservationPositions,
+} from '../../services/reservationService';
+import { linkBudgetItemToReservation } from '../../services/budgetService';
+import { getDay } from '../../services/dayService';
+import { placeExists, getAssignmentForTrip } from '../../services/assignmentService';
+import {
+ safeBroadcast, TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE,
+ TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
+} from './_shared';
+import { canWrite } from '../scopes';
+
+export function registerReservationTools(server: McpServer, userId: number, scopes: string[] | null): void {
+ if (!canWrite(scopes, 'reservations')) return;
+
+
+ server.registerTool(
+ 'create_reservation',
+ {
+ description: 'Recommend a reservation for a trip. Created as pending — the user must confirm it. For flights, trains, cars, and cruises, use create_transport instead. Linking: hotel → use place_id + start_day_id + end_day_id (all three required to create the accommodation link); restaurant/event/tour/activity/other → use assignment_id. Set price to record the cost; it will appear on the booking and in the Budget tab.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ title: z.string().min(1).max(200),
+ type: z.enum(['hotel', 'restaurant', 'event', 'tour', 'activity', 'other']).describe('Reservation type: "hotel", "restaurant", "event", "tour", "activity", or "other"'),
+ reservation_time: z.string().optional().describe('ISO 8601 datetime or time string'),
+ location: z.string().max(500).optional(),
+ confirmation_number: z.string().max(100).optional(),
+ notes: z.string().max(1000).optional(),
+ day_id: z.number().int().positive().optional(),
+ place_id: z.number().int().positive().optional().describe('Hotel place to link (hotel type only)'),
+ start_day_id: z.number().int().positive().optional().describe('Check-in day (hotel type only; requires place_id and end_day_id)'),
+ end_day_id: z.number().int().positive().optional().describe('Check-out day (hotel type only; requires place_id and start_day_id)'),
+ check_in: z.string().max(10).optional().describe('Check-in time (e.g. "15:00", hotel type only)'),
+ check_out: z.string().max(10).optional().describe('Check-out time (e.g. "11:00", hotel type only)'),
+ assignment_id: z.number().int().positive().optional().describe('Link to a day assignment (restaurant, train, car, cruise, event, tour, activity, other)'),
+ price: z.number().nonnegative().optional().describe('Reservation cost — shown on the booking and linked in the Budget tab'),
+ budget_category: z.string().max(100).optional().describe('Budget category for the price entry (defaults to reservation type)'),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ tripId, title, type, reservation_time, location, confirmation_number, notes, day_id, place_id, start_day_id, end_day_id, check_in, check_out, assignment_id, price, budget_category }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied();
+
+ // Validate that all referenced IDs belong to this trip
+ if (day_id && !getDay(day_id, tripId))
+ return { content: [{ type: 'text' as const, text: 'day_id does not belong to this trip.' }], isError: true };
+ if (place_id && !placeExists(place_id, tripId))
+ return { content: [{ type: 'text' as const, text: 'place_id does not belong to this trip.' }], isError: true };
+ if (start_day_id && !getDay(start_day_id, tripId))
+ return { content: [{ type: 'text' as const, text: 'start_day_id does not belong to this trip.' }], isError: true };
+ if (end_day_id && !getDay(end_day_id, tripId))
+ return { content: [{ type: 'text' as const, text: 'end_day_id does not belong to this trip.' }], isError: true };
+ if (assignment_id && !getAssignmentForTrip(assignment_id, tripId))
+ return { content: [{ type: 'text' as const, text: 'assignment_id does not belong to this trip.' }], isError: true };
+
+ const createAccommodation = (type === 'hotel' && place_id && start_day_id && end_day_id)
+ ? { place_id, start_day_id, end_day_id, check_in: check_in || undefined, check_out: check_out || undefined, confirmation: confirmation_number || undefined }
+ : undefined;
+
+ const metadata = price != null ? { price: String(price) } : undefined;
+
+ const { reservation, accommodationCreated } = createReservation(tripId, {
+ title, type, reservation_time, location, confirmation_number,
+ notes, day_id, place_id, assignment_id,
+ create_accommodation: createAccommodation,
+ metadata,
+ });
+
+ if (accommodationCreated) {
+ safeBroadcast(tripId, 'accommodation:created', {});
+ }
+
+ if (price != null && price > 0) {
+ const item = linkBudgetItemToReservation(tripId, reservation.id, {
+ name: title,
+ category: budget_category || type,
+ total_price: price,
+ });
+ safeBroadcast(tripId, 'budget:created', { item });
+ }
+
+ safeBroadcast(tripId, 'reservation:created', { reservation });
+ return ok({ reservation });
+ }
+ );
+
+ server.registerTool(
+ 'update_reservation',
+ {
+ description: 'Update an existing reservation in a trip. Use status "confirmed" to confirm a pending recommendation, or "pending" to revert it. For flights, trains, cars, and cruises, use update_transport instead. Linking: hotel → use place_id to link to an accommodation place; restaurant/event/tour/activity/other → use assignment_id to link to a day assignment.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ reservationId: z.number().int().positive(),
+ title: z.string().min(1).max(200).optional(),
+ type: z.enum(['hotel', 'restaurant', 'event', 'tour', 'activity', 'other']).optional().describe('Reservation type: "hotel", "restaurant", "event", "tour", "activity", or "other"'),
+ reservation_time: z.string().optional().describe('ISO 8601 datetime or time string'),
+ location: z.string().max(500).optional(),
+ confirmation_number: z.string().max(100).optional(),
+ notes: z.string().max(1000).optional(),
+ status: z.enum(['pending', 'confirmed', 'cancelled']).optional().describe('Reservation status: "pending", "confirmed", or "cancelled"'),
+ place_id: z.number().int().positive().nullable().optional().describe('Link to a place (use for hotel type), or null to unlink'),
+ assignment_id: z.number().int().positive().nullable().optional().describe('Link to a day assignment (use for restaurant, train, car, cruise, event, tour, activity, other), or null to unlink'),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, reservationId, title, type, reservation_time, location, confirmation_number, notes, status, place_id, assignment_id }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied();
+ const existing = getReservation(reservationId, tripId);
+ if (!existing) return { content: [{ type: 'text' as const, text: 'Reservation not found.' }], isError: true };
+
+ if (place_id != null && !placeExists(place_id, tripId))
+ return { content: [{ type: 'text' as const, text: 'place_id does not belong to this trip.' }], isError: true };
+ if (assignment_id != null && !getAssignmentForTrip(assignment_id, tripId))
+ return { content: [{ type: 'text' as const, text: 'assignment_id does not belong to this trip.' }], isError: true };
+
+ const { reservation } = updateReservation(reservationId, tripId, {
+ title, type, reservation_time, location, confirmation_number, notes, status,
+ place_id: place_id !== undefined ? place_id ?? undefined : undefined,
+ assignment_id: assignment_id !== undefined ? assignment_id ?? undefined : undefined,
+ }, existing);
+ safeBroadcast(tripId, 'reservation:updated', { reservation });
+ return ok({ reservation });
+ }
+ );
+
+ server.registerTool(
+ 'delete_reservation',
+ {
+ description: 'Delete a reservation from a trip.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ reservationId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ tripId, reservationId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied();
+ const { deleted, accommodationDeleted } = deleteReservation(reservationId, tripId);
+ if (!deleted) return { content: [{ type: 'text' as const, text: 'Reservation not found.' }], isError: true };
+ if (accommodationDeleted) {
+ safeBroadcast(tripId, 'accommodation:deleted', { accommodationId: deleted.accommodation_id });
+ }
+ safeBroadcast(tripId, 'reservation:deleted', { reservationId });
+ return ok({ success: true });
+ }
+ );
+
+ server.registerTool(
+ 'reorder_reservations',
+ {
+ description: 'Update the display order of reservations within a day.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ positions: z.array(z.object({
+ id: z.number().int().positive(),
+ day_plan_position: z.number().int().min(0),
+ })).describe('Array of { id, day_plan_position } pairs'),
+ dayId: z.number().int().positive().optional().describe('Optionally scope the update to a specific day'),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, positions, dayId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied();
+ updateReservationPositions(tripId, positions, dayId);
+ safeBroadcast(tripId, 'reservation:positions', { positions, dayId });
+ return ok({ success: true });
+ }
+ );
+
+ server.registerTool(
+ 'link_hotel_accommodation',
+ {
+ description: 'Set or update the check-in/check-out day links for a hotel reservation. Creates or updates the accommodation record that ties the reservation to a place and a date range. Use the day IDs from get_trip_summary.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ reservationId: z.number().int().positive(),
+ place_id: z.number().int().positive().describe('The hotel place to link'),
+ start_day_id: z.number().int().positive().describe('Check-in day ID'),
+ end_day_id: z.number().int().positive().describe('Check-out day ID'),
+ check_in: z.string().max(10).optional().describe('Check-in time (e.g. "15:00")'),
+ check_out: z.string().max(10).optional().describe('Check-out time (e.g. "11:00")'),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, reservationId, place_id, start_day_id, end_day_id, check_in, check_out }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied();
+ const current = getReservation(reservationId, tripId);
+ if (!current) return { content: [{ type: 'text' as const, text: 'Reservation not found.' }], isError: true };
+ if (current.type !== 'hotel') return { content: [{ type: 'text' as const, text: 'Reservation is not of type hotel.' }], isError: true };
+
+ if (!placeExists(place_id, tripId))
+ return { content: [{ type: 'text' as const, text: 'place_id does not belong to this trip.' }], isError: true };
+ if (!getDay(start_day_id, tripId))
+ return { content: [{ type: 'text' as const, text: 'start_day_id does not belong to this trip.' }], isError: true };
+ if (!getDay(end_day_id, tripId))
+ return { content: [{ type: 'text' as const, text: 'end_day_id does not belong to this trip.' }], isError: true };
+
+ const isNewAccommodation = !current.accommodation_id;
+ const { reservation } = updateReservation(reservationId, tripId, {
+ place_id,
+ type: current.type,
+ status: current.status as string,
+ create_accommodation: { place_id, start_day_id, end_day_id, check_in: check_in || undefined, check_out: check_out || undefined },
+ }, current);
+
+ safeBroadcast(tripId, isNewAccommodation ? 'accommodation:created' : 'accommodation:updated', {});
+ safeBroadcast(tripId, 'reservation:updated', { reservation });
+ return ok({ reservation, accommodation_id: (reservation as any).accommodation_id });
+ }
+ );
+}
diff --git a/server/src/mcp/tools/tags.ts b/server/src/mcp/tools/tags.ts
new file mode 100644
index 0000000000000000000000000000000000000000..70f4fe8e81019fc04c605fd4eeaaf4bb2697fd13
--- /dev/null
+++ b/server/src/mcp/tools/tags.ts
@@ -0,0 +1,84 @@
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
+import { z } from 'zod';
+import { isDemoUser } from '../../services/authService';
+import { listTags, createTag, getTagByIdAndUser, updateTag, deleteTag } from '../../services/tagService';
+import {
+ TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
+ TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ demoDenied, ok,
+} from './_shared';
+import { canRead, canWrite } from '../scopes';
+
+export function registerTagTools(server: McpServer, userId: number, scopes: string[] | null): void {
+ const R = canRead(scopes, 'places');
+ const W = canWrite(scopes, 'places');
+
+ // --- TAGS ---
+
+ if (R) server.registerTool(
+ 'list_tags',
+ {
+ description: 'List all tags belonging to the current user.',
+ inputSchema: {},
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async () => {
+ const tags = listTags(userId);
+ return ok({ tags });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'create_tag',
+ {
+ description: 'Create a new tag (user-scoped label for places).',
+ inputSchema: {
+ name: z.string().min(1).max(100),
+ color: z.string().optional().describe('Hex color string e.g. #6366f1'),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ name, color }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const tag = createTag(userId, name, color);
+ return ok({ tag });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'update_tag',
+ {
+ description: 'Update the name or color of an existing tag.',
+ inputSchema: {
+ tagId: z.number().int().positive(),
+ name: z.string().optional(),
+ color: z.string().optional(),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tagId, name, color }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!getTagByIdAndUser(tagId, userId)) return { content: [{ type: 'text' as const, text: 'Tag not found.' }], isError: true };
+ const tag = updateTag(tagId, name, color);
+ if (!tag) return { content: [{ type: 'text' as const, text: 'Tag not found.' }], isError: true };
+ return ok({ tag });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'delete_tag',
+ {
+ description: 'Delete a tag (removes it from all places it was attached to).',
+ inputSchema: {
+ tagId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ tagId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!getTagByIdAndUser(tagId, userId)) return { content: [{ type: 'text' as const, text: 'Tag not found.' }], isError: true };
+ deleteTag(tagId);
+ return ok({ success: true });
+ }
+ );
+}
diff --git a/server/src/mcp/tools/todos.ts b/server/src/mcp/tools/todos.ts
new file mode 100644
index 0000000000000000000000000000000000000000..b7a164e36e646e7614af55129dd9a13ff7a8869b
--- /dev/null
+++ b/server/src/mcp/tools/todos.ts
@@ -0,0 +1,199 @@
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
+import { z } from 'zod';
+import { canAccessTrip } from '../../db/database';
+import { isDemoUser } from '../../services/authService';
+import {
+ listItems as listTodoItems, createItem as createTodoItem, updateItem as updateTodoItem,
+ deleteItem as deleteTodoItem, reorderItems as reorderTodoItems,
+ getCategoryAssignees as getTodoCategoryAssignees, updateCategoryAssignees as updateTodoCategoryAssignees,
+} from '../../services/todoService';
+import {
+ safeBroadcast, TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
+ TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
+} from './_shared';
+import { canRead, canWrite } from '../scopes';
+import { isAddonEnabled } from '../../services/adminService';
+import { ADDON_IDS } from '../../addons';
+
+export function registerTodoTools(server: McpServer, userId: number, scopes: string[] | null): void {
+ const R = canRead(scopes, 'todos');
+ const W = canWrite(scopes, 'todos');
+
+ if (!isAddonEnabled(ADDON_IDS.PACKING)) return;
+
+ // --- TODOS ---
+
+ if (R) server.registerTool(
+ 'list_todos',
+ {
+ description: 'List all to-do items for a trip, ordered by position.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ tripId }) => {
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ const items = listTodoItems(tripId);
+ return ok({ items });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'create_todo',
+ {
+ description: 'Create a new to-do item for a trip.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ name: z.string().min(1).max(500).describe('To-do item name'),
+ category: z.string().max(100).optional().describe('Category (e.g. "Logistics", "Booking")'),
+ due_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Due date (YYYY-MM-DD)'),
+ description: z.string().max(2000).optional().describe('Additional description'),
+ assigned_user_id: z.number().int().positive().optional().describe('User ID to assign this task to'),
+ priority: z.number().int().min(0).max(3).optional().describe('Priority: 0=none, 1=low, 2=medium, 3=high'),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ tripId, name, category, due_date, description, assigned_user_id, priority }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
+ const item = createTodoItem(tripId, { name, category, due_date, description, assigned_user_id, priority });
+ safeBroadcast(tripId, 'todo:created', { item });
+ return ok({ item });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'update_todo',
+ {
+ description: 'Update an existing to-do item. Only provided fields are changed; omitted fields stay as-is. Pass null to clear a nullable field.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ itemId: z.number().int().positive(),
+ name: z.string().min(1).max(500).optional(),
+ category: z.string().max(100).optional(),
+ due_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).nullable().optional().describe('Set to null to clear the due date'),
+ description: z.string().max(2000).nullable().optional().describe('Set to null to clear'),
+ assigned_user_id: z.number().int().positive().nullable().optional().describe('Set to null to unassign'),
+ priority: z.number().int().min(0).max(3).nullable().optional(),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, itemId, name, category, due_date, description, assigned_user_id, priority }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
+ // Build bodyKeys to signal which nullable fields were explicitly provided
+ const bodyKeys: string[] = [];
+ if (due_date !== undefined) bodyKeys.push('due_date');
+ if (description !== undefined) bodyKeys.push('description');
+ if (assigned_user_id !== undefined) bodyKeys.push('assigned_user_id');
+ if (priority !== undefined) bodyKeys.push('priority');
+ const item = updateTodoItem(tripId, itemId, { name, category, due_date, description, assigned_user_id, priority }, bodyKeys);
+ if (!item) return { content: [{ type: 'text' as const, text: 'To-do item not found.' }], isError: true };
+ safeBroadcast(tripId, 'todo:updated', { item });
+ return ok({ item });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'toggle_todo',
+ {
+ description: 'Mark a to-do item as checked (done) or unchecked.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ itemId: z.number().int().positive(),
+ checked: z.boolean().describe('True to mark done, false to uncheck'),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, itemId, checked }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
+ const item = updateTodoItem(tripId, itemId, { checked: checked ? 1 : 0 }, []);
+ if (!item) return { content: [{ type: 'text' as const, text: 'To-do item not found.' }], isError: true };
+ safeBroadcast(tripId, 'todo:updated', { item });
+ return ok({ item });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'delete_todo',
+ {
+ description: 'Delete a to-do item.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ itemId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ tripId, itemId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
+ const deleted = deleteTodoItem(tripId, itemId);
+ if (!deleted) return { content: [{ type: 'text' as const, text: 'To-do item not found.' }], isError: true };
+ safeBroadcast(tripId, 'todo:deleted', { itemId });
+ return ok({ success: true });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'reorder_todos',
+ {
+ description: 'Reorder to-do items within a trip by providing a new ordered list of item IDs.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ orderedIds: z.array(z.number().int().positive()).min(1).describe('All item IDs in the desired order'),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, orderedIds }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
+ reorderTodoItems(tripId, orderedIds);
+ return ok({ success: true });
+ }
+ );
+
+ if (R) server.registerTool(
+ 'get_todo_category_assignees',
+ {
+ description: 'Get the default assignees configured per to-do category for a trip.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ tripId }) => {
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ const assignees = getTodoCategoryAssignees(tripId);
+ return ok({ assignees });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'set_todo_category_assignees',
+ {
+ description: 'Set the default assignees for a to-do category on a trip. Pass an empty array to clear.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ categoryName: z.string().min(1).max(100).describe('Category name'),
+ userIds: z.array(z.number().int().positive()).describe('User IDs to assign as defaults for this category'),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, categoryName, userIds }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
+ const assignees = updateTodoCategoryAssignees(tripId, categoryName, userIds);
+ safeBroadcast(tripId, 'todo:assignees', { category: categoryName, assignees });
+ return ok({ assignees });
+ }
+ );
+}
diff --git a/server/src/mcp/tools/transports.ts b/server/src/mcp/tools/transports.ts
new file mode 100644
index 0000000000000000000000000000000000000000..578566c8789b15f821805f413ca74fb05cb592a9
--- /dev/null
+++ b/server/src/mcp/tools/transports.ts
@@ -0,0 +1,177 @@
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
+import { z } from 'zod';
+import { canAccessTrip } from '../../db/database';
+import { isDemoUser } from '../../services/authService';
+import {
+ createReservation, deleteReservation, getReservation, updateReservation,
+} from '../../services/reservationService';
+import { linkBudgetItemToReservation } from '../../services/budgetService';
+import { getDay } from '../../services/dayService';
+import {
+ safeBroadcast, TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ TOOL_ANNOTATIONS_WRITE, demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
+} from './_shared';
+import { canWrite } from '../scopes';
+
+const TRANSPORT_TYPES = ['flight', 'train', 'car', 'cruise'] as const;
+
+const endpointSchema = z.array(z.object({
+ role: z.enum(['from', 'to', 'stop']).describe('Endpoint role: "from" (origin), "to" (destination), or "stop" (intermediate)'),
+ sequence: z.number().int().min(0).describe('Order within the route (0-based)'),
+ name: z.string().min(1).describe('Location name (e.g. "Paris Gare de Lyon", "ZRH Terminal 2")'),
+ code: z.string().optional().describe('IATA airport code for flights (e.g. "ZRH"). Leave empty for other transport types.'),
+ lat: z.number().optional(),
+ lng: z.number().optional(),
+ timezone: z.string().optional().describe('IANA timezone (e.g. "Europe/Zurich"). Use airport tz for flights.'),
+ local_time: z.string().optional().describe('Local departure/arrival time at this endpoint, e.g. "14:35"'),
+ local_date: z.string().optional().describe('Local date at this endpoint, YYYY-MM-DD'),
+})).optional();
+
+export function registerTransportTools(server: McpServer, userId: number, scopes: string[] | null): void {
+ if (!canWrite(scopes, 'reservations')) return;
+
+ server.registerTool(
+ 'create_transport',
+ {
+ description: 'Create a transport booking (flight, train, car, or cruise) for a trip. Use endpoints[] to record origin/destination and intermediate stops — for flights, set code to the IATA airport code (use search_airports first). Created as pending — confirm with update_transport. Set price to record the cost; it will appear on the booking and in the Budget tab.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ type: z.enum(['flight', 'train', 'car', 'cruise']),
+ title: z.string().min(1).max(200),
+ status: z.enum(['pending', 'confirmed', 'cancelled']).optional().default('pending'),
+ start_day_id: z.number().int().positive().optional().describe('Departure day'),
+ end_day_id: z.number().int().positive().optional().describe('Arrival day (if different from departure)'),
+ reservation_time: z.string().optional().describe('ISO 8601 datetime or time string for departure'),
+ reservation_end_time: z.string().optional().describe('ISO 8601 datetime or time string for arrival'),
+ confirmation_number: z.string().max(100).optional(),
+ notes: z.string().max(1000).optional(),
+ metadata: z.record(z.string(), z.string()).optional().describe('Type-specific metadata: flights → { airline, flight_number, departure_airport, arrival_airport }; trains → { train_number, platform, seat }'),
+ endpoints: endpointSchema,
+ needs_review: z.boolean().optional(),
+ price: z.number().nonnegative().optional().describe('Transport cost — shown on the booking and linked in the Budget tab'),
+ budget_category: z.string().max(100).optional().describe('Budget category for the price entry (defaults to transport type)'),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ tripId, type, title, status, start_day_id, end_day_id, reservation_time, reservation_end_time, confirmation_number, notes, metadata, endpoints, needs_review, price, budget_category }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied();
+
+ if (start_day_id && !getDay(start_day_id, tripId))
+ return { content: [{ type: 'text' as const, text: 'start_day_id does not belong to this trip.' }], isError: true };
+ if (end_day_id && !getDay(end_day_id, tripId))
+ return { content: [{ type: 'text' as const, text: 'end_day_id does not belong to this trip.' }], isError: true };
+
+ const meta: Record = { ...(metadata ?? {}) };
+ if (price != null) meta.price = String(price);
+
+ const { reservation } = createReservation(tripId, {
+ title,
+ type,
+ reservation_time,
+ reservation_end_time,
+ location: undefined,
+ confirmation_number,
+ notes,
+ day_id: start_day_id,
+ end_day_id: end_day_id ?? start_day_id,
+ status: status ?? 'pending',
+ metadata: Object.keys(meta).length > 0 ? meta : undefined,
+ endpoints,
+ needs_review,
+ });
+
+ if (price != null && price > 0) {
+ const item = linkBudgetItemToReservation(tripId, reservation.id, {
+ name: title,
+ category: budget_category || type,
+ total_price: price,
+ });
+ safeBroadcast(tripId, 'budget:created', { item });
+ }
+
+ safeBroadcast(tripId, 'reservation:created', { reservation });
+ return ok({ reservation });
+ }
+ );
+
+ server.registerTool(
+ 'update_transport',
+ {
+ description: 'Update an existing transport booking. Pass endpoints[] to replace the full list of stops (origin, destination, intermediates). Use status "confirmed" to confirm.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ reservationId: z.number().int().positive(),
+ type: z.enum(['flight', 'train', 'car', 'cruise']).optional(),
+ title: z.string().min(1).max(200).optional(),
+ status: z.enum(['pending', 'confirmed', 'cancelled']).optional(),
+ start_day_id: z.number().int().positive().optional().describe('Departure day'),
+ end_day_id: z.number().int().positive().optional().describe('Arrival day (if different from departure)'),
+ reservation_time: z.string().optional().describe('ISO 8601 datetime or time string for departure'),
+ reservation_end_time: z.string().optional().describe('ISO 8601 datetime or time string for arrival'),
+ confirmation_number: z.string().max(100).optional(),
+ notes: z.string().max(1000).optional(),
+ metadata: z.record(z.string(), z.string()).optional().describe('Type-specific metadata: flights → { airline, flight_number, departure_airport, arrival_airport }; trains → { train_number, platform, seat }'),
+ endpoints: endpointSchema,
+ needs_review: z.boolean().optional(),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, reservationId, type, title, status, start_day_id, end_day_id, reservation_time, reservation_end_time, confirmation_number, notes, metadata, endpoints, needs_review }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied();
+
+ const existing = getReservation(reservationId, tripId);
+ if (!existing) return { content: [{ type: 'text' as const, text: 'Transport not found.' }], isError: true };
+
+ const resolvedType = type ?? existing.type;
+ if (!(TRANSPORT_TYPES as readonly string[]).includes(resolvedType))
+ return { content: [{ type: 'text' as const, text: 'Reservation is not a transport type. Use update_reservation instead.' }], isError: true };
+
+ if (start_day_id && !getDay(start_day_id, tripId))
+ return { content: [{ type: 'text' as const, text: 'start_day_id does not belong to this trip.' }], isError: true };
+ if (end_day_id && !getDay(end_day_id, tripId))
+ return { content: [{ type: 'text' as const, text: 'end_day_id does not belong to this trip.' }], isError: true };
+
+ const { reservation } = updateReservation(reservationId, tripId, {
+ title,
+ type,
+ reservation_time,
+ reservation_end_time,
+ confirmation_number,
+ notes,
+ day_id: start_day_id,
+ end_day_id,
+ status,
+ metadata,
+ endpoints,
+ needs_review,
+ }, existing);
+ safeBroadcast(tripId, 'reservation:updated', { reservation });
+ return ok({ reservation });
+ }
+ );
+
+ server.registerTool(
+ 'delete_transport',
+ {
+ description: 'Delete a transport booking from a trip.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ reservationId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ tripId, reservationId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied();
+ const { deleted } = deleteReservation(reservationId, tripId);
+ if (!deleted) return { content: [{ type: 'text' as const, text: 'Transport not found.' }], isError: true };
+ safeBroadcast(tripId, 'reservation:deleted', { reservationId });
+ return ok({ success: true });
+ }
+ );
+}
diff --git a/server/src/mcp/tools/trips.ts b/server/src/mcp/tools/trips.ts
new file mode 100644
index 0000000000000000000000000000000000000000..b5056bb4397e41ac5a096073c1ed695bf9e0fee1
--- /dev/null
+++ b/server/src/mcp/tools/trips.ts
@@ -0,0 +1,381 @@
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
+import { z } from 'zod';
+import { canAccessTrip } from '../../db/database';
+import { isDemoUser } from '../../services/authService';
+import {
+ listTrips, createTrip, updateTrip, deleteTrip, getTripSummary,
+ isOwner, verifyTripAccess,
+ listMembers as listTripMembers, getTripOwner, addMember as addTripMember,
+ removeMember as removeTripMember,
+ copyTripById, exportICS, NotFoundError, ValidationError,
+} from '../../services/tripService';
+import {
+ createOrUpdateShareLink, getShareLink, deleteShareLink,
+} from '../../services/shareService';
+import { isAddonEnabled, getCollabFeatures } from '../../services/adminService';
+import { ADDON_IDS } from '../../addons';
+import { countMessages, listPolls } from '../../services/collabService';
+import {
+ listItems as listTodoItems,
+} from '../../services/todoService';
+import {
+ safeBroadcast, MAX_MCP_TRIP_DAYS,
+ TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
+ TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
+} from './_shared';
+import { canRead, canReadTrips, canWrite, canDeleteTrips, canShareTrips } from '../scopes';
+
+export function registerTripTools(server: McpServer, userId: number, scopes: string[] | null, getDeprecationNotice: () => string | null = () => null): void {
+ const R = canReadTrips(scopes);
+ const W = canWrite(scopes, 'trips');
+ const D = canDeleteTrips(scopes);
+ const S = canShareTrips(scopes);
+
+ // --- TRIPS ---
+
+ if (W) server.registerTool(
+ 'create_trip',
+ {
+ description: 'Create a new trip. Returns the created trip with its generated days.',
+ inputSchema: {
+ title: z.string().min(1).max(200).describe('Trip title'),
+ description: z.string().max(2000).optional().describe('Trip description'),
+ start_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Start date (YYYY-MM-DD)'),
+ end_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('End date (YYYY-MM-DD)'),
+ currency: z.string().length(3).optional().describe('Currency code (e.g. EUR, USD)'),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ title, description, start_date, end_date, currency }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (start_date) {
+ const d = new Date(start_date + 'T00:00:00Z');
+ if (isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== start_date)
+ return { content: [{ type: 'text' as const, text: 'start_date is not a valid calendar date.' }], isError: true };
+ }
+ if (end_date) {
+ const d = new Date(end_date + 'T00:00:00Z');
+ if (isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== end_date)
+ return { content: [{ type: 'text' as const, text: 'end_date is not a valid calendar date.' }], isError: true };
+ }
+ if (start_date && end_date && new Date(end_date) < new Date(start_date)) {
+ return { content: [{ type: 'text' as const, text: 'End date must be after start date.' }], isError: true };
+ }
+ const { trip } = createTrip(userId, { title, description, start_date, end_date, currency }, MAX_MCP_TRIP_DAYS);
+ return ok({ trip });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'update_trip',
+ {
+ description: 'Update an existing trip\'s details.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ title: z.string().min(1).max(200).optional(),
+ description: z.string().max(2000).optional(),
+ start_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
+ end_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
+ currency: z.string().length(3).optional(),
+ is_archived: z.boolean().optional().describe('Archive (true) or unarchive (false) the trip'),
+ cover_image: z.string().optional().describe('Cover image path, e.g. /uploads/covers/abc.jpg'),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, title, description, start_date, end_date, currency, is_archived, cover_image }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('trip_edit', tripId, userId)) return permissionDenied();
+ if (start_date) {
+ const d = new Date(start_date + 'T00:00:00Z');
+ if (isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== start_date)
+ return { content: [{ type: 'text' as const, text: 'start_date is not a valid calendar date.' }], isError: true };
+ }
+ if (end_date) {
+ const d = new Date(end_date + 'T00:00:00Z');
+ if (isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== end_date)
+ return { content: [{ type: 'text' as const, text: 'end_date is not a valid calendar date.' }], isError: true };
+ }
+ const { updatedTrip } = updateTrip(tripId, userId, { title, description, start_date, end_date, currency, is_archived, cover_image }, 'user');
+ safeBroadcast(tripId, 'trip:updated', { trip: updatedTrip });
+ return ok({ trip: updatedTrip });
+ }
+ );
+
+ if (D) server.registerTool(
+ 'delete_trip',
+ {
+ description: 'Delete a trip. Only the trip owner can delete it.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ tripId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!isOwner(tripId, userId)) return noAccess();
+ deleteTrip(tripId, userId, 'user');
+ return ok({ success: true, tripId });
+ }
+ );
+
+ // list_trips and get_trip_summary are always registered regardless of OAuth scopes —
+ // they are navigation tools that any MCP client needs to discover trip IDs.
+ server.registerTool(
+ 'list_trips',
+ {
+ description: 'List all trips the current user owns or is a member of. Use this for trip discovery before calling get_trip_summary.',
+ inputSchema: {
+ include_archived: z.boolean().optional().describe('Include archived trips (default false)'),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ include_archived }) => {
+ const notice = getDeprecationNotice();
+ const trips = listTrips(userId, include_archived ? null : 0);
+ if (notice) return {
+ isError: true as const,
+ content: [
+ { type: 'text' as const, text: notice },
+ { type: 'text' as const, text: JSON.stringify({ trips }, null, 2) },
+ ],
+ };
+ return ok({ trips });
+ }
+ );
+
+ // --- TRIP SUMMARY ---
+
+ server.registerTool(
+ 'get_trip_summary',
+ {
+ description: 'Get a full denormalized summary of a trip in a single call: metadata, members, days with assignments and notes, accommodations, budget line items (when enabled), packing list (when enabled), reservations, collab notes and poll/message counts (when enabled), and to-do items (when enabled). Use this as a context loader before planning or modifying a trip.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ tripId }) => {
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ const summary = getTripSummary(tripId);
+ if (!summary) return noAccess();
+ // Addon availability gates
+ const packingEnabled = isAddonEnabled(ADDON_IDS.PACKING);
+ const budgetEnabled = isAddonEnabled(ADDON_IDS.BUDGET);
+ const collabEnabled = isAddonEnabled(ADDON_IDS.COLLAB);
+ const collabFeatures = collabEnabled ? getCollabFeatures() : null;
+ // Scope gates — sections not covered by the client's OAuth scopes are omitted.
+ // Core trip data (metadata, days, members, accommodations) is always included
+ // because this tool is always registered and needed for navigation.
+ const canReadBudget = budgetEnabled && canRead(scopes, 'budget');
+ const canReadPacking = packingEnabled && canRead(scopes, 'packing');
+ const canReadCollab = collabEnabled && canRead(scopes, 'collab');
+ const canReadTodos = packingEnabled && canRead(scopes, 'todos');
+ const canReadRes = canRead(scopes, 'reservations');
+ const todos = canReadTodos ? listTodoItems(tripId) : [];
+ let pollCount = 0;
+ let messageCount = 0;
+ if (canReadCollab) {
+ if (collabFeatures?.polls) pollCount = listPolls(tripId).length;
+ if (collabFeatures?.chat) messageCount = countMessages(tripId);
+ }
+ const notice = getDeprecationNotice();
+ const summaryData = {
+ ...summary,
+ reservations: canReadRes ? summary.reservations : undefined,
+ packing: canReadPacking ? summary.packing : undefined,
+ budget: canReadBudget ? summary.budget : undefined,
+ collab_notes: canReadCollab && collabFeatures?.notes ? summary.collab_notes : [],
+ todos,
+ pollCount,
+ messageCount,
+ };
+ if (notice) return {
+ isError: true as const,
+ content: [
+ { type: 'text' as const, text: notice },
+ { type: 'text' as const, text: JSON.stringify(summaryData, null, 2) },
+ ],
+ };
+ return ok(summaryData);
+ }
+ );
+
+ // --- TRIP MEMBERS, COPY, ICS, SHARE ---
+
+ if (R) server.registerTool(
+ 'list_trip_members',
+ {
+ description: 'List all members of a trip (owner + collaborators).',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ tripId }) => {
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ const ownerRow = getTripOwner(tripId);
+ if (!ownerRow) return noAccess();
+ const { owner, members } = listTripMembers(tripId, ownerRow.user_id);
+ return ok({ owner, members });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'add_trip_member',
+ {
+ description: 'Add a user to a trip by their username or email address. Only the trip owner can do this.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ identifier: z.string().min(1).describe('Username or email of the user to add'),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ tripId, identifier }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ const ownerRow = getTripOwner(tripId);
+ if (!ownerRow || ownerRow.user_id !== userId)
+ return { content: [{ type: 'text' as const, text: 'Only the trip owner can add members.' }], isError: true };
+ try {
+ const result = addTripMember(tripId, identifier, ownerRow.user_id, userId);
+ safeBroadcast(tripId, 'member:added', { member: result.member });
+ return ok({ member: result.member });
+ } catch (err) {
+ const msg = err instanceof ValidationError || err instanceof NotFoundError ? err.message : 'Failed to add member.';
+ return { content: [{ type: 'text' as const, text: msg }], isError: true };
+ }
+ }
+ );
+
+ if (W) server.registerTool(
+ 'remove_trip_member',
+ {
+ description: 'Remove a member from a trip. Only the trip owner can do this.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ memberId: z.number().int().positive().describe('User ID of the member to remove'),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ tripId, memberId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ const ownerRow = getTripOwner(tripId);
+ if (!ownerRow || ownerRow.user_id !== userId)
+ return { content: [{ type: 'text' as const, text: 'Only the trip owner can remove members.' }], isError: true };
+ removeTripMember(tripId, memberId);
+ safeBroadcast(tripId, 'member:removed', { userId: memberId });
+ return ok({ success: true });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'copy_trip',
+ {
+ description: 'Duplicate a trip (all days, places, itinerary, packing, budget, reservations, day notes). Packing items are reset to unchecked. Returns the new trip.',
+ inputSchema: {
+ tripId: z.number().int().positive().describe('Source trip ID to duplicate'),
+ title: z.string().min(1).max(200).optional().describe('Title for the new trip (defaults to source title)'),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ tripId, title }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ try {
+ const newTripId = copyTripById(tripId, userId, title);
+ const newTrip = canAccessTrip(newTripId, userId);
+ return ok({ trip: { id: newTripId, ...newTrip } });
+ } catch {
+ return { content: [{ type: 'text' as const, text: 'Failed to copy trip.' }], isError: true };
+ }
+ }
+ );
+
+ if (R) server.registerTool(
+ 'export_trip_ics',
+ {
+ description: 'Export a trip\'s itinerary and reservations as iCalendar (.ics) format text. Useful for importing into calendar apps.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ tripId }) => {
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ try {
+ const { ics, filename } = exportICS(tripId);
+ return ok({ ics, filename });
+ } catch {
+ return { content: [{ type: 'text' as const, text: 'Trip not found.' }], isError: true };
+ }
+ }
+ );
+
+ if (S) server.registerTool(
+ 'get_share_link',
+ {
+ description: 'Get the current public share link for a trip, including its permission flags. Returns null if no share link exists.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ tripId }) => {
+ // Read parity with the REST route GET /api/trips/:tripId/share-link, which
+ // only requires trip membership (share_manage gates create/delete, not read).
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ const link = getShareLink(String(tripId));
+ return ok({ link });
+ }
+ );
+
+ if (S) server.registerTool(
+ 'create_share_link',
+ {
+ description: 'Create or update the public share link for a trip. Set permission flags to control what is visible to guests.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ share_map: z.boolean().optional().default(true).describe('Share the map and places'),
+ share_bookings: z.boolean().optional().default(true).describe('Share reservations'),
+ share_packing: z.boolean().optional().default(false).describe('Share packing list'),
+ share_budget: z.boolean().optional().default(false).describe('Share budget'),
+ share_collab: z.boolean().optional().default(false).describe('Share collab messages'),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ tripId, share_map, share_bookings, share_packing, share_budget, share_collab }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('share_manage', tripId, userId)) return permissionDenied();
+ const { token, created } = createOrUpdateShareLink(String(tripId), userId, {
+ share_map: share_map ?? true,
+ share_bookings: share_bookings ?? true,
+ share_packing: share_packing ?? false,
+ share_budget: share_budget ?? false,
+ share_collab: share_collab ?? false,
+ });
+ return ok({ token, created });
+ }
+ );
+
+ if (S) server.registerTool(
+ 'delete_share_link',
+ {
+ description: 'Revoke the public share link for a trip. Guests will no longer be able to access the shared view.',
+ inputSchema: {
+ tripId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ tripId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ if (!canAccessTrip(tripId, userId)) return noAccess();
+ if (!hasTripPermission('share_manage', tripId, userId)) return permissionDenied();
+ deleteShareLink(String(tripId));
+ return ok({ success: true });
+ }
+ );
+}
diff --git a/server/src/mcp/tools/vacay.ts b/server/src/mcp/tools/vacay.ts
new file mode 100644
index 0000000000000000000000000000000000000000..b5ce85baa314da002813467e033afab40febece5
--- /dev/null
+++ b/server/src/mcp/tools/vacay.ts
@@ -0,0 +1,398 @@
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
+import { z } from 'zod';
+import { isDemoUser, getCurrentUser } from '../../services/authService';
+import {
+ getOwnPlan, getActivePlan, getActivePlanId, getPlanData,
+ updatePlan, setUserColor,
+ sendInvite as sendVacayInvite, acceptInvite, declineInvite, cancelInvite, dissolvePlan,
+ getAvailableUsers,
+ listYears, addYear, deleteYear,
+ getEntries as getVacayEntries, toggleEntry, toggleCompanyHoliday,
+ getStats as getVacayStats, updateStats as updateVacayStats,
+ addHolidayCalendar, updateHolidayCalendar, deleteHolidayCalendar,
+ getCountries as getHolidayCountries, getHolidays,
+} from '../../services/vacayService';
+import { isAddonEnabled } from '../../services/adminService';
+import { ADDON_IDS } from '../../addons';
+import {
+ TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
+ TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ demoDenied, ok,
+} from './_shared';
+import { canRead, canWrite } from '../scopes';
+
+export function registerVacayTools(server: McpServer, userId: number, scopes: string[] | null): void {
+ const R = canRead(scopes, 'vacay');
+ const W = canWrite(scopes, 'vacay');
+
+ if (isAddonEnabled(ADDON_IDS.VACAY)) {
+ if (R) server.registerTool(
+ 'get_vacay_plan',
+ {
+ description: "Get the current user's active vacation plan (own or joined).",
+ inputSchema: {},
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async () => {
+ const plan = getPlanData(userId);
+ return ok({ plan });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'update_vacay_plan',
+ {
+ description: 'Update vacation plan settings (weekends blocking, holidays, carry-over).',
+ inputSchema: {
+ block_weekends: z.boolean().optional(),
+ holidays_enabled: z.boolean().optional(),
+ holidays_region: z.string().nullable().optional(),
+ company_holidays_enabled: z.boolean().optional(),
+ carry_over_enabled: z.boolean().optional(),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ block_weekends, holidays_enabled, holidays_region, company_holidays_enabled, carry_over_enabled }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const planId = getActivePlanId(userId);
+ await updatePlan(planId, { block_weekends, holidays_enabled, holidays_region, company_holidays_enabled, carry_over_enabled }, undefined);
+ return ok({ success: true });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'set_vacay_color',
+ {
+ description: "Set the current user's color in the vacation plan calendar.",
+ inputSchema: {
+ color: z.string().describe('Hex color e.g. #6366f1'),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ color }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const planId = getActivePlanId(userId);
+ setUserColor(userId, planId, color, undefined);
+ return ok({ success: true });
+ }
+ );
+
+ if (R) server.registerTool(
+ 'get_available_vacay_users',
+ {
+ description: 'List users who can be invited to the current vacation plan.',
+ inputSchema: {},
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async () => {
+ const planId = getActivePlanId(userId);
+ const users = getAvailableUsers(userId, planId);
+ return ok({ users });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'send_vacay_invite',
+ {
+ description: 'Invite a user to join the vacation plan by their user ID.',
+ inputSchema: {
+ targetUserId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ targetUserId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const planId = getActivePlanId(userId);
+ const me = getCurrentUser(userId);
+ if (!me) return { content: [{ type: 'text' as const, text: 'User not found.' }], isError: true };
+ const result = sendVacayInvite(planId, userId, me.username, me.email, targetUserId);
+ if (result.error) return { content: [{ type: 'text' as const, text: result.error }], isError: true };
+ return ok({ success: true });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'accept_vacay_invite',
+ {
+ description: 'Accept a pending invitation to join another user\'s vacation plan.',
+ inputSchema: {
+ planId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ planId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const result = acceptInvite(userId, planId, undefined);
+ if (result.error) return { content: [{ type: 'text' as const, text: result.error }], isError: true };
+ return ok({ success: true });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'decline_vacay_invite',
+ {
+ description: 'Decline a pending vacation plan invitation.',
+ inputSchema: {
+ planId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ planId }) => {
+ declineInvite(userId, planId, undefined);
+ return ok({ success: true });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'cancel_vacay_invite',
+ {
+ description: 'Cancel an outgoing invitation (owner cancels invite they sent).',
+ inputSchema: {
+ targetUserId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ targetUserId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const planId = getActivePlanId(userId);
+ cancelInvite(planId, targetUserId);
+ return ok({ success: true });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'dissolve_vacay_plan',
+ {
+ description: 'Dissolve the shared plan — all members are removed and everyone returns to their own individual plan.',
+ inputSchema: {},
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async () => {
+ if (isDemoUser(userId)) return demoDenied();
+ dissolvePlan(userId, undefined);
+ return ok({ success: true });
+ }
+ );
+
+ if (R) server.registerTool(
+ 'list_vacay_years',
+ {
+ description: 'List calendar years tracked in the current vacation plan.',
+ inputSchema: {},
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async () => {
+ const planId = getActivePlanId(userId);
+ const years = listYears(planId);
+ return ok({ years });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'add_vacay_year',
+ {
+ description: 'Add a calendar year to the vacation plan.',
+ inputSchema: {
+ year: z.number().int().min(2000).max(2100),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ year }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const planId = getActivePlanId(userId);
+ const years = addYear(planId, year, undefined);
+ return ok({ years });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'delete_vacay_year',
+ {
+ description: 'Remove a calendar year from the vacation plan.',
+ inputSchema: {
+ year: z.number().int(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ year }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const planId = getActivePlanId(userId);
+ const years = deleteYear(planId, year, undefined);
+ return ok({ years });
+ }
+ );
+
+ if (R) server.registerTool(
+ 'get_vacay_entries',
+ {
+ description: 'Get all vacation day entries for a plan and year.',
+ inputSchema: {
+ year: z.number().int(),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ year }) => {
+ const planId = getActivePlanId(userId);
+ const entries = getVacayEntries(planId, String(year));
+ return ok({ entries });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'toggle_vacay_entry',
+ {
+ description: 'Toggle a day on or off as a vacation day for the current user.',
+ inputSchema: {
+ date: z.string().describe('ISO date YYYY-MM-DD'),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ date }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const planId = getActivePlanId(userId);
+ const result = toggleEntry(userId, planId, date, undefined);
+ return ok(result);
+ }
+ );
+
+ if (W) server.registerTool(
+ 'toggle_company_holiday',
+ {
+ description: 'Toggle a date as a company holiday for the whole plan.',
+ inputSchema: {
+ date: z.string(),
+ note: z.string().optional(),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ date, note }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const planId = getActivePlanId(userId);
+ const result = toggleCompanyHoliday(planId, date, note, undefined);
+ return ok(result);
+ }
+ );
+
+ if (R) server.registerTool(
+ 'get_vacay_stats',
+ {
+ description: 'Get vacation statistics for a specific year (days used, remaining, carried over).',
+ inputSchema: {
+ year: z.number().int(),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ year }) => {
+ const planId = getActivePlanId(userId);
+ const stats = getVacayStats(planId, year);
+ return ok({ stats });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'update_vacay_stats',
+ {
+ description: 'Update the vacation day allowance for a specific user and year.',
+ inputSchema: {
+ year: z.number().int(),
+ vacationDays: z.number().int().min(0),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ year, vacationDays }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const planId = getActivePlanId(userId);
+ updateVacayStats(userId, planId, year, vacationDays, undefined);
+ return ok({ success: true });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'add_holiday_calendar',
+ {
+ description: 'Add a public holiday calendar (by region code) to the vacation plan.',
+ inputSchema: {
+ region: z.string().describe('Country/region code e.g. US, GB, DE'),
+ label: z.string().nullable().optional(),
+ color: z.string().optional(),
+ sortOrder: z.number().int().optional(),
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ },
+ async ({ region, label, color, sortOrder }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const planId = getActivePlanId(userId);
+ const calendar = addHolidayCalendar(planId, region, label ?? null, color, sortOrder, undefined);
+ return ok({ calendar });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'update_holiday_calendar',
+ {
+ description: 'Update label or color for a holiday calendar.',
+ inputSchema: {
+ calendarId: z.number().int().positive(),
+ label: z.string().nullable().optional(),
+ color: z.string().optional(),
+ },
+ annotations: TOOL_ANNOTATIONS_WRITE,
+ },
+ async ({ calendarId, label, color }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const planId = getActivePlanId(userId);
+ const cal = updateHolidayCalendar(calendarId, planId, { label, color }, undefined);
+ if (!cal) return { content: [{ type: 'text' as const, text: 'Holiday calendar not found.' }], isError: true };
+ return ok({ calendar: cal });
+ }
+ );
+
+ if (W) server.registerTool(
+ 'delete_holiday_calendar',
+ {
+ description: 'Remove a holiday calendar from the vacation plan.',
+ inputSchema: {
+ calendarId: z.number().int().positive(),
+ },
+ annotations: TOOL_ANNOTATIONS_DELETE,
+ },
+ async ({ calendarId }) => {
+ if (isDemoUser(userId)) return demoDenied();
+ const planId = getActivePlanId(userId);
+ deleteHolidayCalendar(calendarId, planId, undefined);
+ return ok({ success: true });
+ }
+ );
+
+ if (R) server.registerTool(
+ 'list_holiday_countries',
+ {
+ description: 'List countries available for public holiday calendars.',
+ inputSchema: {},
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async () => {
+ const result = await getHolidayCountries();
+ if (result.error) return { content: [{ type: 'text' as const, text: result.error }], isError: true };
+ return ok({ countries: result.data });
+ }
+ );
+
+ if (R) server.registerTool(
+ 'list_holidays',
+ {
+ description: 'List public holidays for a country and year.',
+ inputSchema: {
+ country: z.string().describe('ISO 3166-1 alpha-2 code'),
+ year: z.number().int(),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ },
+ async ({ country, year }) => {
+ const result = await getHolidays(String(year), country);
+ if (result.error) return { content: [{ type: 'text' as const, text: result.error }], isError: true };
+ return ok({ holidays: result.data });
+ }
+ );
+ }
+}
diff --git a/server/src/middleware/auth.ts b/server/src/middleware/auth.ts
new file mode 100644
index 0000000000000000000000000000000000000000..6631a4524f88cd3714a61a6e95677a3d63d5a916
--- /dev/null
+++ b/server/src/middleware/auth.ts
@@ -0,0 +1,119 @@
+import { Request, Response, NextFunction } from 'express';
+import jwt from 'jsonwebtoken';
+import { db } from '../db/database';
+import { JWT_SECRET } from '../config';
+import { AuthRequest, OptionalAuthRequest, User } from '../types';
+import { applyIdempotency } from './idempotency';
+import { isDemoEmail } from '../services/demo';
+
+export function extractToken(req: Request): string | null {
+ // Prefer httpOnly cookie; fall back to Authorization: Bearer (MCP, API clients)
+ const cookieToken = (req as any).cookies?.trek_session;
+ if (cookieToken) return cookieToken;
+ const authHeader = req.headers['authorization'];
+ return (authHeader && authHeader.split(' ')[1]) || null;
+}
+
+/**
+ * Verify a JWT and load its user, enforcing the password_version gate.
+ *
+ * Exported so every auth surface in the codebase (MCP bearer tokens,
+ * file download query tokens, the photo-serving route) goes through the
+ * same check. A password reset bumps `users.password_version`, which
+ * invalidates every JWT that embedded the prior value — but only if
+ * every verify path actually compares the claim. Previously several
+ * paths called `jwt.verify` directly and skipped the DB lookup, so a
+ * stolen token kept working after the victim reset.
+ */
+export function verifyJwtAndLoadUser(token: string): User | null {
+ try {
+ const decoded = jwt.verify(token, JWT_SECRET, { algorithms: ['HS256'] }) as { id: number; pv?: number; purpose?: string };
+ // Purpose-scoped tokens (e.g. the short-lived mfa_login token) share this
+ // secret but are not full session tokens — only their dedicated endpoint
+ // may accept them, so reject any token carrying a purpose claim here.
+ if (decoded.purpose) return null;
+ const row = db.prepare(
+ 'SELECT id, username, email, role, password_version FROM users WHERE id = ?'
+ ).get(decoded.id) as (User & { password_version?: number }) | undefined;
+ if (!row) return null;
+ // Session invalidation: any token whose embedded password_version
+ // predates the user's current one is rejected. Tokens issued before
+ // the `pv` claim existed (decoded.pv === undefined) are treated as
+ // version 0 so legacy sessions keep working until the user resets.
+ const tokenPv = typeof decoded.pv === 'number' ? decoded.pv : 0;
+ const currentPv = typeof row.password_version === 'number' ? row.password_version : 0;
+ if (tokenPv !== currentPv) return null;
+ // Don't leak password_version beyond the middleware.
+ const { password_version: _pv, ...user } = row;
+ return user as User;
+ } catch {
+ return null;
+ }
+}
+
+const authenticate = (req: Request, res: Response, next: NextFunction): void => {
+ const token = extractToken(req);
+
+ if (!token) {
+ res.status(401).json({ error: 'Access token required', code: 'AUTH_REQUIRED' });
+ return;
+ }
+
+ const user = verifyJwtAndLoadUser(token);
+ if (!user) {
+ res.status(401).json({ error: 'Invalid or expired token', code: 'AUTH_REQUIRED' });
+ return;
+ }
+ (req as AuthRequest).user = user;
+ applyIdempotency(req, res, next, user.id);
+};
+
+/** Like `authenticate` but rejects requests that don't carry an httpOnly session cookie.
+ * Used on state-mutating OAuth endpoints (consent POST, client CRUD, session revoke)
+ * to prevent Bearer JWT tokens obtained by other means from managing OAuth clients. */
+const requireCookieAuth = (req: Request, res: Response, next: NextFunction): void => {
+ const cookieToken = (req as any).cookies?.trek_session;
+ if (!cookieToken) {
+ res.status(401).json({ error: 'Cookie session required for this endpoint', code: 'COOKIE_AUTH_REQUIRED' });
+ return;
+ }
+ const user = verifyJwtAndLoadUser(cookieToken);
+ if (!user) {
+ res.status(401).json({ error: 'Invalid or expired session', code: 'AUTH_REQUIRED' });
+ return;
+ }
+ (req as AuthRequest).user = user;
+ next();
+};
+
+const optionalAuth = (req: Request, res: Response, next: NextFunction): void => {
+ const token = extractToken(req);
+
+ if (!token) {
+ (req as OptionalAuthRequest).user = null;
+ return next();
+ }
+
+ (req as OptionalAuthRequest).user = verifyJwtAndLoadUser(token) || null;
+ next();
+};
+
+const adminOnly = (req: Request, res: Response, next: NextFunction): void => {
+ const authReq = req as AuthRequest;
+ if (!authReq.user || authReq.user.role !== 'admin') {
+ res.status(403).json({ error: 'Admin access required' });
+ return;
+ }
+ next();
+};
+
+const demoUploadBlock = (req: Request, res: Response, next: NextFunction): void => {
+ const authReq = req as AuthRequest;
+ if (process.env.DEMO_MODE?.toLowerCase() === 'true' && isDemoEmail(authReq.user?.email)) {
+ res.status(403).json({ error: 'Uploads are disabled in demo mode. Self-host TREK for full functionality.' });
+ return;
+ }
+ next();
+};
+
+export { authenticate, requireCookieAuth, optionalAuth, adminOnly, demoUploadBlock };
diff --git a/server/src/middleware/globalMiddleware.ts b/server/src/middleware/globalMiddleware.ts
new file mode 100644
index 0000000000000000000000000000000000000000..5def1bd489348c44cb07d9dc2271f4b2cf12ce7d
--- /dev/null
+++ b/server/src/middleware/globalMiddleware.ts
@@ -0,0 +1,165 @@
+import express, { Request, Response, NextFunction } from 'express';
+import cors from 'cors';
+import helmet from 'helmet';
+import cookieParser from 'cookie-parser';
+import { logDebug, logWarn, logError } from '../services/auditLog';
+import { enforceGlobalMfaPolicy } from './mfaPolicy';
+
+/**
+ * The global request pipeline shared by the legacy Express app and the NestJS
+ * instance. Both mount the *exact same* config so a request hitting a migrated
+ * Nest route is protected identically to one hitting the legacy fallback
+ * (helmet/CSP, CORS, HSTS, forced-HTTPS, the global MFA policy and request
+ * logging). Keeping it in one place is what makes the strangler dispatch
+ * behaviourally transparent — and is the prerequisite for retiring Express,
+ * since the Nest instance must carry the whole shell on its own.
+ *
+ * `bodyParser` is opt-out: the Nest instance does its own body parsing, so it
+ * passes `false` to avoid parsing the request twice.
+ */
+export function applyGlobalMiddleware(
+ app: express.Application,
+ opts: { bodyParser?: boolean } = {},
+): void {
+ const { bodyParser = true } = opts;
+
+ // Trust first proxy (nginx/Docker) for correct req.ip
+ if (process.env.NODE_ENV?.toLowerCase() === 'production' || process.env.TRUST_PROXY) {
+ app.set('trust proxy', Number.parseInt(process.env.TRUST_PROXY) || 1);
+ }
+
+ const allowedOrigins = process.env.ALLOWED_ORIGINS
+ ? process.env.ALLOWED_ORIGINS.split(',').map(o => o.trim()).filter(Boolean)
+ : null;
+
+ let corsOrigin: cors.CorsOptions['origin'];
+ if (allowedOrigins) {
+ corsOrigin = (origin: string | undefined, callback: (err: Error | null, allow?: boolean) => void) => {
+ if (!origin || allowedOrigins.includes(origin)) callback(null, true);
+ else callback(new Error('Not allowed by CORS'));
+ };
+ } else if (process.env.NODE_ENV?.toLowerCase() === 'production') {
+ corsOrigin = false;
+ } else {
+ corsOrigin = true;
+ }
+
+ const shouldForceHttps = process.env.FORCE_HTTPS?.toLowerCase() === 'true';
+ // HSTS is worth enabling any time we're serving production traffic,
+ // not only when FORCE_HTTPS is set. Self-hosters behind Traefik /
+ // Caddy / Cloudflare Tunnel typically leave FORCE_HTTPS unset (the
+ // proxy handles the redirect for them), and the previous "HSTS off by
+ // default" meant those instances never advertised HSTS at all.
+ //
+ // `includeSubDomains` stays OFF by default on purpose: an instance
+ // running on an apex domain would otherwise force HTTPS on every
+ // sibling subdomain the same operator may still be running over plain
+ // HTTP. Operators who want the stricter policy opt in with
+ // `HSTS_INCLUDE_SUBDOMAINS=true`.
+ const hstsActive = shouldForceHttps || process.env.NODE_ENV === 'production';
+ const hstsIncludeSubdomains = process.env.HSTS_INCLUDE_SUBDOMAINS === 'true';
+
+ // RFC 8414 / RFC 9728 / RFC 7591: discovery docs and DCR are world-readable/writable.
+ // /mcp needs open CORS so external MCP clients (ChatGPT, Claude.ai, Inspector) can call it
+ // with Bearer tokens from any origin. /oauth/register and /oauth/authorize need it for
+ // browser-based DCR/authorization preflights — the global cors({ origin: false }) would
+ // answer OPTIONS without Access-Control-Allow-Origin before the SDK's own cors() runs.
+ // All /.well-known/* paths get open CORS so clients probing openid-configuration or the
+ // RFC 8414 path-suffixed AS metadata form don't get CORS-blocked (they get 404 JSON instead).
+ app.use(
+ (req: Request, _res: Response, next: NextFunction) => {
+ if (
+ req.path.startsWith('/.well-known/') ||
+ req.path === '/oauth/register' ||
+ req.path === '/oauth/authorize' ||
+ req.path === '/oauth/userinfo' ||
+ req.path === '/mcp'
+ ) {
+ cors({ origin: '*', credentials: false })(req, _res, next);
+ } else {
+ next();
+ }
+ },
+ );
+ app.use(cors({ origin: corsOrigin, credentials: true }));
+ app.use(helmet({
+ contentSecurityPolicy: {
+ directives: {
+ defaultSrc: ["'self'"],
+ scriptSrc: ["'self'", "'wasm-unsafe-eval'", "'unsafe-eval'"],
+ styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com", "https://unpkg.com"],
+ imgSrc: ["'self'", "data:", "blob:", "https:"],
+ connectSrc: [
+ "'self'", "ws:", "wss:",
+ "https://nominatim.openstreetmap.org", "https://overpass-api.de",
+ "https://places.googleapis.com", "https://api.openweathermap.org",
+ "https://en.wikipedia.org", "https://commons.wikimedia.org",
+ "https://*.basemaps.cartocdn.com", "https://*.tile.openstreetmap.org",
+ "https://unpkg.com", "https://open-meteo.com", "https://api.open-meteo.com",
+ "https://geocoding-api.open-meteo.com", "https://api.frankfurter.dev",
+ "https://router.project-osrm.org/route/v1/", "https://routing.openstreetmap.de/",
+ "https://api.mapbox.com", "https://*.tiles.mapbox.com", "https://events.mapbox.com"
+ ],
+ workerSrc: ["'self'", "blob:"],
+ childSrc: ["'self'", "blob:"],
+ fontSrc: ["'self'", "https://fonts.gstatic.com", "data:"],
+ objectSrc: ["'none'"],
+ frameSrc: ["'none'"],
+ frameAncestors: ["'self'"],
+ // Restrict ]