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 [![Build Status](https://travis-ci.org/chalk/supports-color.svg?branch=master)](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-) + + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
+ +--- 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
submission targets (form-action has no default-src + // fallback, so it must be set explicitly). + formAction: ["'self'"], + upgradeInsecureRequests: shouldForceHttps ? [] : null + } + }, + crossOriginEmbedderPolicy: false, + hsts: hstsActive ? { maxAge: 31536000, includeSubDomains: hstsIncludeSubdomains } : false, + referrerPolicy: { policy: 'strict-origin-when-cross-origin' }, + })); + + if (shouldForceHttps) { + app.use((req: Request, res: Response, next: NextFunction) => { + if (req.path === '/api/health') return next(); + if (req.secure || req.headers['x-forwarded-proto'] === 'https') return next(); + res.redirect(301, 'https://' + req.headers.host + req.url); + }); + } + + if (bodyParser) { + app.use(express.json({ limit: '100kb' })); + app.use(express.urlencoded({ extended: true })); + } + app.use(cookieParser()); + app.use(enforceGlobalMfaPolicy); + + // Request logging with sensitive field redaction + const SENSITIVE_KEYS = new Set(['password', 'new_password', 'current_password', 'token', 'jwt', 'authorization', 'cookie', 'client_secret', 'mfa_token', 'code', 'smtp_pass']); + const redact = (value: unknown): unknown => { + if (!value || typeof value !== 'object') return value; + if (Array.isArray(value)) return (value as unknown[]).map(redact); + const out: Record = {}; + for (const [k, v] of Object.entries(value as Record)) { + out[k] = SENSITIVE_KEYS.has(k.toLowerCase()) ? '[REDACTED]' : redact(v); + } + return out; + }; + + app.use((req: Request, res: Response, next: NextFunction) => { + if (req.path === '/api/health') return next(); + const startedAt = Date.now(); + res.on('finish', () => { + const ms = Date.now() - startedAt; + if (res.statusCode >= 500) { + logError(`${req.method} ${req.path} ${res.statusCode} ${ms}ms ip=${req.ip}`); + } else if (res.statusCode === 401 || res.statusCode === 403) { + logDebug(`${req.method} ${req.path} ${res.statusCode} ${ms}ms ip=${req.ip}`); + } else if (res.statusCode >= 400) { + logWarn(`${req.method} ${req.path} ${res.statusCode} ${ms}ms ip=${req.ip}`); + } + const q = Object.keys(req.query).length ? ` query=${JSON.stringify(redact(req.query))}` : ''; + const b = req.body && Object.keys(req.body).length ? ` body=${JSON.stringify(redact(req.body))}` : ''; + logDebug(`${req.method} ${req.path} ${res.statusCode} ${ms}ms ip=${req.ip}${q}${b}`); + }); + next(); + }); +} diff --git a/server/src/middleware/idempotency.ts b/server/src/middleware/idempotency.ts new file mode 100644 index 0000000000000000000000000000000000000000..0e6acfd910596e488f416fbd250e053d118adab2 --- /dev/null +++ b/server/src/middleware/idempotency.ts @@ -0,0 +1,80 @@ +import { Request, Response, NextFunction } from 'express'; +import { db } from '../db/database'; + +const MUTATING_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']); +// Reject pathological client-supplied keys outright instead of hashing +// everything — 128 chars is plenty for any realistic UUID / ULID / nonce. +const MAX_KEY_LENGTH = 128; +// Responses larger than this are not worth caching — a backup-restore +// endpoint could otherwise store a megabyte-sized JSON body per request +// key and, with mass key creation, blow up idempotency_keys. +const MAX_CACHED_BODY_BYTES = 256 * 1024; + +interface IdempotencyRow { + status_code: number; + response_body: string; +} + +/** + * Called from within `authenticate` after req.user is set. + * + * For mutating requests carrying X-Idempotency-Key: + * - If (key, userId, method, path) already stored: replays the cached response. + * - Otherwise: wraps res.json to capture and store a successful response. + * + * The lookup is scoped by method + path as well as user so the same key + * replayed against a different endpoint doesn't return the cached body + * of an unrelated request. Key length is capped and the cached body is + * skipped when it exceeds `MAX_CACHED_BODY_BYTES`. + * + * Storing happens in idempotency_keys (24h TTL, cleaned by scheduler). + */ +export function applyIdempotency(req: Request, res: Response, next: NextFunction, userId: number): void { + if (!MUTATING_METHODS.has(req.method)) { + next(); + return; + } + + const key = req.headers['x-idempotency-key'] as string | undefined; + if (!key) { + next(); + return; + } + if (key.length > MAX_KEY_LENGTH) { + res.status(400).json({ error: 'X-Idempotency-Key exceeds maximum length of 128 characters' }); + return; + } + + // Return cached response only if the same key was seen for the same + // user AND the same method+path — avoids a POST's cached body leaking + // into an unrelated PATCH that reused the idempotency-key string. + const existing = db.prepare( + 'SELECT status_code, response_body FROM idempotency_keys WHERE key = ? AND user_id = ? AND method = ? AND path = ?' + ).get(key, userId, req.method, req.path) as IdempotencyRow | undefined; + + if (existing) { + res.status(existing.status_code).json(JSON.parse(existing.response_body)); + return; + } + + // Wrap res.json to capture the response on first successful execution + const originalJson = res.json.bind(res); + res.json = function (body: unknown): Response { + if (res.statusCode >= 200 && res.statusCode < 300) { + try { + const serialized = JSON.stringify(body); + if (serialized.length <= MAX_CACHED_BODY_BYTES) { + db.prepare( + `INSERT OR IGNORE INTO idempotency_keys (key, user_id, method, path, status_code, response_body, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?)` + ).run(key, userId, req.method, req.path, res.statusCode, serialized, Math.floor(Date.now() / 1000)); + } + } catch { + // Non-fatal: if storage fails, the request still succeeds + } + } + return originalJson(body); + }; + + next(); +} diff --git a/server/src/middleware/mfaPolicy.ts b/server/src/middleware/mfaPolicy.ts new file mode 100644 index 0000000000000000000000000000000000000000..e153841950108acaec512a79aa5b3efd379e8030 --- /dev/null +++ b/server/src/middleware/mfaPolicy.ts @@ -0,0 +1,111 @@ +import { Request, Response, NextFunction } from 'express'; +import { db } from '../db/database'; +import { extractToken, verifyJwtAndLoadUser } from './auth'; +import { DEMO_EMAILS } from '../services/demo'; + +/** Paths that never require MFA (public or pre-auth). */ +export function isPublicApiPath(method: string, pathNoQuery: string): boolean { + if (method === 'GET' && pathNoQuery === '/api/health') return true; + if (method === 'GET' && pathNoQuery === '/api/auth/app-config') return true; + if (method === 'POST' && pathNoQuery === '/api/auth/login') return true; + if (method === 'POST' && pathNoQuery === '/api/auth/register') return true; + if (method === 'POST' && pathNoQuery === '/api/auth/demo-login') return true; + if (method === 'GET' && pathNoQuery.startsWith('/api/auth/invite/')) return true; + if (method === 'POST' && pathNoQuery === '/api/auth/mfa/verify-login') return true; + // Unauthenticated passkey (primary) login ceremony. + if (method === 'POST' && pathNoQuery === '/api/auth/passkey/login/options') return true; + if (method === 'POST' && pathNoQuery === '/api/auth/passkey/login/verify') return true; + if (pathNoQuery.startsWith('/api/auth/oidc/')) return true; + return false; +} + +/** Authenticated paths allowed while MFA is not yet enabled (setup + lockout recovery). */ +export function isMfaSetupExemptPath(method: string, pathNoQuery: string): boolean { + if (method === 'GET' && pathNoQuery === '/api/auth/me') return true; + if (method === 'POST' && pathNoQuery === '/api/auth/mfa/setup') return true; + if (method === 'POST' && pathNoQuery === '/api/auth/mfa/enable') return true; + // Allow enrolling a passkey as the second factor (a user-verified passkey + // satisfies require_mfa), so a fresh user under the policy isn't stuck. + if (method === 'POST' && pathNoQuery === '/api/auth/passkey/register/options') return true; + if (method === 'POST' && pathNoQuery === '/api/auth/passkey/register/verify') return true; + if (method === 'GET' && pathNoQuery === '/api/auth/passkey/credentials') return true; + if ((method === 'GET' || method === 'PUT') && pathNoQuery === '/api/auth/app-settings') return true; + return false; +} + +/** + * When app_settings.require_mfa is true, block API access for users without MFA enabled, + * except for public routes and MFA setup endpoints. + */ +export function enforceGlobalMfaPolicy(req: Request, res: Response, next: NextFunction): void { + const pathNoQuery = (req.originalUrl || req.url || '').split('?')[0]; + + if (!pathNoQuery.startsWith('/api')) { + next(); + return; + } + + if (isPublicApiPath(req.method, pathNoQuery)) { + next(); + return; + } + + // Accept both the httpOnly session cookie (regular SPA users) and the + // Authorization header (MCP / API clients). Previously this only looked + // at the header so every normal cookie-authenticated session sailed + // past `require_mfa` unchecked. + const token = extractToken(req); + if (!token) { + next(); + return; + } + + // Use the shared verify helper so the `password_version` gate applies + // here too — a JWT stolen before a password reset would otherwise + // continue to satisfy this middleware until its natural 24h expiry. + const verified = verifyJwtAndLoadUser(token); + if (!verified) { + next(); + return; + } + const userId = verified.id; + + const requireRow = db.prepare("SELECT value FROM app_settings WHERE key = 'require_mfa'").get() as { value: string } | undefined; + if (requireRow?.value !== 'true') { + next(); + return; + } + + if (process.env.DEMO_MODE?.toLowerCase() === 'true' && verified.email && DEMO_EMAILS.has(verified.email)) { + next(); + return; + } + + const row = db.prepare('SELECT mfa_enabled FROM users WHERE id = ?').get(userId) as + | { mfa_enabled: number | boolean } + | undefined; + if (!row) { + next(); + return; + } + + // A user-verified passkey is phishing-resistant and inherently two-factor, so + // owning at least one satisfies the require_mfa policy exactly like TOTP does. + // (All stored passkeys were registered with userVerification required.) + const mfaOk = row.mfa_enabled === 1 || row.mfa_enabled === true; + const passkeyOk = !!db.prepare('SELECT 1 FROM webauthn_credentials WHERE user_id = ? LIMIT 1').get(userId); + if (mfaOk || passkeyOk) { + next(); + return; + } + + if (isMfaSetupExemptPath(req.method, pathNoQuery)) { + next(); + return; + } + + res.status(403).json({ + error: 'Two-factor authentication is required. Complete setup in Settings.', + code: 'MFA_REQUIRED', + }); +} diff --git a/server/src/middleware/tripAccess.ts b/server/src/middleware/tripAccess.ts new file mode 100644 index 0000000000000000000000000000000000000000..2c973f50dba382f9b60d65b1a0ea511d2333011e --- /dev/null +++ b/server/src/middleware/tripAccess.ts @@ -0,0 +1,37 @@ +import { Request, Response, NextFunction } from 'express'; +import { canAccessTrip, isOwner } from '../db/database'; +import { AuthRequest } from '../types'; + +/** Middleware: verifies the authenticated user is an owner or member of the trip, then attaches trip to req. */ +function requireTripAccess(req: Request, res: Response, next: NextFunction): void { + const authReq = req as AuthRequest; + const tripId = req.params.tripId || req.params.id; + if (!tripId) { + res.status(400).json({ error: 'Trip ID required' }); + return; + } + const trip = canAccessTrip(Number(tripId), authReq.user.id); + if (!trip) { + res.status(404).json({ error: 'Trip not found' }); + return; + } + authReq.trip = trip; + next(); +} + +/** Middleware: verifies the authenticated user is the trip owner (not just a member). */ +function requireTripOwner(req: Request, res: Response, next: NextFunction): void { + const authReq = req as AuthRequest; + const tripId = req.params.tripId || req.params.id; + if (!tripId) { + res.status(400).json({ error: 'Trip ID required' }); + return; + } + if (!isOwner(Number(tripId), authReq.user.id)) { + res.status(403).json({ error: 'Only the trip owner can do this' }); + return; + } + next(); +} + +export { requireTripAccess, requireTripOwner }; diff --git a/server/src/middleware/validate.ts b/server/src/middleware/validate.ts new file mode 100644 index 0000000000000000000000000000000000000000..90101e7b3d029b5e9562716d32ac8d60bb396122 --- /dev/null +++ b/server/src/middleware/validate.ts @@ -0,0 +1,26 @@ +import { Request, Response, NextFunction } from 'express'; + +function maxLength(field: string, max: number) { + return (req: Request, res: Response, next: NextFunction): void => { + if (req.body[field] && typeof req.body[field] === 'string' && req.body[field].length > max) { + res.status(400).json({ error: `${field} must be ${max} characters or less` }); + return; + } + next(); + }; +} + +function validateStringLengths(maxLengths: Record) { + return (req: Request, res: Response, next: NextFunction): void => { + for (const [field, max] of Object.entries(maxLengths)) { + const value = req.body[field]; + if (value && typeof value === 'string' && value.length > max) { + res.status(400).json({ error: `${field} must be ${max} characters or less` }); + return; + } + } + next(); + }; +} + +export { maxLength, validateStringLengths }; diff --git a/server/src/nest/README.md b/server/src/nest/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8d46179240cf6fc7cfe4b0da9cc7b9b951e04cd9 --- /dev/null +++ b/server/src/nest/README.md @@ -0,0 +1,84 @@ +# NestJS migration layer — module & test guide + +This folder holds the co-hosted NestJS app that incrementally strangles the legacy +Express API (see the "Brownfield Rewrite" board). Until a prefix is migrated, the +top-level dispatcher in `src/index.ts` routes it to the legacy app; migrated +prefixes go to Nest. **Weather (`weather/`) is the reference implementation** — copy +its shape when migrating a new domain. + +## Module layout (per domain) + +``` +shared/src//.schema.ts(.spec.ts) # Zod contract — single source of truth +server/src/nest//.service.ts # business logic (ported 1:1 from the Express service) +server/src/nest//.controller.ts # same routes/verbs/params/status codes as Express +server/src/nest//.module.ts # registered in app.module.ts +``` + +Add the prefix to `DEFAULT_NEST_PREFIXES` in `strangler.ts` to route it to Nest +(operators can override at runtime via the `NEST_PREFIXES` env var — instant +rollback, no redeploy). Trip-scoped mounts use a pattern prefix with a `:param` +segment (e.g. `/api/trips/:tripId/packing`); the matcher routes only that nested +mount to Nest and leaves the sibling trip routes (days, places, ...) on Express. + +## Migrated so far + +- **Phase 1 (leaf):** weather, airports, config (public), system-notices, maps, + categories, tags, notifications, atlas. +- **Phase 2 (trip sub-domains):** vacay (addon), packing, todo. + +## Cross-cutting Foundation pieces + +- `common/idempotency.interceptor.ts` — global `APP_INTERCEPTOR` replaying the + client's `X-Idempotency-Key` on mutations, mirroring the legacy + `applyIdempotency` middleware so retried writes don't double-apply. +- `strangler.ts` — supports both static prefixes and `:param` pattern prefixes. + +## Parity gotchas worth remembering + +- A POST that answers with `res.json` in Express stays **200**; add `@HttpCode(200)` + (Nest defaults POST to 201). Creates that Express sends as 201 need nothing. +- Static sub-routes that collide with a `:id` param (e.g. `/in-app/all` vs + `/in-app/:id`, `/reorder` vs `/:id`) must be declared **before** the param route. +- Reproduce bespoke admin/error wording exactly — e.g. notifications' `test-smtp` + returns `{ error: 'Admin only' }`, not the AdminGuard's `Admin access required`. +- Trip-scoped routes verify trip access (404) and the relevant permission (403) + per handler and forward `X-Socket-Id` to the WebSocket broadcast. + +## Parity is law + +A migrated route must be **byte-identical** for the client: same URL, method, +query/body, HTTP status, `Set-Cookie`, and JSON body — including bespoke error +strings. Where the legacy route returns a hand-written error (e.g. weather's +`{ error: 'Latitude and longitude are required' }`), reproduce that exact body in +the controller rather than relying on the generic `ZodValidationPipe` envelope. + +## How to write the tests + +Every module ships three kinds of tests; the coverage gate (`vitest.config.ts`, +scoped to `src/nest/**`) requires ≥80%. + +1. **Service / controller unit spec** — `tests/unit/nest/.controller.test.ts`. + Instantiate the controller with a mocked service; assert status codes, the exact + `{ error }` bodies, and that inputs are forwarded correctly (defaults, coercion). + See `weather.controller.test.ts`. + +2. **Parity test** — `tests/parity/.parity.test.ts`. Mock the shared service + identically for both apps, then fire the same request at the Express route and the + Nest controller with the `expectParity()` harness (`tests/parity/parity.ts`) and + assert identical status + body. This is the gate before flipping the toggle. + See `weather.parity.test.ts`. + +3. **e2e** — `tests/e2e/.e2e.test.ts`. Boot the Nest module against a temp + in-memory SQLite db via the shared harness (`tests/e2e/harness.ts`: + `createTempDb`/`seedUser`/`sessionCookie`), exercising the **real** `JwtAuthGuard` + end-to-end (401 without cookie, 200 with a signed session). Mock external I/O + (HTTP/etc.). See `weather.e2e.test.ts`. + +## Definition of Done (per module) + +Contract in `@trek/shared` → service ported 1:1 → controller with identical routes → +validation/error parity → unit + parity + e2e tests over the gate → prefix toggled to +Nest → parity verified on the demo DB → **then** decommission the old Express +route/service (separate step, after the toggle is confirmed in prod) → frontend points +at the typed contract (Frontend Track). diff --git a/server/src/nest/addons/addons.controller.ts b/server/src/nest/addons/addons.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..b9cf54ffd9ffb6061de5fb6c7cec96e1bb0eb661 --- /dev/null +++ b/server/src/nest/addons/addons.controller.ts @@ -0,0 +1,22 @@ +import { Controller, Get, UseGuards } from '@nestjs/common'; +import { AddonsService } from './addons.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; + +/** + * GET /api/addons — the enabled trip add-ons + photo providers feed. + * Byte-identical to the legacy inline handler in server/src/app.ts + * (authenticate-gated, returns { collabFeatures, addons: [...] }). + * + * Distinct from the addon sub-mounts /api/addons/atlas and /api/addons/vacay + * (their own Nest modules); the strangler routes only the EXACT /api/addons here. + */ +@Controller('api/addons') +@UseGuards(JwtAuthGuard) +export class AddonsController { + constructor(private readonly addons: AddonsService) {} + + @Get() + list() { + return this.addons.list(); + } +} diff --git a/server/src/nest/addons/addons.module.ts b/server/src/nest/addons/addons.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..078c3b52a8189a1a7502ba8824459309414be65f --- /dev/null +++ b/server/src/nest/addons/addons.module.ts @@ -0,0 +1,14 @@ +import { Module } from '@nestjs/common'; +import { AddonsController } from './addons.controller'; +import { AddonsService } from './addons.service'; + +/** + * GET /api/addons — enabled add-ons + photo providers (was an inline handler in + * server/src/app.ts). The addon sub-features (atlas, vacay) keep their own + * modules; this only serves the EXACT /api/addons listing. + */ +@Module({ + controllers: [AddonsController], + providers: [AddonsService], +}) +export class AddonsModule {} diff --git a/server/src/nest/addons/addons.service.ts b/server/src/nest/addons/addons.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..32a94a5f586de1be0e2e2b43258ca22fb959cf67 --- /dev/null +++ b/server/src/nest/addons/addons.service.ts @@ -0,0 +1,82 @@ +import { Injectable } from '@nestjs/common'; +import { db } from '../../db/database'; +import type { Addon } from '../../types'; +import { getBagTracking, getCollabFeatures } from '../../services/adminService'; +import { getPhotoProviderConfig } from '../../services/memories/helpersService'; + +/** + * Thin wrapper around the enabled-addons + photo-provider read that the legacy + * inline `GET /api/addons` handler performed (server/src/app.ts). The SQL, + * ordering, boolean coercions and the merged photo-provider entries are + * reproduced 1:1 so the body is byte-identical for the client. + */ +@Injectable() +export class AddonsService { + list() { + const addons = db + .prepare('SELECT id, name, type, icon, enabled FROM addons WHERE enabled = 1 ORDER BY sort_order') + .all() as Pick[]; + const providers = db + .prepare( + `SELECT id, name, icon, enabled, sort_order + FROM photo_providers + WHERE enabled = 1 + ORDER BY sort_order, id`, + ) + .all() as Array<{ id: string; name: string; icon: string; enabled: number; sort_order: number }>; + const fields = db + .prepare( + `SELECT provider_id, field_key, label, input_type, placeholder, hint, required, secret, settings_key, payload_key, sort_order + FROM photo_provider_fields + ORDER BY sort_order, id`, + ) + .all() as Array<{ + provider_id: string; + field_key: string; + label: string; + input_type: string; + placeholder?: string | null; + hint?: string | null; + required: number; + secret: number; + settings_key?: string | null; + payload_key?: string | null; + sort_order: number; + }>; + + const fieldsByProvider = new Map(); + for (const field of fields) { + const arr = fieldsByProvider.get(field.provider_id) || []; + arr.push(field); + fieldsByProvider.set(field.provider_id, arr); + } + + return { + collabFeatures: getCollabFeatures(), + bagTracking: getBagTracking().enabled, + addons: [ + ...addons.map((a) => ({ ...a, enabled: !!a.enabled })), + ...providers.map((p) => ({ + id: p.id, + name: p.name, + type: 'photo_provider', + icon: p.icon, + enabled: !!p.enabled, + config: getPhotoProviderConfig(p.id), + fields: (fieldsByProvider.get(p.id) || []).map((f) => ({ + key: f.field_key, + label: f.label, + input_type: f.input_type, + placeholder: f.placeholder || '', + hint: f.hint || null, + required: !!f.required, + secret: !!f.secret, + settings_key: f.settings_key || null, + payload_key: f.payload_key || null, + sort_order: f.sort_order, + })), + })), + ], + }; + } +} diff --git a/server/src/nest/admin/admin.controller.ts b/server/src/nest/admin/admin.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..340e165d0dc54318a056ca476e4b332b023ca32e --- /dev/null +++ b/server/src/nest/admin/admin.controller.ts @@ -0,0 +1,346 @@ +import { Body, Controller, Delete, Get, HttpCode, HttpException, NotFoundException, Param, Post, Put, Query, Req, UseGuards } from '@nestjs/common'; +import type { Request } from 'express'; +import { AdminService } from './admin.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { AdminGuard } from '../auth/admin.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; +import { writeAudit, getClientIp, logInfo } from '../../services/auditLog'; +import { send as sendNotification } from '../../services/notificationService'; +import type { User } from '../../types'; + +/** Throw the legacy {error,status} envelope when a service call reports failure. */ +function ok(result: T): Exclude { + if (result && typeof result === 'object' && 'error' in (result as Record)) { + const r = result as unknown as { error: string; status?: number }; + throw new HttpException({ error: r.error }, r.status ?? 400); + } + return result as Exclude; +} + +/** + * /api/admin — admin-only control surface (users, stats, permissions, audit log, + * OIDC settings, invites, feature toggles, packing templates, addons, MCP/OAuth + * sessions, JWT rotation, default user settings). + * + * Byte-identical to the legacy Express route (server/src/routes/admin.ts): + * admin-gated, the {error,status} envelopes, the audit-log writes, the MCP + * session invalidation on addon/collab changes, create-201 vs the rest 200, and + * the dev-only test-notification endpoint (404 outside development). + */ +@Controller('api/admin') +@UseGuards(JwtAuthGuard, AdminGuard) +export class AdminController { + constructor(private readonly admin: AdminService) {} + + // ── Users ── + @Get('users') + listUsers() { return { users: this.admin.listUsers() }; } + + @Post('users') + @HttpCode(201) + createUser(@CurrentUser() user: User, @Body() body: unknown, @Req() req: Request) { + const result = ok(this.admin.createUser(body)); + writeAudit({ userId: user.id, action: 'admin.user_create', resource: String(result.insertedId), ip: getClientIp(req), details: result.auditDetails }); + return { user: result.user }; + } + + @Put('users/:id') + updateUser(@CurrentUser() user: User, @Param('id') id: string, @Body() body: unknown, @Req() req: Request) { + const result = ok(this.admin.updateUser(id, body)); + writeAudit({ userId: user.id, action: 'admin.user_update', resource: String(id), ip: getClientIp(req), details: { targetUser: result.previousEmail, fields: result.changed } }); + logInfo(`Admin ${user.email} edited user ${result.previousEmail} (fields: ${result.changed.join(', ')})`); + return { user: result.user }; + } + + @Delete('users/:id') + deleteUser(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) { + const result = ok(this.admin.deleteUser(id, user.id)); + writeAudit({ userId: user.id, action: 'admin.user_delete', resource: String(id), ip: getClientIp(req), details: { targetUser: result.email } }); + logInfo(`Admin ${user.email} deleted user ${result.email}`); + return { success: true }; + } + + @Delete('users/:id/passkeys') + resetUserPasskeys(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) { + const result = ok(this.admin.resetUserPasskeys(id)); + writeAudit({ userId: user.id, action: 'admin.user_passkeys_reset', resource: String(id), ip: getClientIp(req), details: { targetUser: result.email, deleted: result.deleted } }); + return { success: true, deleted: result.deleted }; + } + + // ── Stats / permissions / audit ── + @Get('stats') + stats() { return this.admin.getStats(); } + + @Get('permissions') + permissions() { return this.admin.getPermissions(); } + + @Put('permissions') + savePermissions(@CurrentUser() user: User, @Body() body: { permissions?: unknown }, @Req() req: Request) { + if (!body.permissions || typeof body.permissions !== 'object') { + throw new HttpException({ error: 'permissions object required' }, 400); + } + const result = this.admin.savePermissions(body.permissions as unknown as Parameters[0]); + writeAudit({ userId: user.id, action: 'admin.permissions_update', resource: 'permissions', ip: getClientIp(req), details: body.permissions as Record }); + return { success: true, permissions: result.permissions, ...(result.skipped.length ? { skipped: result.skipped } : {}) }; + } + + @Get('audit-log') + auditLog(@Query() query: { limit?: string; offset?: string }) { return this.admin.getAuditLog(query); } + + // ── OIDC ── + @Get('oidc') + getOidc() { return this.admin.getOidcSettings(); } + + @Put('oidc') + updateOidc(@CurrentUser() user: User, @Body() body: { issuer?: string } & Record, @Req() req: Request) { + const result = this.admin.updateOidcSettings(body); + if (result.error) { + throw new HttpException({ error: result.error }, result.status || 400); + } + writeAudit({ userId: user.id, action: 'admin.oidc_update', ip: getClientIp(req), details: { issuer_set: !!body.issuer } }); + return { success: true }; + } + + @Post('save-demo-baseline') + @HttpCode(200) + saveDemoBaseline(@CurrentUser() user: User, @Req() req: Request) { + const result = this.admin.saveDemoBaseline(); + if (result.error) { + throw new HttpException({ error: result.error }, result.status!); + } + writeAudit({ userId: user.id, action: 'admin.demo_baseline_save', ip: getClientIp(req) }); + return { success: true, message: result.message }; + } + + // ── GitHub / version ── + @Get('github-releases') + async githubReleases(@Query('per_page') perPage = '10', @Query('page') page = '1') { + return this.admin.getGithubReleases(String(perPage), String(page)); + } + + @Get('version-check') + async versionCheck() { return this.admin.checkVersion(); } + + // ── Admin notification preferences ── + @Get('notification-preferences') + getNotificationPrefs(@CurrentUser() user: User) { return this.admin.getPreferencesMatrix(user.id, user.role); } + + @Put('notification-preferences') + setNotificationPrefs(@CurrentUser() user: User, @Body() body: unknown) { + this.admin.setAdminPreferences(user.id, body); + return this.admin.getPreferencesMatrix(user.id, user.role); + } + + // ── Invites ── + @Get('invites') + listInvites() { return { invites: this.admin.listInvites() }; } + + @Post('invites') + @HttpCode(201) + createInvite(@CurrentUser() user: User, @Body() body: unknown, @Req() req: Request) { + const result = this.admin.createInvite(user.id, body); + writeAudit({ userId: user.id, action: 'admin.invite_create', resource: String(result.inviteId), ip: getClientIp(req), details: { max_uses: result.uses, expires_in_days: result.expiresInDays } }); + return { invite: result.invite }; + } + + @Delete('invites/:id') + deleteInvite(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) { + ok(this.admin.deleteInvite(id)); + writeAudit({ userId: user.id, action: 'admin.invite_delete', resource: String(id), ip: getClientIp(req) }); + return { success: true }; + } + + // ── Feature toggles ── + @Get('bag-tracking') + getBagTracking() { return this.admin.getBagTracking(); } + + @Put('bag-tracking') + updateBagTracking(@CurrentUser() user: User, @Body() body: { enabled?: unknown }, @Req() req: Request) { + const result = this.admin.updateBagTracking(body.enabled); + writeAudit({ userId: user.id, action: 'admin.bag_tracking', ip: getClientIp(req), details: { enabled: result.enabled } }); + return result; + } + + @Get('places-photos') + getPlacesPhotos() { return this.admin.getPlacesPhotos(); } + + @Put('places-photos') + updatePlacesPhotos(@CurrentUser() user: User, @Body() body: { enabled?: unknown }, @Req() req: Request) { + if (typeof body.enabled !== 'boolean') throw new HttpException({ error: 'enabled must be a boolean' }, 400); + const result = this.admin.updatePlacesPhotos(body.enabled); + writeAudit({ userId: user.id, action: 'admin.places_photos', ip: getClientIp(req), details: { enabled: result.enabled } }); + return result; + } + + @Get('places-autocomplete') + getPlacesAutocomplete() { return this.admin.getPlacesAutocomplete(); } + + @Put('places-autocomplete') + updatePlacesAutocomplete(@CurrentUser() user: User, @Body() body: { enabled?: unknown }, @Req() req: Request) { + if (typeof body.enabled !== 'boolean') throw new HttpException({ error: 'enabled must be a boolean' }, 400); + const result = this.admin.updatePlacesAutocomplete(body.enabled); + writeAudit({ userId: user.id, action: 'admin.places_autocomplete', ip: getClientIp(req), details: { enabled: result.enabled } }); + return result; + } + + @Get('places-details') + getPlacesDetails() { return this.admin.getPlacesDetails(); } + + @Put('places-details') + updatePlacesDetails(@CurrentUser() user: User, @Body() body: { enabled?: unknown }, @Req() req: Request) { + if (typeof body.enabled !== 'boolean') throw new HttpException({ error: 'enabled must be a boolean' }, 400); + const result = this.admin.updatePlacesDetails(body.enabled); + writeAudit({ userId: user.id, action: 'admin.places_details', ip: getClientIp(req), details: { enabled: result.enabled } }); + return result; + } + + @Get('collab-features') + getCollabFeatures() { return this.admin.getCollabFeatures(); } + + @Put('collab-features') + updateCollabFeatures(@CurrentUser() user: User, @Body() body: unknown, @Req() req: Request) { + const result = this.admin.updateCollabFeatures(body); + this.admin.invalidateMcpSessions(); + writeAudit({ userId: user.id, action: 'admin.collab_features', ip: getClientIp(req), details: result }); + return result; + } + + // ── Packing templates ── + @Get('packing-templates') + listPackingTemplates() { return { templates: this.admin.listPackingTemplates() }; } + + @Get('packing-templates/:id') + getPackingTemplate(@Param('id') id: string) { return ok(this.admin.getPackingTemplate(id)); } + + @Post('packing-templates') + @HttpCode(201) + createPackingTemplate(@CurrentUser() user: User, @Body() body: { name?: unknown }) { + return ok(this.admin.createPackingTemplate(body.name, user.id)); + } + + @Put('packing-templates/:id') + updatePackingTemplate(@Param('id') id: string, @Body() body: unknown) { return ok(this.admin.updatePackingTemplate(id, body)); } + + @Delete('packing-templates/:id') + deletePackingTemplate(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) { + const result = ok(this.admin.deletePackingTemplate(id)); + writeAudit({ userId: user.id, action: 'admin.packing_template_delete', resource: String(id), ip: getClientIp(req), details: { name: result.name } }); + return { success: true }; + } + + @Post('packing-templates/:id/categories') + @HttpCode(201) + createTemplateCategory(@Param('id') id: string, @Body() body: { name?: unknown }) { + return ok(this.admin.createTemplateCategory(id, body.name)); + } + + @Put('packing-templates/:templateId/categories/:catId') + updateTemplateCategory(@Param('templateId') templateId: string, @Param('catId') catId: string, @Body() body: unknown) { + return ok(this.admin.updateTemplateCategory(templateId, catId, body)); + } + + @Delete('packing-templates/:templateId/categories/:catId') + deleteTemplateCategory(@Param('templateId') templateId: string, @Param('catId') catId: string) { + ok(this.admin.deleteTemplateCategory(templateId, catId)); + return { success: true }; + } + + @Post('packing-templates/:templateId/categories/:catId/items') + @HttpCode(201) + createTemplateItem(@Param('templateId') templateId: string, @Param('catId') catId: string, @Body() body: { name?: unknown }) { + return ok(this.admin.createTemplateItem(templateId, catId, body.name)); + } + + @Put('packing-templates/:templateId/items/:itemId') + updateTemplateItem(@Param('itemId') itemId: string, @Body() body: unknown) { return ok(this.admin.updateTemplateItem(itemId, body)); } + + @Delete('packing-templates/:templateId/items/:itemId') + deleteTemplateItem(@Param('itemId') itemId: string) { + ok(this.admin.deleteTemplateItem(itemId)); + return { success: true }; + } + + // ── Addons ── + @Get('addons') + listAddons() { return { addons: this.admin.listAddons() }; } + + @Put('addons/:id') + updateAddon(@CurrentUser() user: User, @Param('id') id: string, @Body() body: unknown, @Req() req: Request) { + const result = ok(this.admin.updateAddon(id, body)); + writeAudit({ userId: user.id, action: 'admin.addon_update', resource: String(id), ip: getClientIp(req), details: result.auditDetails }); + this.admin.invalidateMcpSessions(); + return { addon: result.addon }; + } + + // ── MCP tokens / OAuth sessions ── + @Get('mcp-tokens') + listMcpTokens() { return { tokens: this.admin.listMcpTokens() }; } + + @Delete('mcp-tokens/:id') + deleteMcpToken(@Param('id') id: string) { + ok(this.admin.deleteMcpToken(id)); + return { success: true }; + } + + @Get('oauth-sessions') + listOAuthSessions() { return { sessions: this.admin.listOAuthSessions() }; } + + @Delete('oauth-sessions/:id') + revokeOAuthSession(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) { + ok(this.admin.revokeOAuthSession(id)); + writeAudit({ userId: user.id, action: 'admin.oauth_session.revoke', resource: String(id), ip: getClientIp(req) }); + return { success: true }; + } + + // ── JWT rotation ── + @Post('rotate-jwt-secret') + @HttpCode(200) + rotateJwtSecret(@CurrentUser() user: User, @Req() req: Request) { + const result = this.admin.rotateJwtSecret(); + if (result.error) { + throw new HttpException({ error: result.error }, result.status!); + } + writeAudit({ userId: user.id, action: 'admin.rotate_jwt_secret', ip: getClientIp(req) }); + return { success: true }; + } + + // ── Default user settings ── + @Get('default-user-settings') + getDefaultUserSettings() { return this.admin.getAdminUserDefaults(); } + + @Put('default-user-settings') + setDefaultUserSettings(@CurrentUser() user: User, @Body() body: unknown, @Req() req: Request) { + if (!body || typeof body !== 'object' || Array.isArray(body)) { + throw new HttpException({ error: 'Object body required' }, 400); + } + try { + this.admin.setAdminUserDefaults(body as unknown as Record); + writeAudit({ userId: user.id, action: 'admin.default_user_settings_update', ip: getClientIp(req), details: body as Record }); + return this.admin.getAdminUserDefaults(); + } catch (err) { + throw new HttpException({ error: err instanceof Error ? err.message : String(err) }, 400); + } + } + + // ── Dev-only: test notification (404 outside development, mirroring the conditional mount) ── + @Post('dev/test-notification') + @HttpCode(200) + async devTestNotification(@CurrentUser() user: User, @Body() body: { event?: string; scope?: string; targetId?: number; params?: Record; inApp?: boolean }) { + if (process.env.NODE_ENV?.toLowerCase() !== 'development') { + throw new NotFoundException(); + } + try { + await sendNotification({ + event: body.event ?? 'trip_reminder', + actorId: user.id, + scope: body.scope ?? 'user', + targetId: body.targetId ?? user.id, + params: { actor: user.email, ...(body.params ?? {}) }, + inApp: body.inApp, + } as unknown as Parameters[0]); + return { success: true }; + } catch (err) { + throw new HttpException({ error: err instanceof Error ? err.message : String(err) }, 400); + } + } +} diff --git a/server/src/nest/admin/admin.module.ts b/server/src/nest/admin/admin.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..10aa83bafdd79319957157bf50767d1de668e4c6 --- /dev/null +++ b/server/src/nest/admin/admin.module.ts @@ -0,0 +1,9 @@ +import { Module } from '@nestjs/common'; +import { AdminController } from './admin.controller'; +import { AdminService } from './admin.service'; + +@Module({ + controllers: [AdminController], + providers: [AdminService], +}) +export class AdminModule {} diff --git a/server/src/nest/admin/admin.service.ts b/server/src/nest/admin/admin.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..27340ccbf33ca2fcd81536ae111b1e40f77fa2d6 --- /dev/null +++ b/server/src/nest/admin/admin.service.ts @@ -0,0 +1,81 @@ +import { Injectable } from '@nestjs/common'; +import * as svc from '../../services/adminService'; +import { getAdminUserDefaults, setAdminUserDefaults } from '../../services/settingsService'; +import { invalidateMcpSessions } from '../../mcp'; +import { getPreferencesMatrix, setAdminPreferences } from '../../services/notificationPreferencesService'; +import { adminResetPasskeys } from '../../services/passkeyService'; + +/** + * Thin Nest wrapper around the existing admin service (+ the settings, + * MCP-session and notification-preference helpers the legacy route used). All + * business logic, audit-relevant return shapes and the addon/MCP invalidation + * reuse the legacy code unchanged. + */ +@Injectable() +export class AdminService { + // Users + listUsers() { return svc.listUsers(); } + createUser(body: unknown) { return svc.createUser(body as Parameters[0]); } + updateUser(id: string, body: unknown) { return svc.updateUser(id, body as Parameters[1]); } + deleteUser(id: string, actingUserId: number) { return svc.deleteUser(id, actingUserId); } + resetUserPasskeys(id: string) { return adminResetPasskeys(Number(id)); } + + getStats() { return svc.getStats(); } + getPermissions() { return svc.getPermissions(); } + savePermissions(permissions: Parameters[0]) { return svc.savePermissions(permissions); } + getAuditLog(query: { limit?: string; offset?: string }) { return svc.getAuditLog(query); } + + getOidcSettings() { return svc.getOidcSettings(); } + updateOidcSettings(body: unknown) { return svc.updateOidcSettings(body as Parameters[0]); } + saveDemoBaseline() { return svc.saveDemoBaseline(); } + + getGithubReleases(perPage: string, page: string) { return svc.getGithubReleases(perPage, page); } + checkVersion() { return svc.checkVersion(); } + + // Invites + listInvites() { return svc.listInvites(); } + createInvite(userId: number, body: unknown) { return svc.createInvite(userId, body as Parameters[1]); } + deleteInvite(id: string) { return svc.deleteInvite(id); } + + // Feature toggles + getBagTracking() { return svc.getBagTracking(); } + updateBagTracking(enabled: unknown) { return svc.updateBagTracking(enabled as boolean); } + getPlacesPhotos() { return svc.getPlacesPhotos(); } + updatePlacesPhotos(enabled: boolean) { return svc.updatePlacesPhotos(enabled); } + getPlacesAutocomplete() { return svc.getPlacesAutocomplete(); } + updatePlacesAutocomplete(enabled: boolean) { return svc.updatePlacesAutocomplete(enabled); } + getPlacesDetails() { return svc.getPlacesDetails(); } + updatePlacesDetails(enabled: boolean) { return svc.updatePlacesDetails(enabled); } + getCollabFeatures() { return svc.getCollabFeatures(); } + updateCollabFeatures(body: unknown) { return svc.updateCollabFeatures(body as Parameters[0]); } + + // Packing templates + listPackingTemplates() { return svc.listPackingTemplates(); } + getPackingTemplate(id: string) { return svc.getPackingTemplate(id); } + createPackingTemplate(name: unknown, userId: number) { return svc.createPackingTemplate(name as string, userId); } + updatePackingTemplate(id: string, body: unknown) { return svc.updatePackingTemplate(id, body as Parameters[1]); } + deletePackingTemplate(id: string) { return svc.deletePackingTemplate(id); } + createTemplateCategory(templateId: string, name: unknown) { return svc.createTemplateCategory(templateId, name as string); } + updateTemplateCategory(templateId: string, catId: string, body: unknown) { return svc.updateTemplateCategory(templateId, catId, body as Parameters[2]); } + deleteTemplateCategory(templateId: string, catId: string) { return svc.deleteTemplateCategory(templateId, catId); } + createTemplateItem(templateId: string, catId: string, name: unknown) { return svc.createTemplateItem(templateId, catId, name as string); } + updateTemplateItem(itemId: string, body: unknown) { return svc.updateTemplateItem(itemId, body as Parameters[1]); } + deleteTemplateItem(itemId: string) { return svc.deleteTemplateItem(itemId); } + + // Addons + tokens + sessions + listAddons() { return svc.listAddons(); } + updateAddon(id: string, body: unknown) { return svc.updateAddon(id, body as Parameters[1]); } + listMcpTokens() { return svc.listMcpTokens(); } + deleteMcpToken(id: string) { return svc.deleteMcpToken(id); } + listOAuthSessions() { return svc.listOAuthSessions(); } + revokeOAuthSession(id: string) { return svc.revokeOAuthSession(id); } + rotateJwtSecret() { return svc.rotateJwtSecret(); } + + invalidateMcpSessions() { invalidateMcpSessions(); } + + // Settings + notification preference helpers (non-admin-service modules) + getAdminUserDefaults() { return getAdminUserDefaults(); } + setAdminUserDefaults(body: Record) { return setAdminUserDefaults(body); } + getPreferencesMatrix(userId: number, role: string) { return getPreferencesMatrix(userId, role, 'admin'); } + setAdminPreferences(userId: number, body: unknown) { return setAdminPreferences(userId, body as Parameters[1]); } +} diff --git a/server/src/nest/airports/airports.controller.ts b/server/src/nest/airports/airports.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..8ac3f463a51f896fffb96c71aec92b51a27b0d91 --- /dev/null +++ b/server/src/nest/airports/airports.controller.ts @@ -0,0 +1,38 @@ +import { Controller, Get, HttpException, Param, Query, UseGuards } from '@nestjs/common'; +import type { Airport } from '@trek/shared'; +import { AirportsService } from './airports.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; + +/** + * /api/airports — typeahead search + single lookup by IATA code. + * + * Behaviour is byte-identical to the legacy Express route (server/src/routes/ + * airports.ts): both endpoints require auth, an absent/non-string query answers + * with `[]` (not a 400), and an unknown IATA code 404s with the exact + * `{ error: 'Airport not found' }` body. + * + * The `search` route is declared before `:iata` so the static segment wins over + * the param, matching the legacy router's registration order. + */ +@Controller('api/airports') +@UseGuards(JwtAuthGuard) +export class AirportsController { + constructor(private readonly airports: AirportsService) {} + + @Get('search') + search(@Query('q') q?: string | string[]): Airport[] { + // Express coerces a missing/array query to '' and returns [] for it. + const term = typeof q === 'string' ? q : ''; + if (!term) return []; + return this.airports.search(term); + } + + @Get(':iata') + findByIata(@Param('iata') iata: string): Airport { + const airport = this.airports.findByIata(iata); + if (!airport) { + throw new HttpException({ error: 'Airport not found' }, 404); + } + return airport; + } +} diff --git a/server/src/nest/airports/airports.module.ts b/server/src/nest/airports/airports.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..ca7f7279739432c5cfb7700f04d3cd24c938881c --- /dev/null +++ b/server/src/nest/airports/airports.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { AirportsController } from './airports.controller'; +import { AirportsService } from './airports.service'; + +/** Airports domain (L2 leaf module). Registered in AppModule. */ +@Module({ + controllers: [AirportsController], + providers: [AirportsService], +}) +export class AirportsModule {} diff --git a/server/src/nest/airports/airports.service.ts b/server/src/nest/airports/airports.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..934e2e21449882d267f3f93517dd87310761a835 --- /dev/null +++ b/server/src/nest/airports/airports.service.ts @@ -0,0 +1,19 @@ +import { Injectable } from '@nestjs/common'; +import type { Airport } from '@trek/shared'; +import { searchAirports, findByIata } from '../../services/airportService'; + +/** + * Thin Nest wrapper around the existing airport service. It delegates to the + * same `searchAirports` / `findByIata` functions the legacy route uses, so the + * in-memory dataset and lookup behaviour stay identical and unduplicated. + */ +@Injectable() +export class AirportsService { + search(query: string): Airport[] { + return searchAirports(query) as Airport[]; + } + + findByIata(code: string): Airport | null { + return findByIata(code) as Airport | null; + } +} diff --git a/server/src/nest/app.module.ts b/server/src/nest/app.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c1f75019ec07ce4938471e1b36e16fc0e7a8607 --- /dev/null +++ b/server/src/nest/app.module.ts @@ -0,0 +1,65 @@ +import { Module } from '@nestjs/common'; +import { APP_FILTER, APP_INTERCEPTOR } from '@nestjs/core'; +import { DatabaseModule } from './database/database.module'; +import { HealthController } from './health/health.controller'; +import { HealthService } from './health/health.service'; +import { WeatherModule } from './weather/weather.module'; +import { AirportsModule } from './airports/airports.module'; +import { ConfigModule } from './config/config.module'; +import { SystemNoticesModule } from './system-notices/system-notices.module'; +import { MapsModule } from './maps/maps.module'; +import { CategoriesModule } from './categories/categories.module'; +import { TagsModule } from './tags/tags.module'; +import { NotificationsModule } from './notifications/notifications.module'; +import { AtlasModule } from './atlas/atlas.module'; +import { VacayModule } from './vacay/vacay.module'; +import { PackingModule } from './packing/packing.module'; +import { BudgetModule } from './budget/budget.module'; +import { ReservationsModule } from './reservations/reservations.module'; +import { DaysModule } from './days/days.module'; +import { AssignmentsModule } from './assignments/assignments.module'; +import { PlacesModule } from './places/places.module'; +import { TripsModule } from './trips/trips.module'; +import { TodoModule } from './todo/todo.module'; +import { CollabModule } from './collab/collab.module'; +import { FilesModule } from './files/files.module'; +import { PhotosModule } from './photos/photos.module'; +import { MemoriesModule } from './memories/memories.module'; +import { AirtrailModule } from './integrations/airtrail.module'; +import { JourneyModule } from './journey/journey.module'; +import { ShareModule } from './share/share.module'; +import { SettingsModule } from './settings/settings.module'; +import { BackupModule } from './backup/backup.module'; +import { BookingImportModule } from './booking-import/booking-import.module'; +import { AuthModule } from './auth/auth.module'; +import { OidcModule } from './oidc/oidc.module'; +import { OauthModule } from './oauth/oauth.module'; +import { AdminModule } from './admin/admin.module'; +import { AddonsModule } from './addons/addons.module'; +import { TrekExceptionFilter } from './common/trek-exception.filter'; +import { SpaFallbackFilter } from './platform/spa-fallback.filter'; +import { IdempotencyInterceptor } from './common/idempotency.interceptor'; + +/** + * Root NestJS module for the incremental migration. Domain modules + * (weather, notifications, integrations, ...) get registered here as they are + * migrated. + */ +@Module({ + imports: [DatabaseModule, WeatherModule, AirportsModule, ConfigModule, SystemNoticesModule, MapsModule, CategoriesModule, TagsModule, NotificationsModule, AtlasModule, VacayModule, PackingModule, TodoModule, BudgetModule, ReservationsModule, DaysModule, AssignmentsModule, PlacesModule, TripsModule, CollabModule, FilesModule, PhotosModule, MemoriesModule, AirtrailModule, JourneyModule, ShareModule, SettingsModule, BackupModule, AuthModule, OidcModule, OauthModule, AdminModule, AddonsModule, BookingImportModule], + controllers: [HealthController], + providers: [ + HealthService, + // Global error-envelope normaliser (DI-registered so it also catches + // framework-level exceptions like the not-found handler). + { provide: APP_FILTER, useClass: TrekExceptionFilter }, + // SPA fallback: serves index.html for unmatched GETs in production (the Nest + // equivalent of the legacy Express app.get('*') catch-all). @Catch(NotFoundException) + // is more specific than TrekExceptionFilter, so Nest routes 404s here. + { provide: APP_FILTER, useClass: SpaFallbackFilter }, + // Replays the X-Idempotency-Key the client sends on every write, matching + // the legacy applyIdempotency middleware so retried mutations don't double-apply. + { provide: APP_INTERCEPTOR, useClass: IdempotencyInterceptor }, + ], +}) +export class AppModule {} diff --git a/server/src/nest/assignments/assignments.controller.ts b/server/src/nest/assignments/assignments.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..032a3fab418f64b9743c6c15e2a56ec3595668a1 --- /dev/null +++ b/server/src/nest/assignments/assignments.controller.ts @@ -0,0 +1,189 @@ +import { + Body, + Controller, + Delete, + Get, + Headers, + HttpException, + Param, + Post, + Put, + UseGuards, +} from '@nestjs/common'; +import type { User } from '../../types'; +import { AssignmentsService } from './assignments.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; + +type Trip = NonNullable>; + +/** Shared trip-access guard (mirrors requireTripAccess → 404 "Trip not found"). */ +function requireTrip(svc: AssignmentsService, tripId: string, user: User): Trip { + const trip = svc.verifyTripAccess(tripId, user.id); + if (!trip) { + throw new HttpException({ error: 'Trip not found' }, 404); + } + return trip; +} + +function requireEdit(svc: AssignmentsService, trip: Trip, user: User): void { + if (!svc.canEdit(trip, user)) { + throw new HttpException({ error: 'No permission' }, 403); + } +} + +/** + * /api/trips/:tripId/days/:dayId/assignments — the day's ordered itinerary items. + * + * Byte-identical to the legacy Express route (server/src/routes/assignments.ts): + * trip access (404), 'day_edit' on mutations (403, GET is access-only), create + * 201 / rest 200, the bespoke "Day not found" / "Place not found" / "Assignment + * not found" bodies, the journey place-created hook, and WebSocket broadcasts. + */ +@Controller('api/trips/:tripId/days/:dayId/assignments') +@UseGuards(JwtAuthGuard) +export class DayAssignmentsController { + constructor(private readonly assignments: AssignmentsService) {} + + @Get() + list(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('dayId') dayId: string) { + requireTrip(this.assignments, tripId, user); + if (!this.assignments.dayExists(dayId, tripId)) { + throw new HttpException({ error: 'Day not found' }, 404); + } + return { assignments: this.assignments.listDayAssignments(dayId) }; + } + + @Post() + create( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('dayId') dayId: string, + @Body() body: { place_id?: unknown; notes?: string | null }, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = requireTrip(this.assignments, tripId, user); + requireEdit(this.assignments, trip, user); + if (!this.assignments.dayExists(dayId, tripId)) { + throw new HttpException({ error: 'Day not found' }, 404); + } + if (!this.assignments.placeExists(body.place_id, tripId)) { + throw new HttpException({ error: 'Place not found' }, 404); + } + const assignment = this.assignments.createAssignment(dayId, body.place_id, body.notes); + this.assignments.broadcast(tripId, 'assignment:created', { assignment }, socketId); + this.assignments.notifyPlaceCreated(tripId, body.place_id); + return { assignment }; + } + + @Put('reorder') + reorder( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('dayId') dayId: string, + @Body('orderedIds') orderedIds: number[], + @Headers('x-socket-id') socketId?: string, + ) { + const trip = requireTrip(this.assignments, tripId, user); + requireEdit(this.assignments, trip, user); + if (!this.assignments.dayExists(dayId, tripId)) { + throw new HttpException({ error: 'Day not found' }, 404); + } + this.assignments.reorderAssignments(dayId, orderedIds); + this.assignments.broadcast(tripId, 'assignment:reordered', { dayId: Number(dayId), orderedIds }, socketId); + return { success: true }; + } + + @Delete(':id') + remove( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('dayId') dayId: string, + @Param('id') id: string, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = requireTrip(this.assignments, tripId, user); + requireEdit(this.assignments, trip, user); + if (!this.assignments.assignmentExistsInDay(id, dayId, tripId)) { + throw new HttpException({ error: 'Assignment not found' }, 404); + } + this.assignments.deleteAssignment(id); + this.assignments.broadcast(tripId, 'assignment:deleted', { assignmentId: Number(id), dayId: Number(dayId) }, socketId); + return { success: true }; + } +} + +/** + * /api/trips/:tripId/assignments/:id/* — per-assignment ops (move, time, + * participants), independent of the day path. Same parity rules as above. + */ +@Controller('api/trips/:tripId/assignments') +@UseGuards(JwtAuthGuard) +export class AssignmentOpsController { + constructor(private readonly assignments: AssignmentsService) {} + + @Put(':id/move') + move( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('id') id: string, + @Body() body: { new_day_id?: unknown; order_index?: number }, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = requireTrip(this.assignments, tripId, user); + requireEdit(this.assignments, trip, user); + const existing = this.assignments.getAssignmentForTrip(id, tripId); + if (!existing) { + throw new HttpException({ error: 'Assignment not found' }, 404); + } + if (!this.assignments.dayExists(String(body.new_day_id), tripId)) { + throw new HttpException({ error: 'Target day not found' }, 404); + } + const oldDayId = (existing as { day_id: number }).day_id; + const { assignment } = this.assignments.moveAssignment(id, body.new_day_id, body.order_index, oldDayId); + this.assignments.broadcast(tripId, 'assignment:moved', { assignment, oldDayId: Number(oldDayId), newDayId: Number(body.new_day_id) }, socketId); + return { assignment }; + } + + @Get(':id/participants') + participants(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string) { + requireTrip(this.assignments, tripId, user); + return { participants: this.assignments.getParticipants(id) }; + } + + @Put(':id/time') + time( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('id') id: string, + @Body() body: { place_time?: string | null; end_time?: string | null }, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = requireTrip(this.assignments, tripId, user); + requireEdit(this.assignments, trip, user); + if (!this.assignments.getAssignmentForTrip(id, tripId)) { + throw new HttpException({ error: 'Assignment not found' }, 404); + } + const assignment = this.assignments.updateTime(id, body.place_time, body.end_time); + this.assignments.broadcast(tripId, 'assignment:updated', { assignment }, socketId); + return { assignment }; + } + + @Put(':id/participants') + setParticipants( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('id') id: string, + @Body('user_ids') userIds: unknown, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = requireTrip(this.assignments, tripId, user); + requireEdit(this.assignments, trip, user); + if (!Array.isArray(userIds)) { + throw new HttpException({ error: 'user_ids must be an array' }, 400); + } + const participants = this.assignments.setParticipants(id, userIds); + this.assignments.broadcast(tripId, 'assignment:participants', { assignmentId: Number(id), participants }, socketId); + return { participants }; + } +} diff --git a/server/src/nest/assignments/assignments.module.ts b/server/src/nest/assignments/assignments.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..908a12836cd8782d0ba28e593517e690bd22d43a --- /dev/null +++ b/server/src/nest/assignments/assignments.module.ts @@ -0,0 +1,14 @@ +import { Module } from '@nestjs/common'; +import { DayAssignmentsController, AssignmentOpsController } from './assignments.controller'; +import { AssignmentsService } from './assignments.service'; + +/** + * Assignments domain (S7 — Phase 2 trip sub-domain). The day-assignments mount + * sits under the /api/trips/:tripId/days prefix (S6); the per-assignment ops use + * the /api/trips/:tripId/assignments prefix. + */ +@Module({ + controllers: [DayAssignmentsController, AssignmentOpsController], + providers: [AssignmentsService], +}) +export class AssignmentsModule {} diff --git a/server/src/nest/assignments/assignments.service.ts b/server/src/nest/assignments/assignments.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..35fde3e1ed9a49c44308c255f38821a1dd159097 --- /dev/null +++ b/server/src/nest/assignments/assignments.service.ts @@ -0,0 +1,83 @@ +import { Injectable } from '@nestjs/common'; +import { broadcast } from '../../websocket'; +import { canAccessTrip } from '../../db/database'; +import { checkPermission } from '../../services/permissions'; +import type { User } from '../../types'; +import * as svc from '../../services/assignmentService'; +import { onPlaceCreated } from '../../services/journeyService'; + +type Trip = { user_id: number }; + +/** + * Thin Nest wrapper around the existing assignment service. Trip access mirrors + * the requireTripAccess middleware (canAccessTrip); mutations use 'day_edit'. + * The SQL, the move/reorder logic and the journey "place created" hook reuse the + * legacy code unchanged. + */ +@Injectable() +export class AssignmentsService { + verifyTripAccess(tripId: string, userId: number) { + return canAccessTrip(Number(tripId), userId) as Trip | null | undefined; + } + + canEdit(trip: Trip, user: User): boolean { + return checkPermission('day_edit', user.role, trip.user_id, user.id, trip.user_id !== user.id); + } + + broadcast(tripId: string, event: string, payload: Record, socketId: string | undefined): void { + broadcast(tripId, event, payload, socketId); + } + + dayExists(dayId: string, tripId: string) { + return svc.dayExists(dayId, tripId); + } + + placeExists(placeId: unknown, tripId: string) { + return svc.placeExists(placeId as never, tripId); + } + + listDayAssignments(dayId: string) { + return svc.listDayAssignments(dayId); + } + + createAssignment(dayId: string, placeId: unknown, notes?: string | null) { + return svc.createAssignment(dayId, placeId as never, notes as never); + } + + /** Mirrors the legacy POST hook; non-fatal, like the route's try/catch. */ + notifyPlaceCreated(tripId: string, placeId: unknown): void { + try { onPlaceCreated(Number(tripId), Number(placeId)); } catch { /* non-fatal */ } + } + + assignmentExistsInDay(id: string, dayId: string, tripId: string) { + return svc.assignmentExistsInDay(id, dayId, tripId); + } + + deleteAssignment(id: string): void { + svc.deleteAssignment(id); + } + + reorderAssignments(dayId: string, orderedIds: number[]): void { + svc.reorderAssignments(dayId, orderedIds as never); + } + + getAssignmentForTrip(id: string, tripId: string) { + return svc.getAssignmentForTrip(id, tripId); + } + + moveAssignment(id: string, newDayId: unknown, orderIndex: number | undefined, oldDayId: unknown) { + return svc.moveAssignment(id, newDayId as never, orderIndex as never, oldDayId as never); + } + + getParticipants(id: string) { + return svc.getParticipants(id); + } + + updateTime(id: string, placeTime: unknown, endTime: unknown) { + return svc.updateTime(id, placeTime as never, endTime as never); + } + + setParticipants(id: string, userIds: number[]) { + return svc.setParticipants(id, userIds); + } +} diff --git a/server/src/nest/atlas/atlas.controller.ts b/server/src/nest/atlas/atlas.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..7b195c2d656e68293155639e5dd7d04b32338e5d --- /dev/null +++ b/server/src/nest/atlas/atlas.controller.ts @@ -0,0 +1,148 @@ +import { + Body, + Controller, + Delete, + Get, + Header, + HttpCode, + HttpException, + Param, + Post, + Put, + Query, + Res, + UseGuards, +} from '@nestjs/common'; +import type { Response } from 'express'; +import type { RegionGeo } from '@trek/shared'; +import type { User } from '../../types'; +import { AtlasService } from './atlas.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; + +/** + * /api/addons/atlas — visited countries/regions, region GeoJSON, bucket list. + * + * Byte-identical to the legacy Express route (server/src/routes/atlas.ts): all + * endpoints require auth; country/region codes are upper-cased; /regions is + * always no-store while /regions/geo is cached for a day only on a non-empty + * result; the mark POSTs answer 200 (not Nest's default 201); and the bespoke + * 400/404 bodies are reproduced exactly. No addon gate — the legacy route has + * none, so adding one would break clients when the addon is off. + */ +@Controller('api/addons/atlas') +@UseGuards(JwtAuthGuard) +export class AtlasController { + constructor(private readonly atlas: AtlasService) {} + + @Get('stats') + stats(@CurrentUser() user: User) { + return this.atlas.stats(user.id); + } + + @Get('regions') + @Header('Cache-Control', 'no-cache, no-store') + regions(@CurrentUser() user: User) { + return this.atlas.visitedRegions(user.id); + } + + @Get('regions/geo') + async regionGeo( + @Query('countries') countries: string | undefined, + @Res({ passthrough: true }) res: Response, + ): Promise { + const list = (countries || '').split(',').filter(Boolean); + if (list.length === 0) { + return { type: 'FeatureCollection', features: [] }; + } + const geo = await this.atlas.regionGeo(list); + // Cache only a non-empty result, matching the legacy route (the empty + // short-circuit above sends no Cache-Control header). + res.setHeader('Cache-Control', 'public, max-age=86400'); + return geo; + } + + @Get('countries/geo') + @Header('Cache-Control', 'public, max-age=86400') + countryGeo(): RegionGeo { + return this.atlas.countryGeo(); + } + + @Get('country/:code') + countryPlaces(@CurrentUser() user: User, @Param('code') code: string) { + return this.atlas.countryPlaces(user.id, code.toUpperCase()); + } + + @Post('country/:code/mark') + @HttpCode(200) + markCountry(@CurrentUser() user: User, @Param('code') code: string): { success: boolean } { + this.atlas.markCountry(user.id, code.toUpperCase()); + return { success: true }; + } + + @Delete('country/:code/mark') + unmarkCountry(@CurrentUser() user: User, @Param('code') code: string): { success: boolean } { + this.atlas.unmarkCountry(user.id, code.toUpperCase()); + return { success: true }; + } + + @Post('region/:code/mark') + @HttpCode(200) + markRegion( + @CurrentUser() user: User, + @Param('code') code: string, + @Body('name') name?: string, + @Body('country_code') countryCode?: string, + ): { success: boolean } { + if (!name || !countryCode) { + throw new HttpException({ error: 'name and country_code are required' }, 400); + } + this.atlas.markRegion(user.id, code.toUpperCase(), name, countryCode.toUpperCase()); + return { success: true }; + } + + @Delete('region/:code/mark') + unmarkRegion(@CurrentUser() user: User, @Param('code') code: string): { success: boolean } { + this.atlas.unmarkRegion(user.id, code.toUpperCase()); + return { success: true }; + } + + @Get('bucket-list') + bucketList(@CurrentUser() user: User) { + return { items: this.atlas.bucketList(user.id) }; + } + + @Post('bucket-list') + createBucketItem( + @CurrentUser() user: User, + @Body() body: { name?: string; lat?: number | null; lng?: number | null; country_code?: string | null; notes?: string | null; target_date?: string | null }, + ): { item: unknown } { + if (!body.name?.trim()) { + throw new HttpException({ error: 'Name is required' }, 400); + } + const { name, lat, lng, country_code, notes, target_date } = body; + return { item: this.atlas.createBucketItem(user.id, { name, lat, lng, country_code, notes, target_date }) }; + } + + @Put('bucket-list/:id') + updateBucketItem( + @CurrentUser() user: User, + @Param('id') id: string, + @Body() body: { name?: string; notes?: string; lat?: number | null; lng?: number | null; country_code?: string | null; target_date?: string | null }, + ): { item: unknown } { + const { name, notes, lat, lng, country_code, target_date } = body; + const item = this.atlas.updateBucketItem(user.id, id, { name, notes, lat, lng, country_code, target_date }); + if (!item) { + throw new HttpException({ error: 'Item not found' }, 404); + } + return { item }; + } + + @Delete('bucket-list/:id') + deleteBucketItem(@CurrentUser() user: User, @Param('id') id: string): { success: boolean } { + if (!this.atlas.deleteBucketItem(user.id, id)) { + throw new HttpException({ error: 'Item not found' }, 404); + } + return { success: true }; + } +} diff --git a/server/src/nest/atlas/atlas.module.ts b/server/src/nest/atlas/atlas.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..8d4844189a0241ea45001f650480cbc6b26f2b75 --- /dev/null +++ b/server/src/nest/atlas/atlas.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { AtlasController } from './atlas.controller'; +import { AtlasService } from './atlas.service'; + +/** Atlas addon domain (L7 leaf module). Registered in AppModule. */ +@Module({ + controllers: [AtlasController], + providers: [AtlasService], +}) +export class AtlasModule {} diff --git a/server/src/nest/atlas/atlas.service.ts b/server/src/nest/atlas/atlas.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..36e56b3a4b32ba116eb497370d51b44b6b691423 --- /dev/null +++ b/server/src/nest/atlas/atlas.service.ts @@ -0,0 +1,80 @@ +import { Injectable } from '@nestjs/common'; +import { + getStats, + getCountryPlaces, + markCountryVisited, + unmarkCountryVisited, + markRegionVisited, + unmarkRegionVisited, + getVisitedRegions, + getRegionGeo, + getCountryGeo, + listBucketList, + createBucketItem, + updateBucketItem, + deleteBucketItem, +} from '../../services/atlasService'; + +type CreateBucketData = Parameters[1]; +type UpdateBucketData = Parameters[2]; + +/** + * Thin Nest wrapper around the existing atlas service. The Admin-1 GeoJSON + * cache, the stats aggregation and the visited-region logic all stay in + * atlasService, so behaviour is unchanged. Returns native service shapes; the + * client-facing contracts live in @trek/shared. + */ +@Injectable() +export class AtlasService { + stats(userId: number) { + return getStats(userId); + } + + visitedRegions(userId: number) { + return getVisitedRegions(userId); + } + + regionGeo(countries: string[]) { + return getRegionGeo(countries); + } + + countryGeo() { + return getCountryGeo(); + } + + countryPlaces(userId: number, code: string) { + return getCountryPlaces(userId, code); + } + + markCountry(userId: number, code: string): void { + markCountryVisited(userId, code); + } + + unmarkCountry(userId: number, code: string): void { + unmarkCountryVisited(userId, code); + } + + markRegion(userId: number, code: string, name: string, countryCode: string): void { + markRegionVisited(userId, code, name, countryCode); + } + + unmarkRegion(userId: number, code: string): void { + unmarkRegionVisited(userId, code); + } + + bucketList(userId: number) { + return listBucketList(userId); + } + + createBucketItem(userId: number, data: CreateBucketData) { + return createBucketItem(userId, data); + } + + updateBucketItem(userId: number, itemId: string, data: UpdateBucketData) { + return updateBucketItem(userId, itemId, data); + } + + deleteBucketItem(userId: number, itemId: string): boolean { + return deleteBucketItem(userId, itemId); + } +} diff --git a/server/src/nest/auth/admin.guard.ts b/server/src/nest/auth/admin.guard.ts new file mode 100644 index 0000000000000000000000000000000000000000..b41d2f7938b83ee737de68662e0dc41f2bf9a45b --- /dev/null +++ b/server/src/nest/auth/admin.guard.ts @@ -0,0 +1,18 @@ +import { CanActivate, ExecutionContext, HttpException, Injectable } from '@nestjs/common'; +import type { Request } from 'express'; + +/** + * Mirrors the legacy `adminOnly` middleware: requires an authenticated admin. + * Use together with JwtAuthGuard (which populates req.user): + * `@UseGuards(JwtAuthGuard, AdminGuard)`. + */ +@Injectable() +export class AdminGuard implements CanActivate { + canActivate(context: ExecutionContext): boolean { + const req = context.switchToHttp().getRequest(); + if (!req.user || req.user.role !== 'admin') { + throw new HttpException({ error: 'Admin access required' }, 403); + } + return true; + } +} diff --git a/server/src/nest/auth/auth-public.controller.ts b/server/src/nest/auth/auth-public.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..eecb531cd4a6c04d74aaeab933bd079083f28b33 --- /dev/null +++ b/server/src/nest/auth/auth-public.controller.ts @@ -0,0 +1,159 @@ +import { Body, Controller, Get, HttpCode, HttpException, Param, Post, Req, Res, UseGuards } from '@nestjs/common'; +import type { Request, Response } from 'express'; +import { AuthService } from './auth.service'; +import { RateLimitService } from './rate-limit.service'; +import { OptionalJwtGuard } from './optional-jwt.guard'; +import { writeAudit, getClientIp } from '../../services/auditLog'; +import type { User } from '../../types'; + +const WINDOW = 15 * 60 * 1000; +const LOGIN_MIN_LATENCY_MS = 350; +const FORGOT_MIN_LATENCY_MS = 350; +const GENERIC_FORGOT_RESPONSE = { ok: true }; + +const delay = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +/** + * Public auth endpoints (no session required) — byte-identical to the legacy + * Express route (server/src/routes/auth.ts): the same per-IP rate-limit buckets + * + limits, the constant-time login/forgot latency padding, the enumeration-safe + * forgot response, the audit writes and the JWT httpOnly cookie set/clear via + * the shared cookie service (no new token shape). + */ +@Controller('api/auth') +export class AuthPublicController { + constructor(private readonly auth: AuthService, private readonly rl: RateLimitService) {} + + private limit(bucket: string, req: Request, max: number): void { + if (!this.rl.check(bucket, req.ip || 'unknown', max, WINDOW, Date.now())) { + throw new HttpException({ error: 'Too many attempts. Please try again later.' }, 429); + } + } + + @Get('app-config') + @UseGuards(OptionalJwtGuard) + appConfig(@Req() req: Request) { + return this.auth.getAppConfig((req.user as User | undefined) ?? undefined); + } + + @Post('demo-login') + @HttpCode(200) + demoLogin(@Req() req: Request, @Res({ passthrough: true }) res: Response) { + const result = this.auth.demoLogin(); + if (result.error) { + throw new HttpException({ error: result.error }, result.status!); + } + this.auth.setAuthCookie(res, result.token!, req); + return { token: result.token, user: result.user }; + } + + @Get('invite/:token') + invite(@Param('token') token: string, @Req() req: Request) { + this.limit('login', req, 10); + const result = this.auth.validateInviteToken(token); + if (result.error) { + throw new HttpException({ error: result.error }, result.status!); + } + return { valid: result.valid, max_uses: result.max_uses, used_count: result.used_count, expires_at: result.expires_at }; + } + + @Post('register') + @HttpCode(201) + register(@Body() body: unknown, @Req() req: Request, @Res({ passthrough: true }) res: Response) { + this.limit('login', req, 10); + const result = this.auth.registerUser(body); + if (result.error) { + throw new HttpException({ error: result.error }, result.status!); + } + writeAudit({ userId: result.auditUserId!, action: 'user.register', ip: getClientIp(req), details: result.auditDetails }); + this.auth.setAuthCookie(res, result.token!, req); + return { token: result.token, user: result.user }; + } + + @Post('login') + @HttpCode(200) + async login(@Body() body: unknown, @Req() req: Request, @Res({ passthrough: true }) res: Response) { + this.limit('login', req, 10); + const started = Date.now(); + const result = this.auth.loginUser(body); + if (result.auditAction) { + writeAudit({ userId: result.auditUserId ?? null, action: result.auditAction, ip: getClientIp(req), details: result.auditDetails }); + } + const elapsed = Date.now() - started; + if (elapsed < LOGIN_MIN_LATENCY_MS) await delay(LOGIN_MIN_LATENCY_MS - elapsed); + if (result.error) { + throw new HttpException({ error: result.error }, result.status!); + } + if (result.mfa_required) { + return { mfa_required: true, mfa_token: result.mfa_token }; + } + this.auth.setAuthCookie(res, result.token!, req, result.remember); + return { token: result.token, user: result.user }; + } + + @Post('forgot-password') + @HttpCode(200) + async forgotPassword(@Body() body: { email?: unknown }, @Req() req: Request) { + this.limit('forgot', req, 3); + const started = Date.now(); + const rawEmail = typeof body?.email === 'string' ? body.email : ''; + const ip = getClientIp(req); + + const outcome = this.auth.requestPasswordReset(rawEmail, ip); + if (outcome.reason === 'issued' && outcome.tokenForDelivery && outcome.userEmail) { + const origin = this.auth.getAppUrl(); + const url = `${origin.replace(/\/$/, '')}/reset-password?token=${encodeURIComponent(outcome.tokenForDelivery)}`; + writeAudit({ userId: outcome.userId, action: 'user.password_reset_request', ip, details: { delivered: 'pending' } }); + try { + const delivery = await this.auth.sendPasswordResetEmail(outcome.userEmail, url, outcome.userId); + writeAudit({ userId: outcome.userId, action: 'user.password_reset_request', ip, details: { delivered: delivery.delivered } }); + } catch { + writeAudit({ userId: outcome.userId, action: 'user.password_reset_request', ip, details: { delivered: 'failed' } }); + } + } else { + writeAudit({ userId: outcome.userId, action: 'user.password_reset_request', ip, details: { reason: outcome.reason } }); + } + const elapsed = Date.now() - started; + if (elapsed < FORGOT_MIN_LATENCY_MS) await delay(FORGOT_MIN_LATENCY_MS - elapsed); + return GENERIC_FORGOT_RESPONSE; + } + + @Post('reset-password') + @HttpCode(200) + resetPassword(@Body() body: unknown, @Req() req: Request) { + // Per-IP brute-force guard, parity with the legacy resetLimiter (5 / 15 min on + // a dedicated bucket) — without it reset tokens could be guessed unthrottled. + this.limit('reset', req, 5); + const ip = getClientIp(req); + const result = this.auth.resetPassword(body); + if (result.error) { + writeAudit({ userId: null, action: 'user.password_reset_fail', ip, details: { reason: result.error } }); + throw new HttpException({ error: result.error }, result.status!); + } + if (result.mfa_required) { + return { mfa_required: true }; + } + writeAudit({ userId: result.userId ?? null, action: 'user.password_reset_success', ip }); + return { success: true }; + } + + @Post('mfa/verify-login') + @HttpCode(200) + verifyMfaLogin(@Body() body: unknown, @Req() req: Request, @Res({ passthrough: true }) res: Response) { + this.limit('mfa', req, 5); + const result = this.auth.verifyMfaLogin(body); + if (result.error) { + throw new HttpException({ error: result.error }, result.status!); + } + writeAudit({ userId: result.auditUserId!, action: 'user.login', ip: getClientIp(req), details: { mfa: true } }); + this.auth.setAuthCookie(res, result.token!, req, result.remember); + return { token: result.token, user: result.user }; + } + + @Post('logout') + @HttpCode(200) + logout(@Req() req: Request, @Res({ passthrough: true }) res: Response) { + this.auth.clearAuthCookie(res, req); + return { success: true }; + } +} diff --git a/server/src/nest/auth/auth.controller.ts b/server/src/nest/auth/auth.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..5da251fc410706973673488d831cdc02012ec034 --- /dev/null +++ b/server/src/nest/auth/auth.controller.ts @@ -0,0 +1,271 @@ +import { + Body, + Controller, + Delete, + Get, + HttpCode, + HttpException, + Param, + Post, + Put, + Req, + Res, + UploadedFile, + UseGuards, + UseInterceptors, +} from '@nestjs/common'; +import { FileInterceptor } from '@nestjs/platform-express'; +import { diskStorage } from 'multer'; +import type { Request, Response } from 'express'; +import path from 'path'; +import fs from 'fs'; +import { v4 as uuid } from 'uuid'; +import { AuthService } from './auth.service'; +import { RateLimitService } from './rate-limit.service'; +import { JwtAuthGuard } from './jwt-auth.guard'; +import { CurrentUser } from './current-user.decorator'; +import { writeAudit, getClientIp } from '../../services/auditLog'; +import { isDemoEmail } from '../../services/demo'; +import type { User } from '../../types'; + +const WINDOW = 15 * 60 * 1000; +const avatarDir = path.join(__dirname, '../../../uploads/avatars'); +const ALLOWED_AVATAR_EXTS = ['.jpg', '.jpeg', '.png', '.gif', '.webp']; +const AVATAR_UPLOAD = { + storage: diskStorage({ + destination: (_req, _file, cb) => { if (!fs.existsSync(avatarDir)) fs.mkdirSync(avatarDir, { recursive: true }); cb(null, avatarDir); }, + filename: (_req, file, cb) => cb(null, uuid() + path.extname(file.originalname)), + }), + limits: { fileSize: 5 * 1024 * 1024 }, + fileFilter: (_req: unknown, file: Express.Multer.File, cb: (err: Error | null, accept: boolean) => void) => { + const ext = path.extname(file.originalname).toLowerCase(); + if (!file.mimetype.startsWith('image/') || !ALLOWED_AVATAR_EXTS.includes(ext)) { + const err: Error & { statusCode?: number } = new Error('Only image files (jpg, png, gif, webp) are allowed'); + err.statusCode = 400; + return cb(err, false); + } + cb(null, true); + }, +}; + +/** + * Authenticated account endpoints — byte-identical to the legacy Express route + * (server/src/routes/auth.ts): the same /me/* account ops, avatar upload (with + * the demo-mode block), settings, key validation, MFA setup/enable/disable, MCP + * tokens and the short-lived ws/resource tokens. The per-IP rate limits reuse + * the shared buckets (the inline rateLimiter(5) shares the 'login' bucket, as in + * the legacy code). create-token answers 201; everything else 200. + */ +@Controller('api/auth') +@UseGuards(JwtAuthGuard) +export class AuthController { + constructor(private readonly auth: AuthService, private readonly rl: RateLimitService) {} + + private limit(bucket: string, req: Request, max: number): void { + if (!this.rl.check(bucket, req.ip || 'unknown', max, WINDOW, Date.now())) { + throw new HttpException({ error: 'Too many attempts. Please try again later.' }, 429); + } + } + + @Get('me') + me(@CurrentUser() user: User) { + const loaded = this.auth.getCurrentUser(user.id); + if (!loaded) { + throw new HttpException({ error: 'User not found' }, 404); + } + return { user: loaded }; + } + + @Put('me/password') + changePassword(@CurrentUser() user: User, @Body() body: unknown, @Req() req: Request, @Res({ passthrough: true }) res: Response) { + this.limit('login', req, 5); + const result = this.auth.changePassword(user.id, user.email, body); + if (result.error) { + throw new HttpException({ error: result.error }, result.status!); + } + // Refresh this device's cookie with the new password_version so the user + // stays logged in here while all other sessions are invalidated. + if (result.token) this.auth.setAuthCookie(res, result.token, req); + writeAudit({ userId: user.id, action: 'user.password_change', ip: getClientIp(req) }); + return { success: true }; + } + + @Delete('me') + deleteAccount(@CurrentUser() user: User, @Req() req: Request) { + const result = this.auth.deleteAccount(user.id, user.email, user.role); + if (result.error) { + throw new HttpException({ error: result.error }, result.status!); + } + writeAudit({ userId: user.id, action: 'user.account_delete', ip: getClientIp(req) }); + return { success: true }; + } + + @Put('me/maps-key') + mapsKey(@CurrentUser() user: User, @Body() body: { maps_api_key?: unknown }) { + return this.auth.updateMapsKey(user.id, body.maps_api_key); + } + + @Put('me/api-keys') + apiKeys(@CurrentUser() user: User, @Body() body: unknown) { + return this.auth.updateApiKeys(user.id, body); + } + + @Put('me/settings') + updateSettings(@CurrentUser() user: User, @Body() body: unknown) { + const result = this.auth.updateSettings(user.id, body); + if (result.error) { + throw new HttpException({ error: result.error }, result.status!); + } + return { success: result.success, user: result.user }; + } + + @Get('me/settings') + getSettings(@CurrentUser() user: User) { + const result = this.auth.getSettings(user.id); + if (result.error) { + throw new HttpException({ error: result.error }, result.status!); + } + return { settings: result.settings }; + } + + @Post('avatar') + @HttpCode(200) + @UseInterceptors(FileInterceptor('avatar', AVATAR_UPLOAD)) + async avatar(@CurrentUser() user: User, @UploadedFile() file: Express.Multer.File | undefined) { + if (process.env.DEMO_MODE?.toLowerCase() === 'true' && isDemoEmail(user.email)) { + throw new HttpException({ error: 'Uploads are disabled in demo mode. Self-host TREK for full functionality.' }, 403); + } + if (!file) { + throw new HttpException({ error: 'No image uploaded' }, 400); + } + return this.auth.saveAvatar(user.id, file.filename); + } + + @Delete('avatar') + async deleteAvatar(@CurrentUser() user: User) { + return this.auth.deleteAvatar(user.id); + } + + @Get('users') + users(@CurrentUser() user: User) { + return { users: this.auth.listUsers(user.id) }; + } + + @Get('validate-keys') + async validateKeys(@CurrentUser() user: User) { + const result = await this.auth.validateKeys(user.id); + if (result.error) { + throw new HttpException({ error: result.error }, result.status!); + } + return { maps: result.maps, weather: result.weather, maps_details: result.maps_details }; + } + + @Get('app-settings') + getAppSettings(@CurrentUser() user: User) { + const result = this.auth.getAppSettings(user.id); + if (result.error) { + throw new HttpException({ error: result.error }, result.status!); + } + return result.data; + } + + @Put('app-settings') + updateAppSettings(@CurrentUser() user: User, @Body() body: unknown, @Req() req: Request) { + const result = this.auth.updateAppSettings(user.id, body); + if (result.error) { + throw new HttpException({ error: result.error }, result.status!); + } + writeAudit({ userId: user.id, action: 'settings.app_update', ip: getClientIp(req), details: result.auditSummary, debugDetails: result.auditDebugDetails }); + return { success: true }; + } + + @Get('travel-stats') + travelStats(@CurrentUser() user: User) { + return this.auth.getTravelStats(user.id); + } + + @Post('mfa/setup') + @HttpCode(200) + async mfaSetup(@CurrentUser() user: User) { + const result = this.auth.setupMfa(user.id, user.email); + if (result.error) { + throw new HttpException({ error: result.error }, result.status!); + } + try { + const qr_svg = await result.qrPromise!; + return { secret: result.secret, otpauth_url: result.otpauth_url, qr_svg }; + } catch (err) { + console.error('[MFA] QR code generation error:', err); + throw new HttpException({ error: 'Could not generate QR code' }, 500); + } + } + + @Post('mfa/enable') + @HttpCode(200) + mfaEnable(@CurrentUser() user: User, @Body() body: { code?: unknown }, @Req() req: Request) { + this.limit('mfa', req, 5); + const result = this.auth.enableMfa(user.id, body.code); + if (result.error) { + throw new HttpException({ error: result.error }, result.status!); + } + writeAudit({ userId: user.id, action: 'user.mfa_enable', ip: getClientIp(req) }); + return { success: true, mfa_enabled: result.mfa_enabled, backup_codes: result.backup_codes }; + } + + @Post('mfa/disable') + @HttpCode(200) + mfaDisable(@CurrentUser() user: User, @Body() body: unknown, @Req() req: Request) { + this.limit('login', req, 5); + const result = this.auth.disableMfa(user.id, user.email, body); + if (result.error) { + throw new HttpException({ error: result.error }, result.status!); + } + writeAudit({ userId: user.id, action: 'user.mfa_disable', ip: getClientIp(req) }); + return { success: true, mfa_enabled: result.mfa_enabled }; + } + + @Get('mcp-tokens') + listMcpTokens(@CurrentUser() user: User) { + return { tokens: this.auth.listMcpTokens(user.id) }; + } + + @Post('mcp-tokens') + @HttpCode(201) + createMcpToken(@CurrentUser() user: User, @Body() body: { name?: unknown }, @Req() req: Request) { + this.limit('login', req, 5); + const result = this.auth.createMcpToken(user.id, body.name); + if (result.error) { + throw new HttpException({ error: result.error }, result.status!); + } + return { token: result.token }; + } + + @Delete('mcp-tokens/:id') + deleteMcpToken(@CurrentUser() user: User, @Param('id') id: string) { + const result = this.auth.deleteMcpToken(user.id, id); + if (result.error) { + throw new HttpException({ error: result.error }, result.status!); + } + return { success: true }; + } + + @Post('ws-token') + @HttpCode(200) + wsToken(@CurrentUser() user: User) { + const result = this.auth.createWsToken(user.id); + if (result.error) { + throw new HttpException({ error: result.error }, result.status!); + } + return { token: result.token }; + } + + @Post('resource-token') + @HttpCode(200) + resourceToken(@CurrentUser() user: User, @Body() body: { purpose?: unknown }) { + const token = this.auth.createResourceToken(user.id, body.purpose); + if (!token) { + throw new HttpException({ error: 'Service unavailable' }, 503); + } + return token; + } +} diff --git a/server/src/nest/auth/auth.module.ts b/server/src/nest/auth/auth.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..7c649537a6367085684e04279f2d617746aff98e --- /dev/null +++ b/server/src/nest/auth/auth.module.ts @@ -0,0 +1,18 @@ +import { Module } from '@nestjs/common'; +import { AuthPublicController } from './auth-public.controller'; +import { AuthController } from './auth.controller'; +import { PasskeyController } from './passkey.controller'; +import { AuthService } from './auth.service'; +import { RateLimitService } from './rate-limit.service'; + +/** + * Auth module — public flows (login/register/reset/mfa-verify/logout) and the + * authenticated account/MFA/token endpoints. The OIDC sub-mount (/api/auth/oidc) + * is a separate, not-yet-migrated route, so the strangler lists the auth + * sub-paths explicitly rather than claiming all of /api/auth. + */ +@Module({ + controllers: [AuthPublicController, AuthController, PasskeyController], + providers: [AuthService, RateLimitService], +}) +export class AuthModule {} diff --git a/server/src/nest/auth/auth.service.ts b/server/src/nest/auth/auth.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..049106111979bbd4a439d5553b8842cb99e44d33 --- /dev/null +++ b/server/src/nest/auth/auth.service.ts @@ -0,0 +1,61 @@ +import { Injectable } from '@nestjs/common'; +import type { Request, Response } from 'express'; +import * as auth from '../../services/authService'; +import { setAuthCookie, clearAuthCookie } from '../../services/cookie'; +import { sendPasswordResetEmail, getAppUrl } from '../../services/notifications'; +import type { User } from '../../types'; + +/** + * Thin Nest wrapper around the existing auth service. Token generation, the + * password/MFA/backup-code crypto, the JWT cookie set/clear and the reset-email + * delivery all reuse the legacy code unchanged. Access control + audit stay in + * the controller (mirroring the legacy route handlers). + */ +@Injectable() +export class AuthService { + // Cookie + setAuthCookie(res: Response, token: string, req: Request, remember?: boolean) { setAuthCookie(res, token, req, remember); } + clearAuthCookie(res: Response, req: Request) { clearAuthCookie(res, req); } + + // Reset-email delivery (canonical app URL, never request headers) + getAppUrl() { return getAppUrl(); } + sendPasswordResetEmail(email: string, url: string, userId: number | null) { return sendPasswordResetEmail(email, url, userId); } + + // Public config + auth flows + getAppConfig(user: User | undefined) { return auth.getAppConfig(user); } + demoLogin() { return auth.demoLogin(); } + validateInviteToken(token: string) { return auth.validateInviteToken(token); } + registerUser(body: unknown) { return auth.registerUser(body as Parameters[0]); } + loginUser(body: unknown) { return auth.loginUser(body as Parameters[0]); } + requestPasswordReset(email: string, ip: string) { return auth.requestPasswordReset(email, ip); } + resetPassword(body: unknown) { return auth.resetPassword(body as Parameters[0]); } + verifyMfaLogin(body: unknown) { return auth.verifyMfaLogin(body as Parameters[0]); } + + // Account + getCurrentUser(userId: number) { return auth.getCurrentUser(userId); } + changePassword(userId: number, email: string, body: unknown) { return auth.changePassword(userId, email, body as Parameters[2]); } + deleteAccount(userId: number, email: string, role: string) { return auth.deleteAccount(userId, email, role); } + updateMapsKey(userId: number, key: unknown) { return auth.updateMapsKey(userId, key as string); } + updateApiKeys(userId: number, body: unknown) { return auth.updateApiKeys(userId, body as Parameters[1]); } + updateSettings(userId: number, body: unknown) { return auth.updateSettings(userId, body as Parameters[1]); } + getSettings(userId: number) { return auth.getSettings(userId); } + saveAvatar(userId: number, filename: string) { return auth.saveAvatar(userId, filename); } + deleteAvatar(userId: number) { return auth.deleteAvatar(userId); } + listUsers(userId: number) { return auth.listUsers(userId); } + validateKeys(userId: number) { return auth.validateKeys(userId); } + getAppSettings(userId: number) { return auth.getAppSettings(userId); } + updateAppSettings(userId: number, body: unknown) { return auth.updateAppSettings(userId, body as Parameters[1]); } + getTravelStats(userId: number) { return auth.getTravelStats(userId); } + + // MFA + setupMfa(userId: number, email: string) { return auth.setupMfa(userId, email); } + enableMfa(userId: number, code: unknown) { return auth.enableMfa(userId, code as string); } + disableMfa(userId: number, email: string, body: unknown) { return auth.disableMfa(userId, email, body as Parameters[2]); } + + // MCP tokens + short-lived tokens + listMcpTokens(userId: number) { return auth.listMcpTokens(userId); } + createMcpToken(userId: number, name: unknown) { return auth.createMcpToken(userId, name as string); } + deleteMcpToken(userId: number, id: string) { return auth.deleteMcpToken(userId, id); } + createWsToken(userId: number) { return auth.createWsToken(userId); } + createResourceToken(userId: number, purpose: unknown) { return auth.createResourceToken(userId, purpose as string); } +} diff --git a/server/src/nest/auth/cookie-auth.guard.ts b/server/src/nest/auth/cookie-auth.guard.ts new file mode 100644 index 0000000000000000000000000000000000000000..c7c0dea302a2e41c4733e9c6afdef2153c024048 --- /dev/null +++ b/server/src/nest/auth/cookie-auth.guard.ts @@ -0,0 +1,26 @@ +import { CanActivate, ExecutionContext, HttpException, Injectable } from '@nestjs/common'; +import type { Request } from 'express'; +import { verifyJwtAndLoadUser } from '../../middleware/auth'; + +/** + * Mirrors the legacy `requireCookieAuth` middleware: accepts ONLY the httpOnly + * trek_session cookie (never a Bearer token), so CSRF-sensitive state-changing + * OAuth endpoints (consent submit, client/session mutations) can't be driven by + * a leaked Bearer. Error bodies + codes match the legacy 401 shapes exactly. + */ +@Injectable() +export class CookieAuthGuard implements CanActivate { + canActivate(context: ExecutionContext): boolean { + const req = context.switchToHttp().getRequest }>(); + const cookieToken = req.cookies?.trek_session; + if (!cookieToken) { + throw new HttpException({ error: 'Cookie session required for this endpoint', code: 'COOKIE_AUTH_REQUIRED' }, 401); + } + const user = verifyJwtAndLoadUser(cookieToken); + if (!user) { + throw new HttpException({ error: 'Invalid or expired session', code: 'AUTH_REQUIRED' }, 401); + } + req.user = user; + return true; + } +} diff --git a/server/src/nest/auth/current-user.decorator.ts b/server/src/nest/auth/current-user.decorator.ts new file mode 100644 index 0000000000000000000000000000000000000000..c4734891bd4ec2a9eeaf51d5171b3ef3a92338ff --- /dev/null +++ b/server/src/nest/auth/current-user.decorator.ts @@ -0,0 +1,12 @@ +import { createParamDecorator, ExecutionContext } from '@nestjs/common'; +import type { User } from '../../types'; + +/** + * Resolves the authenticated user attached by JwtAuthGuard. + * Use on guarded handlers: `getThing(@CurrentUser() user: User) { ... }`. + */ +export const CurrentUser = createParamDecorator( + (_data: unknown, context: ExecutionContext): User | undefined => { + return context.switchToHttp().getRequest().user; + }, +); diff --git a/server/src/nest/auth/jwt-auth.guard.ts b/server/src/nest/auth/jwt-auth.guard.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e1f6c6fb0192af1a172cb66f39c3a63df77a7bf --- /dev/null +++ b/server/src/nest/auth/jwt-auth.guard.ts @@ -0,0 +1,28 @@ +import { CanActivate, ExecutionContext, HttpException, Injectable } from '@nestjs/common'; +import type { Request } from 'express'; +import { extractToken, verifyJwtAndLoadUser } from '../../middleware/auth'; + +/** + * Validates TREK's existing JWT session — the same httpOnly `trek_session` + * cookie (or `Authorization: Bearer`) the legacy app uses. Reuses the canonical + * `verifyJwtAndLoadUser` so the secret, the password_version invalidation gate + * and the loaded user are IDENTICAL to the Express middleware. No new tokens. + * + * Error bodies match the legacy 401 shape exactly so the client is unaffected. + */ +@Injectable() +export class JwtAuthGuard implements CanActivate { + canActivate(context: ExecutionContext): boolean { + const req = context.switchToHttp().getRequest(); + const token = extractToken(req); + if (!token) { + throw new HttpException({ error: 'Access token required', code: 'AUTH_REQUIRED' }, 401); + } + const user = verifyJwtAndLoadUser(token); + if (!user) { + throw new HttpException({ error: 'Invalid or expired token', code: 'AUTH_REQUIRED' }, 401); + } + req.user = user; + return true; + } +} diff --git a/server/src/nest/auth/optional-jwt.guard.ts b/server/src/nest/auth/optional-jwt.guard.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c1ade6db302f1ed72b17ec34978dac5aa9ad163 --- /dev/null +++ b/server/src/nest/auth/optional-jwt.guard.ts @@ -0,0 +1,19 @@ +import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; +import type { Request } from 'express'; +import { extractToken, verifyJwtAndLoadUser } from '../../middleware/auth'; + +/** + * Mirrors the legacy `optionalAuth` middleware: populates req.user with the + * loaded user when a valid token is present, otherwise leaves it null — and + * always allows the request through (never 401). Used for endpoints whose + * response varies by auth state but don't require it (e.g. /app-config). + */ +@Injectable() +export class OptionalJwtGuard implements CanActivate { + canActivate(context: ExecutionContext): boolean { + const req = context.switchToHttp().getRequest(); + const token = extractToken(req); + (req as { user: unknown }).user = (token ? verifyJwtAndLoadUser(token) : null) || null; + return true; + } +} diff --git a/server/src/nest/auth/passkey-enabled.guard.ts b/server/src/nest/auth/passkey-enabled.guard.ts new file mode 100644 index 0000000000000000000000000000000000000000..26954162a0105d5476ea0966a6fd314145b37b43 --- /dev/null +++ b/server/src/nest/auth/passkey-enabled.guard.ts @@ -0,0 +1,22 @@ +import { CanActivate, HttpException, Injectable } from '@nestjs/common'; +import { resolveAuthToggles } from '../../services/authService'; + +/** + * Server-side enforcement of the instance-wide `passkey_login` toggle. Placed + * BEFORE the auth guard on every passkey ceremony route so a disabled feature + * returns 404 (not "auth required") and cannot be driven by direct API calls — + * hiding the button in the UI is not enough. Mirrors JourneyAddonGuard. + * + * The credential-management routes (list/rename/delete) are deliberately NOT + * gated by this guard so users can still clean up their passkeys after an admin + * turns the feature off. + */ +@Injectable() +export class PasskeyEnabledGuard implements CanActivate { + canActivate(): boolean { + if (!resolveAuthToggles().passkey_login) { + throw new HttpException({ error: 'Passkey login is not enabled' }, 404); + } + return true; + } +} diff --git a/server/src/nest/auth/passkey.controller.ts b/server/src/nest/auth/passkey.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..e4f70749d45b0b65464f62c8d077f047b00fe782 --- /dev/null +++ b/server/src/nest/auth/passkey.controller.ts @@ -0,0 +1,114 @@ +import { Body, Controller, Delete, Get, HttpCode, HttpException, Param, Patch, Post, Req, Res, UseGuards } from '@nestjs/common'; +import type { Request, Response } from 'express'; +import { RateLimitService } from './rate-limit.service'; +import { JwtAuthGuard } from './jwt-auth.guard'; +import { PasskeyEnabledGuard } from './passkey-enabled.guard'; +import { CurrentUser } from './current-user.decorator'; +import { setAuthCookie } from '../../services/cookie'; +import { writeAudit, getClientIp } from '../../services/auditLog'; +import * as passkey from '../../services/passkeyService'; +import type { User } from '../../types'; + +const WINDOW = 15 * 60 * 1000; +const LOGIN_MIN_LATENCY_MS = 350; +const delay = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +/** + * /api/auth/passkey — WebAuthn (passkey) registration, primary login and + * credential management. + * + * - register/* : authenticated, gated by the admin toggle + password re-auth. + * - login/* : UNauthenticated discoverable-credential login, gated by the + * admin toggle; mints the SAME session cookie as password login. + * - credentials : owner-scoped management — intentionally NOT toggle-gated so a + * user can always view/remove their passkeys. + * + * PasskeyEnabledGuard is listed first so a disabled feature 404s before auth. + */ +@Controller('api/auth/passkey') +export class PasskeyController { + constructor(private readonly rl: RateLimitService) {} + + private limit(bucket: string, req: Request, max: number): void { + if (!this.rl.check(bucket, req.ip || 'unknown', max, WINDOW, Date.now())) { + throw new HttpException({ error: 'Too many attempts. Please try again later.' }, 429); + } + } + + // ── Registration (authenticated) ── + @Post('register/options') + @HttpCode(200) + @UseGuards(PasskeyEnabledGuard, JwtAuthGuard) + async registerOptions(@CurrentUser() user: User, @Body() body: { password?: string }, @Req() req: Request) { + this.limit('mfa', req, 5); + const result = await passkey.passkeyRegisterOptions(user.id, body?.password); + if (result.error) throw new HttpException({ error: result.error }, result.status!); + return result.options; + } + + @Post('register/verify') + @HttpCode(200) + @UseGuards(PasskeyEnabledGuard, JwtAuthGuard) + async registerVerify(@CurrentUser() user: User, @Body() body: unknown, @Req() req: Request) { + const result = await passkey.passkeyRegisterVerify(user.id, body as Parameters[1]); + if (result.error) throw new HttpException({ error: result.error }, result.status!); + writeAudit({ userId: user.id, action: 'user.passkey_register', ip: getClientIp(req) }); + return { success: true, credential: result.credential }; + } + + // ── Authentication (public — primary login) ── + @Post('login/options') + @HttpCode(200) + @UseGuards(PasskeyEnabledGuard) + async loginOptions(@Req() req: Request) { + this.limit('login', req, 10); + const result = await passkey.passkeyLoginOptions(); + if (result.error) throw new HttpException({ error: result.error }, result.status!); + return result.options; + } + + @Post('login/verify') + @HttpCode(200) + @UseGuards(PasskeyEnabledGuard) + async loginVerify(@Body() body: unknown, @Req() req: Request, @Res({ passthrough: true }) res: Response) { + this.limit('login', req, 10); + const started = Date.now(); + const result = await passkey.passkeyLoginVerify(body as Parameters[0]); + if (result.auditAction) { + writeAudit({ userId: result.auditUserId ?? null, action: result.auditAction, ip: getClientIp(req) }); + } + // Pad to the same floor as password login so timing can't distinguish a + // known credential from an unknown one. + const elapsed = Date.now() - started; + if (elapsed < LOGIN_MIN_LATENCY_MS) await delay(LOGIN_MIN_LATENCY_MS - elapsed); + if (result.error) throw new HttpException({ error: result.error }, result.status!); + writeAudit({ userId: result.auditUserId!, action: 'user.login', ip: getClientIp(req), details: { method: 'passkey' } }); + setAuthCookie(res, result.token!, req); + return { token: result.token, user: result.user }; + } + + // ── Management (authenticated, owner-scoped — NOT toggle-gated) ── + @Get('credentials') + @UseGuards(JwtAuthGuard) + list(@CurrentUser() user: User) { + return { credentials: passkey.listPasskeys(user.id) }; + } + + @Patch('credentials/:id') + @UseGuards(JwtAuthGuard) + rename(@CurrentUser() user: User, @Param('id') id: string, @Body() body: { name?: unknown }) { + const result = passkey.renamePasskey(user.id, id, body?.name); + if (result.error) throw new HttpException({ error: result.error }, result.status!); + return { success: true }; + } + + @Delete('credentials/:id') + @UseGuards(JwtAuthGuard) + remove(@CurrentUser() user: User, @Param('id') id: string, @Body() body: { password?: string }, @Req() req: Request) { + this.limit('login', req, 5); + const result = passkey.deletePasskey(user.id, id, body?.password); + if (result.error) throw new HttpException({ error: result.error }, result.status!); + writeAudit({ userId: user.id, action: 'user.passkey_delete', resource: String(id), ip: getClientIp(req) }); + return { success: true }; + } +} diff --git a/server/src/nest/auth/rate-limit.service.ts b/server/src/nest/auth/rate-limit.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..04239a0c8b049f84dafa2737d791ab888d422bab --- /dev/null +++ b/server/src/nest/auth/rate-limit.service.ts @@ -0,0 +1,45 @@ +import { Injectable } from '@nestjs/common'; + +interface Attempt { count: number; first: number } + +/** + * In-memory per-IP rate limiter, ported 1:1 from the legacy auth route's + * `rateLimiter`. Each named bucket keeps its own attempt map; `check` returns + * false once a key exceeds `max` within `windowMs` (the caller answers 429). + * + * The legacy route also ran a setInterval to garbage-collect expired records; + * that was pure memory housekeeping (the window check below already treats an + * expired record as fresh), so it is intentionally omitted — the limit + * behaviour is identical and there's no dangling timer to leak in tests. + */ +@Injectable() +export class RateLimitService { + private readonly buckets = new Map>(); + + private store(bucket: string): Map { + let s = this.buckets.get(bucket); + if (!s) { s = new Map(); this.buckets.set(bucket, s); } + return s; + } + + /** Returns true when the request is allowed, false when it should be rejected (429). */ + check(bucket: string, key: string, max: number, windowMs: number, now: number): boolean { + const store = this.store(bucket); + const record = store.get(key); + if (record && record.count >= max && now - record.first < windowMs) { + return false; + } + if (!record || now - record.first >= windowMs) { + store.set(key, { count: 1, first: now }); + } else { + record.count++; + } + return true; + } + + /** Test helper: clear a bucket (mirrors the legacy exported maps used for resets). */ + reset(bucket?: string): void { + if (bucket) this.buckets.get(bucket)?.clear(); + else this.buckets.clear(); + } +} diff --git a/server/src/nest/backup/backup.controller.ts b/server/src/nest/backup/backup.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..07da9e9e95e870f352e56a6091844bd29def9a42 --- /dev/null +++ b/server/src/nest/backup/backup.controller.ts @@ -0,0 +1,167 @@ +import { + Body, + Controller, + Delete, + Get, + HttpCode, + HttpException, + Param, + Post, + Put, + Req, + Res, + UploadedFile, + UseGuards, + UseInterceptors, +} from '@nestjs/common'; +import { FileInterceptor } from '@nestjs/platform-express'; +import type { Request, Response } from 'express'; +import fs from 'fs'; +import type { User } from '../../types'; +import { BackupService } from './backup.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { AdminGuard } from '../auth/admin.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; +import { writeAudit, getClientIp } from '../../services/auditLog'; +import { getUploadTmpDir, MAX_BACKUP_UPLOAD_SIZE } from '../../services/backupService'; + +const UPLOAD = { + dest: getUploadTmpDir(), + fileFilter: (_req: unknown, file: Express.Multer.File, cb: (err: Error | null, accept: boolean) => void) => { + if (file.originalname.endsWith('.zip')) return cb(null, true); + cb(new Error('Only ZIP files allowed'), false); + }, + limits: { fileSize: MAX_BACKUP_UPLOAD_SIZE }, +}; + +/** + * /api/backup — admin-only database backup management (list, create, download, + * restore from a stored or uploaded zip, auto-backup settings, delete). + * + * Byte-identical to the legacy Express route (server/src/routes/backup.ts): + * admin-gated, the create rate-limit (429), the filename validation (400/404), + * the audit-log writes, res.download for downloads and the tmp-file cleanup for + * uploads. All JSON responses answer 200. + */ +@Controller('api/backup') +@UseGuards(JwtAuthGuard, AdminGuard) +export class BackupController { + constructor(private readonly backup: BackupService) {} + + @Get('list') + list() { + try { + return { backups: this.backup.listBackups() }; + } catch { + throw new HttpException({ error: 'Error loading backups' }, 500); + } + } + + @Post('create') + @HttpCode(200) // Express answers create with res.json (200), not the POST-default 201. + async create(@CurrentUser() user: User, @Req() req: Request) { + if (!this.backup.checkRateLimit(req.ip || 'unknown', 3, this.backup.rateWindow)) { + throw new HttpException({ error: 'Too many backup requests. Please try again later.' }, 429); + } + try { + const backup = await this.backup.createBackup(); + writeAudit({ userId: user.id, action: 'backup.create', resource: backup.filename, ip: getClientIp(req), details: { size: backup.size } }); + return { success: true, backup }; + } catch { + throw new HttpException({ error: 'Error creating backup' }, 500); + } + } + + @Get('download/:filename') + download(@Param('filename') filename: string, @Res() res: Response): void { + if (!this.backup.isValidBackupFilename(filename)) { + throw new HttpException({ error: 'Invalid filename' }, 400); + } + if (!this.backup.backupFileExists(filename)) { + throw new HttpException({ error: 'Backup not found' }, 404); + } + res.download(this.backup.backupFilePath(filename), filename); + } + + @Post('restore/:filename') + @HttpCode(200) // Express answers restore with res.json (200). + async restore(@CurrentUser() user: User, @Param('filename') filename: string, @Req() req: Request) { + if (!this.backup.isValidBackupFilename(filename)) { + throw new HttpException({ error: 'Invalid filename' }, 400); + } + if (!this.backup.backupFileExists(filename)) { + throw new HttpException({ error: 'Backup not found' }, 404); + } + try { + const result = await this.backup.restoreFromZip(this.backup.backupFilePath(filename)); + if (!result.success) { + throw new HttpException({ error: result.error }, result.status || 400); + } + writeAudit({ userId: user.id, action: 'backup.restore', resource: filename, ip: getClientIp(req) }); + return { success: true }; + } catch (err) { + if (err instanceof HttpException) throw err; + throw new HttpException({ error: 'Error restoring backup' }, 500); + } + } + + @Post('upload-restore') + @HttpCode(200) // Express answers upload-restore with res.json (200). + @UseInterceptors(FileInterceptor('backup', UPLOAD)) + async uploadRestore(@CurrentUser() user: User, @UploadedFile() file: Express.Multer.File | undefined, @Req() req: Request) { + if (!file) { + throw new HttpException({ error: 'No file uploaded' }, 400); + } + const zipPath = file.path; + const origName = file.originalname || 'upload.zip'; + try { + const result = await this.backup.restoreFromZip(zipPath); + if (!result.success) { + throw new HttpException({ error: result.error }, result.status || 400); + } + writeAudit({ userId: user.id, action: 'backup.upload_restore', resource: origName, ip: getClientIp(req) }); + return { success: true }; + } catch (err) { + if (err instanceof HttpException) throw err; + throw new HttpException({ error: 'Error restoring backup' }, 500); + } finally { + if (fs.existsSync(zipPath)) fs.unlinkSync(zipPath); + } + } + + @Get('auto-settings') + autoSettings() { + try { + return this.backup.getAutoSettings(); + } catch (err) { + console.error('[backup] GET auto-settings:', err); + throw new HttpException({ error: 'Could not load backup settings' }, 500); + } + } + + @Put('auto-settings') + updateAutoSettings(@CurrentUser() user: User, @Body() body: Record, @Req() req: Request) { + try { + const settings = this.backup.updateAutoSettings(body || {}); + writeAudit({ userId: user.id, action: 'backup.auto_settings', ip: getClientIp(req), details: { enabled: settings.enabled, interval: settings.interval, keep_days: settings.keep_days } }); + return { settings }; + } catch (err) { + console.error('[backup] PUT auto-settings:', err); + const msg = err instanceof Error ? err.message : String(err); + throw new HttpException({ error: 'Could not save auto-backup settings', detail: process.env.NODE_ENV?.toLowerCase() !== 'production' ? msg : undefined }, 500); + } + } + + @Delete(':filename') + remove(@CurrentUser() user: User, @Param('filename') filename: string, @Req() req: Request) { + if (!this.backup.isValidBackupFilename(filename)) { + throw new HttpException({ error: 'Invalid filename' }, 400); + } + if (!this.backup.backupFileExists(filename)) { + throw new HttpException({ error: 'Backup not found' }, 404); + } + this.backup.deleteBackup(filename); + writeAudit({ userId: user.id, action: 'backup.delete', resource: filename, ip: getClientIp(req) }); + return { success: true }; + } +} diff --git a/server/src/nest/backup/backup.module.ts b/server/src/nest/backup/backup.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..4a79055aec51f6c2416914e5a9b56558153b1252 --- /dev/null +++ b/server/src/nest/backup/backup.module.ts @@ -0,0 +1,9 @@ +import { Module } from '@nestjs/common'; +import { BackupController } from './backup.controller'; +import { BackupService } from './backup.service'; + +@Module({ + controllers: [BackupController], + providers: [BackupService], +}) +export class BackupModule {} diff --git a/server/src/nest/backup/backup.service.ts b/server/src/nest/backup/backup.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..ea9fddfa47a03a4e8cf6391518f8589341c0dafd --- /dev/null +++ b/server/src/nest/backup/backup.service.ts @@ -0,0 +1,24 @@ +import { Injectable } from '@nestjs/common'; +import * as svc from '../../services/backupService'; + +/** + * Thin Nest wrapper around the existing backup service. The zip packing/restore, + * the auto-backup scheduler settings, the filename validation, the rate-limit + * bookkeeping and the tmp-dir all reuse the legacy code unchanged. + */ +@Injectable() +export class BackupService { + listBackups() { return svc.listBackups(); } + createBackup() { return svc.createBackup(); } + restoreFromZip(zipPath: string) { return svc.restoreFromZip(zipPath); } + getAutoSettings() { return svc.getAutoSettings(); } + updateAutoSettings(body: Record) { return svc.updateAutoSettings(body); } + deleteBackup(filename: string) { return svc.deleteBackup(filename); } + + isValidBackupFilename(filename: string) { return svc.isValidBackupFilename(filename); } + backupFilePath(filename: string) { return svc.backupFilePath(filename); } + backupFileExists(filename: string) { return svc.backupFileExists(filename); } + checkRateLimit(key: string, maxAttempts: number, windowMs: number) { return svc.checkRateLimit(key, maxAttempts, windowMs); } + + get rateWindow() { return svc.BACKUP_RATE_WINDOW; } +} diff --git a/server/src/nest/booking-import/booking-import.controller.ts b/server/src/nest/booking-import/booking-import.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..6d20b3aa002d7f88e522b13c61c2fd775ad241bf --- /dev/null +++ b/server/src/nest/booking-import/booking-import.controller.ts @@ -0,0 +1,102 @@ +import { + Controller, + Post, + Body, + Param, + Headers, + HttpException, + UseGuards, + UseInterceptors, + UploadedFiles, +} from '@nestjs/common'; +import { FilesInterceptor } from '@nestjs/platform-express'; +import { memoryStorage } from 'multer'; +import type { User } from '../../types'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; +import { BookingImportService } from './booking-import.service'; +import type { BookingImportPreviewItem, BookingImportPreviewResponse, BookingImportConfirmResponse } from '@trek/shared'; + +const ACCEPTED_EXTS = new Set(['.eml', '.pdf', '.pkpass', '.html', '.htm', '.txt']); +const MAX_FILE_BYTES = 10 * 1024 * 1024; +const MAX_FILES = 5; + +const UPLOAD = { + storage: memoryStorage(), + limits: { fileSize: MAX_FILE_BYTES, files: MAX_FILES }, +}; + +@Controller('api/trips/:tripId/reservations/import') +@UseGuards(JwtAuthGuard) +export class BookingImportController { + constructor(private readonly bookingImport: BookingImportService) {} + + private requireTrip(tripId: string, user: User) { + const trip = this.bookingImport.verifyTripAccess(tripId, user.id); + if (!trip) throw new HttpException({ error: 'Trip not found' }, 404); + return trip; + } + + private requireEdit(trip: ReturnType, user: User): void { + if (!this.bookingImport.canEdit(trip!, user)) { + throw new HttpException({ error: 'No permission' }, 403); + } + } + + /** + * POST /api/trips/:tripId/reservations/import/booking + * Accepts up to 5 booking confirmation files (EML, PDF, PKPass, HTML, TXT). + * Returns a preview list without persisting anything. + */ + @Post('booking') + @UseInterceptors(FilesInterceptor('files', MAX_FILES, UPLOAD)) + async preview( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @UploadedFiles() files: Express.Multer.File[] | undefined, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + + if (!this.bookingImport.isAvailable()) { + throw new HttpException({ error: 'KItinerary extractor is not available on this server' }, 503); + } + + if (!files || files.length === 0) { + throw new HttpException({ error: 'No files uploaded' }, 400); + } + + // Validate extensions + for (const f of files) { + const ext = f.originalname.toLowerCase().slice(f.originalname.lastIndexOf('.')); + if (!ACCEPTED_EXTS.has(ext)) { + throw new HttpException({ error: `Unsupported file type: ${f.originalname}. Accepted: EML, PDF, PKPass, HTML, TXT` }, 400); + } + } + + const result: BookingImportPreviewResponse = await this.bookingImport.preview(files); + return result; + } + + /** + * POST /api/trips/:tripId/reservations/import/booking/confirm + * Persists the user-confirmed subset of parsed items. + */ + @Post('booking/confirm') + async confirm( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body() body: { items?: BookingImportPreviewItem[] }, + @Headers('x-socket-id') socketId?: string, + ): Promise { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + + const items = body?.items; + if (!Array.isArray(items) || items.length === 0) { + throw new HttpException({ error: 'items must be a non-empty array' }, 400); + } + + return this.bookingImport.confirm(tripId, items, socketId); + } +} diff --git a/server/src/nest/booking-import/booking-import.module.ts b/server/src/nest/booking-import/booking-import.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..332bcd32c842158d58a2d867afbb6f042962ecef --- /dev/null +++ b/server/src/nest/booking-import/booking-import.module.ts @@ -0,0 +1,11 @@ +import { Module } from '@nestjs/common'; +import { BookingImportController } from './booking-import.controller'; +import { BookingImportService } from './booking-import.service'; +import { KitineraryExtractorService } from './kitinerary-extractor.service'; +import { FeaturesController } from './features.controller'; + +@Module({ + controllers: [BookingImportController, FeaturesController], + providers: [BookingImportService, KitineraryExtractorService], +}) +export class BookingImportModule {} diff --git a/server/src/nest/booking-import/booking-import.service.ts b/server/src/nest/booking-import/booking-import.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..68cd5b9123287d5487a999d761d3230ebc5d568a --- /dev/null +++ b/server/src/nest/booking-import/booking-import.service.ts @@ -0,0 +1,165 @@ +import { Injectable, HttpException } from '@nestjs/common'; +import { broadcast } from '../../websocket'; +import { checkPermission } from '../../services/permissions'; +import { verifyTripAccess } from '../../services/tripAccess'; +import { createReservation } from '../../services/reservationService'; +import { createPlace } from '../../services/placeService'; +import { searchNominatim } from '../../services/mapsService'; +import { db } from '../../db/database'; +import type { User } from '../../types'; +import { KitineraryExtractorService } from './kitinerary-extractor.service'; +import { mapReservations } from './kitinerary-mapper'; +import type { BookingImportPreviewItem, BookingImportPreviewResponse, BookingImportConfirmResponse, Reservation } from '@trek/shared'; +import type { ParsedBookingItem } from './kitinerary.types'; + +function resolveDayId(tripId: string, iso: string | null | undefined): number | null { + if (!iso) return null; + const date = iso.slice(0, 10); + if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) return null; + const row = db.prepare('SELECT id FROM days WHERE trip_id = ? AND date = ? LIMIT 1').get(tripId, date) as { id: number } | undefined; + return row?.id ?? null; +} + +@Injectable() +export class BookingImportService { + constructor(private readonly extractor: KitineraryExtractorService) {} + + isAvailable(): boolean { + return this.extractor.isAvailable(); + } + + verifyTripAccess(tripId: string, userId: number) { + return verifyTripAccess(tripId, userId); + } + + canEdit(trip: NonNullable>, user: User): boolean { + return checkPermission('reservation_edit', user.role, trip.user_id, user.id, trip.user_id !== user.id); + } + + /** + * Parse uploaded files through kitinerary-extractor and return a preview list. + * Does NOT persist anything. + */ + async preview(files: Express.Multer.File[]): Promise { + if (!this.extractor.isAvailable()) { + throw new HttpException({ error: 'KItinerary extractor is not available on this server' }, 503); + } + + const allItems: ParsedBookingItem[] = []; + const allWarnings: string[] = []; + + for (const file of files) { + let kiItems; + try { + kiItems = await this.extractor.extract(file.buffer, file.originalname); + } catch (err) { + allWarnings.push(`${file.originalname}: extraction failed — ${err instanceof Error ? err.message : String(err)}`); + continue; + } + + if (kiItems.length === 0) { + allWarnings.push(`${file.originalname}: no reservations found`); + continue; + } + + const { items, warnings } = mapReservations(kiItems, file.originalname); + allItems.push(...items); + allWarnings.push(...warnings); + } + + return { items: allItems, warnings: allWarnings }; + } + + /** + * Persist a confirmed list of parsed items. + * Creates place rows for hotel/restaurant/event venues, then calls createReservation. + * Broadcasts reservation:created (and accommodation:created if applicable) per item. + */ + async confirm( + tripId: string, + items: BookingImportPreviewItem[], + socketId: string | undefined, + ): Promise { + const created: Reservation[] = []; + + for (const item of items) { + try { + const { _venue, _accommodation, source: _src, ...reservationData } = item; + + // Auto-create a place row for venue-based reservations + let placeId: number | undefined; + if (_venue?.name) { + // Geocode before creating so the broadcast carries the coordinates + let lat = _venue.lat; + let lng = _venue.lng; + if (lat == null && (_venue.address || _venue.name)) { + try { + const queries = [ + _venue.address ? `${_venue.name} ${_venue.address}` : null, + _venue.address ?? null, + _venue.name, + ].filter((q): q is string => !!q); + + for (const q of queries) { + const results = await searchNominatim(q); + const hit = results[0]; + if (hit?.lat != null && hit?.lng != null) { + lat = hit.lat; + lng = hit.lng; + break; + } + } + } catch { + // geocoding failure is non-fatal + } + } + + const place = createPlace(tripId, { + name: _venue.name, + lat, + lng, + address: _venue.address, + website: _venue.website, + phone: _venue.phone, + }); + placeId = (place as any).id; + broadcast(tripId, 'place:created', { place }, socketId); + } + + // Build create_accommodation for hotel reservations. + // start_day_id / end_day_id are resolved from check-in/out ISO dates so + // the accommodation row is actually inserted (createReservation gates on them). + let createAccommodation: { place_id?: number; start_day_id?: number; end_day_id?: number; check_in?: string; check_out?: string; confirmation?: string } | undefined; + if (item.type === 'hotel' && _accommodation) { + const startDayId = resolveDayId(tripId, _accommodation.check_in); + const endDayId = resolveDayId(tripId, _accommodation.check_out); + createAccommodation = { + place_id: placeId, + start_day_id: startDayId ?? undefined, + end_day_id: endDayId ?? undefined, + check_in: _accommodation.check_in, + check_out: _accommodation.check_out, + confirmation: _accommodation.confirmation, + }; + } + + const { reservation, accommodationCreated } = createReservation(tripId, { + ...reservationData, + place_id: placeId, + create_accommodation: createAccommodation, + } as any); + + broadcast(tripId, 'reservation:created', { reservation }, socketId); + if (accommodationCreated) { + broadcast(tripId, 'accommodation:created', {}, socketId); + } + + created.push(reservation); + } catch (err) { + console.error(`[booking-import] Failed to create reservation "${item.title}":`, err instanceof Error ? err.message : err); + } + } + + return { created }; + } +} diff --git a/server/src/nest/booking-import/features.controller.ts b/server/src/nest/booking-import/features.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..50b3b8494c592510c4938dfdc7ad597889d47f8f --- /dev/null +++ b/server/src/nest/booking-import/features.controller.ts @@ -0,0 +1,15 @@ +import { Controller, Get } from '@nestjs/common'; +import { KitineraryExtractorService } from './kitinerary-extractor.service'; + +/** Exposes server feature flags consumed by the frontend to show/hide optional UI. */ +@Controller('api/health') +export class FeaturesController { + constructor(private readonly extractor: KitineraryExtractorService) {} + + @Get('features') + features() { + return { + bookingImport: this.extractor.isAvailable(), + }; + } +} diff --git a/server/src/nest/booking-import/kitinerary-extractor.service.ts b/server/src/nest/booking-import/kitinerary-extractor.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..fbb476a02351fcc4242c0e0340a42800c2107947 --- /dev/null +++ b/server/src/nest/booking-import/kitinerary-extractor.service.ts @@ -0,0 +1,104 @@ +import { Injectable, OnModuleInit } from '@nestjs/common'; +import { execFile } from 'node:child_process'; +import { existsSync, readdirSync, writeFileSync, unlinkSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, extname } from 'node:path'; +import { randomUUID } from 'node:crypto'; +import { execSync } from 'node:child_process'; +import { promisify } from 'node:util'; +import type { KiReservation } from './kitinerary.types'; + +const execFileAsync = promisify(execFile); +const TIMEOUT_MS = 30_000; +const MAX_BUFFER = 5 * 1024 * 1024; + +@Injectable() +export class KitineraryExtractorService implements OnModuleInit { + private binaryPath: string | null = null; + + onModuleInit() { + this.binaryPath = this.findBinary(); + if (this.binaryPath) { + console.log(`[KItinerary] extractor found at: ${this.binaryPath}`); + } else { + console.info('[KItinerary] extractor not found — booking import feature disabled'); + } + } + + isAvailable(): boolean { + return this.binaryPath !== null; + } + + async extract(buffer: Buffer, fileName: string): Promise { + if (!this.binaryPath) { + throw new Error('kitinerary-extractor is not available on this system'); + } + + const ext = extname(fileName).toLowerCase(); + const tmpFile = join(tmpdir(), `trek-ki-${randomUUID()}${ext}`); + + try { + writeFileSync(tmpFile, buffer); + + const { stdout, stderr } = await execFileAsync(this.binaryPath, [tmpFile], { + timeout: TIMEOUT_MS, + maxBuffer: MAX_BUFFER, + }); + + if (stderr?.trim()) { + // Filter expected noise: currency-symbol ambiguity warnings and vendor + // extractor script errors are normal (every matching script is tried; + // most won't match the current document). + const unexpected = stderr + .split('\n') + .filter(l => l.trim()) + .filter(l => !l.includes('Ambig') && !l.includes('JS ERROR') && !l.includes('Invalid result type from script')); + if (unexpected.length) { + console.warn(`[KItinerary] stderr for "${fileName}":`, unexpected.join('\n')); + } + } + + const text = stdout.trim(); + if (!text) return []; + + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch { + console.warn(`[KItinerary] non-JSON output for "${fileName}"`); + return []; + } + + if (Array.isArray(parsed)) return parsed as KiReservation[]; + if (typeof parsed === 'object' && parsed !== null) return [parsed as KiReservation]; + return []; + } finally { + try { unlinkSync(tmpFile); } catch {} + } + } + + private findBinary(): string | null { + const envPath = process.env.KITINERARY_EXTRACTOR_PATH; + if (envPath) { + if (existsSync(envPath)) return envPath; + console.warn(`[KItinerary] KITINERARY_EXTRACTOR_PATH="${envPath}" not found`); + return null; + } + + // Debian/Ubuntu: /usr/lib//libexec/kf6/kitinerary-extractor + try { + for (const dir of readdirSync('/usr/lib')) { + const candidate = join('/usr/lib', dir, 'libexec', 'kf6', 'kitinerary-extractor'); + if (existsSync(candidate)) return candidate; + } + } catch { /* not a Debian system */ } + + // Fallback: binary in PATH + try { + execSync('kitinerary-extractor --version', { stdio: 'pipe', timeout: 3000 }); + return 'kitinerary-extractor'; + } catch { /* not in PATH */ } + + return null; + } +} diff --git a/server/src/nest/booking-import/kitinerary-mapper.ts b/server/src/nest/booking-import/kitinerary-mapper.ts new file mode 100644 index 0000000000000000000000000000000000000000..c0ada0e4f69a3a29802ef6ca170901f4f56abc2a --- /dev/null +++ b/server/src/nest/booking-import/kitinerary-mapper.ts @@ -0,0 +1,355 @@ +import { findByIata } from '../../services/airportService'; +import type { + KiReservation, KiFlight, KiTrainTrip, KiBusTrip, KiBoatTrip, + KiLodgingBusiness, KiFoodEstablishment, KiRentalCar, KiEvent, + KiGeo, KiAddress, KiDateTimeish, ParsedBookingItem, ParsedEndpoint, ParsedVenue, +} from './kitinerary.types'; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +/** Extract a plain ISO string from either a string or a KDE QDateTime object. */ +function toIsoString(dt: KiDateTimeish): string | null { + if (!dt) return null; + if (typeof dt === 'string') return dt || null; + if (typeof dt === 'object' && dt['@type'] === 'QDateTime') return dt['@value'] || null; + return null; +} + +function splitIso(dt: KiDateTimeish): { date: string | null; time: string | null } { + const iso = toIsoString(dt); + if (!iso) return { date: null, time: null }; + return { date: iso.slice(0, 10) || null, time: iso.length > 10 ? iso.slice(11, 16) || null : null }; +} + +function formatAddress(address: string | KiAddress | undefined): string | null { + if (!address) return null; + if (typeof address === 'string') return address || null; + const joined = [address.streetAddress, address.addressLocality, address.postalCode, address.addressCountry].filter(Boolean).join(', '); + return joined || null; +} + +function coords(geo: KiGeo | undefined): { lat: number; lng: number } | null { + if (!geo || geo.latitude == null || geo.longitude == null) return null; + return { lat: Number(geo.latitude), lng: Number(geo.longitude) }; +} + +// --------------------------------------------------------------------------- +// Type mappers +// --------------------------------------------------------------------------- + +function mapFlight(r: KiReservation, source: ParsedBookingItem['source']): ParsedBookingItem | null { + const f = r.reservationFor as KiFlight | undefined; + if (!f) return null; + + const depIata = f.departureAirport?.iataCode?.toUpperCase() ?? null; + const arrIata = f.arrivalAirport?.iataCode?.toUpperCase() ?? null; + const depAp = depIata ? findByIata(depIata) : null; + const arrAp = arrIata ? findByIata(arrIata) : null; + + const depLabel = depAp ? (depAp.city ? `${depAp.city} (${depAp.iata})` : depAp.name) : (f.departureAirport?.name ?? depIata ?? 'Unknown'); + const arrLabel = arrAp ? (arrAp.city ? `${arrAp.city} (${arrAp.iata})` : arrAp.name) : (f.arrivalAirport?.name ?? arrIata ?? 'Unknown'); + + const airline = f.airline?.name ?? f.airline?.iataCode ?? ''; + const flightNum = f.flightNumber ?? ''; + const title = [airline, flightNum].filter(Boolean).join(' ') || `Flight ${depLabel} → ${arrLabel}`; + + const { date: depDate, time: depTime } = splitIso(f.departureTime); + const { date: arrDate, time: arrTime } = splitIso(f.arrivalTime); + + const endpoints: ParsedEndpoint[] = []; + if (depAp) { + endpoints.push({ role: 'from', sequence: 0, name: depLabel, code: depAp.iata, lat: depAp.lat, lng: depAp.lng, timezone: depAp.tz, local_time: depTime, local_date: depDate }); + } else { + const c = coords(f.departureAirport?.geo); + if (c) endpoints.push({ role: 'from', sequence: 0, name: depLabel, code: depIata, lat: c.lat, lng: c.lng, timezone: null, local_time: depTime, local_date: depDate }); + } + if (arrAp) { + endpoints.push({ role: 'to', sequence: 1, name: arrLabel, code: arrAp.iata, lat: arrAp.lat, lng: arrAp.lng, timezone: arrAp.tz, local_time: arrTime, local_date: arrDate }); + } else { + const c = coords(f.arrivalAirport?.geo); + if (c) endpoints.push({ role: 'to', sequence: 1, name: arrLabel, code: arrIata, lat: c.lat, lng: c.lng, timezone: null, local_time: arrTime, local_date: arrDate }); + } + + return { + type: 'flight', + title, + reservation_time: toIsoString(f.departureTime), + reservation_end_time: toIsoString(f.arrivalTime), + confirmation_number: r.reservationNumber ?? null, + metadata: { + ...(airline ? { airline } : {}), + ...(flightNum ? { flight_number: flightNum } : {}), + ...(depIata ? { departure_airport: depIata } : {}), + ...(arrIata ? { arrival_airport: arrIata } : {}), + }, + endpoints, + needs_review: endpoints.length < 2, + source, + }; +} + +/** True when flight `b` is a short layover connection that continues flight `a`. */ +function sameConnection(a: KiReservation, b: KiReservation): boolean { + const fa = a.reservationFor as KiFlight | undefined; + const fb = b.reservationFor as KiFlight | undefined; + if (!fa || !fb) return false; + const arrIata = fa.arrivalAirport?.iataCode?.toUpperCase(); + const depIata = fb.departureAirport?.iataCode?.toUpperCase(); + if (!arrIata || !depIata || arrIata !== depIata) return false; // must connect at the same airport + const arrIso = toIsoString(fa.arrivalTime); + const depIso = toIsoString(fb.departureTime); + if (arrIso && depIso) { + const gapMs = new Date(depIso).getTime() - new Date(arrIso).getTime(); + // A real layover is forward in time and short — anything longer (e.g. a + // round-trip return days later) stays a separate booking. + if (gapMs < 0 || gapMs > 24 * 3600 * 1000) return false; + } + return true; +} + +/** Collapse several connecting flight legs (same PNR) into one multi-leg booking. */ +function mapFlightGroup(legs: KiReservation[], source: ParsedBookingItem['source']): ParsedBookingItem | null { + const flights = legs.map(l => l.reservationFor as KiFlight | undefined); + if (flights.some(f => !f)) return mapFlight(legs[0], source); // malformed → fall back to single + const fs = flights as KiFlight[]; + + const iataOf = (ap: KiFlight['departureAirport']) => ap?.iataCode?.toUpperCase() ?? null; + const makeEndpoint = ( + ap: KiFlight['departureAirport'], role: 'from' | 'stop' | 'to', time: string | null, date: string | null, + ): ParsedEndpoint | null => { + const iata = iataOf(ap); + const found = iata ? findByIata(iata) : null; + const label = found ? (found.city ? `${found.city} (${found.iata})` : found.name) : (ap?.name ?? iata ?? 'Unknown'); + if (found) return { role, sequence: 0, name: label, code: found.iata, lat: found.lat, lng: found.lng, timezone: found.tz, local_time: time, local_date: date }; + const c = coords(ap?.geo); + if (c) return { role, sequence: 0, name: label, code: iata, lat: c.lat, lng: c.lng, timezone: null, local_time: time, local_date: date }; + return null; + }; + + const endpoints: ParsedEndpoint[] = []; + const metaLegs: Record[] = []; + const first = fs[0]; + const firstDep = splitIso(first.departureTime); + const originEp = makeEndpoint(first.departureAirport, 'from', firstDep.time, firstDep.date); + if (originEp) endpoints.push(originEp); + + fs.forEach((f, i) => { + const isLast = i === fs.length - 1; + const arr = splitIso(f.arrivalTime); + const arrEp = makeEndpoint(f.arrivalAirport, isLast ? 'to' : 'stop', arr.time, arr.date); + if (arrEp) endpoints.push(arrEp); + const airline = f.airline?.name ?? f.airline?.iataCode ?? ''; + metaLegs.push({ + from: iataOf(f.departureAirport), + to: iataOf(f.arrivalAirport), + ...(airline ? { airline } : {}), + ...(f.flightNumber ? { flight_number: f.flightNumber } : {}), + dep_time: splitIso(f.departureTime).time, + arr_time: arr.time, + }); + }); + endpoints.forEach((e, i) => { e.sequence = i; }); + + const last = fs[fs.length - 1]; + const airline = first.airline?.name ?? first.airline?.iataCode ?? ''; + const route = [iataOf(first.departureAirport), ...fs.map(f => iataOf(f.arrivalAirport))].filter(Boolean).join(' → '); + return { + type: 'flight', + title: airline ? `${airline} ${route}` : `Flight ${route}`, + reservation_time: toIsoString(first.departureTime), + reservation_end_time: toIsoString(last.arrivalTime), + confirmation_number: legs[0].reservationNumber ?? null, + metadata: { + ...(airline ? { airline } : {}), + ...(first.flightNumber ? { flight_number: first.flightNumber } : {}), + ...(iataOf(first.departureAirport) ? { departure_airport: iataOf(first.departureAirport) } : {}), + ...(iataOf(last.arrivalAirport) ? { arrival_airport: iataOf(last.arrivalAirport) } : {}), + legs: metaLegs, + }, + endpoints, + needs_review: endpoints.length < fs.length + 1, + source, + }; +} + +function mapTrain(r: KiReservation, source: ParsedBookingItem['source']): ParsedBookingItem | null { + const t = r.reservationFor as KiTrainTrip | undefined; + if (!t) return null; + + const depName = t.departureStation?.name ?? 'Unknown'; + const arrName = t.arrivalStation?.name ?? 'Unknown'; + const trainId = t.trainNumber ?? t.trainName ?? ''; + const title = trainId ? `${trainId} (${depName} → ${arrName})` : `Train ${depName} → ${arrName}`; + + const { date: depDate, time: depTime } = splitIso(t.departureTime); + const { date: arrDate, time: arrTime } = splitIso(t.arrivalTime); + + const endpoints: ParsedEndpoint[] = []; + const dc = coords(t.departureStation?.geo); + const ac = coords(t.arrivalStation?.geo); + if (dc) endpoints.push({ role: 'from', sequence: 0, name: depName, code: null, lat: dc.lat, lng: dc.lng, timezone: null, local_time: depTime, local_date: depDate }); + if (ac) endpoints.push({ role: 'to', sequence: 1, name: arrName, code: null, lat: ac.lat, lng: ac.lng, timezone: null, local_time: arrTime, local_date: arrDate }); + + return { + type: 'train', + title, + reservation_time: toIsoString(t.departureTime), + reservation_end_time: toIsoString(t.arrivalTime), + confirmation_number: r.reservationNumber ?? null, + metadata: trainId ? { train_number: trainId } : undefined, + endpoints, + needs_review: endpoints.length < 2, + source, + }; +} + +function mapBus(r: KiReservation, source: ParsedBookingItem['source']): ParsedBookingItem | null { + const b = r.reservationFor as KiBusTrip | undefined; + if (!b) return null; + + const depName = b.departureBusStop?.name ?? 'Unknown'; + const arrName = b.arrivalBusStop?.name ?? 'Unknown'; + const busId = b.busNumber ?? b.busName ?? ''; + const title = busId ? `${busId} (${depName} → ${arrName})` : `Bus ${depName} → ${arrName}`; + + const { date: depDate, time: depTime } = splitIso(b.departureTime); + const { date: arrDate, time: arrTime } = splitIso(b.arrivalTime); + + const endpoints: ParsedEndpoint[] = []; + const dc = coords(b.departureBusStop?.geo); + const ac = coords(b.arrivalBusStop?.geo); + if (dc) endpoints.push({ role: 'from', sequence: 0, name: depName, code: null, lat: dc.lat, lng: dc.lng, timezone: null, local_time: depTime, local_date: depDate }); + if (ac) endpoints.push({ role: 'to', sequence: 1, name: arrName, code: null, lat: ac.lat, lng: ac.lng, timezone: null, local_time: arrTime, local_date: arrDate }); + + return { type: 'train', title, reservation_time: toIsoString(b.departureTime), reservation_end_time: toIsoString(b.arrivalTime), confirmation_number: r.reservationNumber ?? null, endpoints, needs_review: endpoints.length < 2, source }; +} + +function mapBoat(r: KiReservation, source: ParsedBookingItem['source']): ParsedBookingItem | null { + const b = r.reservationFor as KiBoatTrip | undefined; + if (!b) return null; + + const depName = b.departureBoatTerminal?.name ?? 'Unknown'; + const arrName = b.arrivalBoatTerminal?.name ?? 'Unknown'; + const title = (b as any).name ?? `Cruise ${depName} → ${arrName}`; + + const { date: depDate, time: depTime } = splitIso(b.departureTime); + const { date: arrDate, time: arrTime } = splitIso(b.arrivalTime); + + const endpoints: ParsedEndpoint[] = []; + const dc = coords(b.departureBoatTerminal?.geo); + const ac = coords(b.arrivalBoatTerminal?.geo); + if (dc) endpoints.push({ role: 'from', sequence: 0, name: depName, code: null, lat: dc.lat, lng: dc.lng, timezone: null, local_time: depTime, local_date: depDate }); + if (ac) endpoints.push({ role: 'to', sequence: 1, name: arrName, code: null, lat: ac.lat, lng: ac.lng, timezone: null, local_time: arrTime, local_date: arrDate }); + + return { type: 'cruise', title, reservation_time: toIsoString(b.departureTime), reservation_end_time: toIsoString(b.arrivalTime), confirmation_number: r.reservationNumber ?? null, endpoints, source }; +} + +function mapLodging(r: KiReservation, source: ParsedBookingItem['source']): ParsedBookingItem | null { + const l = r.reservationFor as KiLodgingBusiness | undefined; + if (!l?.name) return null; + + const c = coords(l.geo); + const venue: ParsedVenue = { name: l.name, ...(c ?? {}), address: formatAddress(l.address) ?? undefined, website: l.url ?? undefined, phone: l.telephone ?? undefined }; + + const { date: checkInDate, time: checkInTime } = splitIso(r.checkinTime); + const { date: checkOutDate, time: checkOutTime } = splitIso(r.checkoutTime); + const checkIn = checkInDate ? `${checkInDate}${checkInTime ? `T${checkInTime}` : ''}` : undefined; + const checkOut = checkOutDate ? `${checkOutDate}${checkOutTime ? `T${checkOutTime}` : ''}` : undefined; + + return { + type: 'hotel', + title: l.name, + confirmation_number: r.reservationNumber ?? null, + location: formatAddress(l.address), + _venue: venue, + _accommodation: { check_in: checkIn, check_out: checkOut, confirmation: r.reservationNumber ?? undefined }, + metadata: { ...(checkInTime ? { check_in_time: checkInTime } : {}), ...(checkOutTime ? { check_out_time: checkOutTime } : {}) }, + source, + }; +} + +function mapFood(r: KiReservation, source: ParsedBookingItem['source']): ParsedBookingItem | null { + const f = r.reservationFor as KiFoodEstablishment | undefined; + if (!f?.name) return null; + + const c = coords(f.geo); + const venue: ParsedVenue = { name: f.name, ...(c ?? {}), address: formatAddress(f.address) ?? undefined, website: f.url ?? undefined, phone: f.telephone ?? undefined }; + + return { type: 'restaurant', title: f.name, reservation_time: toIsoString(r.startTime), reservation_end_time: toIsoString(r.endTime), confirmation_number: r.reservationNumber ?? null, location: formatAddress(f.address), _venue: venue, source }; +} + +function mapRentalCar(r: KiReservation, source: ParsedBookingItem['source']): ParsedBookingItem | null { + const car = r.reservationFor as KiRentalCar | undefined; + const company = car?.rentalCompany?.name ?? ''; + const carName = car?.name ?? [car?.make, car?.model].filter(Boolean).join(' ') ?? ''; + const title = [company, carName].filter(Boolean).join(' — ') || 'Rental Car'; + + const pickup = r.pickupLocation as KiReservation['pickupLocation']; + const pc = coords(pickup?.geo); + const venue: ParsedVenue | undefined = pickup?.name ? { name: pickup.name, ...(pc ?? {}), address: formatAddress(pickup.address) ?? undefined } : undefined; + + return { type: 'car', title, reservation_time: toIsoString(r.pickupTime), reservation_end_time: toIsoString(r.dropoffTime), confirmation_number: r.reservationNumber ?? null, ...(venue ? { _venue: venue } : {}), source }; +} + +function mapEvent(r: KiReservation, source: ParsedBookingItem['source']): ParsedBookingItem | null { + const e = r.reservationFor as KiEvent | undefined; + if (!e?.name) return null; + + const loc = e.location; + const c = coords(loc?.geo); + const venue: ParsedVenue | undefined = loc?.name ? { name: loc.name, ...(c ?? {}), address: formatAddress(loc.address) ?? undefined } : undefined; + + return { type: 'event', title: e.name, reservation_time: toIsoString(e.startDate), reservation_end_time: toIsoString(e.endDate), confirmation_number: r.reservationNumber ?? null, location: loc ? (formatAddress(loc.address) ?? loc.name ?? null) : null, ...(venue ? { _venue: venue } : {}), source }; +} + +// --------------------------------------------------------------------------- +// Public +// --------------------------------------------------------------------------- + +export function mapReservations(kiItems: KiReservation[], fileName: string): { items: ParsedBookingItem[]; warnings: string[] } { + const items: ParsedBookingItem[] = []; + const warnings: string[] = []; + + for (let i = 0; i < kiItems.length; i++) { + const r = kiItems[i]; + const source = { fileName, index: i }; + let item: ParsedBookingItem | null = null; + + // Group consecutive connecting flight legs that share a PNR into one booking. + if (r['@type'] === 'FlightReservation') { + const pnr = r.reservationNumber ?? null; + const group = [r]; + while ( + i + 1 < kiItems.length && + kiItems[i + 1]['@type'] === 'FlightReservation' && + pnr != null && + (kiItems[i + 1].reservationNumber ?? null) === pnr && + sameConnection(group[group.length - 1], kiItems[i + 1]) + ) { + group.push(kiItems[++i]); + } + item = group.length > 1 ? mapFlightGroup(group, source) : mapFlight(r, source); + if (item) items.push(item); + continue; + } + + switch (r['@type']) { + case 'TrainReservation': item = mapTrain(r, source); break; + case 'BusReservation': item = mapBus(r, source); break; + case 'BoatReservation': item = mapBoat(r, source); break; + case 'LodgingReservation': item = mapLodging(r, source); break; + case 'FoodEstablishmentReservation': item = mapFood(r, source); break; + case 'RentalCarReservation': item = mapRentalCar(r, source); break; + case 'EventReservation': + case 'TouristAttractionVisit': item = mapEvent(r, source); break; + default: + warnings.push(`Unknown type "${r['@type']}" in ${fileName}[${i}] — skipped`); + } + + if (item) items.push(item); + } + + return { items, warnings }; +} diff --git a/server/src/nest/booking-import/kitinerary.types.ts b/server/src/nest/booking-import/kitinerary.types.ts new file mode 100644 index 0000000000000000000000000000000000000000..b97fcd9ef148ab45e2a35925d50da3802731c02a --- /dev/null +++ b/server/src/nest/booking-import/kitinerary.types.ts @@ -0,0 +1,188 @@ +/** KItinerary JSON-LD output types (schema.org subset) */ + +/** KDE's custom date/time wrapper — used when timezone info is present */ +export interface KiDateTime { + '@type': 'QDateTime'; + '@value': string; // ISO 8601 local time (KDE serializes as @value) + timezone?: string; // IANA timezone id +} + +export type KiDateTimeish = string | KiDateTime | null | undefined; + +export interface KiGeo { + '@type'?: string; + latitude?: number; + longitude?: number; +} + +export interface KiAddress { + '@type'?: string; + streetAddress?: string; + addressLocality?: string; + postalCode?: string; + addressCountry?: string; +} + +export interface KiAirport { + '@type'?: string; + name?: string; + iataCode?: string; + geo?: KiGeo; +} + +export interface KiStation { + '@type'?: string; + name?: string; + geo?: KiGeo; +} + +export interface KiBusStop { + '@type'?: string; + name?: string; + geo?: KiGeo; +} + +export interface KiFlight { + '@type'?: string; + flightNumber?: string; + airline?: { name?: string; iataCode?: string }; + departureAirport?: KiAirport; + arrivalAirport?: KiAirport; + departureTime?: KiDateTimeish; + arrivalTime?: KiDateTimeish; +} + +export interface KiTrainTrip { + '@type'?: string; + trainNumber?: string; + trainName?: string; + departureStation?: KiStation; + arrivalStation?: KiStation; + departureTime?: KiDateTimeish; + arrivalTime?: KiDateTimeish; +} + +export interface KiBusTrip { + '@type'?: string; + busNumber?: string; + busName?: string; + departureBusStop?: KiBusStop; + arrivalBusStop?: KiBusStop; + departureTime?: KiDateTimeish; + arrivalTime?: KiDateTimeish; +} + +export interface KiBoatTrip { + '@type'?: string; + name?: string; + departureBoatTerminal?: KiStation; + arrivalBoatTerminal?: KiStation; + departureTime?: KiDateTimeish; + arrivalTime?: KiDateTimeish; +} + +export interface KiLodgingBusiness { + '@type'?: string; + name?: string; + address?: string | KiAddress; + geo?: KiGeo; + telephone?: string; + url?: string; +} + +export interface KiFoodEstablishment { + '@type'?: string; + name?: string; + address?: string | KiAddress; + geo?: KiGeo; + telephone?: string; + url?: string; +} + +export interface KiRentalCar { + '@type'?: string; + name?: string; + model?: string; + make?: string; + rentalCompany?: { name?: string }; +} + +export interface KiEventVenue { + '@type'?: string; + name?: string; + address?: string | KiAddress; + geo?: KiGeo; +} + +export interface KiEvent { + '@type'?: string; + name?: string; + startDate?: KiDateTimeish; + endDate?: KiDateTimeish; + location?: KiEventVenue; +} + +/** A single output node from kitinerary-extractor's JSON array */ +export interface KiReservation { + '@type': string; + reservationNumber?: string; + checkinTime?: KiDateTimeish; + checkoutTime?: KiDateTimeish; + pickupTime?: KiDateTimeish; + dropoffTime?: KiDateTimeish; + startTime?: KiDateTimeish; + endTime?: KiDateTimeish; + reservationFor?: Record; + pickupLocation?: KiEventVenue; + [key: string]: unknown; +} + +/** Endpoint row shape (matches reservation_endpoints table) */ +export interface ParsedEndpoint { + role: 'from' | 'to' | 'stop'; + sequence: number; + name: string; + code: string | null; + lat: number; + lng: number; + timezone: string | null; + local_time: string | null; + local_date: string | null; +} + +/** Venue used to auto-create a places row on confirm */ +export interface ParsedVenue { + name: string; + lat?: number; + lng?: number; + address?: string; + website?: string; + phone?: string; +} + +/** Hotel accommodation side-effect data */ +export interface ParsedAccommodation { + check_in?: string; + check_out?: string; + confirmation?: string; +} + +/** + * Parsed reservation preview item — sent to the frontend and passed back on confirm. + * Carries everything createReservation() needs plus _venue / _accommodation for + * server-side side effects, and source for the preview UI. + */ +export interface ParsedBookingItem { + type: string; + title: string; + reservation_time?: string | null; + reservation_end_time?: string | null; + confirmation_number?: string | null; + location?: string | null; + metadata?: Record; + endpoints?: ParsedEndpoint[]; + needs_review?: boolean; + _venue?: ParsedVenue; + _accommodation?: ParsedAccommodation; + source: { fileName: string; index: number }; +} diff --git a/server/src/nest/budget/budget.controller.ts b/server/src/nest/budget/budget.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..295c32f2f8ef034466168017ab2eae5133a422a6 --- /dev/null +++ b/server/src/nest/budget/budget.controller.ts @@ -0,0 +1,252 @@ +import { + Body, + Controller, + Delete, + Get, + Headers, + HttpException, + Param, + Post, + Put, + Query, + UseGuards, +} from '@nestjs/common'; +import type { User } from '../../types'; +import { BudgetService } from './budget.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; + +/** + * /api/trips/:tripId/budget — trip-scoped expense planner. + * + * Byte-identical to the legacy Express route (server/src/routes/budget.ts): + * every handler verifies trip access (404); mutations check 'budget_edit' (403); + * create is 201, the rest 200; bespoke 400/404 bodies reproduced; mutations + * broadcast over WebSocket with the forwarded X-Socket-Id. Static sub-routes + * (summary, settlement, reorder/*) are declared before /:id so they win over the + * param. Updating total_price on a reservation-linked item syncs the price back. + */ +@Controller('api/trips/:tripId/budget') +@UseGuards(JwtAuthGuard) +export class BudgetController { + constructor(private readonly budget: BudgetService) {} + + private requireTrip(tripId: string, user: User) { + const trip = this.budget.verifyTripAccess(tripId, user.id); + if (!trip) { + throw new HttpException({ error: 'Trip not found' }, 404); + } + return trip; + } + + private requireEdit(trip: ReturnType, user: User): void { + if (!this.budget.canEdit(trip!, user)) { + throw new HttpException({ error: 'No permission' }, 403); + } + } + + @Get() + list(@CurrentUser() user: User, @Param('tripId') tripId: string) { + this.requireTrip(tripId, user); + return { items: this.budget.list(tripId) }; + } + + @Get('summary/per-person') + perPerson(@CurrentUser() user: User, @Param('tripId') tripId: string) { + this.requireTrip(tripId, user); + return { summary: this.budget.perPersonSummary(tripId) }; + } + + @Get('settlement') + settlement( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Query('base') base?: string, + ) { + const trip = this.requireTrip(tripId, user); + return this.budget.settlement(tripId, base, (trip as { currency?: string }).currency || 'EUR'); + } + + @Get('settlements') + listSettlements(@CurrentUser() user: User, @Param('tripId') tripId: string) { + this.requireTrip(tripId, user); + return { settlements: this.budget.listSettlements(tripId) }; + } + + @Post('settlements') + createSettlement( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body() body: { from_user_id?: number; to_user_id?: number; amount?: number }, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (body.from_user_id == null || body.to_user_id == null || body.amount == null) { + throw new HttpException({ error: 'from_user_id, to_user_id and amount are required' }, 400); + } + const settlement = this.budget.createSettlement( + tripId, + { from_user_id: body.from_user_id, to_user_id: body.to_user_id, amount: body.amount }, + user.id, + ); + this.budget.broadcast(tripId, 'budget:settlement-created', { settlement }, socketId); + return { settlement }; + } + + @Delete('settlements/:settlementId') + deleteSettlement( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('settlementId') settlementId: string, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!this.budget.deleteSettlement(settlementId, tripId)) { + throw new HttpException({ error: 'Settlement not found' }, 404); + } + this.budget.broadcast(tripId, 'budget:settlement-deleted', { settlementId: Number(settlementId) }, socketId); + return { success: true }; + } + + @Post() + create( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body() body: { name?: string; category?: string; total_price?: number; persons?: number | null; days?: number | null; note?: string | null; expense_date?: string | null }, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!body.name) { + throw new HttpException({ error: 'Name is required' }, 400); + } + const item = this.budget.create(tripId, body as { name: string }); + this.budget.broadcast(tripId, 'budget:created', { item }, socketId); + return { item }; + } + + @Put('reorder/items') + reorderItems( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body('orderedIds') orderedIds: number[], + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + this.budget.reorderItems(tripId, orderedIds); + this.budget.broadcast(tripId, 'budget:reordered', { orderedIds }, socketId); + return { success: true }; + } + + @Put('reorder/categories') + reorderCategories( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body('orderedCategories') orderedCategories: string[], + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + this.budget.reorderCategories(tripId, orderedCategories); + this.budget.broadcast(tripId, 'budget:reordered', { orderedCategories }, socketId); + return { success: true }; + } + + @Put(':id') + update( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('id') id: string, + @Body() body: Record, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + const updated = this.budget.update(id, tripId, body); + if (!updated) { + throw new HttpException({ error: 'Budget item not found' }, 404); + } + if (updated.reservation_id && body.total_price !== undefined) { + this.budget.syncReservationPrice(tripId, updated.reservation_id, updated.total_price, socketId); + } + this.budget.broadcast(tripId, 'budget:updated', { item: updated }, socketId); + return { item: updated }; + } + + @Put(':id/members') + updateMembers( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('id') id: string, + @Body('user_ids') userIds: unknown, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!Array.isArray(userIds)) { + throw new HttpException({ error: 'user_ids must be an array' }, 400); + } + const result = this.budget.updateMembers(id, tripId, userIds); + if (!result) { + throw new HttpException({ error: 'Budget item not found' }, 404); + } + this.budget.broadcast(tripId, 'budget:members-updated', { itemId: Number(id), members: result.members, persons: result.item.persons }, socketId); + return { members: result.members, item: result.item }; + } + + @Put(':id/payers') + setPayers( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('id') id: string, + @Body('payers') payers: unknown, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!Array.isArray(payers)) { + throw new HttpException({ error: 'payers must be an array' }, 400); + } + const item = this.budget.setPayers(id, tripId, payers as { user_id: number; amount: number }[]); + if (!item) { + throw new HttpException({ error: 'Budget item not found' }, 404); + } + this.budget.broadcast(tripId, 'budget:updated', { item }, socketId); + return { item }; + } + + @Put(':id/members/:userId/paid') + toggleMemberPaid( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('id') id: string, + @Param('userId') userId: string, + @Body('paid') paid: boolean, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + const member = this.budget.toggleMemberPaid(id, tripId, userId, paid); + this.budget.broadcast(tripId, 'budget:member-paid-updated', { itemId: Number(id), userId: Number(userId), paid: paid ? 1 : 0 }, socketId); + return { member }; + } + + @Delete(':id') + remove( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('id') id: string, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!this.budget.remove(id, tripId)) { + throw new HttpException({ error: 'Budget item not found' }, 404); + } + this.budget.broadcast(tripId, 'budget:deleted', { itemId: Number(id) }, socketId); + return { success: true }; + } +} diff --git a/server/src/nest/budget/budget.module.ts b/server/src/nest/budget/budget.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..6c5a8d753559512da322df7bbc19b4f037bbfa87 --- /dev/null +++ b/server/src/nest/budget/budget.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { BudgetController } from './budget.controller'; +import { BudgetService } from './budget.service'; + +/** Budget domain (S4 — Phase 2 trip sub-domain). Registered in AppModule. */ +@Module({ + controllers: [BudgetController], + providers: [BudgetService], +}) +export class BudgetModule {} diff --git a/server/src/nest/budget/budget.service.ts b/server/src/nest/budget/budget.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..20bf043470ff949a9601c4f2777e59011a84d883 --- /dev/null +++ b/server/src/nest/budget/budget.service.ts @@ -0,0 +1,108 @@ +import { Injectable } from '@nestjs/common'; +import { db } from '../../db/database'; +import { broadcast } from '../../websocket'; +import { checkPermission } from '../../services/permissions'; +import type { User } from '../../types'; +import * as svc from '../../services/budgetService'; +import { getRates } from '../../services/exchangeRateService'; + +type Trip = NonNullable>; + +/** + * Thin Nest wrapper around the existing budget service. Trip-access, the + * 'budget_edit' permission, the SQL, settlement maths and the WebSocket + * broadcasts all reuse the legacy code unchanged. + */ +@Injectable() +export class BudgetService { + verifyTripAccess(tripId: string, userId: number) { + return svc.verifyTripAccess(tripId, userId); + } + + canEdit(trip: Trip, user: User): boolean { + return checkPermission('budget_edit', user.role, trip.user_id, user.id, trip.user_id !== user.id); + } + + broadcast(tripId: string, event: string, payload: Record, socketId: string | undefined): void { + broadcast(tripId, event, payload, socketId); + } + + list(tripId: string) { + return svc.listBudgetItems(tripId); + } + + perPersonSummary(tripId: string) { + return svc.getPerPersonSummary(tripId); + } + + async settlement(tripId: string, base: string | undefined, tripCurrency: string) { + const effectiveBase = (base || tripCurrency || 'EUR').toUpperCase(); + const rates = await getRates(effectiveBase); + return svc.calculateSettlement(tripId, { base: effectiveBase, rates, tripCurrency }); + } + + create(tripId: string, data: Parameters[1]) { + return svc.createBudgetItem(tripId, data); + } + + update(id: string, tripId: string, data: Parameters[2]) { + return svc.updateBudgetItem(id, tripId, data); + } + + remove(id: string, tripId: string): boolean { + return svc.deleteBudgetItem(id, tripId); + } + + updateMembers(id: string, tripId: string, userIds: number[]) { + return svc.updateMembers(id, tripId, userIds); + } + + toggleMemberPaid(id: string, tripId: string, userId: string, paid: boolean) { + return svc.toggleMemberPaid(id, tripId, userId, paid); + } + + setPayers(id: string, tripId: string, payers: { user_id: number; amount: number }[]) { + return svc.setItemPayers(id, tripId, payers); + } + + listSettlements(tripId: string) { + return svc.listSettlements(tripId); + } + + createSettlement(tripId: string, data: { from_user_id: number; to_user_id: number; amount: number }, userId: number) { + return svc.createSettlement(tripId, data, userId); + } + + deleteSettlement(id: string, tripId: string): boolean { + return svc.deleteSettlement(id, tripId); + } + + reorderItems(tripId: string, orderedIds: number[]): void { + svc.reorderBudgetItems(tripId, orderedIds); + } + + reorderCategories(tripId: string, orderedCategories: string[]): void { + svc.reorderBudgetCategories(tripId, orderedCategories); + } + + /** + * Mirrors the legacy PUT /:id side effect: when a price-linked budget item's + * total_price changes, write it into the reservation's metadata and broadcast + * reservation:updated. Non-fatal — a failure here never breaks the budget update. + */ + syncReservationPrice(tripId: string, reservationId: number, totalPrice: number, socketId: string | undefined): void { + try { + const reservation = db.prepare( + 'SELECT id, metadata FROM reservations WHERE id = ? AND trip_id = ?', + ).get(reservationId, tripId) as { id: number; metadata: string | null } | undefined; + if (!reservation) return; + const meta = reservation.metadata ? JSON.parse(reservation.metadata) : {}; + meta.price = String(totalPrice); + db.prepare('UPDATE reservations SET metadata = ? WHERE id = ?').run(JSON.stringify(meta), reservation.id); + const updatedRes = db.prepare('SELECT * FROM reservations WHERE id = ?').get(reservation.id); + broadcast(tripId, 'reservation:updated', { reservation: updatedRes }, socketId); + } catch (err) { + console.error('[budget] Failed to sync price to reservation:', err); + } + } +} diff --git a/server/src/nest/categories/categories.controller.ts b/server/src/nest/categories/categories.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..cbd9339bcaf4e0469451413e1a97257e09361291 --- /dev/null +++ b/server/src/nest/categories/categories.controller.ts @@ -0,0 +1,65 @@ +import { Body, Controller, Delete, Get, HttpException, Param, Post, Put, UseGuards } from '@nestjs/common'; +import type { Category, CategoryListResponse } from '@trek/shared'; +import type { User } from '../../types'; +import { CategoriesService } from './categories.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { AdminGuard } from '../auth/admin.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; + +/** + * /api/categories — place-category palette CRUD. + * + * Byte-identical to the legacy Express route (server/src/routes/categories.ts): + * listing is open to any authenticated user; create/update/delete require admin + * (JwtAuthGuard + AdminGuard). Status codes match the Nest defaults the legacy + * route also used (201 on create, 200 elsewhere), and the bespoke 400/404 bodies + * are reproduced exactly. + */ +@Controller('api/categories') +export class CategoriesController { + constructor(private readonly categories: CategoriesService) {} + + @Get() + @UseGuards(JwtAuthGuard) + list(): CategoryListResponse { + return { categories: this.categories.list() }; + } + + @Post() + @UseGuards(JwtAuthGuard, AdminGuard) + create( + @CurrentUser() user: User, + @Body('name') name?: string, + @Body('color') color?: string, + @Body('icon') icon?: string, + ): { category: Category } { + if (!name) { + throw new HttpException({ error: 'Category name is required' }, 400); + } + return { category: this.categories.create(user.id, name, color, icon) }; + } + + @Put(':id') + @UseGuards(JwtAuthGuard, AdminGuard) + update( + @Param('id') id: string, + @Body('name') name?: string, + @Body('color') color?: string, + @Body('icon') icon?: string, + ): { category: Category } { + if (!this.categories.getById(id)) { + throw new HttpException({ error: 'Category not found' }, 404); + } + return { category: this.categories.update(id, name, color, icon) }; + } + + @Delete(':id') + @UseGuards(JwtAuthGuard, AdminGuard) + remove(@Param('id') id: string): { success: boolean } { + if (!this.categories.getById(id)) { + throw new HttpException({ error: 'Category not found' }, 404); + } + this.categories.remove(id); + return { success: true }; + } +} diff --git a/server/src/nest/categories/categories.module.ts b/server/src/nest/categories/categories.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..a4ef57f6c8bcd9dd769ccca99d6f854114cdeeac --- /dev/null +++ b/server/src/nest/categories/categories.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { CategoriesController } from './categories.controller'; +import { CategoriesService } from './categories.service'; + +/** Categories domain (L4 leaf module). Registered in AppModule. */ +@Module({ + controllers: [CategoriesController], + providers: [CategoriesService], +}) +export class CategoriesModule {} diff --git a/server/src/nest/categories/categories.service.ts b/server/src/nest/categories/categories.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..5f652f804a158caa64d37dffdd24cac197bc48bd --- /dev/null +++ b/server/src/nest/categories/categories.service.ts @@ -0,0 +1,37 @@ +import { Injectable } from '@nestjs/common'; +import type { Category } from '@trek/shared'; +import { + listCategories, + getCategoryById, + createCategory, + updateCategory, + deleteCategory, +} from '../../services/categoryService'; + +/** + * Thin Nest wrapper around the existing category service. The SQL and the + * default colour/icon fallbacks stay in categoryService, so behaviour is + * unchanged. + */ +@Injectable() +export class CategoriesService { + list(): Category[] { + return listCategories() as Category[]; + } + + getById(id: string | number): Category | undefined { + return getCategoryById(id) as Category | undefined; + } + + create(userId: number, name: string, color?: string, icon?: string): Category { + return createCategory(userId, name, color, icon) as Category; + } + + update(id: string | number, name?: string, color?: string, icon?: string): Category { + return updateCategory(id, name, color, icon) as Category; + } + + remove(id: string | number): void { + deleteCategory(id); + } +} diff --git a/server/src/nest/collab/collab.controller.ts b/server/src/nest/collab/collab.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..b51018b15adbeabc69f7ca2dee190114e35a692f --- /dev/null +++ b/server/src/nest/collab/collab.controller.ts @@ -0,0 +1,300 @@ +import { + Body, + Controller, + Delete, + Get, + Headers, + HttpCode, + HttpException, + Param, + Post, + Put, + Query, + UploadedFile, + UseGuards, + UseInterceptors, +} from '@nestjs/common'; +import { FileInterceptor } from '@nestjs/platform-express'; +import { diskStorage } from 'multer'; +import path from 'path'; +import fs from 'fs'; +import { v4 as uuidv4 } from 'uuid'; +import type { User } from '../../types'; +import { CollabService } from './collab.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; +import { BLOCKED_EXTENSIONS } from '../../services/fileService'; + +const MAX_NOTE_FILE_SIZE = 50 * 1024 * 1024; +const filesDir = path.join(__dirname, '../../../uploads/files'); +const NOTE_UPLOAD = { + storage: diskStorage({ + destination: (_req, _file, cb) => { if (!fs.existsSync(filesDir)) fs.mkdirSync(filesDir, { recursive: true }); cb(null, filesDir); }, + filename: (_req, file, cb) => cb(null, `${uuidv4()}${path.extname(file.originalname)}`), + }), + limits: { fileSize: MAX_NOTE_FILE_SIZE }, + defParamCharset: 'utf8', // parity with legacy routes/collab.ts — preserve non-ASCII original filenames + fileFilter: (_req: unknown, file: Express.Multer.File, cb: (err: Error | null, accept: boolean) => void) => { + const ext = path.extname(file.originalname).toLowerCase(); + if (BLOCKED_EXTENSIONS.includes(ext) || file.mimetype.includes('svg') || file.mimetype.includes('html') || file.mimetype.includes('javascript')) { + const err: Error & { statusCode?: number } = new Error('File type not allowed'); + err.statusCode = 400; + return cb(err, false); + } + cb(null, true); + }, +}; + +/** + * /api/trips/:tripId/collab — shared notes, polls, chat (+ reactions), link + * previews. WebSocket-backed group collaboration. + * + * Byte-identical to the legacy Express route (server/src/routes/collab.ts): trip + * access (404), 'collab_edit' (403) on mutations + 'file_upload' on note files, + * create 201 / rest 200 (vote + react POST stay 200), the bespoke 400/403/404 + * bodies, the chat/note notifications, and all WebSocket broadcasts with the + * forwarded X-Socket-Id. + */ +@Controller('api/trips/:tripId/collab') +@UseGuards(JwtAuthGuard) +export class CollabController { + constructor(private readonly collab: CollabService) {} + + private requireTrip(tripId: string, user: User) { + const trip = this.collab.verifyTripAccess(tripId, user.id); + if (!trip) { + throw new HttpException({ error: 'Trip not found' }, 404); + } + return trip; + } + + private requireEdit(trip: NonNullable>, user: User): void { + if (!this.collab.canEdit(trip, user)) { + throw new HttpException({ error: 'No permission' }, 403); + } + } + + // ── Notes ─────────────────────────────────────────────────────────────── + @Get('notes') + listNotes(@CurrentUser() user: User, @Param('tripId') tripId: string) { + this.requireTrip(tripId, user); + return { notes: this.collab.listNotes(tripId) }; + } + + @Post('notes') + createNote(@CurrentUser() user: User, @Param('tripId') tripId: string, @Body() body: { title?: string; content?: string; category?: string; color?: string; website?: string }, @Headers('x-socket-id') socketId?: string) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!body.title) { + throw new HttpException({ error: 'Title is required' }, 400); + } + const note = this.collab.createNote(tripId, user.id, { + title: body.title, + content: body.content, + category: body.category, + color: body.color, + website: body.website, + }); + this.collab.broadcast(tripId, 'collab:note:created', { note }, socketId); + this.collab.notifyCollab(tripId, user); + return { note }; + } + + @Put('notes/:id') + updateNote(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Body() body: { title?: string; content?: string; category?: string; color?: string; pinned?: number | boolean; website?: string }, @Headers('x-socket-id') socketId?: string) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + const note = this.collab.updateNote(tripId, id, { + title: body.title, + content: body.content, + category: body.category, + color: body.color, + pinned: body.pinned, + website: body.website, + }); + if (!note) { + throw new HttpException({ error: 'Note not found' }, 404); + } + this.collab.broadcast(tripId, 'collab:note:updated', { note }, socketId); + return { note }; + } + + @Delete('notes/:id') + deleteNote(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Headers('x-socket-id') socketId?: string) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!this.collab.deleteNote(tripId, id)) { + throw new HttpException({ error: 'Note not found' }, 404); + } + this.collab.broadcast(tripId, 'collab:note:deleted', { noteId: Number(id) }, socketId); + return { success: true }; + } + + @Post('notes/:id/files') + @UseInterceptors(FileInterceptor('file', NOTE_UPLOAD)) + addNoteFile(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @UploadedFile() file: Express.Multer.File | undefined, @Headers('x-socket-id') socketId?: string) { + const trip = this.requireTrip(tripId, user); + if (!this.collab.canUploadFiles(trip, user)) { + throw new HttpException({ error: 'No permission to upload files' }, 403); + } + if (!file) { + throw new HttpException({ error: 'No file uploaded' }, 400); + } + const result = this.collab.addNoteFile(tripId, id, file); + if (!result) { + throw new HttpException({ error: 'Note not found' }, 404); + } + this.collab.broadcast(tripId, 'collab:note:updated', { note: this.collab.getFormattedNoteById(id) }, socketId); + return result; + } + + @Delete('notes/:id/files/:fileId') + deleteNoteFile(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Param('fileId') fileId: string, @Headers('x-socket-id') socketId?: string) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!this.collab.deleteNoteFile(id, fileId)) { + throw new HttpException({ error: 'File not found' }, 404); + } + this.collab.broadcast(tripId, 'collab:note:updated', { note: this.collab.getFormattedNoteById(id) }, socketId); + return { success: true }; + } + + // ── Polls ─────────────────────────────────────────────────────────────── + @Get('polls') + listPolls(@CurrentUser() user: User, @Param('tripId') tripId: string) { + this.requireTrip(tripId, user); + return { polls: this.collab.listPolls(tripId) }; + } + + @Post('polls') + createPoll(@CurrentUser() user: User, @Param('tripId') tripId: string, @Body() body: { question?: string; options?: unknown[]; multiple?: boolean; multiple_choice?: boolean; deadline?: string }, @Headers('x-socket-id') socketId?: string) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!body.question) { + throw new HttpException({ error: 'Question is required' }, 400); + } + if (!Array.isArray(body.options) || body.options.length < 2) { + throw new HttpException({ error: 'At least 2 options are required' }, 400); + } + const poll = this.collab.createPoll(tripId, user.id, { + question: body.question, + options: body.options, + multiple: body.multiple, + multiple_choice: body.multiple_choice, + deadline: body.deadline, + }); + this.collab.broadcast(tripId, 'collab:poll:created', { poll }, socketId); + return { poll }; + } + + @Post('polls/:id/vote') + @HttpCode(200) + votePoll(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Body('option_index') optionIndex: number, @Headers('x-socket-id') socketId?: string) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + const result = this.collab.votePoll(tripId, id, user.id, optionIndex); + if (result.error === 'not_found') throw new HttpException({ error: 'Poll not found' }, 404); + if (result.error === 'closed') throw new HttpException({ error: 'Poll is closed' }, 400); + if (result.error === 'invalid_index') throw new HttpException({ error: 'Invalid option index' }, 400); + this.collab.broadcast(tripId, 'collab:poll:voted', { poll: result.poll }, socketId); + return { poll: result.poll }; + } + + @Put('polls/:id/close') + closePoll(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Headers('x-socket-id') socketId?: string) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + const poll = this.collab.closePoll(tripId, id); + if (!poll) { + throw new HttpException({ error: 'Poll not found' }, 404); + } + this.collab.broadcast(tripId, 'collab:poll:closed', { poll }, socketId); + return { poll }; + } + + @Delete('polls/:id') + deletePoll(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Headers('x-socket-id') socketId?: string) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!this.collab.deletePoll(tripId, id)) { + throw new HttpException({ error: 'Poll not found' }, 404); + } + this.collab.broadcast(tripId, 'collab:poll:deleted', { pollId: Number(id) }, socketId); + return { success: true }; + } + + // ── Messages ──────────────────────────────────────────────────────────── + @Get('messages') + listMessages(@CurrentUser() user: User, @Param('tripId') tripId: string, @Query('before') before?: string) { + this.requireTrip(tripId, user); + return { messages: this.collab.listMessages(tripId, before) }; + } + + @Post('messages') + createMessage(@CurrentUser() user: User, @Param('tripId') tripId: string, @Body() body: { text?: string; reply_to?: number | null }, @Headers('x-socket-id') socketId?: string) { + if (body.text && body.text.length > 5000) { + throw new HttpException({ error: 'text must be 5000 characters or less' }, 400); + } + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!body.text || !body.text.trim()) { + throw new HttpException({ error: 'Message text is required' }, 400); + } + const result = this.collab.createMessage(tripId, user.id, body.text, body.reply_to); + if (result.error === 'reply_not_found') { + throw new HttpException({ error: 'Reply target message not found' }, 400); + } + this.collab.broadcast(tripId, 'collab:message:created', { message: result.message }, socketId); + const t = body.text.trim(); + this.collab.notifyCollab(tripId, user, t.length > 80 ? t.substring(0, 80) + '...' : t); + return { message: result.message }; + } + + @Post('messages/:id/react') + @HttpCode(200) + react(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Body('emoji') emoji: string, @Headers('x-socket-id') socketId?: string) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!emoji) { + throw new HttpException({ error: 'Emoji is required' }, 400); + } + const result = this.collab.reactMessage(id, tripId, user.id, emoji); + if (!result.found) { + throw new HttpException({ error: 'Message not found' }, 404); + } + this.collab.broadcast(tripId, 'collab:message:reacted', { messageId: Number(id), reactions: result.reactions }, socketId); + return { reactions: result.reactions }; + } + + @Delete('messages/:id') + deleteMessage(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Headers('x-socket-id') socketId?: string) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + const result = this.collab.deleteMessage(tripId, id, user.id); + if (result.error === 'not_found') throw new HttpException({ error: 'Message not found' }, 404); + if (result.error === 'not_owner') throw new HttpException({ error: 'You can only delete your own messages' }, 403); + this.collab.broadcast(tripId, 'collab:message:deleted', { messageId: Number(id), username: result.username || user.username }, socketId); + return { success: true }; + } + + // ── Link preview ────────────────────────────────────────────────────────── + @Get('link-preview') + async linkPreview(@CurrentUser() user: User, @Param('tripId') tripId: string, @Query('url') url?: string) { + // NB: the legacy route does not verify trip access on link-preview; kept 1:1. + void user; void tripId; + if (!url) { + throw new HttpException({ error: 'URL is required' }, 400); + } + try { + const preview = await this.collab.linkPreview(url); + const asRecord = preview as { error?: string }; + if (asRecord.error) { + throw new HttpException({ error: asRecord.error }, 400); + } + return preview; + } catch (err) { + if (err instanceof HttpException) throw err; + return { title: null, description: null, image: null, url }; + } + } +} diff --git a/server/src/nest/collab/collab.module.ts b/server/src/nest/collab/collab.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..118dda846ef6fa4d41cd08b68dfe251f4698f9df --- /dev/null +++ b/server/src/nest/collab/collab.module.ts @@ -0,0 +1,9 @@ +import { Module } from '@nestjs/common'; +import { CollabController } from './collab.controller'; +import { CollabService } from './collab.service'; + +@Module({ + controllers: [CollabController], + providers: [CollabService], +}) +export class CollabModule {} diff --git a/server/src/nest/collab/collab.service.ts b/server/src/nest/collab/collab.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..c7a3435661a990905c537d3fdf821a4fe0ee8579 --- /dev/null +++ b/server/src/nest/collab/collab.service.ts @@ -0,0 +1,63 @@ +import { Injectable } from '@nestjs/common'; +import { db } from '../../db/database'; +import { broadcast } from '../../websocket'; +import { checkPermission } from '../../services/permissions'; +import type { User } from '../../types'; +import * as svc from '../../services/collabService'; + +type Trip = NonNullable>; + +/** + * Thin Nest wrapper around the existing collab service. Trip access, the + * 'collab_edit' / 'file_upload' permissions, the SQL and the WebSocket + * broadcasts reuse the legacy code unchanged. + */ +@Injectable() +export class CollabService { + verifyTripAccess(tripId: string, userId: number) { + return svc.verifyTripAccess(tripId, userId); + } + + canEdit(trip: Trip, user: User): boolean { + return checkPermission('collab_edit', user.role, trip.user_id, user.id, trip.user_id !== user.id); + } + + canUploadFiles(trip: Trip, user: User): boolean { + return checkPermission('file_upload', user.role, trip.user_id, user.id, trip.user_id !== user.id); + } + + broadcast(tripId: string, event: string, payload: Record, socketId: string | undefined): void { + broadcast(tripId, event, payload, socketId); + } + + listNotes(tripId: string) { return svc.listNotes(tripId); } + createNote(tripId: string, userId: number, data: Parameters[2]) { return svc.createNote(tripId, userId, data); } + updateNote(tripId: string, id: string, data: Parameters[2]) { return svc.updateNote(tripId, id, data); } + deleteNote(tripId: string, id: string): boolean { return svc.deleteNote(tripId, id); } + addNoteFile(tripId: string, id: string, file: Parameters[2]) { return svc.addNoteFile(tripId, id, file); } + getFormattedNoteById(id: string) { return svc.getFormattedNoteById(id); } + deleteNoteFile(id: string, fileId: string): boolean { return svc.deleteNoteFile(id, fileId); } + + listPolls(tripId: string) { return svc.listPolls(tripId); } + createPoll(tripId: string, userId: number, data: Parameters[2]) { return svc.createPoll(tripId, userId, data); } + votePoll(tripId: string, id: string, userId: number, optionIndex: number) { return svc.votePoll(tripId, id, userId, optionIndex); } + closePoll(tripId: string, id: string) { return svc.closePoll(tripId, id); } + deletePoll(tripId: string, id: string): boolean { return svc.deletePoll(tripId, id); } + + listMessages(tripId: string, before?: string) { return svc.listMessages(tripId, before); } + createMessage(tripId: string, userId: number, text: string, replyTo?: number | null) { return svc.createMessage(tripId, userId, text, replyTo); } + deleteMessage(tripId: string, id: string, userId: number) { return svc.deleteMessage(tripId, id, userId); } + reactMessage(id: string, tripId: string, userId: number, emoji: string) { return svc.addOrRemoveReaction(id, tripId, userId, emoji); } + + linkPreview(url: string) { return svc.fetchLinkPreview(url); } + + /** Fire-and-forget collab notification (mirrors the route's dynamic import). */ + notifyCollab(tripId: string, actor: User, preview?: string): void { + import('../../services/notificationService').then(({ send }) => { + const tripInfo = db.prepare('SELECT title FROM trips WHERE id = ?').get(tripId) as { title: string } | undefined; + const params: Record = { trip: tripInfo?.title || 'Untitled', actor: actor.email, tripId: String(tripId) }; + if (preview !== undefined) params.preview = preview; + send({ event: 'collab_message', actorId: actor.id, scope: 'trip', targetId: Number(tripId), params }).catch(() => {}); + }); + } +} diff --git a/server/src/nest/common/idempotency.interceptor.ts b/server/src/nest/common/idempotency.interceptor.ts new file mode 100644 index 0000000000000000000000000000000000000000..d7a91c2793cde37c8a164436d27588515e72e1b3 --- /dev/null +++ b/server/src/nest/common/idempotency.interceptor.ts @@ -0,0 +1,90 @@ +import { CallHandler, ExecutionContext, HttpException, Injectable, NestInterceptor } from '@nestjs/common'; +import type { Request, Response } from 'express'; +import { Observable, of } from 'rxjs'; +import { DatabaseService } from '../database/database.service'; + +/** + * Nest counterpart of the legacy `applyIdempotency` middleware + * (server/src/middleware/idempotency.ts), which the Express `authenticate` + * middleware runs on every authenticated request. + * + * The TREK client attaches an `X-Idempotency-Key` to ALL write operations (see + * client/src/api/client.ts) and the offline sync queue replays mutations with + * that key, so a migrated mutating route MUST honour it — otherwise a replayed + * POST would create a duplicate instead of returning the cached response. This + * reproduces the legacy behaviour exactly, against the same `idempotency_keys` + * table: + * - non-mutating method, or no key, or no authenticated user -> pass through + * - key longer than the cap -> 400 with the exact legacy message + * - (key, user, method, path) already stored -> replay the cached response + * - otherwise -> capture a successful JSON response under the key + * + * Capturing wraps `res.json`, so 204 / `res.end()` responses are not cached — + * matching the Express wrapper, which only fires on `res.json`. + */ + +const MUTATING_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']); +const MAX_KEY_LENGTH = 128; +const MAX_CACHED_BODY_BYTES = 256 * 1024; + +interface IdempotencyRow { + status_code: number; + response_body: string; +} + +@Injectable() +export class IdempotencyInterceptor implements NestInterceptor { + constructor(private readonly database: DatabaseService) {} + + intercept(context: ExecutionContext, next: CallHandler): Observable { + const req = context.switchToHttp().getRequest(); + const res = context.switchToHttp().getResponse(); + + if (!MUTATING_METHODS.has(req.method)) return next.handle(); + + const key = req.headers['x-idempotency-key'] as string | undefined; + if (!key) return next.handle(); + + // Idempotency only applies to authenticated requests — the legacy code runs + // inside `authenticate`, after req.user is set. + const userId = req.user?.id; + if (userId == null) return next.handle(); + + if (key.length > MAX_KEY_LENGTH) { + throw new HttpException({ error: 'X-Idempotency-Key exceeds maximum length of 128 characters' }, 400); + } + + // Scope the lookup by method + path as well as user, so the same key replayed + // against a different endpoint can't return an unrelated cached body. + const existing = this.database.get( + 'SELECT status_code, response_body FROM idempotency_keys WHERE key = ? AND user_id = ? AND method = ? AND path = ?', + key, userId, req.method, req.path, + ); + if (existing) { + res.status(existing.status_code); + return of(JSON.parse(existing.response_body)); + } + + const originalJson = res.json.bind(res); + const database = this.database; + res.json = function (body: unknown): Response { + if (res.statusCode >= 200 && res.statusCode < 300) { + try { + const serialized = JSON.stringify(body); + if (serialized.length <= MAX_CACHED_BODY_BYTES) { + database.run( + `INSERT OR IGNORE INTO idempotency_keys (key, user_id, method, path, status_code, response_body, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?)`, + key, userId, req.method, req.path, res.statusCode, serialized, Math.floor(Date.now() / 1000), + ); + } + } catch { + // Non-fatal: if storage fails, the request still succeeds. + } + } + return originalJson(body); + }; + + return next.handle(); + } +} diff --git a/server/src/nest/common/trek-exception.filter.ts b/server/src/nest/common/trek-exception.filter.ts new file mode 100644 index 0000000000000000000000000000000000000000..6b8910788fd9fde6270c4057fc6f394b4757ad03 --- /dev/null +++ b/server/src/nest/common/trek-exception.filter.ts @@ -0,0 +1,69 @@ +import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from '@nestjs/common'; +import type { Response } from 'express'; +import { MulterError } from 'multer'; + +/** + * Normalises every Nest exception to TREK's legacy error envelope so migrated + * routes are byte-identical for the client. This mirrors the legacy global + * Express error handler (server/src/app.ts) exactly: + * - multer errors -> 413 (LIMIT_FILE_SIZE) / 400, body { error: } + * - { error, code? } bodies -> passed through unchanged (auth guards, ZodValidationPipe) + * - other HttpExceptions -> { error: } at the same status + * - plain errors w/ statusCode/status -> that status, { error: } for 4xx + * - everything else -> 500 { error: 'Internal server error' } + * + * Without the multer + statusCode handling, file-upload rejections (multer's + * LIMIT_FILE_SIZE and the fileFilter errors that carry `statusCode = 400`) would + * collapse to Nest's `{ statusCode, message, error }` 413 body or a 500, diverging + * from the legacy `{ error: 'File too large' }` (413) and `{ error: '' }` (400). + */ +@Catch() +export class TrekExceptionFilter implements ExceptionFilter { + catch(exception: unknown, host: ArgumentsHost): void { + const res = host.switchToHttp().getResponse(); + + // 1. Raw multer errors that slipped past @nestjs/platform-express's + // transformException (it leaves codes it does not recognise untouched). + // Legacy: LIMIT_FILE_SIZE -> 413, everything else -> 400, body { error: message }. + if (exception instanceof MulterError) { + const status = exception.code === 'LIMIT_FILE_SIZE' ? 413 : 400; + res.status(status).json({ error: exception.message }); + return; + } + + if (exception instanceof HttpException) { + const status = exception.getStatus(); + const body = exception.getResponse(); + + if (body && typeof body === 'object') { + const obj = body as Record; + // TREK-native shape ({ error } / { error, code } from guards + the Zod + // pipe): pass through verbatim. Nest's own exceptions instead carry the + // { statusCode, message, error } trio (incl. transformException's + // PayloadTooLargeException for LIMIT_FILE_SIZE) and must be normalised. + if ('error' in obj && !('statusCode' in obj) && !('message' in obj)) { + res.status(status).json(obj); + return; + } + const raw = obj.message ?? obj.error; + const message = + status < 500 ? (Array.isArray(raw) ? raw.join(', ') : String(raw ?? 'Error')) : 'Internal server error'; + res.status(status).json({ error: message }); + return; + } + + const message = status < 500 ? String(body ?? 'Error') : 'Internal server error'; + res.status(status).json({ error: message }); + return; + } + + // 2. Plain errors carrying an explicit status (the fileFilter rejections set + // `statusCode = 400`; transformException returns them unchanged). Legacy: + // status = err.statusCode || err.status || 500; 4xx exposes err.message. + const err = exception as { statusCode?: number; status?: number; message?: unknown } | null; + const status = (err && (err.statusCode || err.status)) || 500; + if (status >= 500) console.error('Unhandled error:', exception); + const message = status < 500 ? String(err?.message ?? 'Error') : 'Internal server error'; + res.status(status).json({ error: message }); + } +} diff --git a/server/src/nest/common/zod-validation.pipe.ts b/server/src/nest/common/zod-validation.pipe.ts new file mode 100644 index 0000000000000000000000000000000000000000..3a855b59abc2bf9f76449a3590f58ad290e3ad99 --- /dev/null +++ b/server/src/nest/common/zod-validation.pipe.ts @@ -0,0 +1,26 @@ +import { ArgumentMetadata, HttpException, Injectable, PipeTransform } from '@nestjs/common'; +import type { ZodType } from 'zod'; + +/** + * Validates an incoming @Body()/@Query() against a Zod schema (from @trek/shared) + * and returns the parsed, typed value. On failure it throws TREK's error envelope + * `{ error: string }` with status 400 — the same shape the legacy routes produce, + * so the client's error handling is unaffected. + * + * Usage: `@Body(new ZodValidationPipe(someSchema)) dto: Dto`. + */ +@Injectable() +export class ZodValidationPipe implements PipeTransform { + constructor(private readonly schema: ZodType) {} + + transform(value: unknown, _metadata: ArgumentMetadata): unknown { + const result = this.schema.safeParse(value); + if (!result.success) { + const message = result.error.issues + .map((i) => `${i.path.join('.') || 'body'}: ${i.message}`) + .join('; '); + throw new HttpException({ error: message }, 400); + } + return result.data; + } +} diff --git a/server/src/nest/config/config.controller.ts b/server/src/nest/config/config.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..8cf047ceaa909afd4d9aa8c11b89075d95aa3d34 --- /dev/null +++ b/server/src/nest/config/config.controller.ts @@ -0,0 +1,18 @@ +import { Controller, Get } from '@nestjs/common'; +import type { PublicConfig } from '@trek/shared'; +import { DEFAULT_LANGUAGE } from '../../config'; + +/** + * /api/config — public (unauthenticated) bootstrap config. + * + * Byte-identical to the legacy Express route (server/src/routes/publicConfig.ts): + * no auth guard, returns the server's configured default language. Deliberately + * has no service — it just surfaces a config constant, exactly like the original. + */ +@Controller('api/config') +export class ConfigController { + @Get() + getConfig(): PublicConfig { + return { defaultLanguage: DEFAULT_LANGUAGE }; + } +} diff --git a/server/src/nest/config/config.module.ts b/server/src/nest/config/config.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..84d2dfaf9f5bb4e88e3bd9f1ba907fc9439451dc --- /dev/null +++ b/server/src/nest/config/config.module.ts @@ -0,0 +1,8 @@ +import { Module } from '@nestjs/common'; +import { ConfigController } from './config.controller'; + +/** Public config domain (L2 leaf module). Registered in AppModule. */ +@Module({ + controllers: [ConfigController], +}) +export class ConfigModule {} diff --git a/server/src/nest/database/database.module.ts b/server/src/nest/database/database.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..e805238b6fb20dd0cc909c9eaa2fa8031d16c788 --- /dev/null +++ b/server/src/nest/database/database.module.ts @@ -0,0 +1,13 @@ +import { Global, Module } from '@nestjs/common'; +import { DatabaseService } from './database.service'; + +/** + * Global so every migrated module can inject DatabaseService without re-importing. + * Wraps the existing better-sqlite3 singleton (no new connection). + */ +@Global() +@Module({ + providers: [DatabaseService], + exports: [DatabaseService], +}) +export class DatabaseModule {} diff --git a/server/src/nest/database/database.service.ts b/server/src/nest/database/database.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..b43731b89156b0cbffe0ed53f260e7a8bafdf105 --- /dev/null +++ b/server/src/nest/database/database.service.ts @@ -0,0 +1,39 @@ +import { Injectable } from '@nestjs/common'; +import type Database from 'better-sqlite3'; +import { db } from '../../db/database'; + +/** + * Injectable wrapper around TREK's existing better-sqlite3 connection. + * + * `db` is a Proxy onto the singleton connection the legacy app already uses + * (WAL enabled), so Nest modules share the exact same connection — no second + * connection, no split state, single writer preserved. + */ +@Injectable() +export class DatabaseService { + /** The shared better-sqlite3 connection (same singleton the legacy app uses). */ + get connection(): Database.Database { + return db; + } + + prepare(sql: string): Database.Statement { + return db.prepare(sql); + } + + get(sql: string, ...params: unknown[]): T | undefined { + return db.prepare(sql).get(...params) as T | undefined; + } + + all(sql: string, ...params: unknown[]): T[] { + return db.prepare(sql).all(...params) as T[]; + } + + run(sql: string, ...params: unknown[]): Database.RunResult { + return db.prepare(sql).run(...params); + } + + /** Run `fn` inside a synchronous better-sqlite3 transaction. */ + transaction(fn: (conn: Database.Database) => T): T { + return db.transaction(() => fn(db))(); + } +} diff --git a/server/src/nest/days/day-notes.controller.ts b/server/src/nest/days/day-notes.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..a293e95071d5fe58c33d3be503e98eb3ddf2787e --- /dev/null +++ b/server/src/nest/days/day-notes.controller.ts @@ -0,0 +1,127 @@ +import { + Body, + Controller, + Delete, + Get, + Headers, + HttpException, + Param, + Post, + Put, + UseGuards, +} from '@nestjs/common'; +import type { User } from '../../types'; +import { DayNotesService } from './day-notes.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; + +type DayNoteBody = { text?: string; time?: string; icon?: string; sort_order?: number }; + +// Mirrors the legacy validateStringLengths({ text: 500, time: 150 }) middleware, +// which runs BEFORE the trip-access check — so an over-long field 400s first. +const MAX_LENGTHS: Record = { text: 500, time: 150 }; + +function validateLengths(body: Record): void { + for (const [field, max] of Object.entries(MAX_LENGTHS)) { + const value = body[field]; + if (value && typeof value === 'string' && value.length > max) { + throw new HttpException({ error: `${field} must be ${max} characters or less` }, 400); + } + } +} + +/** + * /api/trips/:tripId/days/:dayId/notes — free-text annotations on a day. + * + * Byte-identical to the legacy Express route (server/src/routes/dayNotes.ts): + * the string-length guard runs first (400), then trip access (404), then the + * 'day_edit' permission (403); create 201 / rest 200; the bespoke "Day not + * found" / "Note not found" / "Text required" bodies; WebSocket broadcasts with + * the forwarded X-Socket-Id. + */ +@Controller('api/trips/:tripId/days/:dayId/notes') +@UseGuards(JwtAuthGuard) +export class DayNotesController { + constructor(private readonly notes: DayNotesService) {} + + private requireTrip(tripId: string, user: User) { + const trip = this.notes.verifyTripAccess(tripId, user.id); + if (!trip) { + throw new HttpException({ error: 'Trip not found' }, 404); + } + return trip; + } + + private requireEdit(trip: NonNullable>, user: User): void { + if (!this.notes.canEdit(trip, user)) { + throw new HttpException({ error: 'No permission' }, 403); + } + } + + @Get() + list(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('dayId') dayId: string) { + this.requireTrip(tripId, user); + return { notes: this.notes.list(dayId, tripId) }; + } + + @Post() + create( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('dayId') dayId: string, + @Body() body: DayNoteBody, + @Headers('x-socket-id') socketId?: string, + ) { + validateLengths(body); + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!this.notes.dayExists(dayId, tripId)) { + throw new HttpException({ error: 'Day not found' }, 404); + } + if (!body.text?.trim()) { + throw new HttpException({ error: 'Text required' }, 400); + } + const note = this.notes.create(dayId, tripId, body.text, body.time, body.icon, body.sort_order); + this.notes.broadcast(tripId, 'dayNote:created', { dayId: Number(dayId), note }, socketId); + return { note }; + } + + @Put(':id') + update( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('dayId') dayId: string, + @Param('id') id: string, + @Body() body: DayNoteBody, + @Headers('x-socket-id') socketId?: string, + ) { + validateLengths(body); + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + const current = this.notes.getNote(id, dayId, tripId); + if (!current) { + throw new HttpException({ error: 'Note not found' }, 404); + } + const note = this.notes.update(id, current as never, { text: body.text, time: body.time, icon: body.icon, sort_order: body.sort_order }); + this.notes.broadcast(tripId, 'dayNote:updated', { dayId: Number(dayId), note }, socketId); + return { note }; + } + + @Delete(':id') + remove( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('dayId') dayId: string, + @Param('id') id: string, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!this.notes.getNote(id, dayId, tripId)) { + throw new HttpException({ error: 'Note not found' }, 404); + } + this.notes.remove(id); + this.notes.broadcast(tripId, 'dayNote:deleted', { noteId: Number(id), dayId: Number(dayId) }, socketId); + return { success: true }; + } +} diff --git a/server/src/nest/days/day-notes.service.ts b/server/src/nest/days/day-notes.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..b43cde8b62ceabb6051d803a92657aaac1980159 --- /dev/null +++ b/server/src/nest/days/day-notes.service.ts @@ -0,0 +1,50 @@ +import { Injectable } from '@nestjs/common'; +import { broadcast } from '../../websocket'; +import { checkPermission } from '../../services/permissions'; +import type { User } from '../../types'; +import * as dayNoteService from '../../services/dayNoteService'; + +type Trip = NonNullable>; + +/** + * Thin Nest wrapper around the existing day-note service. Trip access + the + * 'day_edit' permission reuse the legacy checks; the SQL is unchanged. + */ +@Injectable() +export class DayNotesService { + verifyTripAccess(tripId: string, userId: number) { + return dayNoteService.verifyTripAccess(tripId, userId); + } + + canEdit(trip: Trip, user: User): boolean { + return checkPermission('day_edit', user.role, trip.user_id, user.id, trip.user_id !== user.id); + } + + broadcast(tripId: string, event: string, payload: Record, socketId: string | undefined): void { + broadcast(tripId, event, payload, socketId); + } + + list(dayId: string, tripId: string) { + return dayNoteService.listNotes(dayId, tripId); + } + + dayExists(dayId: string, tripId: string) { + return dayNoteService.dayExists(dayId, tripId); + } + + getNote(id: string, dayId: string, tripId: string) { + return dayNoteService.getNote(id, dayId, tripId); + } + + create(dayId: string, tripId: string, text: string, time?: string, icon?: string, sortOrder?: number) { + return dayNoteService.createNote(dayId, tripId, text, time, icon, sortOrder); + } + + update(id: string, current: Parameters[1], fields: { text?: string; time?: string; icon?: string; sort_order?: number }) { + return dayNoteService.updateNote(id, current, fields); + } + + remove(id: string): void { + dayNoteService.deleteNote(id); + } +} diff --git a/server/src/nest/days/days.controller.ts b/server/src/nest/days/days.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..1a669039d49312feb7e75742ab6de082a33840d8 --- /dev/null +++ b/server/src/nest/days/days.controller.ts @@ -0,0 +1,132 @@ +import { + Body, + Controller, + Delete, + Get, + Headers, + HttpException, + Param, + Post, + Put, + UseGuards, +} from '@nestjs/common'; +import type { User } from '../../types'; +import { DaysService } from './days.service'; +import { DayReorderError } from '../../services/dayService'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; + +/** + * /api/trips/:tripId/days — trip itinerary days. + * + * Byte-identical to the legacy Express route (server/src/routes/days.ts): trip + * access (404 "Trip not found"), the 'day_edit' permission on mutations (403), + * create 201 / rest 200, the bespoke 404 "Day not found", and WebSocket + * broadcasts with the forwarded X-Socket-Id. + */ +@Controller('api/trips/:tripId/days') +@UseGuards(JwtAuthGuard) +export class DaysController { + constructor(private readonly days: DaysService) {} + + private requireTrip(tripId: string, user: User) { + const trip = this.days.verifyTripAccess(tripId, user.id); + if (!trip) { + throw new HttpException({ error: 'Trip not found' }, 404); + } + return trip; + } + + private requireEdit(trip: NonNullable>, user: User): void { + if (!this.days.canEdit(trip, user)) { + throw new HttpException({ error: 'No permission' }, 403); + } + } + + @Get() + list(@CurrentUser() user: User, @Param('tripId') tripId: string) { + this.requireTrip(tripId, user); + return this.days.list(tripId); + } + + @Post() + create( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body() body: { date?: string; notes?: string; position?: number }, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + // A `position` means "insert a new empty day here" (which on a dated trip + // extends the trip and re-pins dates); without it, the legacy append. + const day = body.position !== undefined + ? this.days.insert(tripId, body.position) + : this.days.create(tripId, body.date, body.notes); + // An insert can shuffle dates/positions of other days, so collaborators + // refetch the whole list; a plain append only needs the new day. + const event = body.position !== undefined ? 'day:reordered' : 'day:created'; + this.days.broadcast(tripId, event, { day }, socketId); + return { day }; + } + + @Put('reorder') + reorder( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body() body: { orderedIds?: number[] }, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!Array.isArray(body.orderedIds)) { + throw new HttpException({ error: 'orderedIds must be an array' }, 400); + } + try { + this.days.reorder(tripId, body.orderedIds); + } catch (err) { + if (err instanceof DayReorderError) { + throw new HttpException({ error: err.message }, 400); + } + throw err; + } + this.days.broadcast(tripId, 'day:reordered', { orderedIds: body.orderedIds }, socketId); + return { success: true }; + } + + @Put(':id') + update( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('id') id: string, + @Body() body: { notes?: string; title?: string | null }, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + const current = this.days.getDay(id, tripId); + if (!current) { + throw new HttpException({ error: 'Day not found' }, 404); + } + const day = this.days.update(id, current as never, { notes: body.notes, title: body.title }); + this.days.broadcast(tripId, 'day:updated', { day }, socketId); + return { day }; + } + + @Delete(':id') + remove( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('id') id: string, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!this.days.getDay(id, tripId)) { + throw new HttpException({ error: 'Day not found' }, 404); + } + this.days.remove(id); + this.days.broadcast(tripId, 'day:deleted', { dayId: Number(id) }, socketId); + return { success: true }; + } +} diff --git a/server/src/nest/days/days.module.ts b/server/src/nest/days/days.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..eb19bfe98f9130270550fd3ec922b3ed3a2912ee --- /dev/null +++ b/server/src/nest/days/days.module.ts @@ -0,0 +1,16 @@ +import { Module } from '@nestjs/common'; +import { DaysController } from './days.controller'; +import { DaysService } from './days.service'; +import { DayNotesController } from './day-notes.controller'; +import { DayNotesService } from './day-notes.service'; + +/** + * Days + day-notes domain (S6 — Phase 2 trip sub-domain). The single prefix + * /api/trips/:tripId/days covers both the days mount and the nested + * /days/:dayId/notes mount. + */ +@Module({ + controllers: [DaysController, DayNotesController], + providers: [DaysService, DayNotesService], +}) +export class DaysModule {} diff --git a/server/src/nest/days/days.service.ts b/server/src/nest/days/days.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..b40fac7cc79a739450edadf8c8f4656014bf39aa --- /dev/null +++ b/server/src/nest/days/days.service.ts @@ -0,0 +1,57 @@ +import { Injectable } from '@nestjs/common'; +import { broadcast } from '../../websocket'; +import { canAccessTrip } from '../../db/database'; +import { checkPermission } from '../../services/permissions'; +import type { User } from '../../types'; +import * as dayService from '../../services/dayService'; + +type Trip = { user_id: number }; + +/** + * Thin Nest wrapper around the day parts of the existing day service. Trip access + * mirrors the requireTripAccess middleware (canAccessTrip); mutations use the + * 'day_edit' permission. The SQL and the day/assignment shaping reuse the legacy + * code unchanged. + */ +@Injectable() +export class DaysService { + verifyTripAccess(tripId: string, userId: number) { + return canAccessTrip(Number(tripId), userId) as Trip | null | undefined; + } + + canEdit(trip: Trip, user: User): boolean { + return checkPermission('day_edit', user.role, trip.user_id, user.id, trip.user_id !== user.id); + } + + broadcast(tripId: string, event: string, payload: Record, socketId: string | undefined): void { + broadcast(tripId, event, payload, socketId); + } + + list(tripId: string) { + return dayService.listDays(tripId); + } + + getDay(id: string, tripId: string) { + return dayService.getDay(id, tripId); + } + + create(tripId: string, date?: string, notes?: string) { + return dayService.createDay(tripId, date, notes); + } + + insert(tripId: string, position?: number) { + return dayService.insertDay(tripId, position); + } + + reorder(tripId: string, orderedIds: number[]) { + return dayService.reorderDays(tripId, orderedIds); + } + + update(id: string, current: Parameters[1], fields: { notes?: string; title?: string | null }) { + return dayService.updateDay(id, current, fields); + } + + remove(id: string): void { + dayService.deleteDay(id); + } +} diff --git a/server/src/nest/files/files-download.controller.ts b/server/src/nest/files/files-download.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..2fab2d18a4f0c41144fad5750560e896bfb4ff7d --- /dev/null +++ b/server/src/nest/files/files-download.controller.ts @@ -0,0 +1,58 @@ +import { Controller, Get, HttpException, Param, Req, Res } from '@nestjs/common'; +import type { Request, Response } from 'express'; +import path from 'path'; +import fs from 'fs'; +import { FilesService } from './files.service'; + +/** + * GET /api/trips/:tripId/files/:id/download — authenticated file download. + * + * Deliberately NOT behind the JwtAuthGuard: it accepts a cookie, a Bearer header + * OR a one-shot `?token=` query param (so links can be opened directly), all via + * the legacy authenticateDownload helper. Byte-identical to the legacy route: + * 401 token, 404 trip/file, 403 path traversal, .pkpass served inline for Wallet. + */ +@Controller('api/trips/:tripId/files') +export class FilesDownloadController { + constructor(private readonly files: FilesService) {} + + @Get(':id/download') + download(@Req() req: Request, @Res() res: Response, @Param('tripId') tripId: string, @Param('id') id: string): void { + const auth = this.files.authenticateDownload(req); + if ('error' in auth) { + throw new HttpException({ error: auth.error }, auth.status); + } + + const trip = this.files.verifyTripAccess(tripId, auth.userId); + if (!trip) { + throw new HttpException({ error: 'Trip not found' }, 404); + } + + const file = this.files.getFileById(id, tripId); + if (!file) { + throw new HttpException({ error: 'File not found' }, 404); + } + + const { resolved, safe } = this.files.resolveFilePath(file.filename); + if (!safe) { + throw new HttpException({ error: 'Forbidden' }, 403); + } + if (!fs.existsSync(resolved)) { + throw new HttpException({ error: 'File not found' }, 404); + } + + // Serve Apple Wallet passes inline with the canonical MIME type so Safari + // (iOS/macOS) hands them to Wallet instead of downloading as a blob. + if (path.extname(resolved).toLowerCase() === '.pkpass') { + res.setHeader('Content-Type', 'application/vnd.apple.pkpass'); + res.setHeader('Content-Disposition', `inline; filename="${path.basename(file.original_name || resolved)}"`); + } + + // Serve with an explicit { root } + basename rather than an absolute path: + // under the Nest ExpressAdapter, res.sendFile(absolutePath) resolves the + // file relative to the (rewritten) req.url and fails with a spurious + // "Not Found", whereas the root-relative form streams correctly. The + // resolveFilePath guard above already pins this to the uploads dir. + res.sendFile(path.basename(resolved), { root: path.dirname(resolved) }); + } +} diff --git a/server/src/nest/files/files.controller.ts b/server/src/nest/files/files.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb290c6671c1b4a761fa3b05029add85ccd50ae6 --- /dev/null +++ b/server/src/nest/files/files.controller.ts @@ -0,0 +1,225 @@ +import { + Body, + Controller, + Delete, + Get, + Headers, + HttpCode, + HttpException, + Param, + Patch, + Post, + Put, + Query, + UploadedFile, + UseGuards, + UseInterceptors, +} from '@nestjs/common'; +import { FileInterceptor } from '@nestjs/platform-express'; +import { diskStorage } from 'multer'; +import path from 'path'; +import fs from 'fs'; +import { v4 as uuidv4 } from 'uuid'; +import type { User } from '../../types'; +import { FilesService } from './files.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; +import { MAX_FILE_SIZE, BLOCKED_EXTENSIONS, filesDir, getAllowedExtensions } from '../../services/fileService'; +import { isDemoEmail } from '../../services/demo'; + +const UPLOAD = { + storage: diskStorage({ + destination: (_req, _file, cb) => { if (!fs.existsSync(filesDir)) fs.mkdirSync(filesDir, { recursive: true }); cb(null, filesDir); }, + filename: (_req, file, cb) => cb(null, `${uuidv4()}${path.extname(file.originalname)}`), + }), + limits: { fileSize: MAX_FILE_SIZE }, + defParamCharset: 'utf8', // parity with legacy routes/files.ts — preserve non-ASCII original filenames + fileFilter: (_req: unknown, file: Express.Multer.File, cb: (err: Error | null, accept: boolean) => void) => { + const ext = path.extname(file.originalname).toLowerCase(); + const reject = () => { + const err: Error & { statusCode?: number } = new Error('File type not allowed'); + err.statusCode = 400; + cb(err, false); + }; + if (BLOCKED_EXTENSIONS.includes(ext) || file.mimetype.includes('svg')) return reject(); + const allowed = getAllowedExtensions().split(',').map((e) => e.trim().toLowerCase()); + const fileExt = ext.replace('.', ''); + if (allowed.includes(fileExt) || (allowed.includes('*') && !BLOCKED_EXTENSIONS.includes(ext))) return cb(null, true); + reject(); + }, +}; + +/** + * /api/trips/:tripId/files — trip file manager (upload, metadata, starring, + * trash + restore, reservation links). The authenticated download lives in the + * separate unguarded FilesDownloadController (it carries its own token auth). + * + * Byte-identical to the legacy Express route (server/src/routes/files.ts): trip + * access (404), the demo-mode upload block (403), the file_upload/file_edit/ + * file_delete permissions (403), create 201 / rest 200, the bespoke bodies and + * the WebSocket broadcasts with the forwarded X-Socket-Id. + */ +@Controller('api/trips/:tripId/files') +@UseGuards(JwtAuthGuard) +export class FilesController { + constructor(private readonly files: FilesService) {} + + private requireTrip(tripId: string, user: User) { + const trip = this.files.verifyTripAccess(tripId, user.id); + if (!trip) { + throw new HttpException({ error: 'Trip not found' }, 404); + } + return trip; + } + + @Get() + list(@CurrentUser() user: User, @Param('tripId') tripId: string, @Query('trash') trash?: string) { + this.requireTrip(tripId, user); + return { files: this.files.listFiles(tripId, trash === 'true') }; + } + + @Post() + @UseInterceptors(FileInterceptor('file', UPLOAD)) + upload( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @UploadedFile() file: Express.Multer.File | undefined, + @Body() body: { place_id?: string; description?: string; reservation_id?: string }, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + if (process.env.DEMO_MODE?.toLowerCase() === 'true' && isDemoEmail(user.email)) { + throw new HttpException({ error: 'Uploads are disabled in demo mode. Self-host TREK for full functionality.' }, 403); + } + if (!this.files.can('file_upload', trip, user)) { + throw new HttpException({ error: 'No permission to upload files' }, 403); + } + if (!file) { + throw new HttpException({ error: 'No file uploaded' }, 400); + } + const created = this.files.createFile(tripId, file, user.id, { + place_id: body.place_id, + description: body.description, + reservation_id: body.reservation_id, + }); + this.files.broadcast(tripId, 'file:created', { file: created }, socketId); + return { file: created }; + } + + @Put(':id') + update(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Body() body: { description?: string; place_id?: string | null; reservation_id?: string | null }, @Headers('x-socket-id') socketId?: string) { + const trip = this.requireTrip(tripId, user); + if (!this.files.can('file_edit', trip, user)) { + throw new HttpException({ error: 'No permission to edit files' }, 403); + } + const file = this.files.getFileById(id, tripId); + if (!file) { + throw new HttpException({ error: 'File not found' }, 404); + } + const updated = this.files.updateFile(id, file, { description: body.description, place_id: body.place_id, reservation_id: body.reservation_id }); + this.files.broadcast(tripId, 'file:updated', { file: updated }, socketId); + return { file: updated }; + } + + @Patch(':id/star') + star(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Headers('x-socket-id') socketId?: string) { + const trip = this.requireTrip(tripId, user); + if (!this.files.can('file_edit', trip, user)) { + throw new HttpException({ error: 'No permission' }, 403); + } + const file = this.files.getFileById(id, tripId); + if (!file) { + throw new HttpException({ error: 'File not found' }, 404); + } + const updated = this.files.toggleStarred(id, file.starred); + this.files.broadcast(tripId, 'file:updated', { file: updated }, socketId); + return { file: updated }; + } + + @Delete('trash/empty') + async emptyTrash(@CurrentUser() user: User, @Param('tripId') tripId: string) { + const trip = this.requireTrip(tripId, user); + if (!this.files.can('file_delete', trip, user)) { + throw new HttpException({ error: 'No permission' }, 403); + } + const deleted = await this.files.emptyTrash(tripId); + return { success: true, deleted }; + } + + @Delete(':id/permanent') + async permanent(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Headers('x-socket-id') socketId?: string) { + const trip = this.requireTrip(tripId, user); + if (!this.files.can('file_delete', trip, user)) { + throw new HttpException({ error: 'No permission' }, 403); + } + const file = this.files.getDeletedFile(id, tripId); + if (!file) { + throw new HttpException({ error: 'File not found in trash' }, 404); + } + await this.files.permanentDeleteFile(file); + this.files.broadcast(tripId, 'file:deleted', { fileId: Number(id) }, socketId); + return { success: true }; + } + + @Delete(':id') + remove(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Headers('x-socket-id') socketId?: string) { + const trip = this.requireTrip(tripId, user); + if (!this.files.can('file_delete', trip, user)) { + throw new HttpException({ error: 'No permission to delete files' }, 403); + } + const file = this.files.getFileById(id, tripId); + if (!file) { + throw new HttpException({ error: 'File not found' }, 404); + } + this.files.softDeleteFile(id); + this.files.broadcast(tripId, 'file:deleted', { fileId: Number(id) }, socketId); + return { success: true }; + } + + @Post(':id/restore') + @HttpCode(200) // Express answers restore with res.json (200), not the POST-default 201. + restore(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Headers('x-socket-id') socketId?: string) { + const trip = this.requireTrip(tripId, user); + if (!this.files.can('file_delete', trip, user)) { + throw new HttpException({ error: 'No permission' }, 403); + } + const file = this.files.getDeletedFile(id, tripId); + if (!file) { + throw new HttpException({ error: 'File not found in trash' }, 404); + } + const restored = this.files.restoreFile(id); + this.files.broadcast(tripId, 'file:created', { file: restored }, socketId); + return { file: restored }; + } + + @Post(':id/link') + @HttpCode(200) // Express answers link with res.json (200). + link(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Body() body: { reservation_id?: string | null; assignment_id?: string | null; place_id?: string | null }) { + const trip = this.requireTrip(tripId, user); + if (!this.files.can('file_edit', trip, user)) { + throw new HttpException({ error: 'No permission' }, 403); + } + const file = this.files.getFileById(id, tripId); + if (!file) { + throw new HttpException({ error: 'File not found' }, 404); + } + const links = this.files.createFileLink(id, { reservation_id: body.reservation_id, assignment_id: body.assignment_id, place_id: body.place_id }); + return { success: true, links }; + } + + @Delete(':id/link/:linkId') + unlink(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Param('linkId') linkId: string) { + const trip = this.requireTrip(tripId, user); + if (!this.files.can('file_edit', trip, user)) { + throw new HttpException({ error: 'No permission' }, 403); + } + this.files.deleteFileLink(linkId, id); + return { success: true }; + } + + @Get(':id/links') + links(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string) { + this.requireTrip(tripId, user); + return { links: this.files.getFileLinks(id) }; + } +} diff --git a/server/src/nest/files/files.module.ts b/server/src/nest/files/files.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..160f404e49dd5005af187e5e6f66b705f13d3d54 --- /dev/null +++ b/server/src/nest/files/files.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { FilesController } from './files.controller'; +import { FilesDownloadController } from './files-download.controller'; +import { FilesService } from './files.service'; + +@Module({ + controllers: [FilesController, FilesDownloadController], + providers: [FilesService], +}) +export class FilesModule {} diff --git a/server/src/nest/files/files.service.ts b/server/src/nest/files/files.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..b21e256b1ebc1267ec1139d5f0cfe7d43150c0f6 --- /dev/null +++ b/server/src/nest/files/files.service.ts @@ -0,0 +1,49 @@ +import { Injectable } from '@nestjs/common'; +import type { Request } from 'express'; +import { broadcast } from '../../websocket'; +import { checkPermission } from '../../services/permissions'; +import type { User, TripFile } from '../../types'; +import * as svc from '../../services/fileService'; + +type Trip = NonNullable>; +type FilePermission = 'file_upload' | 'file_edit' | 'file_delete'; + +/** + * Thin Nest wrapper around the existing file service. Trip access, the + * file_* permissions, the SQL, the path-resolution guard, the download-token + * auth and the WebSocket broadcasts reuse the legacy code unchanged. + */ +@Injectable() +export class FilesService { + verifyTripAccess(tripId: string, userId: number) { + return svc.verifyTripAccess(tripId, userId); + } + + can(action: FilePermission, trip: Trip, user: User): boolean { + return checkPermission(action, user.role, trip.user_id, user.id, trip.user_id !== user.id); + } + + broadcast(tripId: string, event: string, payload: Record, socketId: string | undefined): void { + broadcast(tripId, event, payload, socketId); + } + + // Download-token auth + safe path resolution (used by the unguarded download route). + authenticateDownload(req: Request) { return svc.authenticateDownload(req); } + resolveFilePath(filename: string) { return svc.resolveFilePath(filename); } + + listFiles(tripId: string, showTrash: boolean) { return svc.listFiles(tripId, showTrash); } + getFileById(id: string, tripId: string) { return svc.getFileById(id, tripId); } + getDeletedFile(id: string, tripId: string) { return svc.getDeletedFile(id, tripId); } + createFile(tripId: string, file: Parameters[1], userId: number, opts: Parameters[3]) { + return svc.createFile(tripId, file, userId, opts); + } + updateFile(id: string, current: TripFile, updates: Parameters[2]) { return svc.updateFile(id, current, updates); } + toggleStarred(id: string, currentStarred: number | undefined) { return svc.toggleStarred(id, currentStarred); } + softDeleteFile(id: string) { return svc.softDeleteFile(id); } + restoreFile(id: string) { return svc.restoreFile(id); } + permanentDeleteFile(file: TripFile) { return svc.permanentDeleteFile(file); } + emptyTrash(tripId: string) { return svc.emptyTrash(tripId); } + createFileLink(id: string, opts: Parameters[1]) { return svc.createFileLink(id, opts); } + deleteFileLink(linkId: string, id: string) { return svc.deleteFileLink(linkId, id); } + getFileLinks(id: string) { return svc.getFileLinks(id); } +} diff --git a/server/src/nest/health/health.controller.ts b/server/src/nest/health/health.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..e4c907d39866a5224110b06e242e3d4a6a485a13 --- /dev/null +++ b/server/src/nest/health/health.controller.ts @@ -0,0 +1,41 @@ +import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common'; +import { z } from 'zod'; +import type { User } from '../../types'; +import { HealthService } from './health.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; +import { ZodValidationPipe } from '../common/zod-validation.pipe'; + +// Local demo schema (real domains import their schema from @trek/shared). +const echoSchema = z.object({ name: z.string().min(1) }); + +/** + * Foundation smoke endpoints for the co-hosted NestJS app. + * Proves: boot, routing, type-based DI, the shared SQLite connection, the + * JWT-cookie auth guard, and the Zod validation pipe + error-envelope parity. + * + * Lives under /api/_nest/* so it never collides with the legacy Express API. + */ +@Controller('api/_nest') +export class HealthController { + constructor(private readonly healthService: HealthService) {} + + @Get('health') + getHealth() { + return { ok: true, ...this.healthService.info() }; + } + + /** Guarded: returns the authenticated user, proving JwtAuthGuard + @CurrentUser. */ + @Get('me') + @UseGuards(JwtAuthGuard) + me(@CurrentUser() user: User) { + return user; + } + + /** Validated: proves the Zod pipe (400 + { error } on failure) and body parsing. */ + @Post('echo') + @UseGuards(JwtAuthGuard) + echo(@Body(new ZodValidationPipe(echoSchema)) body: z.infer) { + return { youSent: body }; + } +} diff --git a/server/src/nest/health/health.service.ts b/server/src/nest/health/health.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..4e5b6335c7891119fb17470a3581838d58a22aca --- /dev/null +++ b/server/src/nest/health/health.service.ts @@ -0,0 +1,21 @@ +import { Injectable } from '@nestjs/common'; +import { DatabaseService } from '../database/database.service'; + +/** + * Smoke service proving NestJS DI works under the chosen runtime AND that the + * injected DatabaseService talks to TREK's existing SQLite connection. + */ +@Injectable() +export class HealthService { + constructor(private readonly database: DatabaseService) {} + + info() { + const row = this.database.get<{ n: number }>('SELECT COUNT(*) AS n FROM users'); + return { + runtime: 'nestjs', + diInjected: true, + // Proof the shared connection works: real row count from the existing DB. + userCount: row?.n ?? null, + }; + } +} diff --git a/server/src/nest/integrations/airtrail-addon.guard.ts b/server/src/nest/integrations/airtrail-addon.guard.ts new file mode 100644 index 0000000000000000000000000000000000000000..5ebe5fb7b48f56b9a815a182582d5fb9b49a9ffc --- /dev/null +++ b/server/src/nest/integrations/airtrail-addon.guard.ts @@ -0,0 +1,19 @@ +import { CanActivate, HttpException, Injectable } from '@nestjs/common'; +import { isAddonEnabled } from '../../services/adminService'; +import { ADDON_IDS } from '../../addons'; + +/** + * Gates the AirTrail integration routes on the global `airtrail` addon. When the + * admin has it disabled the whole group answers 404. Declared before the + * JwtAuthGuard so the addon check wins over the 401 (same ordering as the + * Journey addon gate). + */ +@Injectable() +export class AirtrailAddonGuard implements CanActivate { + canActivate(): boolean { + if (!isAddonEnabled(ADDON_IDS.AIRTRAIL)) { + throw new HttpException({ error: 'AirTrail addon is not enabled' }, 404); + } + return true; + } +} diff --git a/server/src/nest/integrations/airtrail-import.controller.ts b/server/src/nest/integrations/airtrail-import.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..15c5dfb28d09229107ad72444ea08577e55f53e6 --- /dev/null +++ b/server/src/nest/integrations/airtrail-import.controller.ts @@ -0,0 +1,42 @@ +import { Body, Controller, Headers, HttpException, Param, Post, UseGuards } from '@nestjs/common'; +import type { User } from '../../types'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; +import { ZodValidationPipe } from '../common/zod-validation.pipe'; +import { AirtrailAddonGuard } from './airtrail-addon.guard'; +import { airtrailImportSchema, type AirtrailImport, type AirtrailImportResult } from '@trek/shared'; +import { verifyTripAccess } from '../../services/tripAccess'; +import { checkPermission } from '../../services/permissions'; +import { importAirtrailFlights } from '../../services/airtrail/airtrailImport'; + +/** + * POST /api/trips/:tripId/reservations/import/airtrail — turn selected AirTrail + * flights into reservations. Trip-scoped (reservation_edit) and addon-gated. The + * flights are re-fetched server-side with the caller's own key. + */ +@Controller('api/trips/:tripId/reservations/import') +@UseGuards(AirtrailAddonGuard, JwtAuthGuard) +export class AirtrailImportController { + private requireEdit(tripId: string, user: User): void { + const trip = verifyTripAccess(tripId, user.id); + if (!trip) throw new HttpException({ error: 'Trip not found' }, 404); + if (!checkPermission('reservation_edit', user.role, trip.user_id, user.id, trip.user_id !== user.id)) { + throw new HttpException({ error: 'No permission' }, 403); + } + } + + @Post('airtrail') + async importAirtrail( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body(new ZodValidationPipe(airtrailImportSchema)) body: AirtrailImport, + @Headers('x-socket-id') socketId?: string, + ): Promise { + this.requireEdit(tripId, user); + try { + return await importAirtrailFlights(tripId, user.id, body.flightIds, socketId); + } catch (err: any) { + throw new HttpException({ error: err?.message || 'AirTrail import failed' }, err?.status === 400 ? 400 : 502); + } + } +} diff --git a/server/src/nest/integrations/airtrail.controller.ts b/server/src/nest/integrations/airtrail.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..395586234dcf094edbf4946b2c4a87c0e66e7039 --- /dev/null +++ b/server/src/nest/integrations/airtrail.controller.ts @@ -0,0 +1,83 @@ +import { Body, Controller, Get, HttpCode, HttpException, Post, Put, Req, UseGuards } from '@nestjs/common'; +import type { Request } from 'express'; +import type { User } from '../../types'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; +import { ZodValidationPipe } from '../common/zod-validation.pipe'; +import { AirtrailAddonGuard } from './airtrail-addon.guard'; +import { getClientIp } from '../../services/auditLog'; +import { airtrailSettingsSchema, type AirtrailSettings } from '@trek/shared'; +import { + getConnectionSettings, + getConnectionStatus, + getFlightsForPicker, + saveSettings, + testConnection, +} from '../../services/airtrail/airtrailService'; +import { runAirtrailSyncForUser } from '../../services/airtrail/airtrailSync'; + +/** + * /api/integrations/airtrail — per-user AirTrail connection (#214). + * + * `status` and `test` answer 200 even on failure (the service shapes + * `{ connected: false, error }`); `settings` PUT validates with a 400. The API + * key is never echoed — `getSettings` returns it masked. The route group is + * gated on the `airtrail` addon (404 when disabled). + */ +@Controller('api/integrations/airtrail') +@UseGuards(AirtrailAddonGuard, JwtAuthGuard) +export class AirtrailController { + @Get('settings') + getSettings(@CurrentUser() user: User) { + return getConnectionSettings(user.id); + } + + @Put('settings') + async putSettings( + @CurrentUser() user: User, + @Body(new ZodValidationPipe(airtrailSettingsSchema)) body: AirtrailSettings, + @Req() req: Request, + ) { + const result = await saveSettings( + user.id, + body.url, + body.apiKey, + !!body.allowInsecureTls, + getClientIp(req), + ); + if (!result.success) { + throw new HttpException({ error: result.error }, 400); + } + return result.warning ? { success: true, warning: result.warning } : { success: true }; + } + + @Get('status') + getStatus(@CurrentUser() user: User) { + return getConnectionStatus(user.id); + } + + @Get('flights') + async flights(@CurrentUser() user: User) { + try { + return { flights: await getFlightsForPicker(user.id) }; + } catch (err: any) { + throw new HttpException({ error: err?.message || 'Could not load AirTrail flights' }, err?.status === 400 ? 400 : 502); + } + } + + /** Pull this user's AirTrail edits into their linked reservations on demand. */ + @Post('sync') + @HttpCode(200) + sync(@CurrentUser() user: User) { + return runAirtrailSyncForUser(user.id); + } + + @Post('test') + @HttpCode(200) + test( + @CurrentUser() user: User, + @Body(new ZodValidationPipe(airtrailSettingsSchema)) body: AirtrailSettings, + ) { + return testConnection(user.id, body.url, body.apiKey, !!body.allowInsecureTls); + } +} diff --git a/server/src/nest/integrations/airtrail.module.ts b/server/src/nest/integrations/airtrail.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..0feec084d599fa4f2fe9228935847fd32d887edb --- /dev/null +++ b/server/src/nest/integrations/airtrail.module.ts @@ -0,0 +1,14 @@ +import { Module } from '@nestjs/common'; +import { AirtrailController } from './airtrail.controller'; +import { AirtrailImportController } from './airtrail-import.controller'; + +/** + * AirTrail integration domain. The connection lives under + * /api/integrations/airtrail; the flight import is trip-scoped under + * /api/trips/:tripId/reservations/import/airtrail. Business logic lives in + * services/airtrail/* (plain functions over better-sqlite3). + */ +@Module({ + controllers: [AirtrailController, AirtrailImportController], +}) +export class AirtrailModule {} diff --git a/server/src/nest/journey/journey-addon.guard.ts b/server/src/nest/journey/journey-addon.guard.ts new file mode 100644 index 0000000000000000000000000000000000000000..0e5c9ed3e59d6d75bfd87171851b43de53ec3534 --- /dev/null +++ b/server/src/nest/journey/journey-addon.guard.ts @@ -0,0 +1,20 @@ +import { CanActivate, HttpException, Injectable } from '@nestjs/common'; +import { JourneyService } from './journey.service'; + +/** + * Mirrors the legacy `/api/journeys` mount gate: when the Journey addon is + * disabled the whole route group answers 404, regardless of auth. Declared + * before the JwtAuthGuard so the addon check wins over the 401, exactly as the + * Express middleware ordering did. + */ +@Injectable() +export class JourneyAddonGuard implements CanActivate { + constructor(private readonly journey: JourneyService) {} + + canActivate(): boolean { + if (!this.journey.journeyAddonEnabled()) { + throw new HttpException({ error: 'Journey addon is not enabled' }, 404); + } + return true; + } +} diff --git a/server/src/nest/journey/journey-public.controller.ts b/server/src/nest/journey/journey-public.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..b78e3f0ea7a8f95072f506c1120face7e221eca9 --- /dev/null +++ b/server/src/nest/journey/journey-public.controller.ts @@ -0,0 +1,78 @@ +import { Controller, Get, HttpException, Param, Res } from '@nestjs/common'; +import type { Response } from 'express'; +import path from 'node:path'; +import fs from 'node:fs'; +import { JourneyService } from './journey.service'; + +/** + * /api/public/journey — unauthenticated, share-token validated read + photo + * proxy for publicly shared journeys. + * + * Byte-identical to the legacy Express route (server/src/routes/journeyPublic.ts): + * NOT behind any guard, every route validates the share token (404 on failure), + * the unified proxy streams by trek_photo_id and the legacy proxy serves local + * files (with the uploads-dir traversal guard) or proxies immich/synology. + */ +@Controller('api/public/journey') +export class JourneyPublicController { + constructor(private readonly journey: JourneyService) {} + + @Get(':token') + get(@Param('token') token: string) { + const data = this.journey.getPublicJourney(token); + if (!data) { + throw new HttpException({ error: 'Not found' }, 404); + } + return data; + } + + @Get(':token/photos/:photoId/:kind') + async photo(@Param('token') token: string, @Param('photoId') photoId: string, @Param('kind') kind: string, @Res() res: Response): Promise { + const valid = this.journey.validateShareTokenForPhoto(token, Number(photoId)); + if (!valid) { + throw new HttpException({ error: 'Not found' }, 404); + } + await this.journey.streamPhoto(res, valid.ownerId, Number(photoId), kind === 'thumbnail' ? 'thumbnail' : 'original'); + } + + @Get(':token/photo/:provider/:assetId/:ownerId/:kind') + async legacyPhoto( + @Param('token') token: string, + @Param('provider') provider: string, + @Param('assetId') assetId: string, + @Param('ownerId') ownerId: string, + @Param('kind') kind: string, + @Res() res: Response, + ): Promise { + const valid = this.journey.validateShareTokenForAsset(token, assetId); + if (!valid) { + throw new HttpException({ error: 'Not found' }, 404); + } + + const wantThumb = kind === 'thumbnail' ? 'thumbnail' : 'original'; + + if (provider === 'local') { + // Local journey assets are flat filenames; use basename() and confine the + // resolved path to the journey upload directory. + const journeyDir = path.resolve(__dirname, '../../../uploads/journey'); + const resolved = path.resolve(path.join(journeyDir, path.basename(assetId))); + if (!resolved.startsWith(journeyDir + path.sep) || !fs.existsSync(resolved)) { + throw new HttpException({ error: 'Not found' }, 404); + } + res.set('Cache-Control', 'public, max-age=86400'); + res.sendFile(resolved); + return; + } + + const effectiveOwnerId = valid.ownerId || Number(ownerId); + if (provider === 'immich') { + await this.journey.streamImmichAsset(res, effectiveOwnerId, assetId, wantThumb, effectiveOwnerId); + } else { + try { + await this.journey.streamSynologyAsset(res, effectiveOwnerId, effectiveOwnerId, assetId, wantThumb); + } catch { + res.status(404).json({ error: 'Provider not supported' }); + } + } + } +} diff --git a/server/src/nest/journey/journey.controller.ts b/server/src/nest/journey/journey.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..2a092f7304b4ec88cd613427503e116d329409de --- /dev/null +++ b/server/src/nest/journey/journey.controller.ts @@ -0,0 +1,419 @@ +import { + Body, + Controller, + Delete, + Get, + Headers, + HttpCode, + HttpException, + Param, + Patch, + Post, + Put, + UploadedFile, + UploadedFiles, + UseGuards, + UseInterceptors, +} from '@nestjs/common'; +import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express'; +import { diskStorage } from 'multer'; +import path from 'node:path'; +import fs from 'node:fs'; +import crypto from 'node:crypto'; +import type { User } from '../../types'; +import { JourneyService } from './journey.service'; +import { JourneyAddonGuard } from './journey-addon.guard'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; +import { getAllowedExtensions } from '../../services/fileService'; + +const uploadsBase = path.join(__dirname, '../../../uploads/journey'); +const IMAGE_UPLOAD = { + storage: diskStorage({ + destination: (_req, _file, cb) => { if (!fs.existsSync(uploadsBase)) fs.mkdirSync(uploadsBase, { recursive: true }); cb(null, uploadsBase); }, + filename: (_req, file, cb) => cb(null, `${crypto.randomUUID()}${path.extname(file.originalname).toLowerCase() || '.jpg'}`), + }), + limits: { fileSize: 20 * 1024 * 1024 }, + fileFilter: (_req: unknown, file: Express.Multer.File, cb: (err: Error | null, accept: boolean) => void) => { + if (!file.mimetype.startsWith('image/') || file.mimetype.includes('svg')) { + const err: Error & { statusCode?: number } = new Error('Only image files are allowed'); + err.statusCode = 400; + return cb(err, false); + } + const ext = path.extname(file.originalname).toLowerCase().replace('.', ''); + const allowed = getAllowedExtensions().split(',').map((e) => e.trim().toLowerCase()); + if (!allowed.includes('*') && !allowed.includes(ext)) { + const err: Error & { statusCode?: number } = new Error(`File type .${ext} is not allowed`); + err.statusCode = 400; + return cb(err, false); + } + cb(null, true); + }, +}; + +/** + * /api/journeys — cross-trip travel narrative (journeys, entries, photo gallery + * + provider mirroring, contributors, preferences, share links). + * + * Byte-identical to the legacy Express route (server/src/routes/journey.ts): + * the Journey-addon gate (404) runs before auth, the service owns access + * control (null/false → 403/404), create routes answer 201 while cover/trips/ + * share-link/reorder/patch answer 200 and the two unlink/gallery-delete routes + * answer 204. Static prefixes (/suggestions, /available-trips, /entries, /photos) + * are declared before /:id so they win over the param. + */ +@Controller('api/journeys') +@UseGuards(JourneyAddonGuard, JwtAuthGuard) +export class JourneyController { + constructor(private readonly journey: JourneyService) {} + + // ── Static prefix routes (before /:id) ────────────────────────────────── + @Get() + list(@CurrentUser() user: User) { + return { journeys: this.journey.listJourneys(user.id) }; + } + + @Post() + create(@CurrentUser() user: User, @Body() body: { title?: string; subtitle?: string; trip_ids?: unknown[] }) { + if (!body.title || typeof body.title !== 'string' || !body.title.trim()) { + throw new HttpException({ error: 'Title is required' }, 400); + } + return this.journey.createJourney(user.id, { + title: body.title.trim(), + subtitle: body.subtitle, + trip_ids: Array.isArray(body.trip_ids) ? body.trip_ids.map(Number) : [], + }); + } + + @Get('suggestions') + suggestions(@CurrentUser() user: User) { + return { trips: this.journey.getSuggestions(user.id) }; + } + + @Get('available-trips') + availableTrips(@CurrentUser() user: User) { + return { trips: this.journey.listUserTrips(user.id) }; + } + + // ── Entries (prefix /entries — before /:id) ───────────────────────────── + @Patch('entries/:entryId') + updateEntry(@CurrentUser() user: User, @Param('entryId') entryId: string, @Body() body: Record, @Headers('x-socket-id') socketId?: string) { + const result = this.journey.updateEntry(Number(entryId), user.id, body, socketId); + if (!result) { + throw new HttpException({ error: 'Entry not found' }, 404); + } + return result; + } + + @Delete('entries/:entryId') + deleteEntry(@CurrentUser() user: User, @Param('entryId') entryId: string, @Headers('x-socket-id') socketId?: string) { + if (!this.journey.deleteEntry(Number(entryId), user.id, socketId)) { + throw new HttpException({ error: 'Entry not found' }, 404); + } + return { success: true }; + } + + @Post('entries/:entryId/photos') + @UseInterceptors(FilesInterceptor('photos', undefined, IMAGE_UPLOAD)) + async uploadEntryPhotos(@CurrentUser() user: User, @Param('entryId') entryId: string, @UploadedFiles() files: Express.Multer.File[] | undefined, @Body() body: { caption?: string }) { + if (!files?.length) { + throw new HttpException({ error: 'No files uploaded' }, 400); + } + const results: unknown[] = []; + for (const file of files) { + const relativePath = `journey/${file.filename}`; + const photo = this.journey.addPhoto(Number(entryId), user.id, relativePath, undefined, body?.caption); + if (!photo) continue; + // Mirror to Immich only when the user explicitly opted in (#730). + if (this.journey.immichAutoUploadEnabled(user.id)) { + try { + const immichId = await this.journey.uploadToImmich(user.id, relativePath, file.originalname); + if (immichId) { + this.journey.setPhotoProvider(photo.id, 'immich', immichId, user.id); + Object.assign(photo, { provider: 'immich', asset_id: immichId, owner_id: user.id }); + } + } catch { + // best-effort mirror; the local photo is already saved + } + } + results.push(photo); + } + if (!results.length) { + throw new HttpException({ error: 'Not allowed' }, 403); + } + return { photos: results }; + } + + @Post('entries/:entryId/provider-photos') + providerPhotos(@CurrentUser() user: User, @Param('entryId') entryId: string, @Body() body: { provider?: string; asset_id?: string; asset_ids?: unknown[]; caption?: string; passphrase?: string }) { + const pp = body.passphrase && typeof body.passphrase === 'string' ? body.passphrase : undefined; + if (Array.isArray(body.asset_ids) && body.provider) { + const added: unknown[] = []; + for (const id of body.asset_ids) { + const photo = this.journey.addProviderPhoto(Number(entryId), user.id, body.provider, String(id), body.caption, pp); + if (photo) added.push(photo); + } + return { photos: added, added: added.length }; + } + if (!body.provider || !body.asset_id) { + throw new HttpException({ error: 'provider and asset_id required' }, 400); + } + const photo = this.journey.addProviderPhoto(Number(entryId), user.id, body.provider, body.asset_id, body.caption, pp); + if (!photo) { + throw new HttpException({ error: 'Not allowed or duplicate' }, 403); + } + return photo; + } + + @Post('entries/:entryId/link-photo') + linkPhoto(@CurrentUser() user: User, @Param('entryId') entryId: string, @Body() body: { journey_photo_id?: unknown; photo_id?: unknown }) { + const journeyPhotoId = body.journey_photo_id ?? body.photo_id; + if (!journeyPhotoId) { + throw new HttpException({ error: 'journey_photo_id required' }, 400); + } + const result = this.journey.linkPhotoToEntry(Number(entryId), Number(journeyPhotoId), user.id); + if (!result) { + throw new HttpException({ error: 'Not allowed' }, 403); + } + return result; + } + + @Delete('entries/:entryId/photos/:journeyPhotoId') + @HttpCode(204) + unlinkPhoto(@CurrentUser() user: User, @Param('entryId') entryId: string, @Param('journeyPhotoId') journeyPhotoId: string): void { + if (!this.journey.unlinkPhotoFromEntry(Number(entryId), Number(journeyPhotoId), user.id)) { + throw new HttpException({ error: 'Not found or not allowed' }, 404); + } + } + + @Patch('photos/:photoId') + updatePhoto(@CurrentUser() user: User, @Param('photoId') photoId: string, @Body() body: Record) { + const result = this.journey.updatePhoto(Number(photoId), user.id, body); + if (!result) { + throw new HttpException({ error: 'Photo not found' }, 404); + } + return result; + } + + @Delete('photos/:photoId') + deletePhoto(@CurrentUser() user: User, @Param('photoId') photoId: string) { + const photo = this.journey.deletePhoto(Number(photoId), user.id); + if (!photo) { + throw new HttpException({ error: 'Photo not found' }, 404); + } + if (photo.file_path) { + try { fs.unlinkSync(path.join(__dirname, '../../../uploads', photo.file_path)); } catch { /* file already gone */ } + } + return { success: true }; + } + + // ── Gallery (prefix /:id/gallery — before /:id) ───────────────────────── + @Post(':id/gallery/photos') + @UseInterceptors(FilesInterceptor('photos', undefined, IMAGE_UPLOAD)) + uploadGalleryPhotos(@CurrentUser() user: User, @Param('id') id: string, @UploadedFiles() files: Express.Multer.File[] | undefined) { + if (!files?.length) { + throw new HttpException({ error: 'No files uploaded' }, 400); + } + const filePaths = files.map((f) => ({ path: `journey/${f.filename}` })); + const photos = this.journey.uploadGalleryPhotos(Number(id), user.id, filePaths); + if (!photos.length) { + throw new HttpException({ error: 'Not allowed' }, 403); + } + return { photos }; + } + + @Post(':id/gallery/provider-photos') + galleryProviderPhotos(@CurrentUser() user: User, @Param('id') id: string, @Body() body: { provider?: string; asset_id?: string; asset_ids?: unknown[]; passphrase?: string }) { + const pp = body.passphrase && typeof body.passphrase === 'string' ? body.passphrase : undefined; + if (Array.isArray(body.asset_ids) && body.provider) { + const added: unknown[] = []; + for (const aid of body.asset_ids) { + const photo = this.journey.addProviderPhotoToGallery(Number(id), user.id, body.provider, String(aid), undefined, pp); + if (photo) added.push(photo); + } + return { photos: added, added: added.length }; + } + if (!body.provider || !body.asset_id) { + throw new HttpException({ error: 'provider and asset_id required' }, 400); + } + const photo = this.journey.addProviderPhotoToGallery(Number(id), user.id, body.provider, body.asset_id, undefined, pp); + if (!photo) { + throw new HttpException({ error: 'Not allowed or duplicate' }, 403); + } + return photo; + } + + @Delete(':id/gallery/:journeyPhotoId') + @HttpCode(204) + deleteGalleryPhoto(@CurrentUser() user: User, @Param('journeyPhotoId') journeyPhotoId: string): void { + const photo = this.journey.deleteGalleryPhoto(Number(journeyPhotoId), user.id); + if (!photo) { + throw new HttpException({ error: 'Photo not found or not allowed' }, 404); + } + if (photo.file_path) { + try { fs.unlinkSync(path.join(__dirname, '../../../uploads', photo.file_path)); } catch { /* file already gone */ } + } + } + + // ── Journeys /:id ─────────────────────────────────────────────────────── + @Get(':id') + get(@CurrentUser() user: User, @Param('id') id: string) { + const data = this.journey.getJourneyFull(Number(id), user.id); + if (!data) { + throw new HttpException({ error: 'Journey not found' }, 404); + } + return data; + } + + @Patch(':id') + update(@CurrentUser() user: User, @Param('id') id: string, @Body() body: Record) { + const result = this.journey.updateJourney(Number(id), user.id, body); + if (!result) { + throw new HttpException({ error: 'Journey not found' }, 404); + } + return result; + } + + @Post(':id/cover') + @HttpCode(200) // Express answers cover with res.json (200). + @UseInterceptors(FileInterceptor('cover', IMAGE_UPLOAD)) + cover(@CurrentUser() user: User, @Param('id') id: string, @UploadedFile() file: Express.Multer.File | undefined) { + if (!file) { + throw new HttpException({ error: 'No file uploaded' }, 400); + } + const result = this.journey.updateJourney(Number(id), user.id, { cover_image: `journey/${file.filename}` }); + if (!result) { + throw new HttpException({ error: 'Journey not found' }, 404); + } + return result; + } + + @Delete(':id') + remove(@CurrentUser() user: User, @Param('id') id: string) { + if (!this.journey.deleteJourney(Number(id), user.id)) { + throw new HttpException({ error: 'Journey not found' }, 404); + } + return { success: true }; + } + + // ── Journey trips ─────────────────────────────────────────────────────── + @Post(':id/trips') + @HttpCode(200) // Express answers with res.json (200). + addTrip(@CurrentUser() user: User, @Param('id') id: string, @Body() body: { trip_id?: unknown }) { + if (!body.trip_id) { + throw new HttpException({ error: 'trip_id required' }, 400); + } + if (!this.journey.addTripToJourney(Number(id), Number(body.trip_id), user.id)) { + throw new HttpException({ error: 'Not allowed' }, 403); + } + return { success: true }; + } + + @Delete(':id/trips/:tripId') + removeTrip(@CurrentUser() user: User, @Param('id') id: string, @Param('tripId') tripId: string) { + if (!this.journey.removeTripFromJourney(Number(id), Number(tripId), user.id)) { + throw new HttpException({ error: 'Not allowed' }, 403); + } + return { success: true }; + } + + // ── Entries under journey ─────────────────────────────────────────────── + @Get(':id/entries') + listEntries(@CurrentUser() user: User, @Param('id') id: string) { + const entries = this.journey.listEntries(Number(id), user.id); + if (!entries) { + throw new HttpException({ error: 'Journey not found' }, 404); + } + return { entries }; + } + + @Post(':id/entries') + createEntry(@CurrentUser() user: User, @Param('id') id: string, @Body() body: Record & { entry_date?: unknown }, @Headers('x-socket-id') socketId?: string) { + if (!body.entry_date) { + throw new HttpException({ error: 'entry_date is required' }, 400); + } + const entry = this.journey.createEntry(Number(id), user.id, body, socketId); + if (!entry) { + throw new HttpException({ error: 'Journey not found' }, 404); + } + return entry; + } + + @Put(':id/entries/reorder') + reorderEntries(@CurrentUser() user: User, @Param('id') id: string, @Body() body: { orderedIds?: unknown }, @Headers('x-socket-id') socketId?: string) { + const orderedIds = body.orderedIds; + if (!Array.isArray(orderedIds) || !orderedIds.every((v) => Number.isFinite(Number(v)))) { + throw new HttpException({ error: 'orderedIds must be an array of numbers' }, 400); + } + if (!this.journey.reorderEntries(Number(id), user.id, orderedIds.map(Number), socketId)) { + throw new HttpException({ error: 'Not allowed' }, 403); + } + return { success: true }; + } + + // ── Contributors ──────────────────────────────────────────────────────── + @Post(':id/contributors') + addContributor(@CurrentUser() user: User, @Param('id') id: string, @Body() body: { user_id?: unknown; role?: 'editor' | 'viewer' }) { + if (!body.user_id) { + throw new HttpException({ error: 'user_id required' }, 400); + } + if (!this.journey.addContributor(Number(id), user.id, Number(body.user_id), body.role || 'viewer')) { + throw new HttpException({ error: 'Not allowed' }, 403); + } + return { success: true }; + } + + @Patch(':id/contributors/:userId') + updateContributor(@CurrentUser() user: User, @Param('id') id: string, @Param('userId') userId: string, @Body() body: { role?: 'editor' | 'viewer' }) { + if (!this.journey.updateContributorRole(Number(id), user.id, Number(userId), body.role as 'editor' | 'viewer')) { + throw new HttpException({ error: 'Not allowed' }, 403); + } + return { success: true }; + } + + @Delete(':id/contributors/:userId') + removeContributor(@CurrentUser() user: User, @Param('id') id: string, @Param('userId') userId: string) { + if (!this.journey.removeContributor(Number(id), user.id, Number(userId))) { + throw new HttpException({ error: 'Not allowed' }, 403); + } + return { success: true }; + } + + // ── User Preferences ──────────────────────────────────────────────────── + @Patch(':id/preferences') + preferences(@CurrentUser() user: User, @Param('id') id: string, @Body() body: Record) { + const result = this.journey.updateJourneyPreferences(Number(id), user.id, body); + if (!result) { + throw new HttpException({ error: 'Not allowed' }, 403); + } + return result; + } + + // ── Share Link ────────────────────────────────────────────────────────── + @Get(':id/share-link') + getShareLink(@CurrentUser() user: User, @Param('id') id: string) { + return { link: this.journey.getJourneyShareLink(Number(id), user.id) }; + } + + @Post(':id/share-link') + @HttpCode(200) // Express answers with res.json (200). + setShareLink(@CurrentUser() user: User, @Param('id') id: string, @Body() body: { share_timeline?: boolean; share_gallery?: boolean; share_map?: boolean }) { + const result = this.journey.createOrUpdateJourneyShareLink(Number(id), user.id, { + share_timeline: body.share_timeline, + share_gallery: body.share_gallery, + share_map: body.share_map, + }); + if (!result) { + throw new HttpException({ error: 'Not allowed' }, 403); + } + return result; + } + + @Delete(':id/share-link') + deleteShareLink(@CurrentUser() user: User, @Param('id') id: string) { + if (!this.journey.deleteJourneyShareLink(Number(id), user.id)) { + throw new HttpException({ error: 'Not allowed' }, 403); + } + return { success: true }; + } +} diff --git a/server/src/nest/journey/journey.module.ts b/server/src/nest/journey/journey.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..4d1f9d8fc6e0fc6698f53561b50c59c36b2c76c5 --- /dev/null +++ b/server/src/nest/journey/journey.module.ts @@ -0,0 +1,11 @@ +import { Module } from '@nestjs/common'; +import { JourneyController } from './journey.controller'; +import { JourneyPublicController } from './journey-public.controller'; +import { JourneyService } from './journey.service'; +import { JourneyAddonGuard } from './journey-addon.guard'; + +@Module({ + controllers: [JourneyController, JourneyPublicController], + providers: [JourneyService, JourneyAddonGuard], +}) +export class JourneyModule {} diff --git a/server/src/nest/journey/journey.service.ts b/server/src/nest/journey/journey.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..bd5e1791e90fa1f4313cae8d85db882f54f4d5f8 --- /dev/null +++ b/server/src/nest/journey/journey.service.ts @@ -0,0 +1,91 @@ +import { Injectable } from '@nestjs/common'; +import { db } from '../../db/database'; +import * as svc from '../../services/journeyService'; +import * as share from '../../services/journeyShareService'; +import { uploadToImmich, streamImmichAsset } from '../../services/memories/immichService'; +import { streamPhoto } from '../../services/memories/photoResolverService'; +import { isAddonEnabled } from '../../services/adminService'; +import { ADDON_IDS } from '../../addons'; +import type { Response } from 'express'; + +/** + * Thin Nest wrapper around the existing journey services. Access control lives + * inside journeyService (each call returns null/false for no-access), so this + * just re-exposes the functions plus the share-link helpers, the Immich mirror + * and the addon gate the legacy mount enforced. + */ +@Injectable() +export class JourneyService { + journeyAddonEnabled(): boolean { + return isAddonEnabled(ADDON_IDS.JOURNEY); + } + + // Journeys + listJourneys(userId: number) { return svc.listJourneys(userId); } + createJourney(userId: number, data: Parameters[1]) { return svc.createJourney(userId, data); } + getJourneyFull(id: number, userId: number) { return svc.getJourneyFull(id, userId); } + updateJourney(id: number, userId: number, data: Parameters[2]) { return svc.updateJourney(id, userId, data); } + deleteJourney(id: number, userId: number) { return svc.deleteJourney(id, userId); } + getSuggestions(userId: number) { return svc.getSuggestions(userId); } + listUserTrips(userId: number) { return svc.listUserTrips(userId); } + updateJourneyPreferences(id: number, userId: number, data: Parameters[2]) { return svc.updateJourneyPreferences(id, userId, data); } + + // Trips + addTripToJourney(id: number, tripId: number, userId: number) { return svc.addTripToJourney(id, tripId, userId); } + removeTripFromJourney(id: number, tripId: number, userId: number) { return svc.removeTripFromJourney(id, tripId, userId); } + + // Entries + listEntries(id: number, userId: number) { return svc.listEntries(id, userId); } + // Entry create/update bodies are free-form in the legacy route (req.body: any); + // the cast keeps that boundary here so callers needn't pre-shape the payload. + createEntry(id: number, userId: number, data: Record, sid?: string) { return svc.createEntry(id, userId, data as Parameters[2], sid); } + updateEntry(entryId: number, userId: number, data: Parameters[2], sid?: string) { return svc.updateEntry(entryId, userId, data, sid); } + deleteEntry(entryId: number, userId: number, sid?: string) { return svc.deleteEntry(entryId, userId, sid); } + reorderEntries(id: number, userId: number, orderedIds: number[], sid?: string) { return svc.reorderEntries(id, userId, orderedIds, sid); } + + // Photos + addPhoto(entryId: number, userId: number, filePath: string, thumbnailPath: string | undefined, caption: string | undefined) { return svc.addPhoto(entryId, userId, filePath, thumbnailPath, caption); } + setPhotoProvider(photoId: number, provider: string, assetId: string, ownerId: number) { return svc.setPhotoProvider(photoId, provider, assetId, ownerId); } + addProviderPhoto(entryId: number, userId: number, provider: string, assetId: string, caption?: string, passphrase?: string) { return svc.addProviderPhoto(entryId, userId, provider, assetId, caption, passphrase); } + linkPhotoToEntry(entryId: number, journeyPhotoId: number, userId: number) { return svc.linkPhotoToEntry(entryId, journeyPhotoId, userId); } + unlinkPhotoFromEntry(entryId: number, journeyPhotoId: number, userId: number) { return svc.unlinkPhotoFromEntry(entryId, journeyPhotoId, userId); } + updatePhoto(photoId: number, userId: number, data: Parameters[2]) { return svc.updatePhoto(photoId, userId, data); } + deletePhoto(photoId: number, userId: number) { return svc.deletePhoto(photoId, userId); } + uploadGalleryPhotos(id: number, userId: number, filePaths: Parameters[2]) { return svc.uploadGalleryPhotos(id, userId, filePaths); } + addProviderPhotoToGallery(id: number, userId: number, provider: string, assetId: string, caption?: string, passphrase?: string) { return svc.addProviderPhotoToGallery(id, userId, provider, assetId, caption, passphrase); } + deleteGalleryPhoto(journeyPhotoId: number, userId: number) { return svc.deleteGalleryPhoto(journeyPhotoId, userId); } + + // Contributors + addContributor(id: number, userId: number, targetUserId: number, role: 'editor' | 'viewer') { return svc.addContributor(id, userId, targetUserId, role); } + updateContributorRole(id: number, userId: number, targetUserId: number, role: 'editor' | 'viewer') { return svc.updateContributorRole(id, userId, targetUserId, role); } + removeContributor(id: number, userId: number, targetUserId: number) { return svc.removeContributor(id, userId, targetUserId); } + + // Share links + // Authorization: only someone with access to the journey may read its public + // share token — same access model as create/delete here and the + // get_journey_share_link MCP tool. + getJourneyShareLink(id: number, userId: number) { + if (!svc.canAccessJourney(id, userId)) return null; + return share.getJourneyShareLink(id); + } + createOrUpdateJourneyShareLink(id: number, userId: number, data: Parameters[2]) { return share.createOrUpdateJourneyShareLink(id, userId, data); } + deleteJourneyShareLink(id: number, userId: number) { return share.deleteJourneyShareLink(id, userId); } + + // Immich mirror (only when the user opted in via integration settings) + immichAutoUploadEnabled(userId: number): boolean { + const prefs = db.prepare('SELECT immich_auto_upload FROM users WHERE id = ?').get(userId) as { immich_auto_upload?: number } | undefined; + return !!prefs?.immich_auto_upload; + } + uploadToImmich(userId: number, relativePath: string, originalName: string) { return uploadToImmich(userId, relativePath, originalName); } + + // Public (share-token) access — no auth, validated by token. + getPublicJourney(token: string) { return share.getPublicJourney(token); } + validateShareTokenForPhoto(token: string, photoId: number) { return share.validateShareTokenForPhoto(token, photoId); } + validateShareTokenForAsset(token: string, assetId: string) { return share.validateShareTokenForAsset(token, assetId); } + streamPhoto(res: Response, ownerId: number, photoId: number, kind: 'thumbnail' | 'original') { return streamPhoto(res, ownerId, photoId, kind); } + streamImmichAsset(res: Response, userId: number, assetId: string, kind: 'thumbnail' | 'original', ownerId: number) { return streamImmichAsset(res, userId, assetId, kind, ownerId); } + async streamSynologyAsset(res: Response, userId: number, ownerId: number, assetId: string, kind: 'thumbnail' | 'original') { + const { streamSynologyAsset } = await import('../../services/memories/synologyService'); + return streamSynologyAsset(res, userId, ownerId, assetId, kind); + } +} diff --git a/server/src/nest/maps/maps.controller.ts b/server/src/nest/maps/maps.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..7cfb56c506bd636ecb691809498da906b16e6950 --- /dev/null +++ b/server/src/nest/maps/maps.controller.ts @@ -0,0 +1,224 @@ +import { + Body, + Controller, + Get, + HttpCode, + HttpException, + Param, + Post, + Query, + Res, + UseGuards, +} from '@nestjs/common'; +import type { Response } from 'express'; +import { createReadStream } from 'node:fs'; +import type { + MapsAutocompleteResult, + MapsPlaceDetailsResult, + MapsPlacePhotoResult, + MapsResolveUrlResult, + MapsReverseResult, + MapsSearchResult, +} from '@trek/shared'; +import type { User } from '../../types'; +import { MapsService } from './maps.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; + +type LocationBias = { low: { lat: number; lng: number }; high: { lat: number; lng: number } }; + +/** Maps a thrown service error to the same status + { error } body Express sent. */ +function toHttpException(err: unknown, fallbackMessage: string, defaultStatus: number): HttpException { + const status = (err as { status?: number }).status || defaultStatus; + const message = err instanceof Error ? err.message : fallbackMessage; + return new HttpException({ error: message }, status); +} + +/** + * /api/maps — place search, autocomplete, details, photos, reverse geocoding and + * Google-Maps-URL resolution. + * + * Behaviour is byte-identical to the legacy Express route (server/src/routes/ + * maps.ts): same auth, same bespoke 400 validation messages, the same + * per-endpoint kill-switch short-circuits, the same error status/body mapping, + * and the same diagnostic logging. The SSRF guard lives in the underlying + * service and is reused unchanged. + */ +@Controller('api/maps') +@UseGuards(JwtAuthGuard) +export class MapsController { + constructor(private readonly maps: MapsService) {} + + @Post('search') + @HttpCode(200) // Express answers with res.json (200); Nest would otherwise default POST to 201. + async search( + @CurrentUser() user: User, + @Body('query') query: unknown, + @Query('lang') lang?: string, + @Body('locationBias') locationBias?: { lat: number; lng: number; radius?: number }, + ): Promise { + if (!query) { + throw new HttpException({ error: 'Search query is required' }, 400); + } + // Optional bias toward a coordinate (lat/lng[/radius]); improves foreign-region queries. + if (locationBias && !(Number.isFinite(locationBias.lat) && Number.isFinite(locationBias.lng))) { + throw new HttpException({ error: 'Invalid locationBias: lat and lng must be finite numbers' }, 400); + } + try { + return await this.maps.search(user.id, query as string, lang, locationBias); + } catch (err: unknown) { + console.error('Maps search error:', err); + throw toHttpException(err, 'Search error', 500); + } + } + + // OSM-only POI explore: places of a category within the current map viewport. + @Get('pois') + async pois( + @Query('category') category?: string, + @Query('south') south?: string, + @Query('west') west?: string, + @Query('north') north?: string, + @Query('east') east?: string, + ) { + if (!category) throw new HttpException({ error: 'A category is required' }, 400); + const bbox = { south: Number(south), west: Number(west), north: Number(north), east: Number(east) }; + if (Object.values(bbox).some(v => !Number.isFinite(v))) { + throw new HttpException({ error: 'A valid bbox (south, west, north, east) is required' }, 400); + } + try { + return await this.maps.pois(category, bbox); + } catch (err: unknown) { + throw toHttpException(err, 'POI search error', 500); + } + } + + @Post('autocomplete') + @HttpCode(200) + async autocomplete( + @CurrentUser() user: User, + @Body('input') input: unknown, + @Body('lang') lang?: string, + @Body('locationBias') locationBias?: LocationBias, + ): Promise { + if (this.maps.autocompleteDisabled()) { + return { suggestions: [], source: 'disabled' }; + } + if (!input || typeof input !== 'string') { + throw new HttpException({ error: 'Input is required' }, 400); + } + if (input.length > 200) { + throw new HttpException({ error: 'Input too long (max 200 chars)' }, 400); + } + if (locationBias) { + const { low, high } = locationBias; + if (!low || !high + || !Number.isFinite(low.lat) || !Number.isFinite(low.lng) + || !Number.isFinite(high.lat) || !Number.isFinite(high.lng)) { + throw new HttpException({ error: 'Invalid locationBias: low and high must have finite lat and lng' }, 400); + } + } + try { + return await this.maps.autocomplete(user.id, input, lang, locationBias); + } catch (err: unknown) { + console.error('Maps autocomplete error:', err); + throw toHttpException(err, 'Autocomplete error', 500); + } + } + + @Get('details/:placeId') + async details( + @CurrentUser() user: User, + @Param('placeId') placeId: string, + @Query('expand') expand?: string, + @Query('lang') lang?: string, + @Query('refresh') refresh?: string, + ): Promise { + if (this.maps.detailsDisabled()) { + return { place: null, disabled: true }; + } + try { + return expand + ? await this.maps.detailsExpanded(user.id, placeId, lang, refresh === '1') + : await this.maps.details(user.id, placeId, lang); + } catch (err: unknown) { + console.error('Maps details error:', err); + throw toHttpException(err, 'Error fetching place details', 500); + } + } + + @Get('place-photo/:placeId') + async placePhoto( + @CurrentUser() user: User, + @Param('placeId') placeId: string, + @Query('lat') lat?: string, + @Query('lng') lng?: string, + @Query('name') name?: string, + ): Promise { + // Kill-switch only applies to Google Places fetches — Wikimedia (coords:) stays allowed. + if (!placeId.startsWith('coords:') && this.maps.photosDisabled()) { + return { photoUrl: null }; + } + try { + return await this.maps.photo(user.id, placeId, parseFloat(lat as string), parseFloat(lng as string), name); + } catch (err: unknown) { + const status = (err as { status?: number }).status || 500; + if (status >= 500) console.error('Place photo error:', err); + throw toHttpException(err, 'Error fetching photo', 500); + } + } + + @Get('place-photo/:placeId/bytes') + placePhotoBytes(@Param('placeId') placeId: string, @Res() res: Response): void { + const fp = this.maps.photoBytesPath(placeId); + if (!fp) { + res.status(404).json({ error: 'Photo not cached' }); + return; + } + // Stream the cached file directly instead of res.sendFile(): the send library + // bundled under @nestjs/platform-express rejects absolute Windows paths (drive + // letter, no `root`) with a NotFoundError that surfaced as an unhandled 500, + // even though the file exists. A plain read stream serves the bytes + // cross-platform; a read error still yields the legacy 404. Cached photos are + // always JPEG (placePhotoCache writes `.jpg`). + res.set('Cache-Control', 'public, max-age=2592000, immutable'); + res.type('image/jpeg'); + const stream = createReadStream(fp); + stream.on('error', () => { + if (!res.headersSent) res.status(404).json({ error: 'Photo not cached' }); + }); + stream.pipe(res); + } + + @Get('reverse') + async reverse( + @Query('lat') lat?: string, + @Query('lng') lng?: string, + @Query('lang') lang?: string, + ): Promise { + if (!lat || !lng) { + throw new HttpException({ error: 'lat and lng required' }, 400); + } + try { + return await this.maps.reverse(lat, lng, lang); + } catch { + // The legacy route swallows reverse-geocode failures into an empty result. + return { name: null, address: null }; + } + } + + @Post('resolve-url') + @HttpCode(200) + async resolveUrl(@Body('url') url: unknown): Promise { + if (!url || typeof url !== 'string') { + throw new HttpException({ error: 'URL is required' }, 400); + } + try { + return await this.maps.resolveUrl(url); + } catch (err: unknown) { + const message = err instanceof Error ? err.message : 'Failed to resolve URL'; + console.error('[Maps] URL resolve error:', message); + throw toHttpException(err, 'Failed to resolve URL', 400); + } + } +} diff --git a/server/src/nest/maps/maps.module.ts b/server/src/nest/maps/maps.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..350f3d3c68fd0f7b3b66892ad551b2c620afdb65 --- /dev/null +++ b/server/src/nest/maps/maps.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { MapsController } from './maps.controller'; +import { MapsService } from './maps.service'; + +/** Maps / geo domain (L3 leaf module). Registered in AppModule. */ +@Module({ + controllers: [MapsController], + providers: [MapsService], +}) +export class MapsModule {} diff --git a/server/src/nest/maps/maps.service.ts b/server/src/nest/maps/maps.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..87c71384a40259bfd9c8303efcf5e69e9382d49e --- /dev/null +++ b/server/src/nest/maps/maps.service.ts @@ -0,0 +1,95 @@ +import { Injectable } from '@nestjs/common'; +import type { + MapsSearchResult, + MapsAutocompleteResult, + MapsPlaceDetailsResult, + MapsPlacePhotoResult, + MapsReverseResult, + MapsResolveUrlResult, +} from '@trek/shared'; +import { DatabaseService } from '../database/database.service'; +import { + searchPlaces, + autocompletePlaces, + getPlaceDetails, + getPlaceDetailsExpanded, + getPlacePhoto, + reverseGeocode, + resolveGoogleMapsUrl, + searchOverpassPois, +} from '../../services/mapsService'; +import { serveFilePath } from '../../services/placePhotoCache'; + +type LocationBias = { low: { lat: number; lng: number }; high: { lat: number; lng: number } }; + +/** + * Thin Nest wrapper around the existing maps service. All geocoding, the + * provider fan-out (Nominatim/Overpass/Google) and — importantly — the SSRF + * guard live in mapsService and are reused unchanged, so behaviour and the + * outbound-URL protection are identical. + * + * The per-endpoint kill-switches are settings reads the legacy route does + * inline; they're encapsulated here as `*Disabled()` helpers over the same + * `app_settings` rows. + */ +@Injectable() +export class MapsService { + constructor(private readonly database: DatabaseService) {} + + private isSettingDisabled(key: string): boolean { + const row = this.database.get<{ value: string }>( + 'SELECT value FROM app_settings WHERE key = ?', + key, + ); + return row?.value === 'false'; + } + + autocompleteDisabled(): boolean { + return this.isSettingDisabled('places_autocomplete_enabled'); + } + + detailsDisabled(): boolean { + return this.isSettingDisabled('places_details_enabled'); + } + + photosDisabled(): boolean { + return this.isSettingDisabled('places_photos_enabled'); + } + + search(userId: number, query: string, lang?: string, locationBias?: { lat: number; lng: number; radius?: number }): Promise { + return searchPlaces(userId, query, lang, locationBias) as Promise; + } + + autocomplete(userId: number, input: string, lang?: string, locationBias?: LocationBias): Promise { + return autocompletePlaces(userId, input, lang, locationBias) as Promise; + } + + details(userId: number, placeId: string, lang?: string): Promise { + return getPlaceDetails(userId, placeId, lang) as Promise; + } + + detailsExpanded(userId: number, placeId: string, lang: string | undefined, refresh: boolean): Promise { + return getPlaceDetailsExpanded(userId, placeId, lang, refresh) as Promise; + } + + photo(userId: number, placeId: string, lat: number, lng: number, name?: string): Promise { + return getPlacePhoto(userId, placeId, lat, lng, name) as Promise; + } + + photoBytesPath(placeId: string): string | null { + return serveFilePath(placeId); + } + + reverse(lat: string, lng: string, lang?: string): Promise { + return reverseGeocode(lat, lng, lang) as Promise; + } + + resolveUrl(url: string): Promise { + return resolveGoogleMapsUrl(url) as Promise; + } + + // OSM-only POI search by category within a viewport bbox (never calls Google). + pois(category: string, bbox: { south: number; west: number; north: number; east: number }) { + return searchOverpassPois(category, bbox); + } +} diff --git a/server/src/nest/memories/immich.controller.ts b/server/src/nest/memories/immich.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..d046ce8791657d316dc927fcf69589398705a396 --- /dev/null +++ b/server/src/nest/memories/immich.controller.ts @@ -0,0 +1,193 @@ +import { Body, Controller, Get, Headers, HttpCode, Param, Post, Put, Req, Res, UseGuards } from '@nestjs/common'; +import type { Request, Response } from 'express'; +import type { User } from '../../types'; +import { MemoriesService } from './memories.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; +import { getClientIp } from '../../services/auditLog'; + +/** + * /api/integrations/memories/immich — Immich connection, browse/search, asset + * proxy and album linking. + * + * Byte-identical to the legacy Express router (server/src/routes/memories/immich.ts): + * `/status` and `/test` answer 200 even on connection failure (the service shapes + * `{ connected: false, ... }`); `/settings` PUT validates with a 400; the asset + * routes do the 400 invalid-id guard then the canAccessUserPhoto 403 ('Forbidden') + * before streaming or returning info; the album sync answers 200 then broadcasts. + * The legacy `canAccessTrip` import there is dead code — intentionally not ported. + */ +@Controller('api/integrations/memories/immich') +@UseGuards(JwtAuthGuard) +export class ImmichMemoriesController { + constructor(private readonly memories: MemoriesService) {} + + @Get('settings') + getSettings(@CurrentUser() user: User) { + return this.memories.immichGetConnectionSettings(user.id); + } + + @Put('settings') + async putSettings( + @CurrentUser() user: User, + @Body() body: { immich_url?: string; immich_api_key?: string; auto_upload?: unknown }, + @Req() req: Request, + @Res() res: Response, + ): Promise { + const { immich_url, immich_api_key, auto_upload } = body; + const result = await this.memories.immichSaveSettings(user.id, immich_url, immich_api_key, getClientIp(req)); + if (!result.success) { + res.status(400).json({ error: result.error }); + return; + } + if (typeof auto_upload === 'boolean') { + this.memories.immichSetAutoUpload(user.id, auto_upload); + } + if (result.warning) { + res.json({ success: true, warning: result.warning }); + return; + } + res.json({ success: true }); + } + + @Get('status') + async getStatus(@CurrentUser() user: User) { + return this.memories.immichGetConnectionStatus(user.id); + } + + @Post('test') + @HttpCode(200) + async test(@Body() body: { immich_url?: string; immich_api_key?: string }) { + const { immich_url, immich_api_key } = body; + if (!immich_url || !immich_api_key) { + return { connected: false, error: 'URL and API key required' }; + } + return this.memories.immichTestConnection(immich_url, immich_api_key); + } + + @Get('browse') + async browse(@CurrentUser() user: User, @Res() res: Response): Promise { + const result = await this.memories.immichBrowseTimeline(user.id); + if (result.error) { + res.status(result.status!).json({ error: result.error }); + return; + } + res.json({ buckets: result.buckets }); + } + + @Post('search') + @HttpCode(200) + async search(@CurrentUser() user: User, @Body() body: Record, @Res() res: Response): Promise { + const { from, to, size, page } = body as { from?: string; to?: string; size?: unknown; page?: unknown }; + const pageNum = Math.max(1, Number(page) || 1); + const pageSize = Math.min(Number(size) || 50, 200); + const result = await this.memories.immichSearchPhotos(user.id, from, to, pageNum, pageSize); + if (result.error) { + res.status(result.status!).json({ error: result.error }); + return; + } + res.json({ assets: result.assets || [], hasMore: !!result.hasMore }); + } + + @Get('assets/:tripId/:assetId/:ownerId/info') + async assetInfo( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('assetId') assetId: string, + @Param('ownerId') ownerId: string, + @Res() res: Response, + ): Promise { + if (!this.memories.immichIsValidAssetId(assetId)) { + res.status(400).json({ error: 'Invalid asset ID' }); + return; + } + if (!this.memories.canAccessUserPhoto(user.id, Number(ownerId), tripId, assetId, 'immich')) { + res.status(403).json({ error: 'Forbidden' }); + return; + } + const result = await this.memories.immichGetAssetInfo(user.id, assetId, Number(ownerId)); + if (result.error) { + res.status(result.status!).json({ error: result.error }); + return; + } + res.json(result.data); + } + + @Get('assets/:tripId/:assetId/:ownerId/thumbnail') + async assetThumbnail( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('assetId') assetId: string, + @Param('ownerId') ownerId: string, + @Res() res: Response, + ): Promise { + if (!this.memories.immichIsValidAssetId(assetId)) { + res.status(400).json({ error: 'Invalid asset ID' }); + return; + } + if (!this.memories.canAccessUserPhoto(user.id, Number(ownerId), tripId, assetId, 'immich')) { + res.status(403).json({ error: 'Forbidden' }); + return; + } + await this.memories.immichStreamAsset(res, user.id, assetId, 'thumbnail', Number(ownerId)); + } + + @Get('assets/:tripId/:assetId/:ownerId/original') + async assetOriginal( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('assetId') assetId: string, + @Param('ownerId') ownerId: string, + @Res() res: Response, + ): Promise { + if (!this.memories.immichIsValidAssetId(assetId)) { + res.status(400).json({ error: 'Invalid asset ID' }); + return; + } + if (!this.memories.canAccessUserPhoto(user.id, Number(ownerId), tripId, assetId, 'immich')) { + res.status(403).json({ error: 'Forbidden' }); + return; + } + await this.memories.immichStreamAsset(res, user.id, assetId, 'original', Number(ownerId)); + } + + @Get('albums') + async albums(@CurrentUser() user: User, @Res() res: Response): Promise { + const result = await this.memories.immichListAlbums(user.id); + if (result.error) { + res.status(result.status!).json({ error: result.error }); + return; + } + res.json({ albums: result.albums }); + } + + @Get('albums/:albumId/photos') + async albumPhotos(@CurrentUser() user: User, @Param('albumId') albumId: string, @Res() res: Response): Promise { + const result = await this.memories.immichGetAlbumPhotos(user.id, albumId); + if (result.error) { + res.status(result.status!).json({ error: result.error }); + return; + } + res.json({ assets: result.assets }); + } + + @Post('trips/:tripId/album-links/:linkId/sync') + @HttpCode(200) + async sync( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('linkId') linkId: string, + @Headers('x-socket-id') sid: string, + @Res() res: Response, + ): Promise { + const result = await this.memories.immichSyncAlbumAssets(tripId, linkId, user.id, sid); + if (result.error) { + res.status(result.status!).json({ error: result.error }); + return; + } + res.json({ success: true, added: result.added, total: result.total }); + if (result.added! > 0) { + this.memories.broadcast(tripId, 'memories:updated', { userId: user.id }, sid); + } + } +} diff --git a/server/src/nest/memories/memories.module.ts b/server/src/nest/memories/memories.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..82a4640b22c85483be1d8858b5aa256cf8ebcafb --- /dev/null +++ b/server/src/nest/memories/memories.module.ts @@ -0,0 +1,19 @@ +import { Module } from '@nestjs/common'; +import { MemoriesService } from './memories.service'; +import { UnifiedMemoriesController } from './unified.controller'; +import { ImmichMemoriesController } from './immich.controller'; +import { SynologyMemoriesController } from './synology.controller'; + +/** + * Memories (photo-providers) domain — mounted at /api/integrations/memories. + * + * Ports the legacy Express router (routes/memories/unified.ts, which composes + * immich.ts + synology.ts) to Nest, reusing services/memories/* unchanged. No + * module-level addon gate — enablement is per-provider-row inside the services, + * exactly as the legacy mount had it. + */ +@Module({ + controllers: [UnifiedMemoriesController, ImmichMemoriesController, SynologyMemoriesController], + providers: [MemoriesService], +}) +export class MemoriesModule {} diff --git a/server/src/nest/memories/memories.service.ts b/server/src/nest/memories/memories.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..e96faf64ac94c30dbe5aac15ee1bcd1a59b6f5cc --- /dev/null +++ b/server/src/nest/memories/memories.service.ts @@ -0,0 +1,183 @@ +import { Injectable } from '@nestjs/common'; +import type { Response } from 'express'; +import { + listTripPhotos, + listTripAlbumLinks, + createTripAlbumLink, + removeAlbumLink, + addTripPhotos, + removeTripPhoto, + setTripPhotoSharing, +} from '../../services/memories/unifiedService'; +import { + getConnectionSettings, + saveImmichSettings, + setImmichAutoUpload, + testConnection, + getConnectionStatus, + browseTimeline, + searchPhotos, + streamImmichAsset, + listAlbums, + getAlbumPhotos, + syncAlbumAssets, + getAssetInfo, + isValidAssetId, +} from '../../services/memories/immichService'; +import { + getSynologySettings, + updateSynologySettings, + getSynologyStatus, + testSynologyConnection, + listSynologyAlbums, + getSynologyAlbumPhotos, + syncSynologyAlbumLink, + searchSynologyPhotos, + getSynologyAssetInfo, + streamSynologyAsset, +} from '../../services/memories/synologyService'; +import { canAccessUserPhoto } from '../../services/memories/helpersService'; +import type { Selection } from '../../services/memories/helpersService'; +import { broadcast } from '../../websocket'; + +/** + * Thin Nest wrapper around the existing memories (photo-providers) services. + * Every method delegates to the legacy `services/memories/*` code unchanged so + * the provider logic, the per-provider access checks and the streaming helpers + * behave byte-identically to the legacy Express routers. No new business logic + * lives here. + */ +@Injectable() +export class MemoriesService { + // ── Access check (reused by both provider asset routes) ────────────────── + canAccessUserPhoto(requestingUserId: number, ownerUserId: number, tripId: string, assetId: string, provider: string): boolean { + return canAccessUserPhoto(requestingUserId, ownerUserId, tripId, assetId, provider); + } + + broadcast(tripId: string, event: string, payload: Record, socketId?: string): void { + broadcast(tripId, event, payload, socketId); + } + + // ── Unified ────────────────────────────────────────────────────────────── + listTripPhotos(tripId: string, userId: number) { + return listTripPhotos(tripId, userId); + } + + addTripPhotos(tripId: string, userId: number, shared: boolean, selections: Selection[], sid: string) { + return addTripPhotos(tripId, userId, shared, selections, sid); + } + + setTripPhotoSharing(tripId: string, userId: number, photoId: number, shared: boolean) { + return setTripPhotoSharing(tripId, userId, photoId, shared); + } + + removeTripPhoto(tripId: string, userId: number, photoId: number) { + return removeTripPhoto(tripId, userId, photoId); + } + + listTripAlbumLinks(tripId: string, userId: number) { + return listTripAlbumLinks(tripId, userId); + } + + createTripAlbumLink(tripId: string, userId: number, provider: unknown, albumId: unknown, albumName: unknown, passphrase?: string) { + return createTripAlbumLink(tripId, userId, provider, albumId, albumName, passphrase); + } + + removeAlbumLink(tripId: string, linkId: string, userId: number) { + return removeAlbumLink(tripId, linkId, userId); + } + + // ── Immich ───────────────────────────────────────────────────────────────── + immichGetConnectionSettings(userId: number) { + return getConnectionSettings(userId); + } + + immichSaveSettings(userId: number, immichUrl: string | undefined, immichApiKey: string | undefined, clientIp: string | null) { + return saveImmichSettings(userId, immichUrl, immichApiKey, clientIp); + } + + immichSetAutoUpload(userId: number, enabled: boolean): void { + setImmichAutoUpload(userId, enabled); + } + + immichGetConnectionStatus(userId: number) { + return getConnectionStatus(userId); + } + + immichTestConnection(immichUrl: string, immichApiKey: string) { + return testConnection(immichUrl, immichApiKey); + } + + immichBrowseTimeline(userId: number) { + return browseTimeline(userId); + } + + immichSearchPhotos(userId: number, from: string | undefined, to: string | undefined, page: number, size: number) { + return searchPhotos(userId, from, to, page, size); + } + + immichIsValidAssetId(assetId: string): boolean { + return isValidAssetId(assetId); + } + + immichGetAssetInfo(userId: number, assetId: string, ownerId: number) { + return getAssetInfo(userId, assetId, ownerId); + } + + immichStreamAsset(res: Response, userId: number, assetId: string, kind: 'thumbnail' | 'original', ownerId: number) { + return streamImmichAsset(res, userId, assetId, kind, ownerId); + } + + immichListAlbums(userId: number) { + return listAlbums(userId); + } + + immichGetAlbumPhotos(userId: number, albumId: string) { + return getAlbumPhotos(userId, albumId); + } + + immichSyncAlbumAssets(tripId: string, linkId: string, userId: number, sid: string) { + return syncAlbumAssets(tripId, linkId, userId, sid); + } + + // ── Synology ──────────────────────────────────────────────────────────────── + synologyGetSettings(userId: number) { + return getSynologySettings(userId); + } + + synologyUpdateSettings(userId: number, url: string, username: string, password: string, skipSsl: boolean) { + return updateSynologySettings(userId, url, username, password, skipSsl); + } + + synologyGetStatus(userId: number) { + return getSynologyStatus(userId); + } + + synologyTestConnection(userId: number, url: string, username: string, password: string, otp: string, skipSsl: boolean) { + return testSynologyConnection(userId, url, username, password, otp, skipSsl); + } + + synologyListAlbums(userId: number) { + return listSynologyAlbums(userId); + } + + synologyGetAlbumPhotos(userId: number, albumId: string, passphrase?: string) { + return getSynologyAlbumPhotos(userId, albumId, passphrase); + } + + synologySyncAlbumLink(userId: number, tripId: string, linkId: string, sid: string) { + return syncSynologyAlbumLink(userId, tripId, linkId, sid); + } + + synologySearchPhotos(userId: number, from: string | undefined, to: string | undefined, offset: number, limit: number) { + return searchSynologyPhotos(userId, from, to, offset, limit); + } + + synologyGetAssetInfo(userId: number, photoId: string, ownerId: number, passphrase?: string) { + return getSynologyAssetInfo(userId, photoId, ownerId, passphrase); + } + + synologyStreamAsset(res: Response, userId: number, ownerId: number, photoId: string, kind: 'thumbnail' | 'original', size: string, passphrase?: string) { + return streamSynologyAsset(res, userId, ownerId, photoId, kind, size, passphrase); + } +} diff --git a/server/src/nest/memories/synology.controller.ts b/server/src/nest/memories/synology.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..88db6133e5aeb64d2e4f929eecb78b65072e421b --- /dev/null +++ b/server/src/nest/memories/synology.controller.ts @@ -0,0 +1,170 @@ +import { Body, Controller, Get, Headers, HttpCode, Param, Post, Put, Query, Res, UseGuards } from '@nestjs/common'; +import type { Response } from 'express'; +import type { User } from '../../types'; +import type { ServiceResult } from '../../services/memories/helpersService'; +import { fail, success } from '../../services/memories/helpersService'; +import { MemoriesService } from './memories.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; + +function _parseStringBodyField(value: unknown): string { + return String(value ?? '').trim(); +} + +function _parseNumberBodyField(value: unknown, fallback: number): number { + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : fallback; +} + +/** + * /api/integrations/memories/synologyphotos — Synology Photos connection, + * search, albums and asset proxy. + * + * Byte-identical to the legacy Express router (server/src/routes/memories/synology.ts): + * every response goes through the service `ServiceResult` envelope (success → + * `res.json(data)` at 200, error → status + `{ error }`); `/status` and `/test` + * always answer 200 (the service shapes `{ connected: false, error }` on + * failure); the asset routes use the distinct 403 string "You don't have access + * to this photo"; `/info` is declared before the catch-all `/:kind` so the + * literal route wins as Express ordered it; lenient hand-rolled coercion is kept. + */ +@Controller('api/integrations/memories/synologyphotos') +@UseGuards(JwtAuthGuard) +export class SynologyMemoriesController { + constructor(private readonly memories: MemoriesService) {} + + private handle(res: Response, result: ServiceResult): void { + if ('error' in result) { + res.status(result.error.status).json({ error: result.error.message }); + } else { + res.json(result.data); + } + } + + @Get('settings') + async getSettings(@CurrentUser() user: User, @Res() res: Response): Promise { + this.handle(res, await this.memories.synologyGetSettings(user.id)); + } + + @Put('settings') + async putSettings(@CurrentUser() user: User, @Body() body: Record, @Res() res: Response): Promise { + const synology_url = _parseStringBodyField(body.synology_url); + const synology_username = _parseStringBodyField(body.synology_username); + const synology_password = _parseStringBodyField(body.synology_password); + const synology_skip_ssl = body.synology_skip_ssl === true || body.synology_skip_ssl === 'true'; + + if (!synology_url || !synology_username) { + this.handle(res, fail('URL and username are required', 400)); + } else { + this.handle(res, await this.memories.synologyUpdateSettings(user.id, synology_url, synology_username, synology_password, synology_skip_ssl)); + } + } + + @Get('status') + async getStatus(@CurrentUser() user: User, @Res() res: Response): Promise { + this.handle(res, await this.memories.synologyGetStatus(user.id)); + } + + @Post('test') + @HttpCode(200) + async test(@CurrentUser() user: User, @Body() body: Record, @Res() res: Response): Promise { + const synology_url = _parseStringBodyField(body.synology_url); + const synology_username = _parseStringBodyField(body.synology_username); + const synology_password = _parseStringBodyField(body.synology_password); + const synology_otp = _parseStringBodyField(body.synology_otp); + const synology_skip_ssl = body.synology_skip_ssl === true || body.synology_skip_ssl === 'true'; + + if (!synology_url || !synology_username || !synology_password) { + const missingFields: string[] = []; + if (!synology_url) missingFields.push('URL'); + if (!synology_username) missingFields.push('Username'); + if (!synology_password) missingFields.push('Password'); + this.handle(res, success({ connected: false, error: `${missingFields.join(', ')} ${missingFields.length > 1 ? 'are' : 'is'} required` })); + } else { + this.handle(res, await this.memories.synologyTestConnection(user.id, synology_url, synology_username, synology_password, synology_otp, synology_skip_ssl)); + } + } + + @Get('albums') + async albums(@CurrentUser() user: User, @Res() res: Response): Promise { + this.handle(res, await this.memories.synologyListAlbums(user.id)); + } + + @Get('albums/:albumId/photos') + async albumPhotos(@CurrentUser() user: User, @Param('albumId') albumId: string, @Query('passphrase') passphraseRaw: string | undefined, @Res() res: Response): Promise { + const passphrase = passphraseRaw ? String(passphraseRaw) : undefined; + this.handle(res, await this.memories.synologyGetAlbumPhotos(user.id, albumId, passphrase)); + } + + @Post('trips/:tripId/album-links/:linkId/sync') + @HttpCode(200) + async sync( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('linkId') linkId: string, + @Headers('x-socket-id') sid: string, + @Res() res: Response, + ): Promise { + this.handle(res, await this.memories.synologySyncAlbumLink(user.id, tripId, linkId, sid)); + } + + @Post('search') + @HttpCode(200) + async search(@CurrentUser() user: User, @Body() body: Record, @Res() res: Response): Promise { + const from = _parseStringBodyField(body.from); + const to = _parseStringBodyField(body.to); + let offset = _parseNumberBodyField(body.offset, 0); + const page = _parseNumberBodyField(body.page, 1) - 1; + let limit = _parseNumberBodyField(body.limit, 100); + const size = _parseNumberBodyField(body.size, 0); + if (size > 0) limit = size; + if (page > 0) offset = page * limit; + + this.handle(res, await this.memories.synologySearchPhotos(user.id, from || undefined, to || undefined, offset, limit)); + } + + @Get('assets/:tripId/:photoId/:ownerId/info') + async assetInfo( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('photoId') photoId: string, + @Param('ownerId') ownerId: string, + @Query('passphrase') passphraseRaw: string | undefined, + @Res() res: Response, + ): Promise { + const passphrase = passphraseRaw ? String(passphraseRaw) : undefined; + if (!this.memories.canAccessUserPhoto(user.id, Number(ownerId), tripId, photoId, 'synologyphotos')) { + this.handle(res, fail("You don't have access to this photo", 403)); + } else { + this.handle(res, await this.memories.synologyGetAssetInfo(user.id, photoId, Number(ownerId), passphrase)); + } + } + + @Get('assets/:tripId/:photoId/:ownerId/:kind') + async asset( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('photoId') photoId: string, + @Param('ownerId') ownerId: string, + @Param('kind') kind: string, + @Query('size') sizeRaw: string | undefined, + @Query('passphrase') passphraseRaw: string | undefined, + @Res() res: Response, + ): Promise { + const VALID_SIZES = ['sm', 'm', 'xl'] as const; + const rawSize = String(sizeRaw ?? 'sm'); + const size = (VALID_SIZES as readonly string[]).includes(rawSize) ? rawSize : 'sm'; + const passphrase = passphraseRaw ? String(passphraseRaw) : undefined; + + if (kind !== 'thumbnail' && kind !== 'original') { + this.handle(res, fail('Invalid asset kind', 400)); + return; + } + + if (!this.memories.canAccessUserPhoto(user.id, Number(ownerId), tripId, photoId, 'synologyphotos')) { + this.handle(res, fail("You don't have access to this photo", 403)); + } else { + await this.memories.synologyStreamAsset(res, user.id, Number(ownerId), photoId, kind, String(size), passphrase); + } + } +} diff --git a/server/src/nest/memories/unified.controller.ts b/server/src/nest/memories/unified.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..0c27708614a26b7028c9bc006792a777b65553b6 --- /dev/null +++ b/server/src/nest/memories/unified.controller.ts @@ -0,0 +1,123 @@ +import { Body, Controller, Delete, Get, Headers, HttpCode, Param, Post, Put, Res, UseGuards } from '@nestjs/common'; +import type { Response } from 'express'; +import type { User } from '../../types'; +import type { Selection } from '../../services/memories/helpersService'; +import { MemoriesService } from './memories.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; + +/** + * /api/integrations/memories/unified — provider-agnostic trip photo + album-link + * management. + * + * Byte-identical to the legacy Express router (server/src/routes/memories/unified.ts): + * bare `authenticate` (JwtAuthGuard), success bodies on 200, and the per-result + * error envelope `{ error }` at `result.error.status` reused from the unified + * service. Lenient hand-rolled body coercion is preserved — no Zod here. + */ +@Controller('api/integrations/memories/unified') +@UseGuards(JwtAuthGuard) +export class UnifiedMemoriesController { + constructor(private readonly memories: MemoriesService) {} + + @Get('trips/:tripId/photos') + listPhotos(@CurrentUser() user: User, @Param('tripId') tripId: string, @Res() res: Response): void { + const result = this.memories.listTripPhotos(tripId, user.id); + if ('error' in result) { + res.status(result.error.status).json({ error: result.error.message }); + return; + } + res.json({ photos: result.data }); + } + + @Post('trips/:tripId/photos') + @HttpCode(200) + async addPhotos( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body() body: Record, + @Headers('x-socket-id') sid: string, + @Res() res: Response, + ): Promise { + const selections: Selection[] = Array.isArray(body?.selections) ? (body.selections as Selection[]) : []; + const shared = body?.shared === undefined ? true : !!body?.shared; + const result = await this.memories.addTripPhotos(tripId, user.id, shared, selections, sid); + if ('error' in result) { + res.status(result.error.status).json({ error: result.error.message }); + return; + } + res.json({ success: true, added: result.data.added }); + } + + @Put('trips/:tripId/photos/sharing') + async setSharing( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body() body: Record, + @Res() res: Response, + ): Promise { + const result = await this.memories.setTripPhotoSharing(tripId, user.id, Number(body?.photo_id), body?.shared as boolean); + if ('error' in result) { + res.status(result.error.status).json({ error: result.error.message }); + return; + } + res.json({ success: true }); + } + + @Delete('trips/:tripId/photos') + async removePhoto( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body() body: Record, + @Res() res: Response, + ): Promise { + const result = this.memories.removeTripPhoto(tripId, user.id, Number(body?.photo_id)); + if ('error' in result) { + res.status(result.error.status).json({ error: result.error.message }); + return; + } + res.json({ success: true }); + } + + @Get('trips/:tripId/album-links') + listAlbumLinks(@CurrentUser() user: User, @Param('tripId') tripId: string, @Res() res: Response): void { + const result = this.memories.listTripAlbumLinks(tripId, user.id); + if ('error' in result) { + res.status(result.error.status).json({ error: result.error.message }); + return; + } + res.json({ links: result.data }); + } + + @Post('trips/:tripId/album-links') + @HttpCode(200) + createAlbumLink( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body() body: Record, + @Res() res: Response, + ): void { + const passphrase = body?.passphrase ? String(body.passphrase) : undefined; + const result = this.memories.createTripAlbumLink(tripId, user.id, body?.provider, body?.album_id, body?.album_name, passphrase); + if ('error' in result) { + res.status(result.error.status).json({ error: result.error.message }); + return; + } + res.json({ success: true }); + } + + @Delete('trips/:tripId/album-links/:linkId') + removeAlbumLink( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('linkId') linkId: string, + @Res() res: Response, + ): void { + const result = this.memories.removeAlbumLink(tripId, linkId, user.id); + if ('error' in result) { + res.status(result.error.status).json({ error: result.error.message }); + return; + } + res.json({ success: true }); + } +} diff --git a/server/src/nest/notifications/notifications.controller.ts b/server/src/nest/notifications/notifications.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..14197f25f9cdc22da607a37ca96c4f59ba84bc57 --- /dev/null +++ b/server/src/nest/notifications/notifications.controller.ts @@ -0,0 +1,188 @@ +import { + Body, + Controller, + Delete, + Get, + HttpCode, + HttpException, + Param, + Post, + Put, + Query, + UseGuards, +} from '@nestjs/common'; +import type { ChannelTestResult, UnreadCountResult } from '@trek/shared'; +import type { User } from '../../types'; +import { NotificationsService } from './notifications.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; + +// The masked placeholder the client sends instead of a stored secret (8× U+2022). +const MASKED = '••••••••'; + +/** + * /api/notifications — channel-preference matrix, channel test pings, and in-app + * notifications. + * + * Byte-identical to the legacy Express route (server/src/routes/notifications.ts): + * same auth, the same inline admin gate on /test-smtp (note: it returns + * { error: 'Admin only' }, NOT the AdminGuard's wording), the same webhook/ntfy + * fallback resolution, the same id parsing + 400/404 bodies, and the same status + * codes. POSTs that answer with res.json stay 200 (Nest would default to 201). + * The static /in-app/read-all and /in-app/all routes are declared before the + * /in-app/:id routes so they win over the param, matching the legacy order. + */ +@Controller('api/notifications') +@UseGuards(JwtAuthGuard) +export class NotificationsController { + constructor(private readonly notifications: NotificationsService) {} + + @Get('preferences') + getPreferences(@CurrentUser() user: User) { + return this.notifications.getPreferences(user.id, user.role); + } + + @Put('preferences') + setPreferences(@CurrentUser() user: User, @Body() body: Record>) { + this.notifications.setPreferences(user.id, body); + return this.notifications.getPreferences(user.id, user.role); + } + + @Post('test-smtp') + @HttpCode(200) + async testSmtp(@CurrentUser() user: User, @Body('email') email?: string): Promise { + if (user.role !== 'admin') { + throw new HttpException({ error: 'Admin only' }, 403); + } + return this.notifications.testSmtp(email || user.email); + } + + @Post('test-webhook') + @HttpCode(200) + async testWebhook(@CurrentUser() user: User, @Body('url') urlInput?: unknown): Promise { + let url = urlInput; + if (!url || url === MASKED) { + url = this.notifications.userWebhookUrl(user.id); + if (!url && user.role === 'admin') url = this.notifications.adminWebhookUrl(); + if (!url) { + throw new HttpException({ error: 'No webhook URL configured' }, 400); + } + } + if (typeof url !== 'string') { + throw new HttpException({ error: 'url must be a string' }, 400); + } + try { + new URL(url); + } catch { + throw new HttpException({ error: 'Invalid URL' }, 400); + } + return this.notifications.testWebhook(url); + } + + @Post('test-ntfy') + @HttpCode(200) + async testNtfy( + @CurrentUser() user: User, + @Body('topic') topic?: string, + @Body('server') server?: string, + @Body('token') token?: string, + ): Promise { + const userCfg = this.notifications.userNtfyConfig(user.id); + const adminCfg = this.notifications.adminNtfyConfig(); + + const resolvedTopic = topic || userCfg?.topic || undefined; + const resolvedServer = server || userCfg?.server || adminCfg.server || undefined; + // Reuse the saved token when the request sends null, empty, or the masked placeholder. + const resolvedToken = (token && token !== MASKED) + ? token + : (userCfg?.token ?? adminCfg.token ?? null); + + if (!resolvedTopic) { + throw new HttpException({ error: 'No ntfy topic configured' }, 400); + } + return this.notifications.testNtfy({ topic: resolvedTopic, server: resolvedServer ?? null, token: resolvedToken }); + } + + @Get('in-app') + listInApp( + @CurrentUser() user: User, + @Query('limit') limit?: string, + @Query('offset') offset?: string, + @Query('unread_only') unreadOnly?: string, + ) { + return this.notifications.listInApp(user.id, { + limit: Math.min(parseInt(limit as string) || 20, 50), + offset: parseInt(offset as string) || 0, + unreadOnly: unreadOnly === 'true', + }); + } + + @Get('in-app/unread-count') + unreadCount(@CurrentUser() user: User): UnreadCountResult { + return { count: this.notifications.unreadCount(user.id) }; + } + + @Put('in-app/read-all') + readAll(@CurrentUser() user: User): { success: boolean; count: number } { + return { success: true, count: this.notifications.markAllRead(user.id) }; + } + + @Delete('in-app/all') + deleteAll(@CurrentUser() user: User): { success: boolean; count: number } { + return { success: true, count: this.notifications.deleteAll(user.id) }; + } + + @Put('in-app/:id/read') + markRead(@CurrentUser() user: User, @Param('id') idParam: string): { success: boolean } { + const id = this.parseId(idParam); + if (!this.notifications.markRead(id, user.id)) { + throw new HttpException({ error: 'Not found' }, 404); + } + return { success: true }; + } + + @Put('in-app/:id/unread') + markUnread(@CurrentUser() user: User, @Param('id') idParam: string): { success: boolean } { + const id = this.parseId(idParam); + if (!this.notifications.markUnread(id, user.id)) { + throw new HttpException({ error: 'Not found' }, 404); + } + return { success: true }; + } + + @Delete('in-app/:id') + deleteOne(@CurrentUser() user: User, @Param('id') idParam: string): { success: boolean } { + const id = this.parseId(idParam); + if (!this.notifications.deleteOne(id, user.id)) { + throw new HttpException({ error: 'Not found' }, 404); + } + return { success: true }; + } + + @Post('in-app/:id/respond') + @HttpCode(200) + async respond( + @CurrentUser() user: User, + @Param('id') idParam: string, + @Body('response') response?: unknown, + ): Promise<{ success: boolean; notification: unknown }> { + const id = this.parseId(idParam); + if (response !== 'positive' && response !== 'negative') { + throw new HttpException({ error: 'response must be "positive" or "negative"' }, 400); + } + const result = await this.notifications.respond(id, user.id, response); + if (!result.success) { + throw new HttpException({ error: result.error }, 400); + } + return { success: true, notification: result.notification }; + } + + /** parseInt + the legacy "Invalid id" 400 guard, shared by the /:id handlers. */ + private parseId(idParam: string): number { + const id = parseInt(idParam); + if (isNaN(id)) { + throw new HttpException({ error: 'Invalid id' }, 400); + } + return id; + } +} diff --git a/server/src/nest/notifications/notifications.module.ts b/server/src/nest/notifications/notifications.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..8591ffdfba6d33132cc8bf4e72401a7258d82fe3 --- /dev/null +++ b/server/src/nest/notifications/notifications.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { NotificationsController } from './notifications.controller'; +import { NotificationsService } from './notifications.service'; + +/** Notifications domain (L6 leaf module). Registered in AppModule. */ +@Module({ + controllers: [NotificationsController], + providers: [NotificationsService], +}) +export class NotificationsModule {} diff --git a/server/src/nest/notifications/notifications.service.ts b/server/src/nest/notifications/notifications.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..06e6c080189575a7c6e5e445d5fa722279a5e67e --- /dev/null +++ b/server/src/nest/notifications/notifications.service.ts @@ -0,0 +1,107 @@ +import { Injectable } from '@nestjs/common'; +import type { ChannelTestResult } from '@trek/shared'; +import { + testSmtp, + testWebhook, + testNtfy, + getAdminWebhookUrl, + getUserWebhookUrl, + getUserNtfyConfig, + getAdminNtfyConfig, +} from '../../services/notifications'; +import { + getNotifications, + getUnreadCount, + markRead, + markUnread, + markAllRead, + deleteNotification, + deleteAll, + respondToBoolean, +} from '../../services/inAppNotifications'; +import { getPreferencesMatrix, setPreferences } from '../../services/notificationPreferencesService'; + +type NtfyConfig = ReturnType; +type RespondResult = Awaited>; +type PreferencesMatrix = ReturnType; + +/** + * Thin Nest wrapper around the existing notification services. Channel delivery + * (including the WebSocket push in inAppNotifications) and the preference + * persistence all stay in the upstream services, so behaviour — including + * real-time delivery — is unchanged. The webhook/ntfy fallback resolution that + * the legacy route does inline is exposed here as small accessors so the + * controller can reproduce it exactly. + */ +@Injectable() +export class NotificationsService { + getPreferences(userId: number, role: string): PreferencesMatrix { + return getPreferencesMatrix(userId, role, 'user'); + } + + setPreferences(userId: number, body: Parameters[1]): void { + setPreferences(userId, body); + } + + testSmtp(to: string): Promise { + return testSmtp(to); + } + + testWebhook(url: string): Promise { + return testWebhook(url); + } + + testNtfy(cfg: { topic: string; server?: string | null; token?: string | null }): Promise { + return testNtfy(cfg); + } + + userWebhookUrl(userId: number): string | null { + return getUserWebhookUrl(userId); + } + + adminWebhookUrl(): string | null { + return getAdminWebhookUrl(); + } + + userNtfyConfig(userId: number): NtfyConfig | null { + return getUserNtfyConfig(userId); + } + + adminNtfyConfig(): NtfyConfig { + return getAdminNtfyConfig(); + } + + // Returns the native service shape (NotificationRow[] is a superset of the + // client-facing InAppListResult contract); the controller surfaces it as-is. + listInApp(userId: number, options: { limit?: number; offset?: number; unreadOnly?: boolean }) { + return getNotifications(userId, options); + } + + unreadCount(userId: number): number { + return getUnreadCount(userId); + } + + markRead(id: number, userId: number): boolean { + return markRead(id, userId); + } + + markUnread(id: number, userId: number): boolean { + return markUnread(id, userId); + } + + markAllRead(userId: number): number { + return markAllRead(userId); + } + + deleteOne(id: number, userId: number): boolean { + return deleteNotification(id, userId); + } + + deleteAll(userId: number): number { + return deleteAll(userId); + } + + respond(id: number, userId: number, response: 'positive' | 'negative'): Promise { + return respondToBoolean(id, userId, response); + } +} diff --git a/server/src/nest/oauth/oauth-api.controller.ts b/server/src/nest/oauth/oauth-api.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..0a761124e4690da424a17f1798e81c9d6b4ae4e6 --- /dev/null +++ b/server/src/nest/oauth/oauth-api.controller.ts @@ -0,0 +1,178 @@ +import { Body, Controller, Delete, Get, HttpCode, HttpException, Param, Post, Query, Req, Res, UseGuards } from '@nestjs/common'; +import type { Request, Response } from 'express'; +import { OauthService } from './oauth.service'; +import { RateLimitService } from '../auth/rate-limit.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CookieAuthGuard } from '../auth/cookie-auth.guard'; +import { OptionalJwtGuard } from '../auth/optional-jwt.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; +import { getClientIp } from '../../services/auditLog'; +import type { User } from '../../types'; +import type { AuthorizeParams } from '../../services/oauthService'; + +const MIN = 60_000; + +/** + * Authenticated OAuth management endpoints (the SPA's consent + client/session + * UI) — byte-identical to the legacy oauthApiRouter (server/src/routes/oauth.ts): + * MCP-addon gated (404 on the anonymous validate to avoid fingerprinting, 403 + * elsewhere), optional-auth on validate, cookie-only auth on state-changing + * routes (consent/create/rotate/delete/revoke) and Bearer-or-cookie auth on the + * read lists. create answers 201; the rest 200. + */ +@Controller('api/oauth') +export class OauthApiController { + constructor(private readonly oauth: OauthService, private readonly rl: RateLimitService) {} + + private requireMcp403(): void { + if (!this.oauth.mcpEnabled()) { + throw new HttpException({ error: 'MCP is not enabled' }, 403); + } + } + + @Get('authorize/validate') + @UseGuards(OptionalJwtGuard) + validate(@Req() req: Request, @Query() params: Partial, @Res({ passthrough: true }) res: Response) { + if (!this.rl.check('oauth_validate', req.ip || 'unknown', 30, MIN, Date.now())) { + throw new HttpException({ error: 'too_many_requests', error_description: 'Too many attempts. Please try again later.' }, 429); + } + if (!this.oauth.mcpEnabled()) { + // 404 (not 403) with an empty body so anonymous callers can't fingerprint the feature. + res.status(404).end(); + return undefined; + } + const userId = (req.user as User | undefined)?.id ?? null; + const result = this.oauth.validateAuthorizeRequest( + { + response_type: params.response_type || '', + client_id: params.client_id || '', + redirect_uri: params.redirect_uri || '', + scope: params.scope || '', + state: params.state, + code_challenge: params.code_challenge || '', + code_challenge_method: params.code_challenge_method || '', + resource: typeof params.resource === 'string' ? params.resource : undefined, + }, + userId, + ); + if (userId === null && result.valid) { + return { valid: result.valid, loginRequired: true }; + } + if (userId === null && !result.valid) { + return { valid: false, error: 'invalid_request', error_description: 'Invalid authorization request' }; + } + return result; + } + + @Post('authorize') + @HttpCode(200) // Express answers consent with res.json (200), not the POST-default 201. + @UseGuards(CookieAuthGuard) + authorize(@CurrentUser() user: User, @Body() body: { + client_id: string; redirect_uri: string; scope: string; state?: string; + code_challenge: string; code_challenge_method: string; approved: boolean; resource?: string; + }, @Req() req: Request) { + const ip = getClientIp(req); + if (!this.oauth.mcpEnabled()) { + throw new HttpException({ error: 'MCP is not enabled' }, 403); + } + if (!body.approved) { + const url = new URL(body.redirect_uri); + url.searchParams.set('error', 'access_denied'); + url.searchParams.set('error_description', 'User denied the authorization request'); + if (body.state) url.searchParams.set('state', body.state); + return { redirect: url.toString() }; + } + const params: AuthorizeParams = { + response_type: 'code', + client_id: body.client_id, + redirect_uri: body.redirect_uri, + scope: body.scope, + state: body.state, + code_challenge: body.code_challenge, + code_challenge_method: body.code_challenge_method, + resource: body.resource, + }; + const validation = this.oauth.validateAuthorizeRequest(params, user.id); + if (!validation.valid) { + throw new HttpException({ error: validation.error, error_description: validation.error_description }, 400); + } + const scopes = validation.scopes!; + this.oauth.saveConsent(body.client_id, user.id, scopes, ip); + const code = this.oauth.createAuthCode({ + clientId: body.client_id, + userId: user.id, + redirectUri: body.redirect_uri, + scopes, + resource: validation.resource ?? null, + codeChallenge: body.code_challenge, + codeChallengeMethod: 'S256', + }); + if (!code) { + throw new HttpException({ error: 'server_error', error_description: 'Authorization server is temporarily unavailable' }, 503); + } + const url = new URL(body.redirect_uri); + url.searchParams.set('code', code); + if (body.state) url.searchParams.set('state', body.state); + return { redirect: url.toString() }; + } + + @Get('clients') + @UseGuards(JwtAuthGuard) + listClients(@CurrentUser() user: User) { + this.requireMcp403(); + return { clients: this.oauth.listOAuthClients(user.id) }; + } + + @Post('clients') + @HttpCode(201) + @UseGuards(CookieAuthGuard) + createClient(@CurrentUser() user: User, @Body() body: { name: string; redirect_uris?: string[]; allowed_scopes: string[]; allows_client_credentials?: boolean }, @Req() req: Request) { + this.requireMcp403(); + const result = this.oauth.createOAuthClient(user.id, body.name, body.redirect_uris ?? [], body.allowed_scopes, getClientIp(req), { allowsClientCredentials: body.allows_client_credentials }); + if (result.error) { + throw new HttpException({ error: result.error }, result.status || 400); + } + return result; + } + + @Post('clients/:id/rotate') + @HttpCode(200) + @UseGuards(CookieAuthGuard) + rotateClient(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) { + this.requireMcp403(); + const result = this.oauth.rotateOAuthClientSecret(user.id, id, getClientIp(req)); + if (result.error) { + throw new HttpException({ error: result.error }, result.status || 400); + } + return { client_secret: result.client_secret }; + } + + @Delete('clients/:id') + @UseGuards(CookieAuthGuard) + deleteClient(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) { + this.requireMcp403(); + const result = this.oauth.deleteOAuthClient(user.id, id, getClientIp(req)); + if (result.error) { + throw new HttpException({ error: result.error }, result.status || 400); + } + return { success: true }; + } + + @Get('sessions') + @UseGuards(JwtAuthGuard) + listSessions(@CurrentUser() user: User) { + this.requireMcp403(); + return { sessions: this.oauth.listOAuthSessions(user.id) }; + } + + @Delete('sessions/:id') + @UseGuards(CookieAuthGuard) + revokeSession(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) { + this.requireMcp403(); + const result = this.oauth.revokeSession(user.id, Number(id), getClientIp(req)); + if (result.error) { + throw new HttpException({ error: result.error }, result.status || 400); + } + return { success: true }; + } +} diff --git a/server/src/nest/oauth/oauth-public.controller.ts b/server/src/nest/oauth/oauth-public.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..9a05d0767120bb811d97216c5482c89ee39f5b94 --- /dev/null +++ b/server/src/nest/oauth/oauth-public.controller.ts @@ -0,0 +1,165 @@ +import { Controller, Get, Headers, HttpCode, Post, Req, Res } from '@nestjs/common'; +import type { Request, Response } from 'express'; +import { OauthService } from './oauth.service'; +import { RateLimitService } from '../auth/rate-limit.service'; +import { writeAudit, getClientIp, logWarn } from '../../services/auditLog'; + +const MIN = 60_000; + +/** + * Public OAuth 2.1 endpoints (no session) — byte-identical to the legacy + * oauthPublicRouter (server/src/routes/oauth.ts): MCP-addon gated (404), the + * per-(ip,client) token / per-ip revoke rate limits, no-store cache headers on + * /token, the WWW-Authenticate challenge on /userinfo, the three grant types + * and the RFC 7009 always-200 revoke. Uses @Res directly because every branch + * sets headers + a specific status the way the spec requires. + */ +@Controller('oauth') +export class OauthPublicController { + constructor(private readonly oauth: OauthService, private readonly rl: RateLimitService) {} + + @Post('token') + @HttpCode(200) // token success uses res.json without an explicit status; Express defaults to 200 (Nest POST would default to 201). + token(@Req() req: Request, @Res() res: Response): void { + if (!this.oauth.mcpEnabled()) { res.status(404).end(); return; } + + const body: Record = typeof req.body === 'object' && req.body ? req.body : {}; + if (!this.rl.check('oauth_token', `${req.ip}|${body.client_id ?? ''}`, 30, MIN, Date.now())) { + res.status(429).json({ error: 'too_many_requests', error_description: 'Too many attempts. Please try again later.' }); + return; + } + + res.set('Cache-Control', 'no-store'); + res.set('Pragma', 'no-cache'); + + const { grant_type, code, redirect_uri, client_id, client_secret, code_verifier, refresh_token, resource } = body; + const ip = getClientIp(req); + + if (!client_id) { + res.status(401).json({ error: 'invalid_client', error_description: 'client_id is required' }); + return; + } + + if (grant_type === 'authorization_code') { + if (!code || !redirect_uri || !code_verifier) { + res.status(400).json({ error: 'invalid_request', error_description: 'code, redirect_uri, and code_verifier are required' }); + return; + } + const pending = this.oauth.consumeAuthCode(code); + const invalidGrant = (reason: string, userId: number | null) => { + writeAudit({ userId, action: 'oauth.token.grant_failed', details: { client_id, reason }, ip }); + res.status(400).json({ error: 'invalid_grant', error_description: 'Authorization grant is invalid.' }); + }; + if (!pending) return invalidGrant('code_invalid_or_expired', null); + if (pending.clientId !== client_id) return invalidGrant('client_id_mismatch', pending.userId); + if (pending.redirectUri !== redirect_uri) return invalidGrant('redirect_uri_mismatch', pending.userId); + if (pending.resource && resource && pending.resource !== resource.replace(/\/+$/, '')) return invalidGrant('resource_mismatch', pending.userId); + if (!this.oauth.authenticateClient(client_id, client_secret)) { + logWarn(`[OAuth] Invalid client credentials for client_id=${client_id} ip=${ip ?? '-'}`); + writeAudit({ userId: pending.userId, action: 'oauth.token.client_auth_failed', details: { client_id }, ip }); + res.status(401).json({ error: 'invalid_client', error_description: 'Invalid client credentials' }); + return; + } + if (!this.oauth.verifyPKCE(code_verifier, pending.codeChallenge)) return invalidGrant('pkce_failed', pending.userId); + const tokens = this.oauth.issueTokens(client_id, pending.userId, pending.scopes, null, pending.resource ?? null); + writeAudit({ userId: pending.userId, action: 'oauth.token.issue', details: { client_id, scopes: pending.scopes, audience: pending.resource ?? null }, ip }); + res.json(tokens); + return; + } + + if (grant_type === 'refresh_token') { + if (!refresh_token) { + res.status(400).json({ error: 'invalid_request', error_description: 'refresh_token is required' }); + return; + } + const result = this.oauth.refreshTokens(refresh_token, client_id, client_secret, ip); + if (result.error) { + if (result.error === 'invalid_client') logWarn(`[OAuth] Invalid client credentials on refresh for client_id=${client_id} ip=${ip ?? '-'}`); + res.status(result.status || 400).json({ error: result.error, error_description: result.error === 'invalid_client' ? 'Invalid client credentials' : 'Refresh token is invalid or expired' }); + return; + } + res.json(result.tokens); + return; + } + + if (grant_type === 'client_credentials') { + if (!client_secret) { + res.status(401).json({ error: 'invalid_client', error_description: 'client_secret is required for client_credentials grant' }); + return; + } + const client = this.oauth.authenticateClient(client_id, client_secret); + if (!client) { + logWarn(`[OAuth] Invalid client credentials for client_id=${client_id} ip=${ip ?? '-'}`); + writeAudit({ userId: null, action: 'oauth.token.client_auth_failed', details: { client_id }, ip }); + res.status(401).json({ error: 'invalid_client', error_description: 'Invalid client credentials' }); + return; + } + if (client.is_public || !client.allows_client_credentials || client.user_id == null) { + writeAudit({ userId: client.user_id ?? null, action: 'oauth.token.grant_failed', details: { client_id, reason: 'unauthorized_client' }, ip }); + res.status(400).json({ error: 'unauthorized_client', error_description: 'This client is not authorized for the client_credentials grant' }); + return; + } + const allowedScopes: string[] = JSON.parse(client.allowed_scopes); + let grantedScopes: string[]; + if (body.scope) { + const requested = body.scope.split(' ').filter(Boolean); + const invalid = requested.filter((s) => !allowedScopes.includes(s)); + if (invalid.length > 0) { + res.status(400).json({ error: 'invalid_scope', error_description: `Scopes not allowed for this client: ${invalid.join(', ')}` }); + return; + } + grantedScopes = requested; + } else { + grantedScopes = allowedScopes; + } + const audience = resource ? resource.replace(/\/+$/, '') : `${this.oauth.mcpSafeUrl().replace(/\/+$/, '')}/mcp`; + const tokens = this.oauth.issueClientCredentialsToken(client_id, client.user_id, grantedScopes, audience); + writeAudit({ userId: client.user_id, action: 'oauth.token.issue', details: { client_id, scopes: grantedScopes, audience, grant: 'client_credentials' }, ip }); + res.json(tokens); + return; + } + + res.status(400).json({ error: 'unsupported_grant_type', error_description: `Unsupported grant_type: ${grant_type}` }); + } + + @Get('userinfo') + userinfo(@Headers('authorization') auth: string | undefined, @Res() res: Response): void { + if (!this.oauth.mcpEnabled()) { res.status(404).end(); return; } + if (!auth || !auth.toLowerCase().startsWith('bearer ')) { + res.set('WWW-Authenticate', 'Bearer realm="TREK MCP"'); + res.status(401).json({ error: 'invalid_token' }); + return; + } + const info = this.oauth.getUserByAccessToken(auth.slice(7)); + if (!info) { + res.set('WWW-Authenticate', 'Bearer realm="TREK MCP", error="invalid_token"'); + res.status(401).json({ error: 'invalid_token' }); + return; + } + res.json({ sub: String(info.user.id), email: info.user.email, email_verified: true, preferred_username: info.user.username }); + } + + @Post('revoke') + revoke(@Req() req: Request, @Res() res: Response): void { + if (!this.oauth.mcpEnabled()) { res.status(404).end(); return; } + if (!this.rl.check('oauth_revoke', req.ip || 'unknown', 10, MIN, Date.now())) { + res.status(429).json({ error: 'too_many_requests', error_description: 'Too many attempts. Please try again later.' }); + return; + } + const body: Record = typeof req.body === 'object' && req.body ? req.body : {}; + const { token, client_id, client_secret } = body; + const ip = getClientIp(req); + if (!token || !client_id) { + res.status(400).json({ error: 'invalid_request', error_description: 'token and client_id are required' }); + return; + } + if (!this.oauth.authenticateClient(client_id, client_secret)) { + logWarn(`[OAuth] Invalid client credentials on revoke for client_id=${client_id} ip=${ip ?? '-'}`); + writeAudit({ userId: null, action: 'oauth.token.client_auth_failed', details: { client_id, endpoint: 'revoke' }, ip }); + res.status(401).json({ error: 'invalid_client', error_description: 'Invalid client credentials' }); + return; + } + this.oauth.revokeToken(token, client_id, undefined, ip); + res.status(200).json({}); + } +} diff --git a/server/src/nest/oauth/oauth.module.ts b/server/src/nest/oauth/oauth.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..ebebe01a3e036e7ab2a00efd657bc692a9eecf1d --- /dev/null +++ b/server/src/nest/oauth/oauth.module.ts @@ -0,0 +1,17 @@ +import { Module } from '@nestjs/common'; +import { OauthPublicController } from './oauth-public.controller'; +import { OauthApiController } from './oauth-api.controller'; +import { OauthService } from './oauth.service'; +import { RateLimitService } from '../auth/rate-limit.service'; + +/** + * OAuth 2.1 server (MCP). Public token/userinfo/revoke endpoints + the SPA's + * authenticated consent/client/session management. The SDK-mounted + * /oauth/authorize, /oauth/register and /oauth/consent stay on Express, so the + * strangler lists /oauth/token, /oauth/userinfo, /oauth/revoke explicitly. + */ +@Module({ + controllers: [OauthPublicController, OauthApiController], + providers: [OauthService, RateLimitService], +}) +export class OauthModule {} diff --git a/server/src/nest/oauth/oauth.service.ts b/server/src/nest/oauth/oauth.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..329b494ab578a772e578960036722e2e8a907490 --- /dev/null +++ b/server/src/nest/oauth/oauth.service.ts @@ -0,0 +1,36 @@ +import { Injectable } from '@nestjs/common'; +import * as oauth from '../../services/oauthService'; +import { isAddonEnabled } from '../../services/adminService'; +import { ADDON_IDS } from '../../addons'; +import { getMcpSafeUrl } from '../../services/notifications'; + +/** + * Thin Nest wrapper around the existing OAuth 2.1 service. The grant handling, + * PKCE, client auth, consent storage, token issue/refresh/revoke and the + * client/session CRUD all reuse the legacy code unchanged. + */ +@Injectable() +export class OauthService { + mcpEnabled(): boolean { return isAddonEnabled(ADDON_IDS.MCP); } + mcpSafeUrl(): string { return getMcpSafeUrl(); } + + consumeAuthCode(code: string) { return oauth.consumeAuthCode(code); } + authenticateClient(clientId: string, clientSecret?: string) { return oauth.authenticateClient(clientId, clientSecret); } + verifyPKCE(verifier: string, challenge: string) { return oauth.verifyPKCE(verifier, challenge); } + issueTokens(...args: Parameters) { return oauth.issueTokens(...args); } + issueClientCredentialsToken(...args: Parameters) { return oauth.issueClientCredentialsToken(...args); } + refreshTokens(...args: Parameters) { return oauth.refreshTokens(...args); } + revokeToken(...args: Parameters) { return oauth.revokeToken(...args); } + getUserByAccessToken(token: string) { return oauth.getUserByAccessToken(token); } + + validateAuthorizeRequest(params: oauth.AuthorizeParams, userId: number | null) { return oauth.validateAuthorizeRequest(params, userId); } + saveConsent(...args: Parameters) { return oauth.saveConsent(...args); } + createAuthCode(...args: Parameters) { return oauth.createAuthCode(...args); } + + listOAuthClients(userId: number) { return oauth.listOAuthClients(userId); } + createOAuthClient(...args: Parameters) { return oauth.createOAuthClient(...args); } + rotateOAuthClientSecret(userId: number, id: string, ip: string | undefined) { return oauth.rotateOAuthClientSecret(userId, id, ip); } + deleteOAuthClient(userId: number, id: string, ip: string | undefined) { return oauth.deleteOAuthClient(userId, id, ip); } + listOAuthSessions(userId: number) { return oauth.listOAuthSessions(userId); } + revokeSession(userId: number, id: number, ip: string | undefined) { return oauth.revokeSession(userId, id, ip); } +} diff --git a/server/src/nest/oidc/oidc.controller.ts b/server/src/nest/oidc/oidc.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..8d783603f62c4f24146b5793fce60d98bb3df5b8 --- /dev/null +++ b/server/src/nest/oidc/oidc.controller.ts @@ -0,0 +1,158 @@ +import { Controller, Get, Query, Req, Res } from '@nestjs/common'; +import type { Request, Response } from 'express'; +import { OidcService } from './oidc.service'; +import { cookieOptions } from '../../services/cookie'; + +const OIDC_STATE_COOKIE = 'trek_oidc_state'; + +/** + * /api/auth/oidc — OIDC SSO login flow (Authorization Code + PKCE). + * + * Byte-identical to the legacy Express route (server/src/routes/oidc.ts): + * unauthenticated, the sso-disabled / not-configured / HTTPS-issuer guards, the + * strict id_token + userinfo.sub cross-check, all the frontend redirect error + * codes, and the auth-code → cookie hand-off on /exchange. Uses @Res directly + * because the flow mixes provider redirects with JSON error bodies. + */ +@Controller('api/auth/oidc') +export class OidcController { + constructor(private readonly oidc: OidcService) {} + + @Get('login') + async login(@Req() req: Request, @Res() res: Response): Promise { + if (!this.oidc.oidcLoginEnabled()) { + res.status(403).json({ error: 'SSO login is disabled.' }); + return; + } + const config = this.oidc.getOidcConfig(); + if (!config) { + res.status(400).json({ error: 'OIDC not configured' }); + return; + } + if (config.issuer && !config.issuer.startsWith('https://') && process.env.NODE_ENV?.toLowerCase() === 'production') { + res.status(400).json({ error: 'OIDC issuer must use HTTPS in production' }); + return; + } + try { + const doc = await this.oidc.discover(config.issuer, config.discoveryUrl); + const appUrl = this.oidc.getAppUrl(); + if (!appUrl) { + res.status(500).json({ error: 'APP_URL is not configured. OIDC cannot be used.' }); + return; + } + const redirectUri = `${appUrl.replace(/\/+$/, '')}/api/auth/oidc/callback`; + const inviteToken = req.query.invite as string | undefined; + const { state, codeChallenge } = this.oidc.createState(redirectUri, inviteToken); + // Bind the state to THIS browser. The callback requires a matching cookie, + // so an attacker-initiated login (whose callback URL carries a valid state + // from the shared server map) cannot be replayed in a victim's browser to + // log them into the attacker's account (OIDC login CSRF / session fixation). + res.cookie(OIDC_STATE_COOKIE, state, { ...cookieOptions(false, req), maxAge: 10 * 60 * 1000 }); + const params = new URLSearchParams({ + response_type: 'code', + client_id: config.clientId, + redirect_uri: redirectUri, + scope: process.env.OIDC_SCOPE || 'openid email profile', + state, + code_challenge: codeChallenge, + code_challenge_method: 'S256', + }); + res.redirect(`${doc.authorization_endpoint}?${params}`); + } catch (err: unknown) { + console.error('[OIDC] Login error:', err instanceof Error ? err.message : err); + res.status(500).json({ error: 'OIDC login failed' }); + } + } + + @Get('callback') + async callback( + @Query('code') code: string | undefined, + @Query('state') state: string | undefined, + @Query('error') oidcError: string | undefined, + @Req() req: Request, + @Res() res: Response, + ): Promise { + const f = (p: string) => res.redirect(this.oidc.frontendUrl(p)); + + // The state cookie is single-use — clear it regardless of the outcome. + const boundState = (req.cookies as Record | undefined)?.[OIDC_STATE_COOKIE]; + res.clearCookie(OIDC_STATE_COOKIE, cookieOptions(true, req)); + + if (!this.oidc.oidcLoginEnabled()) return f('/login?oidc_error=sso_disabled'); + if (oidcError) { + console.error('[OIDC] Provider error:', oidcError); + return f('/login?oidc_error=' + encodeURIComponent(oidcError)); + } + if (!code || !state) return f('/login?oidc_error=missing_params'); + + // Require the callback to come from the browser that started the flow. + if (!boundState || boundState !== state) return f('/login?oidc_error=invalid_state'); + + const pending = this.oidc.consumeState(state); + if (!pending) return f('/login?oidc_error=invalid_state'); + + const config = this.oidc.getOidcConfig(); + if (!config) return f('/login?oidc_error=not_configured'); + if (config.issuer && !config.issuer.startsWith('https://') && process.env.NODE_ENV?.toLowerCase() === 'production') { + return f('/login?oidc_error=issuer_not_https'); + } + + try { + const doc = await this.oidc.discover(config.issuer, config.discoveryUrl); + const tokenData = await this.oidc.exchangeCodeForToken(doc, code, pending.redirectUri, config.clientId, config.clientSecret, pending.codeVerifier); + if (!tokenData._ok || !tokenData.access_token) { + console.error('[OIDC] Token exchange failed: status', tokenData._status); + return f('/login?oidc_error=token_failed'); + } + if (!tokenData.id_token) { + console.error('[OIDC] Token response missing id_token — refusing login'); + return f('/login?oidc_error=no_id_token'); + } + const idVerify = await this.oidc.verifyIdToken( + tokenData.id_token, + doc, + config.clientId, + (doc.issuer ?? '').replace(/\/+$/, '') || config.issuer, + ); + if (idVerify.ok !== true) { + const reason = 'error' in idVerify ? idVerify.error : 'unknown'; + console.error('[OIDC] id_token verification failed:', reason); + return f('/login?oidc_error=id_token_invalid'); + } + const userInfo = await this.oidc.getUserInfo(doc.userinfo_endpoint, tokenData.access_token); + if (!userInfo.email) return f('/login?oidc_error=no_email'); + + const tokenSub = idVerify.claims.sub; + if (typeof tokenSub === 'string' && userInfo.sub && userInfo.sub !== tokenSub) { + console.error('[OIDC] userinfo.sub does not match id_token.sub — refusing login'); + return f('/login?oidc_error=subject_mismatch'); + } + + const result = this.oidc.findOrCreateUser(userInfo, config, pending.inviteToken); + if ('error' in result) return f('/login?oidc_error=' + result.error); + + this.oidc.touchLastLogin(result.user.id); + const jwtToken = this.oidc.generateToken(result.user); + const authCode = this.oidc.createAuthCode(jwtToken); + return f('/login?oidc_code=' + authCode); + } catch (err: unknown) { + console.error('[OIDC] Callback error:', err); + return f('/login?oidc_error=server_error'); + } + } + + @Get('exchange') + exchange(@Query('code') code: string | undefined, @Req() req: Request, @Res() res: Response): void { + if (!code) { + res.status(400).json({ error: 'Code required' }); + return; + } + const result = this.oidc.consumeAuthCode(code); + if ('error' in result) { + res.status(400).json({ error: result.error }); + return; + } + this.oidc.setAuthCookie(res, result.token, req); + res.json({ token: result.token }); + } +} diff --git a/server/src/nest/oidc/oidc.module.ts b/server/src/nest/oidc/oidc.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..e2107bc599119505f51cc33047845e44d10beb7b --- /dev/null +++ b/server/src/nest/oidc/oidc.module.ts @@ -0,0 +1,9 @@ +import { Module } from '@nestjs/common'; +import { OidcController } from './oidc.controller'; +import { OidcService } from './oidc.service'; + +@Module({ + controllers: [OidcController], + providers: [OidcService], +}) +export class OidcModule {} diff --git a/server/src/nest/oidc/oidc.service.ts b/server/src/nest/oidc/oidc.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..726a3e1823bcb89e84f2f546f6ced356c828ceca --- /dev/null +++ b/server/src/nest/oidc/oidc.service.ts @@ -0,0 +1,31 @@ +import { Injectable } from '@nestjs/common'; +import type { Request, Response } from 'express'; +import * as oidc from '../../services/oidcService'; +import { getAppUrl } from '../../services/notifications'; +import { resolveAuthToggles } from '../../services/authService'; +import { setAuthCookie } from '../../services/cookie'; + +/** + * Thin Nest wrapper around the existing OIDC service. PKCE state, discovery, + * the strict id_token/JWKS verification, user provisioning and the auth-code + * hand-off all reuse the legacy code unchanged. + */ +@Injectable() +export class OidcService { + oidcLoginEnabled(): boolean { return resolveAuthToggles().oidc_login; } + getOidcConfig() { return oidc.getOidcConfig(); } + getAppUrl() { return getAppUrl(); } + discover(issuer: string, discoveryUrl?: string | null) { return oidc.discover(issuer, discoveryUrl); } + createState(redirectUri: string, inviteToken?: string) { return oidc.createState(redirectUri, inviteToken); } + consumeState(state: string) { return oidc.consumeState(state); } + exchangeCodeForToken(...args: Parameters) { return oidc.exchangeCodeForToken(...args); } + verifyIdToken(...args: Parameters) { return oidc.verifyIdToken(...args); } + getUserInfo(endpoint: string, accessToken: string) { return oidc.getUserInfo(endpoint, accessToken); } + findOrCreateUser(...args: Parameters) { return oidc.findOrCreateUser(...args); } + touchLastLogin(userId: number) { return oidc.touchLastLogin(userId); } + generateToken(user: { id: number }) { return oidc.generateToken(user); } + createAuthCode(token: string) { return oidc.createAuthCode(token); } + consumeAuthCode(code: string) { return oidc.consumeAuthCode(code); } + frontendUrl(path: string) { return oidc.frontendUrl(path); } + setAuthCookie(res: Response, token: string, req: Request) { setAuthCookie(res, token, req); } +} diff --git a/server/src/nest/packing/packing.controller.ts b/server/src/nest/packing/packing.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..7f49dfc7a717eece1aca9e71b95e9b13b2c76f0a --- /dev/null +++ b/server/src/nest/packing/packing.controller.ts @@ -0,0 +1,282 @@ +import { + Body, + Controller, + Delete, + Get, + Headers, + HttpCode, + HttpException, + Param, + Post, + Put, + UseGuards, +} from '@nestjs/common'; +import type { User } from '../../types'; +import { PackingService } from './packing.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; + +/** + * /api/trips/:tripId/packing — trip-scoped packing list (items, bags, templates, + * assignees). + * + * Byte-identical to the legacy Express route (server/src/routes/packing.ts): + * every handler verifies trip access (404 "Trip not found"); mutations check the + * 'packing_edit' permission (403 "No permission"); status codes match (201 on the + * creates, 200 elsewhere — note POST /apply-template stays 200); and the bespoke + * 400/404 bodies are reproduced. Mutations broadcast over WebSocket with the + * forwarded X-Socket-Id. /reorder is declared before /:id so it wins over the param. + */ +@Controller('api/trips/:tripId/packing') +@UseGuards(JwtAuthGuard) +export class PackingController { + constructor(private readonly packing: PackingService) {} + + /** Loads the trip or throws the legacy 404; returns it for the permission check. */ + private requireTrip(tripId: string, user: User) { + const trip = this.packing.verifyTripAccess(tripId, user.id); + if (!trip) { + throw new HttpException({ error: 'Trip not found' }, 404); + } + return trip; + } + + private requireEdit(trip: ReturnType, user: User): void { + if (!this.packing.canEdit(trip!, user)) { + throw new HttpException({ error: 'No permission' }, 403); + } + } + + @Get() + list(@CurrentUser() user: User, @Param('tripId') tripId: string) { + this.requireTrip(tripId, user); + return { items: this.packing.listItems(tripId) }; + } + + @Post('import') + importItems( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body('items') items: unknown, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!Array.isArray(items) || items.length === 0) { + throw new HttpException({ error: 'items must be a non-empty array' }, 400); + } + const created = this.packing.bulkImport(tripId, items); + for (const item of created) { + this.packing.broadcast(tripId, 'packing:created', { item }, socketId); + } + return { items: created, count: created.length }; + } + + @Post() + create( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body() body: { name?: string; category?: string; checked?: boolean }, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!body.name) { + throw new HttpException({ error: 'Item name is required' }, 400); + } + const item = this.packing.createItem(tripId, { name: body.name, category: body.category, checked: body.checked }); + this.packing.broadcast(tripId, 'packing:created', { item }, socketId); + return { item }; + } + + @Put('reorder') + reorder( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body('orderedIds') orderedIds: number[], + @Headers('x-socket-id') _socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + this.packing.reorderItems(tripId, orderedIds); + return { success: true }; + } + + @Put(':id') + update( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('id') id: string, + @Body() body: Record, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + const { name, checked, category, weight_grams, bag_id, quantity } = body as Record; + const updated = this.packing.updateItem(tripId, id, { name, checked, category, weight_grams, bag_id, quantity }, Object.keys(body)); + if (!updated) { + throw new HttpException({ error: 'Item not found' }, 404); + } + this.packing.broadcast(tripId, 'packing:updated', { item: updated }, socketId); + return { item: updated }; + } + + @Delete(':id') + remove( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('id') id: string, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!this.packing.deleteItem(tripId, id)) { + throw new HttpException({ error: 'Item not found' }, 404); + } + this.packing.broadcast(tripId, 'packing:deleted', { itemId: Number(id) }, socketId); + return { success: true }; + } + + @Get('bags') + listBags(@CurrentUser() user: User, @Param('tripId') tripId: string) { + this.requireTrip(tripId, user); + return { bags: this.packing.listBags(tripId) }; + } + + @Post('bags') + createBag( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body() body: { name?: string; color?: string }, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!body.name?.trim()) { + throw new HttpException({ error: 'Name is required' }, 400); + } + const bag = this.packing.createBag(tripId, { name: body.name, color: body.color }); + this.packing.broadcast(tripId, 'packing:bag-created', { bag }, socketId); + return { bag }; + } + + @Put('bags/:bagId') + updateBag( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('bagId') bagId: string, + @Body() body: Record, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + const { name, color, weight_limit_grams, user_id } = body as Record; + const updated = this.packing.updateBag(tripId, bagId, { name, color, weight_limit_grams, user_id }, Object.keys(body)); + if (!updated) { + throw new HttpException({ error: 'Bag not found' }, 404); + } + this.packing.broadcast(tripId, 'packing:bag-updated', { bag: updated }, socketId); + return { bag: updated }; + } + + @Delete('bags/:bagId') + deleteBag( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('bagId') bagId: string, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!this.packing.deleteBag(tripId, bagId)) { + throw new HttpException({ error: 'Bag not found' }, 404); + } + this.packing.broadcast(tripId, 'packing:bag-deleted', { bagId: Number(bagId) }, socketId); + return { success: true }; + } + + @Get('templates') + listTemplates(@CurrentUser() user: User, @Param('tripId') tripId: string) { + this.requireTrip(tripId, user); + return { templates: this.packing.listTemplates() }; + } + + @Post('apply-template/:templateId') + @HttpCode(200) + applyTemplate( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('templateId') templateId: string, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + const added = this.packing.applyTemplate(tripId, templateId); + if (!added) { + throw new HttpException({ error: 'Template not found or empty' }, 404); + } + this.packing.broadcast(tripId, 'packing:template-applied', { items: added }, socketId); + return { items: added, count: added.length }; + } + + @Put('bags/:bagId/members') + setBagMembers( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('bagId') bagId: string, + @Body('user_ids') userIds: unknown, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + const members = this.packing.setBagMembers(tripId, bagId, Array.isArray(userIds) ? userIds : []); + if (!members) { + throw new HttpException({ error: 'Bag not found' }, 404); + } + this.packing.broadcast(tripId, 'packing:bag-members-updated', { bagId: Number(bagId), members }, socketId); + return { members }; + } + + @Post('save-as-template') + saveAsTemplate( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body('name') name?: string, + ) { + this.requireTrip(tripId, user); + if (user.role !== 'admin') { + throw new HttpException({ error: 'Admin access required' }, 403); + } + if (!name?.trim()) { + throw new HttpException({ error: 'Template name is required' }, 400); + } + const template = this.packing.saveAsTemplate(tripId, user.id, name.trim()); + if (!template) { + throw new HttpException({ error: 'No items to save' }, 400); + } + return { template }; + } + + @Get('category-assignees') + categoryAssignees(@CurrentUser() user: User, @Param('tripId') tripId: string) { + this.requireTrip(tripId, user); + return { assignees: this.packing.getCategoryAssignees(tripId) }; + } + + @Put('category-assignees/:categoryName') + updateCategoryAssignees( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('categoryName') categoryName: string, + @Body('user_ids') userIds: number[], + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + const category = decodeURIComponent(categoryName); + const rows = this.packing.updateCategoryAssignees(tripId, category, userIds); + this.packing.broadcast(tripId, 'packing:assignees', { category, assignees: rows }, socketId); + this.packing.notifyTagged(tripId, user, category, userIds); + return { assignees: rows }; + } +} diff --git a/server/src/nest/packing/packing.module.ts b/server/src/nest/packing/packing.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..a1025a53497b4bab8dd41b9dfa3e1aac041ec183 --- /dev/null +++ b/server/src/nest/packing/packing.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { PackingController } from './packing.controller'; +import { PackingService } from './packing.service'; + +/** Packing domain (S2 — Phase 2 trip sub-domain). Registered in AppModule. */ +@Module({ + controllers: [PackingController], + providers: [PackingService], +}) +export class PackingModule {} diff --git a/server/src/nest/packing/packing.service.ts b/server/src/nest/packing/packing.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..d4f351e895bdff317f09f3001cdff54d1aa45201 --- /dev/null +++ b/server/src/nest/packing/packing.service.ts @@ -0,0 +1,108 @@ +import { Injectable } from '@nestjs/common'; +import { db } from '../../db/database'; +import { broadcast } from '../../websocket'; +import { checkPermission } from '../../services/permissions'; +import type { User } from '../../types'; +import * as svc from '../../services/packingService'; + +type Trip = NonNullable>; + +/** + * Thin Nest wrapper around the existing packing service. Trip-access checks, the + * 'packing_edit' permission, the item/bag SQL, templates and the WebSocket + * broadcasts all reuse the legacy code unchanged, so behaviour is identical. + */ +@Injectable() +export class PackingService { + verifyTripAccess(tripId: string, userId: number) { + return svc.verifyTripAccess(tripId, userId); + } + + /** Mirrors the inline checkPermission('packing_edit', ...) the legacy route runs. */ + canEdit(trip: Trip, user: User): boolean { + return checkPermission('packing_edit', user.role, trip.user_id, user.id, trip.user_id !== user.id); + } + + broadcast(tripId: string, event: string, payload: Record, socketId: string | undefined): void { + broadcast(tripId, event, payload, socketId); + } + + listItems(tripId: string) { + return svc.listItems(tripId); + } + + createItem(tripId: string, data: { name: string; category?: string; checked?: boolean }) { + return svc.createItem(tripId, data); + } + + updateItem(tripId: string, id: string, data: Parameters[2], changedKeys: string[]) { + return svc.updateItem(tripId, id, data, changedKeys); + } + + deleteItem(tripId: string, id: string): boolean { + return svc.deleteItem(tripId, id); + } + + bulkImport(tripId: string, items: Parameters[1]) { + return svc.bulkImport(tripId, items); + } + + reorderItems(tripId: string, orderedIds: Parameters[1]): void { + svc.reorderItems(tripId, orderedIds); + } + + listBags(tripId: string) { + return svc.listBags(tripId); + } + + createBag(tripId: string, data: { name: string; color?: string }) { + return svc.createBag(tripId, data); + } + + updateBag(tripId: string, bagId: string, data: Parameters[2], changedKeys: string[]) { + return svc.updateBag(tripId, bagId, data, changedKeys); + } + + deleteBag(tripId: string, bagId: string): boolean { + return svc.deleteBag(tripId, bagId); + } + + setBagMembers(tripId: string, bagId: string, userIds: number[]) { + return svc.setBagMembers(tripId, bagId, userIds); + } + + listTemplates() { + return svc.listTemplates(); + } + + applyTemplate(tripId: string, templateId: string) { + return svc.applyTemplate(tripId, templateId); + } + + saveAsTemplate(tripId: string, userId: number, name: string) { + return svc.saveAsTemplate(tripId, userId, name); + } + + getCategoryAssignees(tripId: string) { + return svc.getCategoryAssignees(tripId); + } + + updateCategoryAssignees(tripId: string, category: string, userIds: number[]) { + return svc.updateCategoryAssignees(tripId, category, userIds); + } + + /** Fire-and-forget tag notification, mirroring the legacy dynamic import. */ + notifyTagged(tripId: string, actor: User, category: string, userIds: unknown): void { + if (!Array.isArray(userIds) || userIds.length === 0) return; + import('../../services/notificationService').then(({ send }) => { + const tripInfo = db.prepare('SELECT title FROM trips WHERE id = ?').get(tripId) as { title: string } | undefined; + send({ + event: 'packing_tagged', + actorId: actor.id, + scope: 'trip', + targetId: Number(tripId), + params: { trip: tripInfo?.title || 'Untitled', actor: actor.email, category, tripId: String(tripId) }, + }).catch(() => {}); + }); + } +} diff --git a/server/src/nest/photos/photos.controller.ts b/server/src/nest/photos/photos.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..ee845817249d81070e29c6173ef380a246e6983c --- /dev/null +++ b/server/src/nest/photos/photos.controller.ts @@ -0,0 +1,55 @@ +import { Controller, Get, HttpException, Param, Res, UseGuards } from '@nestjs/common'; +import type { Response } from 'express'; +import type { User } from '../../types'; +import { PhotosService } from './photos.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; + +/** + * /api/photos/:id/{thumbnail,original,info} — global (not trip-scoped) photo + * access for the memories/journey features. Streaming endpoints write straight + * to the response via the resolver service. + * + * Byte-identical to the legacy Express route (server/src/routes/photos.ts): + * a finite-id guard (400), the canAccessTrekPhoto check (403), then stream or + * the provider info (404 inside the service / mapped error for info). + */ +@Controller('api/photos') +@UseGuards(JwtAuthGuard) +export class PhotosController { + constructor(private readonly photos: PhotosService) {} + + private requireAccess(user: User, rawId: string): number { + const photoId = Number(rawId); + if (!Number.isFinite(photoId)) { + throw new HttpException({ error: 'Invalid photo ID' }, 400); + } + if (!this.photos.canAccess(user.id, photoId)) { + throw new HttpException({ error: 'Forbidden' }, 403); + } + return photoId; + } + + @Get(':id/thumbnail') + async thumbnail(@CurrentUser() user: User, @Param('id') id: string, @Res() res: Response): Promise { + const photoId = this.requireAccess(user, id); + await this.photos.stream(res, user.id, photoId, 'thumbnail'); + } + + @Get(':id/original') + async original(@CurrentUser() user: User, @Param('id') id: string, @Res() res: Response): Promise { + const photoId = this.requireAccess(user, id); + await this.photos.stream(res, user.id, photoId, 'original'); + } + + @Get(':id/info') + async info(@CurrentUser() user: User, @Param('id') id: string, @Res() res: Response): Promise { + const photoId = this.requireAccess(user, id); + const result = await this.photos.info(user.id, photoId); + if ('error' in result) { + res.status(result.error.status).json({ error: result.error.message }); + return; + } + res.json(result.data); + } +} diff --git a/server/src/nest/photos/photos.module.ts b/server/src/nest/photos/photos.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..2f42baa54ad84549bfb1178c6ccd26a994b83290 --- /dev/null +++ b/server/src/nest/photos/photos.module.ts @@ -0,0 +1,9 @@ +import { Module } from '@nestjs/common'; +import { PhotosController } from './photos.controller'; +import { PhotosService } from './photos.service'; + +@Module({ + controllers: [PhotosController], + providers: [PhotosService], +}) +export class PhotosModule {} diff --git a/server/src/nest/photos/photos.service.ts b/server/src/nest/photos/photos.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..7f867e1312126ccaf2c7f4295580b5bbb11afeea --- /dev/null +++ b/server/src/nest/photos/photos.service.ts @@ -0,0 +1,24 @@ +import { Injectable } from '@nestjs/common'; +import type { Response } from 'express'; +import { streamPhoto, getPhotoInfo } from '../../services/memories/photoResolverService'; +import { canAccessTrekPhoto } from '../../services/memories/helpersService'; + +/** + * Thin Nest wrapper around the existing photo resolver/helper services. Access + * control, streaming and the provider-specific info lookups reuse the legacy + * code unchanged. + */ +@Injectable() +export class PhotosService { + canAccess(userId: number, photoId: number): boolean { + return canAccessTrekPhoto(userId, photoId); + } + + stream(res: Response, userId: number, photoId: number, kind: 'thumbnail' | 'original') { + return streamPhoto(res, userId, photoId, kind); + } + + info(userId: number, photoId: number) { + return getPhotoInfo(userId, photoId); + } +} diff --git a/server/src/nest/places/places.controller.ts b/server/src/nest/places/places.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb8fbe5e93b4faf58b81ab5ece831c2e5d4ba5a4 --- /dev/null +++ b/server/src/nest/places/places.controller.ts @@ -0,0 +1,285 @@ +import { + Body, + Controller, + Delete, + Get, + Headers, + HttpCode, + HttpException, + Param, + Post, + Put, + Query, + UploadedFile, + UseGuards, + UseInterceptors, +} from '@nestjs/common'; +import { FileInterceptor } from '@nestjs/platform-express'; +import { memoryStorage } from 'multer'; +import type { User } from '../../types'; +import { PlacesService } from './places.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; + +const STRING_LIMITS: Record = { name: 200, description: 2000, address: 500, notes: 2000 }; +const UPLOAD = { storage: memoryStorage(), limits: { fileSize: 10 * 1024 * 1024 } }; + +function validateLengths(body: Record): void { + for (const [field, max] of Object.entries(STRING_LIMITS)) { + const value = body[field]; + if (value && typeof value === 'string' && value.length > max) { + throw new HttpException({ error: `${field} must be ${max} characters or less` }, 400); + } + } +} + +function parseBool(v: unknown, defaultVal: boolean): boolean { + return v === undefined || v === null ? defaultVal : String(v) === 'true'; +} + +/** + * /api/trips/:tripId/places — the trip's place pool + importers. + * + * Byte-identical to the legacy Express route (server/src/routes/places.ts): + * trip access (404) runs first, then the string-length guard (400), then the + * 'place_edit' permission (403); create 201 / rest 200; the bespoke 400/404 + * bodies; the journey create/update/delete hooks; and WebSocket broadcasts with + * the forwarded X-Socket-Id. The /import/* and /bulk-delete routes are declared + * before /:id so the static segments win over the param. + */ +@Controller('api/trips/:tripId/places') +@UseGuards(JwtAuthGuard) +export class PlacesController { + constructor(private readonly places: PlacesService) {} + + private requireTrip(tripId: string, user: User) { + const trip = this.places.verifyTripAccess(tripId, user.id); + if (!trip) { + throw new HttpException({ error: 'Trip not found' }, 404); + } + return trip; + } + + private requireEdit(trip: NonNullable>, user: User): void { + if (!this.places.canEdit(trip, user)) { + throw new HttpException({ error: 'No permission' }, 403); + } + } + + @Get() + list( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Query('search') search?: string, + @Query('category') category?: string, + @Query('tag') tag?: string, + ) { + this.requireTrip(tripId, user); + return { places: this.places.list(tripId, { search, category, tag }) }; + } + + @Post() + create( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body() body: Record & { name?: string }, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + validateLengths(body); + this.requireEdit(trip, user); + if (!body.name) { + throw new HttpException({ error: 'Place name is required' }, 400); + } + const place = this.places.create(tripId, body as never); + this.places.broadcast(tripId, 'place:created', { place }, socketId); + this.places.onCreated(tripId, place.id); + return { place }; + } + + @Post('import/gpx') + @UseInterceptors(FileInterceptor('file', UPLOAD)) + importGpx( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @UploadedFile() file: Express.Multer.File | undefined, + @Body() body: Record, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!file) { + throw new HttpException({ error: 'No file uploaded' }, 400); + } + const importWaypoints = parseBool(body.importWaypoints, true); + const importRoutes = parseBool(body.importRoutes, true); + const importTracks = parseBool(body.importTracks, true); + if (!importWaypoints && !importRoutes && !importTracks) { + throw new HttpException({ error: 'No import types selected' }, 400); + } + const result = this.places.importGpx(tripId, file.buffer, { importWaypoints, importRoutes, importTracks, defaultName: file.originalname }); + if (!result) { + throw new HttpException({ error: 'No matching places found in GPX file' }, 400); + } + for (const place of result.places) { + this.places.broadcast(tripId, 'place:created', { place }, socketId); + } + return { places: result.places, count: result.count, skipped: result.skipped }; + } + + @Post('import/map') + @UseInterceptors(FileInterceptor('file', UPLOAD)) + async importMap( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @UploadedFile() file: Express.Multer.File | undefined, + @Body() body: Record, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!file) { + throw new HttpException({ error: 'No file uploaded' }, 400); + } + const importPoints = parseBool(body.importPoints, true); + const importPaths = parseBool(body.importPaths, true); + if (!importPoints && !importPaths) { + throw new HttpException({ error: 'No import types selected' }, 400); + } + try { + const result = await this.places.importMapFile(tripId, file.buffer, file.originalname, { importPoints, importPaths }); + if (result.summary?.totalPlacemarks === 0) { + throw new HttpException({ error: 'No valid Placemarks found in map file', summary: result.summary }, 400); + } + for (const place of result.places) { + this.places.broadcast(tripId, 'place:created', { place }, socketId); + } + return result; + } catch (err: unknown) { + if (err instanceof HttpException) throw err; + const message = err instanceof Error ? err.message : 'Failed to import map file'; + throw new HttpException({ error: message }, 400); + } + } + + @Post('import/google-list') + async importGoogle(@CurrentUser() user: User, @Param('tripId') tripId: string, @Body('url') url: unknown, @Body('enrich') enrich: unknown, @Headers('x-socket-id') socketId?: string) { + return this.importList('google', user, tripId, url, enrich, socketId); + } + + @Post('import/naver-list') + async importNaver(@CurrentUser() user: User, @Param('tripId') tripId: string, @Body('url') url: unknown, @Body('enrich') enrich: unknown, @Headers('x-socket-id') socketId?: string) { + return this.importList('naver', user, tripId, url, enrich, socketId); + } + + /** Shared google/naver list import — identical flow, different provider + error string. */ + private async importList(provider: 'google' | 'naver', user: User, tripId: string, url: unknown, enrich: unknown, socketId?: string) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!url || typeof url !== 'string') { + throw new HttpException({ error: 'URL is required' }, 400); + } + // Opt-in: re-resolve each imported place via the Places API to fill in + // photo / address / website / phone and persist a google_place_id (#886). + const opts = { enrich: parseBool(enrich, false), userId: user.id }; + const label = provider === 'google' ? 'Google' : 'Naver'; + try { + const result = provider === 'google' + ? await this.places.importGoogleList(tripId, url, opts) + : await this.places.importNaverList(tripId, url, opts); + if ('error' in result) { + throw new HttpException({ error: result.error }, result.status); + } + for (const place of result.places) { + this.places.broadcast(tripId, 'place:created', { place }, socketId); + } + return { places: result.places, count: result.places.length, listName: result.listName, skipped: result.skipped }; + } catch (err: unknown) { + if (err instanceof HttpException) throw err; + console.error(`[Places] ${label} list import error:`, err instanceof Error ? err.message : err); + throw new HttpException({ error: `Failed to import ${label} Maps list. Make sure the list is shared publicly.` }, 400); + } + } + + @Post('bulk-delete') + @HttpCode(200) // Express answers bulk-delete with res.json (200), unlike the 201 imports. + bulkDelete( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body('ids') ids: unknown, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!Array.isArray(ids) || ids.some((v) => typeof v !== 'number')) { + throw new HttpException({ error: 'ids must be an array of numbers' }, 400); + } + if (ids.length === 0) { + return { deleted: [], count: 0 }; + } + for (const id of ids) this.places.onDeleted(id); + const deleted = this.places.removeMany(tripId, ids); + for (const id of deleted) { + this.places.broadcast(tripId, 'place:deleted', { placeId: id }, socketId); + } + return { deleted, count: deleted.length }; + } + + @Get(':id') + get(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string) { + this.requireTrip(tripId, user); + const place = this.places.get(tripId, id); + if (!place) { + throw new HttpException({ error: 'Place not found' }, 404); + } + return { place }; + } + + @Get(':id/image') + async image(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string) { + this.requireTrip(tripId, user); + try { + const result = await this.places.searchImage(tripId, id, user.id); + if ('error' in result) { + throw new HttpException({ error: result.error }, result.status); + } + return { photos: result.photos }; + } catch (err: unknown) { + if (err instanceof HttpException) throw err; + console.error('Unsplash error:', err); + throw new HttpException({ error: 'Error searching for image' }, 500); + } + } + + @Put(':id') + update( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('id') id: string, + @Body() body: Record, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + validateLengths(body); + this.requireEdit(trip, user); + const place = this.places.update(tripId, id, body as never); + if (!place) { + throw new HttpException({ error: 'Place not found' }, 404); + } + this.places.broadcast(tripId, 'place:updated', { place }, socketId); + this.places.onUpdated(place.id); + return { place }; + } + + @Delete(':id') + remove(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Headers('x-socket-id') socketId?: string) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + this.places.onDeleted(Number(id)); // sync before actual delete + if (!this.places.remove(tripId, id)) { + throw new HttpException({ error: 'Place not found' }, 404); + } + this.places.broadcast(tripId, 'place:deleted', { placeId: Number(id) }, socketId); + return { success: true }; + } +} diff --git a/server/src/nest/places/places.module.ts b/server/src/nest/places/places.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..60b84e1fe0b84ac0f16236835484fb166a7357e7 --- /dev/null +++ b/server/src/nest/places/places.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { PlacesController } from './places.controller'; +import { PlacesService } from './places.service'; + +/** Places domain (S8 — Phase 2 trip sub-domain). Depends on L4 Categories + L5 Tags. */ +@Module({ + controllers: [PlacesController], + providers: [PlacesService], +}) +export class PlacesModule {} diff --git a/server/src/nest/places/places.service.ts b/server/src/nest/places/places.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..869e852edd75399cb09b3094da5c631ebdd5ed06 --- /dev/null +++ b/server/src/nest/places/places.service.ts @@ -0,0 +1,83 @@ +import { Injectable } from '@nestjs/common'; +import { broadcast } from '../../websocket'; +import { canAccessTrip } from '../../db/database'; +import { checkPermission } from '../../services/permissions'; +import type { User } from '../../types'; +import * as svc from '../../services/placeService'; +import { onPlaceCreated, onPlaceUpdated, onPlaceDeleted } from '../../services/journeyService'; + +type Trip = { user_id: number }; + +/** + * Thin Nest wrapper around the existing place service. Trip access mirrors the + * requireTripAccess middleware (canAccessTrip); mutations use 'place_edit'. The + * SQL, the GPX/map/list importers and the journey hooks reuse the legacy code + * unchanged. + */ +@Injectable() +export class PlacesService { + verifyTripAccess(tripId: string, userId: number) { + return canAccessTrip(Number(tripId), userId) as Trip | null | undefined; + } + + canEdit(trip: Trip, user: User): boolean { + return checkPermission('place_edit', user.role, trip.user_id, user.id, trip.user_id !== user.id); + } + + broadcast(tripId: string, event: string, payload: Record, socketId: string | undefined): void { + broadcast(tripId, event, payload, socketId); + } + + list(tripId: string, filters: { search?: string; category?: string; tag?: string }) { + return svc.listPlaces(tripId, filters); + } + + get(tripId: string, id: string) { + return svc.getPlace(tripId, id); + } + + create(tripId: string, data: Parameters[1]) { + return svc.createPlace(tripId, data); + } + + update(tripId: string, id: string, data: Parameters[2]) { + return svc.updatePlace(tripId, id, data); + } + + remove(tripId: string, id: string): boolean { + return svc.deletePlace(tripId, id); + } + + removeMany(tripId: string, ids: number[]): number[] { + return svc.deletePlacesMany(tripId, ids); + } + + importGpx( + tripId: string, + buffer: Buffer, + opts: { importWaypoints: boolean; importRoutes: boolean; importTracks: boolean; defaultName?: string }, + ) { + return svc.importGpx(tripId, buffer, opts); + } + + importMapFile(tripId: string, buffer: Buffer, filename: string, opts: svc.KmlImportOptions) { + return svc.importMapFile(tripId, buffer, filename, opts); + } + + importGoogleList(tripId: string, url: string, opts?: Parameters[2]) { + return svc.importGoogleList(tripId, url, opts); + } + + importNaverList(tripId: string, url: string, opts?: Parameters[2]) { + return svc.importNaverList(tripId, url, opts); + } + + searchImage(tripId: string, id: string, userId: number) { + return svc.searchPlaceImage(tripId, id, userId); + } + + // Journey hooks — non-fatal, mirroring the route's try/catch wrappers. + onCreated(tripId: string, placeId: number): void { try { onPlaceCreated(Number(tripId), placeId); } catch { /* non-fatal */ } } + onUpdated(placeId: number): void { try { onPlaceUpdated(placeId); } catch { /* non-fatal */ } } + onDeleted(placeId: number): void { try { onPlaceDeleted(placeId); } catch { /* non-fatal */ } } +} diff --git a/server/src/nest/platform/platform.routes.ts b/server/src/nest/platform/platform.routes.ts new file mode 100644 index 0000000000000000000000000000000000000000..6ee045b27295fba48a05c176058d5dd382e4c548 --- /dev/null +++ b/server/src/nest/platform/platform.routes.ts @@ -0,0 +1,268 @@ +import express, { Request, Response, NextFunction } from 'express'; +import path from 'node:path'; +import fs from 'node:fs'; + +import { verifyJwtAndLoadUser } from '../../middleware/auth'; +import { db } from '../../db/database'; +import { mcpHandler } from '../../mcp'; +import { trekOAuthProvider, trekClientsStore } from '../../mcp/oauthProvider'; +import { isAddonEnabled } from '../../services/adminService'; +import { ADDON_IDS } from '../../addons'; +import { ALL_SCOPES } from '../../mcp/scopes'; +import { mcpAuthMetadataRouter } from '@modelcontextprotocol/sdk/server/auth/router'; +import { authorizationHandler } from '@modelcontextprotocol/sdk/server/auth/handlers/authorize'; +import { clientRegistrationHandler } from '@modelcontextprotocol/sdk/server/auth/handlers/register'; +import type { OAuthMetadata } from '@modelcontextprotocol/sdk/shared/auth'; +import { getMcpSafeUrl } from '../../services/notifications'; + +// Platform / transport routes extracted verbatim from createApp() (app.ts) so they can be +// mounted on either the legacy Express app or the NestJS Express instance (strangler A6/A8). +// +// IMPORTANT — path resolution: the original blocks lived in src/app.ts, where __dirname +// resolves to the directory of app.js (one level above the uploads/public anchor), so they +// used '../uploads/...' and '../public'. This file lives three levels deeper +// (src/nest/platform/), so __dirname is three levels deeper too. The relative prefixes are +// therefore '../../../uploads/...' and '../../../public' — which resolve to the EXACT same +// absolute paths as before. This is the only intentional change; everything else is byte-for-byte +// identical. (rootDir/outDir preserve the tree, so the offset holds in both source/test and +// compiled/dist execution — matching the other nest controllers that use '../../../uploads/...'.) + +const UPLOADS_DIR = path.join(__dirname, '../../../uploads'); +export const PUBLIC_DIR = path.join(__dirname, '../../../public'); + +/** + * Static + guarded /uploads/* routes. Must be applied BEFORE the API route mounts + * (identical to its original position near the top of createApp). + */ +export function applyPlatformUploads(app: express.Application): void { + // Static: avatars, covers, and journey photos. + // + // Security model (audit SEC-M9): these paths are unauthenticated by + // design. All filenames are server-chosen UUID v4 (see `uuid()` in + // the multer storage config for avatars / covers / journey uploads), + // which gives each asset >122 bits of namespace entropy — not + // guessable via enumeration. An attacker would need to have already + // seen the URL (email, shared journey, etc.) to request the file. + // + // Moving these behind auth would also break: + // - Unauthenticated trip-card rendering on public share links + // - Journey public-share pages (/public/journey/:token) + // - Email-embedded avatars + // + // The `/uploads/photos/...` route below is DIFFERENT: photo URLs are + // not embedded in unauthenticated UI contexts, so that endpoint IS + // gated (session JWT with pv, or a share token scoped to the photo's + // trip). + app.use('/uploads/avatars', express.static(path.join(UPLOADS_DIR, 'avatars'))); + app.use('/uploads/covers', express.static(path.join(UPLOADS_DIR, 'covers'))); + app.use('/uploads/journey', express.static(path.join(UPLOADS_DIR, 'journey'))); + + // Photos require either a valid logged-in session (via JWT with the + // password_version gate) OR a share token that covers the SPECIFIC + // photo's trip. Previously any share token for any trip could request + // any photo filename by UUID — fine in practice because UUIDs are + // unguessable, but the auth model was wrong. + app.get('/uploads/photos/:filename', (req: Request, res: Response) => { + const safeName = path.basename(req.params.filename); + const filePath = path.join(UPLOADS_DIR, 'photos', safeName); + const resolved = path.resolve(filePath); + if (!resolved.startsWith(path.resolve(UPLOADS_DIR, 'photos'))) { + return res.status(403).send('Forbidden'); + } + // existsSync here is cheap and avoids a sendFile error frame; kept + // sync because the handler is already short-lived. + if (!fs.existsSync(resolved)) return res.status(404).send('Not found'); + + const authHeader = req.headers.authorization; + const rawToken = (req.query.token as string) || (authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : null); + if (!rawToken) return res.status(401).send('Authentication required'); + + // JWT session path (with pv check). + const user = verifyJwtAndLoadUser(rawToken); + if (user) return res.sendFile(resolved); + + // Share-token path: require the token to cover the exact trip the + // photo belongs to. Expired tokens fall through to 401. + const photo = db.prepare('SELECT trip_id FROM photos WHERE filename = ?').get(safeName) as { trip_id: number } | undefined; + if (!photo) return res.status(401).send('Authentication required'); + + const share = db.prepare( + "SELECT trip_id FROM share_tokens WHERE token = ? AND (expires_at IS NULL OR expires_at > datetime('now'))" + ).get(rawToken) as { trip_id: number } | undefined; + if (!share || share.trip_id !== photo.trip_id) { + return res.status(401).send('Authentication required'); + } + res.sendFile(resolved); + }); + + // Block direct access to /uploads/files + app.use('/uploads/files', (_req: Request, res: Response) => { + res.status(401).send('Authentication required'); + }); +} + +/** + * Legacy /api/health handler, the OAuth/MCP SDK + transport wiring (well-known metadata, + * authorize/register SDK handlers, the COOP header, the /mcp routes), and the production + * SPA static + catch-all. Must be applied AFTER the API route mounts and BEFORE the global + * error handler (identical to its original position near the bottom of createApp). + * + * Note: the SDK metadata closures (getOAuthMetadata/getMetaRouter) and their lazy-init + * cache are kept module-local PER CALL so each app instance gets its own lazy state — the + * same as when they were function-local inside createApp. + */ +export function applyPlatformTransport(app: express.Application): void { + app.get('/health', (_req: Request, res: Response) => res.status(200).send('OK')); + app.get('/api/health', (_req: Request, res: Response) => { + res.setHeader('Cache-Control', 'no-store, must-revalidate') + res.json({ status: 'ok' }) + }); + + // OAuth 2.1 — public endpoints + // Gate: 404 when MCP addon is disabled (M2 — prevents feature fingerprinting) + const mcpAddonGate = (_req: Request, res: Response, next: NextFunction) => { + if (!isAddonEnabled(ADDON_IDS.MCP)) return res.status(404).end(); + next(); + }; + + // SDK metadata router — built lazily on first request so getAppUrl() (which queries the DB) + // is not called at createApp() time, before test tables have been created. + // mcpAuthMetadataRouter serves: + // /.well-known/oauth-authorization-server — RFC 8414 AS metadata + // /.well-known/oauth-protected-resource/mcp — RFC 9728 path-based PRM (fixes issue #959 bug 1) + let _oauthMetadata: OAuthMetadata | null = null; + let _sdkMetaRouter: express.Router | null = null; + + function getOAuthMetadata(): OAuthMetadata { + if (_oauthMetadata) return _oauthMetadata; + const base = getMcpSafeUrl().replace(/\/+$/, ''); + _oauthMetadata = { + issuer: base, + authorization_endpoint: `${base}/oauth/authorize`, + token_endpoint: `${base}/oauth/token`, + revocation_endpoint: `${base}/oauth/revoke`, + registration_endpoint: `${base}/oauth/register`, + response_types_supported: ['code'], + grant_types_supported: ['authorization_code', 'refresh_token', 'client_credentials'], + code_challenge_methods_supported: ['S256'], + token_endpoint_auth_methods_supported: ['client_secret_post', 'none'], + scopes_supported: ALL_SCOPES, + }; + return _oauthMetadata; + } + + function getMetaRouter(): express.Router { + if (_sdkMetaRouter) return _sdkMetaRouter; + const metadata = getOAuthMetadata(); + _sdkMetaRouter = mcpAuthMetadataRouter({ + oauthMetadata: metadata, + resourceServerUrl: new URL(`${metadata.issuer}/mcp`), + scopesSupported: ALL_SCOPES as string[], + resourceName: 'TREK MCP', + }); + return _sdkMetaRouter; + } + + // Only invoke the SDK metadata router for /.well-known/* paths. + // Calling getMetaRouter() on every request triggers lazy init (new URL(...)) which + // throws "Invalid URL" when APP_URL lacks a protocol — breaking all page loads. + app.use((req: Request, res: Response, next: NextFunction) => { + if (req.path.startsWith('/.well-known/') && !isAddonEnabled(ADDON_IDS.MCP)) return res.status(404).end(); + getMetaRouter()(req, res, next); + }); + + // ChatGPT (and other OIDC-first clients) bootstrap OAuth discovery via + // /.well-known/openid-configuration. Serve the AS metadata plus the OIDC + // userinfo_endpoint so ChatGPT can fetch the authenticated user's email + // for authorization domain claiming. + app.get('/.well-known/openid-configuration', (_req: Request, res: Response) => { + const meta = getOAuthMetadata(); + res.json({ + ...meta, + userinfo_endpoint: `${meta.issuer}/oauth/userinfo`, + }); + }); + + // RFC 9728 flat well-known URL — served alongside the path-based form the SDK already provides. + // Clients like ChatGPT probe /.well-known/oauth-protected-resource (no path suffix) on every + // fresh discovery. Without this, they get 404, fall back to the issuer URL as the resource + // parameter, and the authorize handler rejects them with invalid_target — showing the user + // the TREK home page instead of the consent form. + app.get('/.well-known/oauth-protected-resource', (_req: Request, res: Response) => { + if (!isAddonEnabled(ADDON_IDS.MCP)) return res.status(404).end(); + const meta = getOAuthMetadata(); + res.json({ + resource: `${meta.issuer}/mcp`, + authorization_servers: [meta.issuer], + bearer_methods_supported: ['header'], + scopes_supported: ALL_SCOPES, + resource_name: 'TREK MCP', + }); + }); + + // SDK authorize handler: validates OAuth params, calls provider.authorize() which redirects + // to the SPA consent page at /oauth/consent + app.use('/oauth/authorize', mcpAddonGate, authorizationHandler({ provider: trekOAuthProvider })); + + // SDK DCR handler: accepts registrations without scope (fixes issue #959 bug 2) + app.use('/oauth/register', mcpAddonGate, clientRegistrationHandler({ clientsStore: trekClientsStore })); + + // MCP endpoint + app.post('/mcp', mcpHandler); + app.get('/mcp', mcpHandler); + app.delete('/mcp', mcpHandler); + + // Return 404 JSON for any /.well-known/* path the SDK metadata router doesn't handle. + // Without this, the SPA catch-all serves HTML — clients probing + // /.well-known/openid-configuration or the RFC 8414 path-suffixed AS metadata URL + // receive a 200 HTML response they can't parse as JSON, causing "does not implement OAuth". + app.use((req: Request, res: Response, next: NextFunction) => { + if (req.path.startsWith('/.well-known/')) return res.status(404).json({ error: 'not_found' }); + next(); + }); + + // Helmet's COOP: same-origin isolates the consent popup from its cross-origin opener (ChatGPT etc.), making window.opener null and breaking the OAuth flow. + app.use('/oauth/consent', (_req: Request, res: Response, next: NextFunction) => { + res.setHeader('Cross-Origin-Opener-Policy', 'unsafe-none'); + next(); + }); +} + +/** + * Production SPA serving: the built client static assets + the index.html catch-all + * for client-side routes. This is the LEGACY (plain Express 4) form — a real + * `app.get(catch-all)` registered as the terminal handler. The NestJS bootstrap can + * NOT use this (its router terminates unmatched requests with a 404 before any + * post-init route runs, and Express 5's path-to-regexp rejects a bare '*'); it serves + * the SPA via the SpaFallbackFilter instead. Both produce the identical result: + * unmatched GET → index.html in production. + */ +export function applyPlatformSpa(app: express.Application): void { + applyPlatformStatic(app); + if (process.env.NODE_ENV !== 'production') return; + // /.*/ rather than '*' so the helper is Express-4 and Express-5 safe. + app.get(/.*/, (_req: Request, res: Response) => { + res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate'); + res.sendFile(path.join(PUBLIC_DIR, 'index.html')); + }); +} + +/** + * Production static serving of the built client (JS/CSS/assets). Split out from + * applyPlatformSpa because the NestJS bootstrap needs the static files served + * BEFORE its router (so a real asset request returns the file, not the SPA + * index.html), while the index.html catch-all is handled separately (legacy: + * app.get catch-all; Nest: SpaFallbackFilter). No-op outside production. + */ +export function applyPlatformStatic(app: express.Application): void { + if (process.env.NODE_ENV !== 'production') return; + app.use( + express.static(PUBLIC_DIR, { + setHeaders: (res, filePath) => { + if (filePath.endsWith('index.html')) { + res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate'); + } + }, + }), + ); +} diff --git a/server/src/nest/platform/spa-fallback.filter.ts b/server/src/nest/platform/spa-fallback.filter.ts new file mode 100644 index 0000000000000000000000000000000000000000..d1a12be26b8eeb94d4bb682e74129e6c14d6b04f --- /dev/null +++ b/server/src/nest/platform/spa-fallback.filter.ts @@ -0,0 +1,37 @@ +import { ArgumentsHost, Catch, ExceptionFilter, NotFoundException } from '@nestjs/common'; +import type { Request, Response } from 'express'; +import path from 'node:path'; +import { PUBLIC_DIR } from './platform.routes'; + +/** + * Serves the built SPA (index.html) for any request the NestJS router did not + * match — the production single-page-app fallback. This replaces the legacy + * Express `app.get('*')` catch-all, which cannot run on the Nest instance: Nest's + * router terminates an unmatched request by throwing NotFoundException (it never + * falls through to a post-init Express route), so the SPA fallback has to live + * inside the Nest pipeline as a NotFound filter instead. + * + * Behaviour matches the legacy catch-all exactly: in production, an unmatched GET + * returns index.html; everything else (non-GET, or dev where there is no built + * client) keeps the standard TREK `{ error }` 404 envelope. The `@Catch(NotFoundException)` + * is more specific than the global TrekExceptionFilter, so Nest routes 404s here + * while every other error still flows through TrekExceptionFilter. + */ +@Catch(NotFoundException) +export class SpaFallbackFilter implements ExceptionFilter { + catch(exception: NotFoundException, host: ArgumentsHost): void { + const ctx = host.switchToHttp(); + const req = ctx.getRequest(); + const res = ctx.getResponse(); + + if (process.env.NODE_ENV === 'production' && req.method === 'GET') { + res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate'); + res.sendFile(path.join(PUBLIC_DIR, 'index.html')); + return; + } + + // Non-production, or a non-GET miss: keep the standard TREK 404 envelope + // (identical to what TrekExceptionFilter produces for a NotFoundException). + res.status(404).json({ error: exception.message || 'Not Found' }); + } +} diff --git a/server/src/nest/reservations/accommodations.controller.ts b/server/src/nest/reservations/accommodations.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..92a85320d3763bf358b5c5f01af0358971e54e67 --- /dev/null +++ b/server/src/nest/reservations/accommodations.controller.ts @@ -0,0 +1,133 @@ +import { + Body, + Controller, + Delete, + Get, + Headers, + HttpException, + Param, + Post, + Put, + UseGuards, +} from '@nestjs/common'; +import type { User } from '../../types'; +import { AccommodationsService } from './accommodations.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; + +type AccommodationBody = { + place_id?: number; + start_day_id?: number; + end_day_id?: number; + check_in?: string | null; + check_in_end?: string | null; + check_out?: string | null; + confirmation?: string | null; + notes?: string | null; +}; + +/** + * /api/trips/:tripId/accommodations — trip-scoped lodging blocks. + * + * Byte-identical to the legacy accommodations sub-router (server/src/routes/ + * days.ts): trip access (404 "Trip not found"), the 'day_edit' permission on + * mutations (403), the bespoke 400 (missing refs) and 404 (validateRefs / not + * found) bodies, create 201 / rest 200, and the cascade broadcasts (a created + * accommodation also emits reservation:created; a delete emits the linked + * reservation/budget deletions) with the forwarded X-Socket-Id. + */ +@Controller('api/trips/:tripId/accommodations') +@UseGuards(JwtAuthGuard) +export class AccommodationsController { + constructor(private readonly accommodations: AccommodationsService) {} + + private requireTrip(tripId: string, user: User) { + const trip = this.accommodations.verifyTripAccess(tripId, user.id); + if (!trip) { + throw new HttpException({ error: 'Trip not found' }, 404); + } + return trip; + } + + private requireEdit(trip: NonNullable>, user: User): void { + if (!this.accommodations.canEdit(trip, user)) { + throw new HttpException({ error: 'No permission' }, 403); + } + } + + @Get() + list(@CurrentUser() user: User, @Param('tripId') tripId: string) { + this.requireTrip(tripId, user); + return { accommodations: this.accommodations.list(tripId) }; + } + + @Post() + create( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body() body: AccommodationBody, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + const { place_id, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, notes } = body; + if (!place_id || !start_day_id || !end_day_id) { + throw new HttpException({ error: 'place_id, start_day_id, and end_day_id are required' }, 400); + } + const errors = this.accommodations.validateRefs(tripId, place_id, start_day_id, end_day_id); + if (errors.length > 0) { + throw new HttpException({ error: errors[0].message }, 404); + } + const accommodation = this.accommodations.create(tripId, { place_id, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, notes } as never); + this.accommodations.broadcast(tripId, 'accommodation:created', { accommodation }, socketId); + this.accommodations.broadcast(tripId, 'reservation:created', {}, socketId); + return { accommodation }; + } + + @Put(':id') + update( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('id') id: string, + @Body() body: AccommodationBody, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + const existing = this.accommodations.get(id, tripId); + if (!existing) { + throw new HttpException({ error: 'Accommodation not found' }, 404); + } + const { place_id, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, notes } = body; + const errors = this.accommodations.validateRefs(tripId, place_id, start_day_id, end_day_id); + if (errors.length > 0) { + throw new HttpException({ error: errors[0].message }, 404); + } + const accommodation = this.accommodations.update(id, existing as never, { place_id, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, notes } as never); + this.accommodations.broadcast(tripId, 'accommodation:updated', { accommodation }, socketId); + return { accommodation }; + } + + @Delete(':id') + remove( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('id') id: string, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!this.accommodations.get(id, tripId)) { + throw new HttpException({ error: 'Accommodation not found' }, 404); + } + const { linkedReservationId, deletedBudgetItemId } = this.accommodations.remove(id); + if (linkedReservationId) { + this.accommodations.broadcast(tripId, 'reservation:deleted', { reservationId: linkedReservationId }, socketId); + } + if (deletedBudgetItemId) { + this.accommodations.broadcast(tripId, 'budget:deleted', { itemId: deletedBudgetItemId }, socketId); + } + this.accommodations.broadcast(tripId, 'accommodation:deleted', { accommodationId: Number(id) }, socketId); + return { success: true }; + } +} diff --git a/server/src/nest/reservations/accommodations.service.ts b/server/src/nest/reservations/accommodations.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..75e5071b071d2704c8b21a5a8684309eca00263a --- /dev/null +++ b/server/src/nest/reservations/accommodations.service.ts @@ -0,0 +1,54 @@ +import { Injectable } from '@nestjs/common'; +import { broadcast } from '../../websocket'; +import { canAccessTrip } from '../../db/database'; +import { checkPermission } from '../../services/permissions'; +import type { User } from '../../types'; +import * as dayService from '../../services/dayService'; + +type Trip = { user_id: number }; + +/** + * Thin Nest wrapper around the accommodation parts of the existing day service. + * Accommodations are gated by the 'day_edit' permission (same as days) and the + * SQL + cascade (linked reservation / budget cleanup on delete) reuse the legacy + * code unchanged. + */ +@Injectable() +export class AccommodationsService { + /** Mirrors the requireTripAccess middleware (owner or member), returning the trip. */ + verifyTripAccess(tripId: string, userId: number) { + return canAccessTrip(Number(tripId), userId) as Trip | null | undefined; + } + + canEdit(trip: Trip, user: User): boolean { + return checkPermission('day_edit', user.role, trip.user_id, user.id, trip.user_id !== user.id); + } + + broadcast(tripId: string, event: string, payload: Record, socketId: string | undefined): void { + broadcast(tripId, event, payload, socketId); + } + + list(tripId: string) { + return dayService.listAccommodations(tripId); + } + + validateRefs(tripId: string, placeId?: number, startDayId?: number, endDayId?: number) { + return dayService.validateAccommodationRefs(tripId, placeId, startDayId, endDayId); + } + + get(id: string, tripId: string) { + return dayService.getAccommodation(id, tripId); + } + + create(tripId: string, data: Parameters[1]) { + return dayService.createAccommodation(tripId, data); + } + + update(id: string, existing: Parameters[1], fields: Parameters[2]) { + return dayService.updateAccommodation(id, existing, fields); + } + + remove(id: string) { + return dayService.deleteAccommodation(id); + } +} diff --git a/server/src/nest/reservations/reservations.controller.ts b/server/src/nest/reservations/reservations.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..efa387103050532810342c27a5c6505fdc8c5d22 --- /dev/null +++ b/server/src/nest/reservations/reservations.controller.ts @@ -0,0 +1,151 @@ +import { + Body, + Controller, + Delete, + Get, + Headers, + HttpException, + Param, + Post, + Put, + UseGuards, +} from '@nestjs/common'; +import type { User } from '../../types'; +import { ReservationsService } from './reservations.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; +import { pushReservationToAirtrail } from '../../services/airtrail/airtrailSync'; + +type ReservationBody = Record & { + title?: string; + type?: string; + create_budget_entry?: { total_price?: number; category?: string }; +}; + +/** + * /api/trips/:tripId/reservations — trip-scoped bookings. + * + * Byte-identical to the legacy Express route (server/src/routes/reservations.ts): + * trip access (404), 'reservation_edit' permission (403), create 201 / rest 200, + * the bespoke 400/404 bodies, the accommodation + budget side effects, the + * booking notifications, and all WebSocket broadcasts with the forwarded + * X-Socket-Id. /positions is declared before /:id so it wins over the param. + */ +@Controller('api/trips/:tripId/reservations') +@UseGuards(JwtAuthGuard) +export class ReservationsController { + constructor(private readonly reservations: ReservationsService) {} + + private requireTrip(tripId: string, user: User) { + const trip = this.reservations.verifyTripAccess(tripId, user.id); + if (!trip) { + throw new HttpException({ error: 'Trip not found' }, 404); + } + return trip; + } + + private requireEdit(trip: ReturnType, user: User): void { + if (!this.reservations.canEdit(trip!, user)) { + throw new HttpException({ error: 'No permission' }, 403); + } + } + + @Get() + list(@CurrentUser() user: User, @Param('tripId') tripId: string) { + this.requireTrip(tripId, user); + return { reservations: this.reservations.list(tripId) }; + } + + @Post() + create( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body() body: ReservationBody, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!body.title) { + throw new HttpException({ error: 'Title is required' }, 400); + } + const { reservation, accommodationCreated } = this.reservations.create(tripId, body as never); + if (accommodationCreated) { + this.reservations.broadcast(tripId, 'accommodation:created', {}, socketId); + } + this.reservations.syncBudgetOnCreate(tripId, reservation.id, body.title, body.type, body.create_budget_entry, socketId); + this.reservations.broadcast(tripId, 'reservation:created', { reservation }, socketId); + this.reservations.notifyBookingChange(tripId, user, body.title, body.type ?? ''); + return { reservation }; + } + + @Put('positions') + updatePositions( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body() body: { positions?: unknown; day_id?: unknown }, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!Array.isArray(body.positions)) { + throw new HttpException({ error: 'positions must be an array' }, 400); + } + this.reservations.updatePositions(tripId, body.positions, body.day_id); + this.reservations.broadcast(tripId, 'reservation:positions', { positions: body.positions, day_id: body.day_id }, socketId); + return { success: true }; + } + + @Put(':id') + update( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('id') id: string, + @Body() body: ReservationBody, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + const current = this.reservations.getReservation(id, tripId); + if (!current) { + throw new HttpException({ error: 'Reservation not found' }, 404); + } + const { reservation, accommodationChanged } = this.reservations.update(id, tripId, body as never, current as never); + if (accommodationChanged) { + this.reservations.broadcast(tripId, 'accommodation:updated', {}, socketId); + } + const cur = current as { title: string; type?: string }; + this.reservations.syncBudgetOnUpdate(tripId, id, body.title ?? '', body.type, cur.title, cur.type, body.create_budget_entry, socketId); + this.reservations.broadcast(tripId, 'reservation:updated', { reservation }, socketId); + // Push a locally-edited AirTrail flight back to AirTrail (fire-and-forget, + // under the importer's credentials — see airtrailSync). #214 + if ((reservation as any)?.external_source === 'airtrail' && (reservation as any)?.sync_enabled) { + void pushReservationToAirtrail(Number((reservation as any).id), Number(tripId)).catch(() => {}); + } + this.reservations.notifyBookingChange(tripId, user, body.title || cur.title, body.type || cur.type || ''); + return { reservation }; + } + + @Delete(':id') + remove( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('id') id: string, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + const { deleted, accommodationDeleted, deletedBudgetItemId } = this.reservations.remove(id, tripId); + if (!deleted) { + throw new HttpException({ error: 'Reservation not found' }, 404); + } + if (accommodationDeleted) { + this.reservations.broadcast(tripId, 'accommodation:deleted', { accommodationId: deleted.accommodation_id }, socketId); + } + if (deletedBudgetItemId) { + this.reservations.broadcast(tripId, 'budget:deleted', { itemId: deletedBudgetItemId }, socketId); + } + this.reservations.broadcast(tripId, 'reservation:deleted', { reservationId: Number(id) }, socketId); + this.reservations.notifyBookingChange(tripId, user, deleted.title, deleted.type || ''); + return { success: true }; + } +} diff --git a/server/src/nest/reservations/reservations.module.ts b/server/src/nest/reservations/reservations.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..9401abde17d86f31d97a3af361c684ad008acb6f --- /dev/null +++ b/server/src/nest/reservations/reservations.module.ts @@ -0,0 +1,17 @@ +import { Module } from '@nestjs/common'; +import { ReservationsController } from './reservations.controller'; +import { ReservationsService } from './reservations.service'; +import { AccommodationsController } from './accommodations.controller'; +import { AccommodationsService } from './accommodations.service'; +import { UpcomingReservationsController } from './upcoming-reservations.controller'; + +/** + * Reservations + accommodations domain (S5 — Phase 2 trip sub-domain). + * Mounts: /api/trips/:tripId/reservations, /accommodations, and the cross-trip + * /api/reservations/upcoming dashboard feed. + */ +@Module({ + controllers: [ReservationsController, AccommodationsController, UpcomingReservationsController], + providers: [ReservationsService, AccommodationsService], +}) +export class ReservationsModule {} diff --git a/server/src/nest/reservations/reservations.service.ts b/server/src/nest/reservations/reservations.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..5d1d7cdc2367fafc54e4b2d4931e8aa0b5bdad41 --- /dev/null +++ b/server/src/nest/reservations/reservations.service.ts @@ -0,0 +1,120 @@ +import { Injectable } from '@nestjs/common'; +import { db } from '../../db/database'; +import { broadcast } from '../../websocket'; +import { checkPermission } from '../../services/permissions'; +import type { User } from '../../types'; +import * as svc from '../../services/reservationService'; +import { createBudgetItem, updateBudgetItem, deleteBudgetItem, linkBudgetItemToReservation } from '../../services/budgetService'; + +type Trip = NonNullable>; +type BudgetEntry = { total_price?: number; category?: string } | undefined; + +/** + * Thin Nest wrapper around the existing reservation service. Trip-access, the + * 'reservation_edit' permission, the SQL and the WebSocket broadcasts reuse the + * legacy code unchanged. The legacy route's budget side effects (auto-create / + * update / delete a linked budget item) and the booking notification are + * encapsulated here so the controller stays thin — behaviour is 1:1. + */ +@Injectable() +export class ReservationsService { + verifyTripAccess(tripId: string, userId: number) { + return svc.verifyTripAccess(tripId, userId); + } + + canEdit(trip: Trip, user: User): boolean { + return checkPermission('reservation_edit', user.role, trip.user_id, user.id, trip.user_id !== user.id); + } + + broadcast(tripId: string, event: string, payload: Record, socketId: string | undefined): void { + broadcast(tripId, event, payload, socketId); + } + + list(tripId: string) { + return svc.listReservations(tripId); + } + + // Cross-trip "upcoming reservations" feed (dashboard widget). Reuses the legacy + // query unchanged; the default limit (6) matches the legacy inline handler. + listUpcoming(userId: number) { + return svc.getUpcomingReservations(userId); + } + + create(tripId: string, data: Parameters[1]) { + return svc.createReservation(tripId, data); + } + + updatePositions(tripId: string, positions: Parameters[1], dayId: unknown): void { + svc.updatePositions(tripId, positions, dayId as Parameters[2]); + } + + getReservation(id: string, tripId: string) { + return svc.getReservation(id, tripId); + } + + update(id: string, tripId: string, data: Parameters[2], current: Parameters[3]) { + return svc.updateReservation(id, tripId, data, current); + } + + remove(id: string, tripId: string) { + return svc.deleteReservation(id, tripId); + } + + /** POST side effect: auto-create a linked budget item when a price is provided. */ + syncBudgetOnCreate(tripId: string, reservationId: number, title: string, type: string | undefined, entry: BudgetEntry, socketId: string | undefined): void { + if (!entry || !(Number(entry.total_price) > 0)) return; + try { + const item = linkBudgetItemToReservation(tripId, reservationId, { + name: title, + category: entry.category || type || 'Other', + total_price: entry.total_price!, + }); + broadcast(tripId, 'budget:created', { item }, socketId); + } catch (err) { + console.error('[reservations] Failed to create budget entry:', err); + } + } + + /** PUT side effect: drop the linked budget item when the price is cleared, else create/update it. */ + syncBudgetOnUpdate(tripId: string, id: string, title: string, type: string | undefined, currentTitle: string, currentType: string | undefined, entry: BudgetEntry, socketId: string | undefined): void { + if (!entry || !entry.total_price) { + const linked = db.prepare('SELECT id FROM budget_items WHERE trip_id = ? AND reservation_id = ?').get(tripId, id) as { id: number } | undefined; + if (linked) { + deleteBudgetItem(linked.id, tripId); + broadcast(tripId, 'budget:deleted', { itemId: linked.id }, socketId); + } + } + if (entry && Number(entry.total_price) > 0) { + try { + const itemName = title || currentTitle; + const category = entry.category || type || currentType || 'Other'; + const existing = db.prepare('SELECT id FROM budget_items WHERE trip_id = ? AND reservation_id = ?').get(tripId, id) as { id: number } | undefined; + if (existing) { + const updated = updateBudgetItem(existing.id, tripId, { name: itemName, category, total_price: entry.total_price }); + broadcast(tripId, 'budget:updated', { item: updated }, socketId); + } else { + const item = createBudgetItem(tripId, { name: itemName, category, total_price: entry.total_price }); + db.prepare('UPDATE budget_items SET reservation_id = ? WHERE id = ?').run(id, item.id); + item.reservation_id = Number(id); + broadcast(tripId, 'budget:created', { item }, socketId); + } + } catch (err) { + console.error('[reservations] Failed to create/update budget entry:', err); + } + } + } + + /** Fire-and-forget booking-change notification, mirroring the legacy dynamic import. */ + notifyBookingChange(tripId: string, actor: User, booking: string, type: string): void { + import('../../services/notificationService').then(({ send }) => { + const tripInfo = db.prepare('SELECT title FROM trips WHERE id = ?').get(tripId) as { title: string } | undefined; + send({ + event: 'booking_change', + actorId: actor.id, + scope: 'trip', + targetId: Number(tripId), + params: { trip: tripInfo?.title || 'Untitled', actor: actor.email, booking, type: type || 'booking', tripId: String(tripId) }, + }).catch(() => {}); + }); + } +} diff --git a/server/src/nest/reservations/upcoming-reservations.controller.ts b/server/src/nest/reservations/upcoming-reservations.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..fc7944499ccc0a4bb710824fc22d960827109cb7 --- /dev/null +++ b/server/src/nest/reservations/upcoming-reservations.controller.ts @@ -0,0 +1,24 @@ +import { Controller, Get, UseGuards } from '@nestjs/common'; +import type { User } from '../../types'; +import { ReservationsService } from './reservations.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; + +/** + * GET /api/reservations/upcoming — the cross-trip "upcoming reservations" feed + * (dashboard widget). Byte-identical to the legacy inline handler in + * server/src/app.ts (authenticate, returns { reservations: [...] }, limit 6). + * + * Separate from the trip-scoped ReservationsController + * (/api/trips/:tripId/reservations) because the base path differs. + */ +@Controller('api/reservations') +@UseGuards(JwtAuthGuard) +export class UpcomingReservationsController { + constructor(private readonly reservations: ReservationsService) {} + + @Get('upcoming') + upcoming(@CurrentUser() user: User) { + return { reservations: this.reservations.listUpcoming(user.id) }; + } +} diff --git a/server/src/nest/settings/settings.controller.ts b/server/src/nest/settings/settings.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..6372b655a1bc93888fe416f70baa9c6c6db7ee40 --- /dev/null +++ b/server/src/nest/settings/settings.controller.ts @@ -0,0 +1,53 @@ +import { Body, Controller, Get, HttpCode, HttpException, Post, Put, UseGuards } from '@nestjs/common'; +import type { User } from '../../types'; +import { SettingsService } from './settings.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; + +const MASKED_VALUE = '••••••••'; + +/** + * /api/settings — per-user key/value preferences. + * + * Byte-identical to the legacy Express route (server/src/routes/settings.ts): + * get-all, single upsert (400 without a key, no-op on the masked sentinel), and + * bulk upsert (400 without an object, 500 on a write error). All answer 200. + */ +@Controller('api/settings') +@UseGuards(JwtAuthGuard) +export class SettingsController { + constructor(private readonly settings: SettingsService) {} + + @Get() + list(@CurrentUser() user: User) { + return { settings: this.settings.getUserSettings(user.id) }; + } + + @Put() + upsert(@CurrentUser() user: User, @Body() body: { key?: string; value?: unknown }) { + if (!body.key) { + throw new HttpException({ error: 'Key is required' }, 400); + } + // The client echoes a redacted secret back unchanged — treat as a no-op. + if (body.value === MASKED_VALUE) { + return { success: true, key: body.key, unchanged: true }; + } + this.settings.upsertSetting(user.id, body.key, body.value); + return { success: true, key: body.key, value: body.value }; + } + + @Post('bulk') + @HttpCode(200) // Express answers bulk with res.json (200), not the POST-default 201. + bulk(@CurrentUser() user: User, @Body() body: { settings?: unknown }) { + if (!body.settings || typeof body.settings !== 'object') { + throw new HttpException({ error: 'Settings object is required' }, 400); + } + try { + const updated = this.settings.bulkUpsertSettings(user.id, body.settings as Record); + return { success: true, updated }; + } catch (err) { + console.error('Error saving settings:', err); + throw new HttpException({ error: 'Error saving settings' }, 500); + } + } +} diff --git a/server/src/nest/settings/settings.module.ts b/server/src/nest/settings/settings.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..63e54df5020ddadb1cdb26f264bfbd507246372c --- /dev/null +++ b/server/src/nest/settings/settings.module.ts @@ -0,0 +1,9 @@ +import { Module } from '@nestjs/common'; +import { SettingsController } from './settings.controller'; +import { SettingsService } from './settings.service'; + +@Module({ + controllers: [SettingsController], + providers: [SettingsService], +}) +export class SettingsModule {} diff --git a/server/src/nest/settings/settings.service.ts b/server/src/nest/settings/settings.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..150bb66cad5f79fa60d2925cf3d53f63ddbb6d54 --- /dev/null +++ b/server/src/nest/settings/settings.service.ts @@ -0,0 +1,13 @@ +import { Injectable } from '@nestjs/common'; +import * as svc from '../../services/settingsService'; + +/** + * Thin Nest wrapper around the existing settings service. The key/value SQL and + * secret-redaction reuse the legacy code unchanged. + */ +@Injectable() +export class SettingsService { + getUserSettings(userId: number) { return svc.getUserSettings(userId); } + upsertSetting(userId: number, key: string, value: unknown) { return svc.upsertSetting(userId, key, value); } + bulkUpsertSettings(userId: number, settings: Record) { return svc.bulkUpsertSettings(userId, settings); } +} diff --git a/server/src/nest/share/share.controller.ts b/server/src/nest/share/share.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..502d7e75a9e98060346867a4a8a953d4563a43c6 --- /dev/null +++ b/server/src/nest/share/share.controller.ts @@ -0,0 +1,108 @@ +import { Body, Controller, Delete, Get, HttpException, Param, Post, Res, UseGuards } from '@nestjs/common'; +import type { Response } from 'express'; +import { createReadStream } from 'node:fs'; +import type { User } from '../../types'; +import { ShareService } from './share.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; + +/** + * /api/trips/:tripId/share-link — manage a trip's public read-only share token. + * + * Byte-identical to the legacy Express route (server/src/routes/share.ts): trip + * access (404), the 'share_manage' permission (403), and the create-vs-update + * status split (201 on first creation, 200 on a subsequent update). + */ +@Controller('api/trips/:tripId/share-link') +@UseGuards(JwtAuthGuard) +export class TripShareController { + constructor(private readonly share: ShareService) {} + + private requireManage(tripId: string, user: User) { + const trip = this.share.verifyTripAccess(tripId, user.id); + if (!trip) { + throw new HttpException({ error: 'Trip not found' }, 404); + } + if (!this.share.canManage(trip, user)) { + throw new HttpException({ error: 'No permission' }, 403); + } + } + + @Post() + create( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body() body: { share_map?: boolean; share_bookings?: boolean; share_packing?: boolean; share_budget?: boolean; share_collab?: boolean }, + @Res({ passthrough: true }) res: Response, + ) { + this.requireManage(tripId, user); + const result = this.share.createOrUpdate(tripId, user.id, { + share_map: body.share_map, + share_bookings: body.share_bookings, + share_packing: body.share_packing, + share_budget: body.share_budget, + share_collab: body.share_collab, + }); + // 201 only on first creation; an update answers 200, mirroring the legacy route. + res.status(result.created ? 201 : 200); + return { token: result.token }; + } + + @Get() + get(@CurrentUser() user: User, @Param('tripId') tripId: string) { + if (!this.share.verifyTripAccess(tripId, user.id)) { + throw new HttpException({ error: 'Trip not found' }, 404); + } + const info = this.share.get(tripId); + return info ? info : { token: null }; + } + + @Delete() + remove(@CurrentUser() user: User, @Param('tripId') tripId: string) { + this.requireManage(tripId, user); + this.share.remove(tripId); + return { success: true }; + } +} + +/** + * GET /api/shared/:token — public, unauthenticated read-only trip snapshot. + * Deliberately NOT behind a guard; an invalid/expired token answers 404. + */ +@Controller('api/shared') +export class SharedController { + constructor(private readonly share: ShareService) {} + + /** + * Public, token-scoped place-photo proxy. The shared payload rewrites place + * image URLs to this route so thumbnails load without a session cookie (the + * /api/maps bytes endpoint is JwtAuthGuard'd). The service validates the token + * and that the place belongs to its trip; a miss streams nothing and answers + * 404. Declared before the bare ':token' read route. Streaming mirrors + * MapsController.placePhotoBytes (cached photos are always JPEG). + */ + @Get(':token/place-photo/:placeId/bytes') + placePhotoBytes(@Param('token') token: string, @Param('placeId') placeId: string, @Res() res: Response): void { + const fp = this.share.getSharedPlacePhotoPath(token, placeId); + if (!fp) { + res.status(404).json({ error: 'Photo not cached' }); + return; + } + res.set('Cache-Control', 'public, max-age=2592000, immutable'); + res.type('image/jpeg'); + const stream = createReadStream(fp); + stream.on('error', () => { + if (!res.headersSent) res.status(404).json({ error: 'Photo not cached' }); + }); + stream.pipe(res); + } + + @Get(':token') + read(@Param('token') token: string) { + const data = this.share.getSharedTripData(token); + if (!data) { + throw new HttpException({ error: 'Invalid or expired link' }, 404); + } + return data; + } +} diff --git a/server/src/nest/share/share.module.ts b/server/src/nest/share/share.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..4e147f48c1800bbbd58e4f71dabe03b9464c1781 --- /dev/null +++ b/server/src/nest/share/share.module.ts @@ -0,0 +1,9 @@ +import { Module } from '@nestjs/common'; +import { TripShareController, SharedController } from './share.controller'; +import { ShareService } from './share.service'; + +@Module({ + controllers: [TripShareController, SharedController], + providers: [ShareService], +}) +export class ShareModule {} diff --git a/server/src/nest/share/share.service.ts b/server/src/nest/share/share.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..03ef92c8506de3c53c91d9c39ccabf60a2c09e44 --- /dev/null +++ b/server/src/nest/share/share.service.ts @@ -0,0 +1,30 @@ +import { Injectable } from '@nestjs/common'; +import { canAccessTrip } from '../../db/database'; +import { checkPermission } from '../../services/permissions'; +import type { User } from '../../types'; +import * as svc from '../../services/shareService'; + +type Trip = NonNullable>; + +/** + * Thin Nest wrapper around the existing share service. Trip access, the + * 'share_manage' permission and the token SQL reuse the legacy code unchanged. + */ +@Injectable() +export class ShareService { + verifyTripAccess(tripId: string, userId: number) { + return canAccessTrip(tripId, userId); + } + + canManage(trip: Trip, user: User): boolean { + return checkPermission('share_manage', user.role, trip.user_id, user.id, trip.user_id !== user.id); + } + + createOrUpdate(tripId: string, userId: number, permissions: Parameters[2]) { + return svc.createOrUpdateShareLink(tripId, userId, permissions); + } + get(tripId: string) { return svc.getShareLink(tripId); } + remove(tripId: string) { return svc.deleteShareLink(tripId); } + getSharedTripData(token: string) { return svc.getSharedTripData(token); } + getSharedPlacePhotoPath(token: string, placeId: string) { return svc.getSharedPlacePhotoPath(token, placeId); } +} diff --git a/server/src/nest/system-notices/system-notices.controller.ts b/server/src/nest/system-notices/system-notices.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..a0cd1e3f2dd6d4a52972fef652eb2fe508c44cba --- /dev/null +++ b/server/src/nest/system-notices/system-notices.controller.ts @@ -0,0 +1,34 @@ +import { Controller, Get, HttpCode, HttpException, Param, Post, UseGuards } from '@nestjs/common'; +import type { SystemNoticeDto } from '@trek/shared'; +import type { User } from '../../types'; +import { SystemNoticesService } from './system-notices.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; + +/** + * /api/system-notices — active announcements for the current user + dismissal. + * + * Byte-identical to the legacy Express route (server/src/routes/systemNotices.ts): + * both endpoints require auth, `/active` returns the evaluated DTO list, and + * dismiss is idempotent — an unknown id 404s with `{ error: 'NOTICE_NOT_FOUND' }` + * and a successful dismiss returns 204 with no body. + */ +@Controller('api/system-notices') +@UseGuards(JwtAuthGuard) +export class SystemNoticesController { + constructor(private readonly notices: SystemNoticesService) {} + + @Get('active') + active(@CurrentUser() user: User): SystemNoticeDto[] { + return this.notices.getActiveFor(user.id); + } + + @Post(':id/dismiss') + @HttpCode(204) + dismiss(@CurrentUser() user: User, @Param('id') id: string): void { + const dismissed = this.notices.dismiss(user.id, id); + if (!dismissed) { + throw new HttpException({ error: 'NOTICE_NOT_FOUND' }, 404); + } + } +} diff --git a/server/src/nest/system-notices/system-notices.module.ts b/server/src/nest/system-notices/system-notices.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..3a676105826bc6bd6311d1f0f4e46421229285f7 --- /dev/null +++ b/server/src/nest/system-notices/system-notices.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { SystemNoticesController } from './system-notices.controller'; +import { SystemNoticesService } from './system-notices.service'; + +/** System-notices domain (L2 leaf module). Registered in AppModule. */ +@Module({ + controllers: [SystemNoticesController], + providers: [SystemNoticesService], +}) +export class SystemNoticesModule {} diff --git a/server/src/nest/system-notices/system-notices.service.ts b/server/src/nest/system-notices/system-notices.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..872dd6990953600b0b96cf6b1d0fd432b965df71 --- /dev/null +++ b/server/src/nest/system-notices/system-notices.service.ts @@ -0,0 +1,19 @@ +import { Injectable } from '@nestjs/common'; +import type { SystemNoticeDto } from '@trek/shared'; +import { getActiveNoticesFor, dismissNotice } from '../../systemNotices/service'; + +/** + * Thin Nest wrapper around the existing system-notices service. The condition + * evaluation, version gating, sorting and dismissal persistence all stay in the + * upstream service — this only adapts it for DI, so behaviour is unchanged. + */ +@Injectable() +export class SystemNoticesService { + getActiveFor(userId: number): SystemNoticeDto[] { + return getActiveNoticesFor(userId) as SystemNoticeDto[]; + } + + dismiss(userId: number, noticeId: string): boolean { + return dismissNotice(userId, noticeId); + } +} diff --git a/server/src/nest/tags/tags.controller.ts b/server/src/nest/tags/tags.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..83de5d9121500826bceff78e0871b0ce2f6bd3b6 --- /dev/null +++ b/server/src/nest/tags/tags.controller.ts @@ -0,0 +1,60 @@ +import { Body, Controller, Delete, Get, HttpException, Param, Post, Put, UseGuards } from '@nestjs/common'; +import type { Tag, TagListResponse } from '@trek/shared'; +import type { User } from '../../types'; +import { TagsService } from './tags.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; + +/** + * /api/tags — per-user place-tag CRUD. + * + * Byte-identical to the legacy Express route (server/src/routes/tags.ts): every + * endpoint requires auth and is scoped to the caller's own tags. Update/delete + * verify ownership via getTagByIdAndUser and 404 otherwise. Status codes match + * the Nest defaults the legacy route used (201 on create, 200 elsewhere); the + * bespoke 400/404 bodies are reproduced exactly. + */ +@Controller('api/tags') +@UseGuards(JwtAuthGuard) +export class TagsController { + constructor(private readonly tags: TagsService) {} + + @Get() + list(@CurrentUser() user: User): TagListResponse { + return { tags: this.tags.list(user.id) }; + } + + @Post() + create( + @CurrentUser() user: User, + @Body('name') name?: string, + @Body('color') color?: string, + ): { tag: Tag } { + if (!name) { + throw new HttpException({ error: 'Tag name is required' }, 400); + } + return { tag: this.tags.create(user.id, name, color) }; + } + + @Put(':id') + update( + @CurrentUser() user: User, + @Param('id') id: string, + @Body('name') name?: string, + @Body('color') color?: string, + ): { tag: Tag } { + if (!this.tags.getByIdAndUser(id, user.id)) { + throw new HttpException({ error: 'Tag not found' }, 404); + } + return { tag: this.tags.update(id, name, color) }; + } + + @Delete(':id') + remove(@CurrentUser() user: User, @Param('id') id: string): { success: boolean } { + if (!this.tags.getByIdAndUser(id, user.id)) { + throw new HttpException({ error: 'Tag not found' }, 404); + } + this.tags.remove(id); + return { success: true }; + } +} diff --git a/server/src/nest/tags/tags.module.ts b/server/src/nest/tags/tags.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..4ffc93bc4a0b74a40ae661a96a54f2fd2ade4bff --- /dev/null +++ b/server/src/nest/tags/tags.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { TagsController } from './tags.controller'; +import { TagsService } from './tags.service'; + +/** Tags domain (L5 leaf module). Registered in AppModule. */ +@Module({ + controllers: [TagsController], + providers: [TagsService], +}) +export class TagsModule {} diff --git a/server/src/nest/tags/tags.service.ts b/server/src/nest/tags/tags.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..468b4bd642219064101440c026ce4728d16105c9 --- /dev/null +++ b/server/src/nest/tags/tags.service.ts @@ -0,0 +1,36 @@ +import { Injectable } from '@nestjs/common'; +import type { Tag } from '@trek/shared'; +import { + listTags, + createTag, + getTagByIdAndUser, + updateTag, + deleteTag, +} from '../../services/tagService'; + +/** + * Thin Nest wrapper around the existing tag service. Ownership scoping and the + * default colour fallback stay in tagService, so behaviour is unchanged. + */ +@Injectable() +export class TagsService { + list(userId: number): Tag[] { + return listTags(userId) as Tag[]; + } + + getByIdAndUser(id: string | number, userId: number): Tag | undefined { + return getTagByIdAndUser(id, userId) as Tag | undefined; + } + + create(userId: number, name: string, color?: string): Tag { + return createTag(userId, name, color) as Tag; + } + + update(id: string | number, name?: string, color?: string): Tag { + return updateTag(id, name, color) as Tag; + } + + remove(id: string | number): void { + deleteTag(id); + } +} diff --git a/server/src/nest/todo/todo.controller.ts b/server/src/nest/todo/todo.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..c737abdb97263a1a7f08369a2b7c4a5b610d8196 --- /dev/null +++ b/server/src/nest/todo/todo.controller.ts @@ -0,0 +1,138 @@ +import { + Body, + Controller, + Delete, + Get, + Headers, + HttpException, + Param, + Post, + Put, + UseGuards, +} from '@nestjs/common'; +import type { User } from '../../types'; +import { TodoService } from './todo.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; + +/** + * /api/trips/:tripId/todo — trip-scoped task list. + * + * Byte-identical to the legacy Express route (server/src/routes/todo.ts): every + * handler verifies trip access (404); mutations check the 'packing_edit' + * permission (403); create is 201, the rest 200; the bespoke 400/404 bodies are + * reproduced; mutations broadcast over WebSocket with the forwarded X-Socket-Id. + * /reorder is declared before /:id so it wins over the param. + */ +@Controller('api/trips/:tripId/todo') +@UseGuards(JwtAuthGuard) +export class TodoController { + constructor(private readonly todo: TodoService) {} + + private requireTrip(tripId: string, user: User) { + const trip = this.todo.verifyTripAccess(tripId, user.id); + if (!trip) { + throw new HttpException({ error: 'Trip not found' }, 404); + } + return trip; + } + + private requireEdit(trip: ReturnType, user: User): void { + if (!this.todo.canEdit(trip!, user)) { + throw new HttpException({ error: 'No permission' }, 403); + } + } + + @Get() + list(@CurrentUser() user: User, @Param('tripId') tripId: string) { + this.requireTrip(tripId, user); + return { items: this.todo.listItems(tripId) }; + } + + @Post() + create( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body() body: { name?: string; category?: string; due_date?: string; description?: string; assigned_user_id?: number; priority?: number }, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!body.name) { + throw new HttpException({ error: 'Item name is required' }, 400); + } + const { name, category, due_date, description, assigned_user_id, priority } = body; + const item = this.todo.createItem(tripId, { name, category, due_date, description, assigned_user_id, priority }); + this.todo.broadcast(tripId, 'todo:created', { item }, socketId); + return { item }; + } + + @Put('reorder') + reorder( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body('orderedIds') orderedIds: number[], + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + this.todo.reorderItems(tripId, orderedIds); + return { success: true }; + } + + @Put(':id') + update( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('id') id: string, + @Body() body: Record, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + const { name, checked, category, due_date, description, assigned_user_id, priority } = body as Record; + const updated = this.todo.updateItem(tripId, id, { name, checked, category, due_date, description, assigned_user_id, priority }, Object.keys(body)); + if (!updated) { + throw new HttpException({ error: 'Item not found' }, 404); + } + this.todo.broadcast(tripId, 'todo:updated', { item: updated }, socketId); + return { item: updated }; + } + + @Delete(':id') + remove( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('id') id: string, + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + if (!this.todo.deleteItem(tripId, id)) { + throw new HttpException({ error: 'Item not found' }, 404); + } + this.todo.broadcast(tripId, 'todo:deleted', { itemId: Number(id) }, socketId); + return { success: true }; + } + + @Get('category-assignees') + categoryAssignees(@CurrentUser() user: User, @Param('tripId') tripId: string) { + this.requireTrip(tripId, user); + return { assignees: this.todo.getCategoryAssignees(tripId) }; + } + + @Put('category-assignees/:categoryName') + updateCategoryAssignees( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('categoryName') categoryName: string, + @Body('user_ids') userIds: number[], + @Headers('x-socket-id') socketId?: string, + ) { + const trip = this.requireTrip(tripId, user); + this.requireEdit(trip, user); + const category = decodeURIComponent(categoryName); + const rows = this.todo.updateCategoryAssignees(tripId, category, userIds); + this.todo.broadcast(tripId, 'todo:assignees', { category, assignees: rows }, socketId); + return { assignees: rows }; + } +} diff --git a/server/src/nest/todo/todo.module.ts b/server/src/nest/todo/todo.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..be89ef3a3a518fc74c377a8caeca3d4ae9a6a272 --- /dev/null +++ b/server/src/nest/todo/todo.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { TodoController } from './todo.controller'; +import { TodoService } from './todo.service'; + +/** To-do domain (S3 — Phase 2 trip sub-domain). Registered in AppModule. */ +@Module({ + controllers: [TodoController], + providers: [TodoService], +}) +export class TodoModule {} diff --git a/server/src/nest/todo/todo.service.ts b/server/src/nest/todo/todo.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..055b35a608382e2f94792adb83cefe296e23b2c3 --- /dev/null +++ b/server/src/nest/todo/todo.service.ts @@ -0,0 +1,55 @@ +import { Injectable } from '@nestjs/common'; +import { broadcast } from '../../websocket'; +import { checkPermission } from '../../services/permissions'; +import type { User } from '../../types'; +import * as svc from '../../services/todoService'; + +type Trip = NonNullable>; + +/** + * Thin Nest wrapper around the existing todo service. Trip-access, the + * 'packing_edit' permission (shared with packing), the SQL and the WebSocket + * broadcasts all reuse the legacy code unchanged. + */ +@Injectable() +export class TodoService { + verifyTripAccess(tripId: string, userId: number) { + return svc.verifyTripAccess(tripId, userId); + } + + canEdit(trip: Trip, user: User): boolean { + return checkPermission('packing_edit', user.role, trip.user_id, user.id, trip.user_id !== user.id); + } + + broadcast(tripId: string, event: string, payload: Record, socketId: string | undefined): void { + broadcast(tripId, event, payload, socketId); + } + + listItems(tripId: string) { + return svc.listItems(tripId); + } + + createItem(tripId: string, data: Parameters[1]) { + return svc.createItem(tripId, data); + } + + updateItem(tripId: string, id: string, data: Parameters[2], changedKeys: string[]) { + return svc.updateItem(tripId, id, data, changedKeys); + } + + deleteItem(tripId: string, id: string): boolean { + return svc.deleteItem(tripId, id); + } + + reorderItems(tripId: string, orderedIds: Parameters[1]): void { + svc.reorderItems(tripId, orderedIds); + } + + getCategoryAssignees(tripId: string) { + return svc.getCategoryAssignees(tripId); + } + + updateCategoryAssignees(tripId: string, category: string, userIds: number[]) { + return svc.updateCategoryAssignees(tripId, category, userIds); + } +} diff --git a/server/src/nest/trips/trips.controller.ts b/server/src/nest/trips/trips.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..749b2b07962a386c86b919933144386e310dac54 --- /dev/null +++ b/server/src/nest/trips/trips.controller.ts @@ -0,0 +1,273 @@ +import { + Body, + Controller, + Delete, + Get, + Headers, + HttpCode, + HttpException, + Param, + Post, + Put, + Query, + Req, + Res, + UploadedFile, + UseGuards, + UseInterceptors, +} from '@nestjs/common'; +import { FileInterceptor } from '@nestjs/platform-express'; +import type { Request, Response } from 'express'; +import { diskStorage } from 'multer'; +import path from 'path'; +import fs from 'fs'; +import { v4 as uuidv4 } from 'uuid'; +import type { User } from '../../types'; +import { TripsService } from './trips.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; +import { writeAudit, getClientIp, logInfo } from '../../services/auditLog'; +import { isDemoEmail } from '../../services/demo'; +import { NotFoundError, ValidationError } from '../../services/tripService'; + +const MAX_COVER_SIZE = 20 * 1024 * 1024; +const coversDir = path.join(__dirname, '../../../uploads/covers'); +const COVER_UPLOAD = { + storage: diskStorage({ + destination: (_req, _file, cb) => { + if (!fs.existsSync(coversDir)) fs.mkdirSync(coversDir, { recursive: true }); + cb(null, coversDir); + }, + filename: (_req, file, cb) => cb(null, `${uuidv4()}${path.extname(file.originalname)}`), + }), + limits: { fileSize: MAX_COVER_SIZE }, + fileFilter: (_req: Request, file: Express.Multer.File, cb: (err: Error | null, accept: boolean) => void) => { + const ext = path.extname(file.originalname).toLowerCase(); + const allowed = ['.jpg', '.jpeg', '.png', '.gif', '.webp']; + if (file.mimetype.startsWith('image/') && !file.mimetype.includes('svg') && allowed.includes(ext)) cb(null, true); + else cb(new Error('Only jpg, png, gif, webp images allowed'), false); + }, +}; + +const toDateStr = (d: Date) => d.toISOString().slice(0, 10); +const addDays = (d: Date, n: number) => { const r = new Date(d); r.setDate(r.getDate() + n); return r; }; + +/** + * /api/trips — the trip aggregate root. + * + * Byte-identical to the legacy Express route (server/src/routes/trips.ts): the + * same per-field permission checks (trip_create / trip_edit / trip_archive / + * trip_cover_upload / trip_delete / member_manage), the date inference on create, + * audit logging, the offline bundle, ICS export and member-invite notification. + * Uses EXACT strangler prefixes so it never swallows the nested sub-domain mounts. + */ +@Controller('api/trips') +@UseGuards(JwtAuthGuard) +export class TripsController { + constructor(private readonly trips: TripsService) {} + + @Get() + list(@CurrentUser() user: User, @Query('archived') archived?: string) { + return { trips: this.trips.list(user.id, archived === '1' ? 1 : 0) }; + } + + @Post() + @HttpCode(201) + create(@CurrentUser() user: User, @Body() body: Record, @Req() req: Request) { + if (!this.trips.can('trip_create', user.role, null, user.id, false)) { + throw new HttpException({ error: 'No permission to create trips' }, 403); + } + const { title, description, currency, reminder_days, day_count } = body as Record; + if (!title) { + throw new HttpException({ error: 'Title is required' }, 400); + } + let start_date: string | null = (body.start_date as string) || null; + let end_date: string | null = (body.end_date as string) || null; + if (start_date && !end_date) end_date = toDateStr(addDays(new Date(start_date), 6)); + else if (!start_date && end_date) start_date = toDateStr(addDays(new Date(end_date), -6)); + if (start_date && end_date && new Date(end_date) < new Date(start_date)) { + throw new HttpException({ error: 'End date must be after start date' }, 400); + } + const parsedDayCount = day_count ? Math.min(Math.max(Number(day_count) || 7, 1), 365) : undefined; + const { trip, tripId, reminderDays } = this.trips.create(user.id, { title, description, start_date, end_date, currency, reminder_days, day_count: parsedDayCount }); + writeAudit({ userId: user.id, action: 'trip.create', ip: getClientIp(req), details: { tripId, title, reminder_days: reminderDays === 0 ? 'none' : `${reminderDays} days` } }); + if (reminderDays > 0) logInfo(`${user.email} set ${reminderDays}-day reminder for trip "${title}"`); + return { trip }; + } + + @Get(':id') + get(@CurrentUser() user: User, @Param('id') id: string) { + const trip = this.trips.get(id, user.id); + if (!trip) { + throw new HttpException({ error: 'Trip not found' }, 404); + } + return { trip }; + } + + @Put(':id') + update(@CurrentUser() user: User, @Param('id') id: string, @Body() body: Record, @Req() req: Request, @Headers('x-socket-id') socketId?: string) { + const access = this.trips.canAccessTrip(id, user.id); + if (!access) { + throw new HttpException({ error: 'Trip not found' }, 404); + } + const ownerId = access.user_id; + const isMember = ownerId !== user.id; + if (body.is_archived !== undefined && !this.trips.can('trip_archive', user.role, ownerId, user.id, isMember)) { + throw new HttpException({ error: 'No permission to archive/unarchive this trip' }, 403); + } + if (body.cover_image !== undefined && !this.trips.can('trip_cover_upload', user.role, ownerId, user.id, isMember)) { + throw new HttpException({ error: 'No permission to change cover image' }, 403); + } + const editFields = ['title', 'description', 'start_date', 'end_date', 'currency', 'reminder_days', 'day_count']; + if (editFields.some((f) => body[f] !== undefined) && !this.trips.can('trip_edit', user.role, ownerId, user.id, isMember)) { + throw new HttpException({ error: 'No permission to edit this trip' }, 403); + } + try { + const result = this.trips.update(id, user.id, body, user.role); + if (Object.keys(result.changes).length > 0) { + writeAudit({ userId: user.id, action: 'trip.update', ip: getClientIp(req), details: { tripId: Number(id), trip: result.newTitle, ...(result.ownerEmail ? { owner: result.ownerEmail } : {}), ...result.changes } }); + if (result.isAdminEdit && result.ownerEmail) logInfo(`Admin ${user.email} edited trip "${result.newTitle}" owned by ${result.ownerEmail}`); + } + if (result.newReminder !== result.oldReminder) { + if (result.newReminder > 0) logInfo(`${user.email} set ${result.newReminder}-day reminder for trip "${result.newTitle}"`); + else logInfo(`${user.email} removed reminder for trip "${result.newTitle}"`); + } + this.trips.broadcast(id, 'trip:updated', { trip: result.updatedTrip }, socketId); + return { trip: result.updatedTrip }; + } catch (e: unknown) { + if (e instanceof NotFoundError) throw new HttpException({ error: e.message }, 404); + if (e instanceof ValidationError) throw new HttpException({ error: e.message }, 400); + throw e; + } + } + + @Post(':id/cover') + @UseInterceptors(FileInterceptor('cover', COVER_UPLOAD)) + cover(@CurrentUser() user: User, @Param('id') id: string, @UploadedFile() file: Express.Multer.File | undefined) { + if (process.env.DEMO_MODE?.toLowerCase() === 'true' && isDemoEmail(user.email)) { + throw new HttpException({ error: 'Uploads are disabled in demo mode. Self-host TREK for full functionality.' }, 403); + } + const access = this.trips.canAccessTrip(id, user.id); + if (!access?.user_id) { + throw new HttpException({ error: 'Trip not found' }, 404); + } + if (!this.trips.can('trip_cover_upload', user.role, access.user_id, user.id, access.user_id !== user.id)) { + throw new HttpException({ error: 'No permission to change the cover image' }, 403); + } + const trip = this.trips.getRaw(id) as { cover_image: string | null } | undefined; + if (!trip) { + throw new HttpException({ error: 'Trip not found' }, 404); + } + if (!file) { + throw new HttpException({ error: 'No image uploaded' }, 400); + } + this.trips.deleteOldCover(trip.cover_image); + const coverUrl = `/uploads/covers/${file.filename}`; + this.trips.updateCoverImage(id, coverUrl); + return { cover_image: coverUrl }; + } + + @Post(':id/copy') + @HttpCode(201) + copy(@CurrentUser() user: User, @Param('id') id: string, @Body('title') title: string | undefined, @Req() req: Request) { + if (!this.trips.can('trip_create', user.role, null, user.id, false)) { + throw new HttpException({ error: 'No permission to create trips' }, 403); + } + if (!this.trips.canAccessTrip(id, user.id)) { + throw new HttpException({ error: 'Trip not found' }, 404); + } + try { + const newTripId = this.trips.copy(id, user.id, title); + writeAudit({ userId: user.id, action: 'trip.copy', ip: getClientIp(req), details: { sourceTripId: Number(id), newTripId, title } }); + return { trip: this.trips.getCopiedTrip(newTripId, user.id) }; + } catch { + throw new HttpException({ error: 'Failed to copy trip' }, 500); + } + } + + @Delete(':id') + remove(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request, @Headers('x-socket-id') socketId?: string) { + const owner = this.trips.getOwner(id); + if (!owner) { + throw new HttpException({ error: 'Trip not found' }, 404); + } + if (!this.trips.can('trip_delete', user.role, owner.user_id, user.id, owner.user_id !== user.id)) { + throw new HttpException({ error: 'No permission to delete this trip' }, 403); + } + const info = this.trips.remove(id, user.id, user.role); + writeAudit({ userId: user.id, action: 'trip.delete', ip: getClientIp(req), details: { tripId: info.tripId, trip: info.title, ...(info.ownerEmail ? { owner: info.ownerEmail } : {}) } }); + if (info.isAdminDelete && info.ownerEmail) logInfo(`Admin ${user.email} deleted trip "${info.title}" owned by ${info.ownerEmail}`); + this.trips.broadcast(String(info.tripId), 'trip:deleted', { id: info.tripId }, socketId); + return { success: true }; + } + + @Get(':id/members') + members(@CurrentUser() user: User, @Param('id') id: string) { + const access = this.trips.canAccessTrip(id, user.id); + if (!access) { + throw new HttpException({ error: 'Trip not found' }, 404); + } + const { owner, members } = this.trips.listMembers(id, access.user_id); + return { owner, members, current_user_id: user.id }; + } + + @Post(':id/members') + @HttpCode(201) + addMember(@CurrentUser() user: User, @Param('id') id: string, @Body('identifier') identifier: string) { + const access = this.trips.canAccessTrip(id, user.id); + if (!access) { + throw new HttpException({ error: 'Trip not found' }, 404); + } + if (!this.trips.can('member_manage', user.role, access.user_id, user.id, access.user_id !== user.id)) { + throw new HttpException({ error: 'No permission to manage members' }, 403); + } + try { + const result = this.trips.addMember(id, identifier, access.user_id, user.id); + this.trips.notifyInvite(id, user, result.targetUserId, result.tripTitle, result.member.email); + return { member: result.member }; + } catch (e: unknown) { + if (e instanceof NotFoundError) throw new HttpException({ error: e.message }, 404); + if (e instanceof ValidationError) throw new HttpException({ error: e.message }, 400); + throw e; + } + } + + @Delete(':id/members/:userId') + removeMember(@CurrentUser() user: User, @Param('id') id: string, @Param('userId') userId: string) { + const access = this.trips.canAccessTrip(id, user.id); + if (!access) { + throw new HttpException({ error: 'Trip not found' }, 404); + } + const targetId = parseInt(userId); + if (targetId !== user.id && !this.trips.can('member_manage', user.role, access.user_id, user.id, access.user_id !== user.id)) { + throw new HttpException({ error: 'No permission to remove members' }, 403); + } + this.trips.removeMember(id, targetId); + return { success: true }; + } + + @Get(':id/bundle') + bundle(@CurrentUser() user: User, @Param('id') id: string) { + const trip = this.trips.get(id, user.id) as { user_id: number } | undefined; + if (!trip) { + throw new HttpException({ error: 'Trip not found' }, 404); + } + return this.trips.bundle(id, trip); + } + + @Get(':id/export.ics') + exportIcs(@CurrentUser() user: User, @Param('id') id: string, @Res() res: Response) { + if (!this.trips.canAccessTrip(id, user.id)) { + throw new HttpException({ error: 'Trip not found' }, 404); + } + try { + const { ics, filename } = this.trips.exportICS(id); + res.setHeader('Content-Type', 'text/calendar; charset=utf-8'); + res.setHeader('Content-Disposition', `attachment; filename="${filename}"`); + res.send(ics); + } catch (e: unknown) { + if (e instanceof NotFoundError) throw new HttpException({ error: e.message }, 404); + throw e; + } + } +} diff --git a/server/src/nest/trips/trips.module.ts b/server/src/nest/trips/trips.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..e1a97d78688d60c60080c1643b8ff79b030593c5 --- /dev/null +++ b/server/src/nest/trips/trips.module.ts @@ -0,0 +1,11 @@ +import { Module } from '@nestjs/common'; +import { TripsController } from './trips.controller'; +import { TripsService } from './trips.service'; + +/** Trips aggregate root (C1 — Phase 3). Uses exact strangler prefixes so it does + * not capture the nested sub-domain mounts (collab, files, ...). */ +@Module({ + controllers: [TripsController], + providers: [TripsService], +}) +export class TripsModule {} diff --git a/server/src/nest/trips/trips.service.ts b/server/src/nest/trips/trips.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..f0fa8a0973d3171ea9b1b1016760d9bf8f400268 --- /dev/null +++ b/server/src/nest/trips/trips.service.ts @@ -0,0 +1,127 @@ +import { Injectable } from '@nestjs/common'; +import { db, canAccessTrip } from '../../db/database'; +import { broadcast } from '../../websocket'; +import { checkPermission } from '../../services/permissions'; +import type { User } from '../../types'; +import * as tripSvc from '../../services/tripService'; +import { listDays, listAccommodations } from '../../services/dayService'; +import { listPlaces } from '../../services/placeService'; +import { listItems as listPackingItems } from '../../services/packingService'; +import { listItems as listTodoItems } from '../../services/todoService'; +import { listBudgetItems } from '../../services/budgetService'; +import { listReservations } from '../../services/reservationService'; +import { listFiles } from '../../services/fileService'; + +/** + * Thin Nest wrapper around the existing trip service + the per-domain list + * services used to build the offline bundle. Auth (canAccessTrip), permissions, + * the SQL and the ICS export reuse the legacy code unchanged. Per-field + * permission checks and audit logging stay in the controller (1:1 with the + * legacy route). + */ +@Injectable() +export class TripsService { + canAccessTrip(tripId: string, userId: number) { + return canAccessTrip(tripId, userId) as { user_id: number } | null | undefined; + } + + can(action: string, role: string, ownerId: number | null, userId: number, isMember: boolean): boolean { + return checkPermission(action, role, ownerId, userId, isMember); + } + + broadcast(tripId: string, event: string, payload: Record, socketId: string | undefined): void { + broadcast(tripId, event, payload, socketId); + } + + list(userId: number, archived: number) { + return tripSvc.listTrips(userId, archived); + } + + create(userId: number, data: Parameters[1]) { + return tripSvc.createTrip(userId, data); + } + + get(tripId: string, userId: number) { + return tripSvc.getTrip(tripId, userId); + } + + getRaw(tripId: string) { + return tripSvc.getTripRaw(tripId); + } + + getOwner(tripId: string) { + return tripSvc.getTripOwner(tripId); + } + + update(tripId: string, userId: number, body: Parameters[2], role: string) { + return tripSvc.updateTrip(tripId, userId, body, role); + } + + remove(tripId: string, userId: number, role: string) { + return tripSvc.deleteTrip(tripId, userId, role); + } + + deleteOldCover(coverImage: string | null | undefined): void { + tripSvc.deleteOldCover(coverImage as never); + } + + updateCoverImage(tripId: string, url: string): void { + tripSvc.updateCoverImage(tripId, url); + } + + copy(tripId: string, userId: number, title?: string) { + return tripSvc.copyTripById(tripId, userId, title); + } + + /** Re-read a freshly copied trip in list shape (mirrors the route's TRIP_SELECT query). */ + getCopiedTrip(newTripId: number, userId: number) { + return db.prepare(`${tripSvc.TRIP_SELECT} WHERE t.id = :tripId`).get({ userId, tripId: newTripId }); + } + + listMembers(tripId: string, ownerId: number) { + return tripSvc.listMembers(tripId, ownerId); + } + + addMember(tripId: string, identifier: string, ownerId: number, userId: number) { + return tripSvc.addMember(tripId, identifier, ownerId, userId); + } + + removeMember(tripId: string, targetId: number): void { + tripSvc.removeMember(tripId, targetId); + } + + exportICS(tripId: string) { + return tripSvc.exportICS(tripId); + } + + /** Aggregates every trip sub-collection for offline caching (legacy /:id/bundle). */ + bundle(tripId: string, trip: { user_id: number }) { + const { days } = listDays(tripId); + const { owner, members } = this.listMembers(tripId, trip.user_id); + return { + trip, + days, + places: listPlaces(String(tripId), {}), + packingItems: listPackingItems(tripId), + todoItems: listTodoItems(tripId), + budgetItems: listBudgetItems(tripId), + reservations: listReservations(tripId), + files: listFiles(tripId, false), + accommodations: listAccommodations(tripId), + members: [owner, ...(members || [])].filter(Boolean), + }; + } + + /** Fire-and-forget trip-invite notification (mirrors the route's dynamic import). */ + notifyInvite(tripId: string, actor: User, targetUserId: number, tripTitle: string, inviteeEmail: string): void { + import('../../services/notificationService').then(({ send }) => { + send({ + event: 'trip_invite', + actorId: actor.id, + scope: 'user', + targetId: targetUserId, + params: { trip: tripTitle, actor: actor.email, invitee: inviteeEmail, tripId: String(tripId) }, + }).catch(() => {}); + }); + } +} diff --git a/server/src/nest/vacay/vacay.controller.ts b/server/src/nest/vacay/vacay.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..949d32ce066c9fa8b1a8f12ef6684949fcc5e7fc --- /dev/null +++ b/server/src/nest/vacay/vacay.controller.ts @@ -0,0 +1,255 @@ +import { + Body, + Controller, + Delete, + Get, + Headers, + HttpCode, + HttpException, + Param, + Post, + Put, + UseGuards, +} from '@nestjs/common'; +import type { User } from '../../types'; +import { VacayService } from './vacay.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; + +/** + * /api/addons/vacay — shared vacation-day planner. + * + * Byte-identical to the legacy Express route (server/src/routes/vacay.ts): all + * endpoints require auth; the X-Socket-Id header is forwarded to the services so + * the originating client is excluded from the broadcast; POSTs answer 200 (the + * legacy route uses res.json, not 201); and the bespoke 400/403/404/502 bodies + * are reproduced exactly. No addon gate — the legacy mount has none. + */ +@Controller('api/addons/vacay') +@UseGuards(JwtAuthGuard) +export class VacayController { + constructor(private readonly vacay: VacayService) {} + + @Get('plan') + getPlan(@CurrentUser() user: User) { + return this.vacay.getPlanData(user.id); + } + + @Put('plan') + async updatePlan(@CurrentUser() user: User, @Body() body: Record, @Headers('x-socket-id') socketId?: string) { + const planId = this.vacay.getActivePlanId(user.id); + return this.vacay.updatePlan(planId, body, socketId); + } + + @Post('plan/holiday-calendars') + @HttpCode(200) + addHolidayCalendar( + @CurrentUser() user: User, + @Body() body: { region?: string; label?: string | null; color?: string; sort_order?: number }, + @Headers('x-socket-id') socketId?: string, + ) { + if (!body.region) { + throw new HttpException({ error: 'region required' }, 400); + } + const planId = this.vacay.getActivePlanId(user.id); + const calendar = this.vacay.addHolidayCalendar(planId, body.region, body.label ?? null, body.color, body.sort_order, socketId); + return { calendar }; + } + + @Put('plan/holiday-calendars/:id') + updateHolidayCalendar( + @CurrentUser() user: User, + @Param('id') idParam: string, + @Body() body: Record, + @Headers('x-socket-id') socketId?: string, + ) { + const id = parseInt(idParam); + const planId = this.vacay.getActivePlanId(user.id); + const calendar = this.vacay.updateHolidayCalendar(id, planId, body, socketId); + if (!calendar) { + throw new HttpException({ error: 'Calendar not found' }, 404); + } + return { calendar }; + } + + @Delete('plan/holiday-calendars/:id') + deleteHolidayCalendar(@CurrentUser() user: User, @Param('id') idParam: string, @Headers('x-socket-id') socketId?: string) { + const id = parseInt(idParam); + const planId = this.vacay.getActivePlanId(user.id); + if (!this.vacay.deleteHolidayCalendar(id, planId, socketId)) { + throw new HttpException({ error: 'Calendar not found' }, 404); + } + return { success: true }; + } + + @Put('color') + setColor( + @CurrentUser() user: User, + @Body() body: { color?: string; target_user_id?: number | string }, + @Headers('x-socket-id') socketId?: string, + ) { + const planId = this.vacay.getActivePlanId(user.id); + const userId = body.target_user_id ? parseInt(String(body.target_user_id)) : user.id; + if (!this.vacay.getPlanUsers(planId).find((u) => u.id === userId)) { + throw new HttpException({ error: 'User not in plan' }, 403); + } + this.vacay.setUserColor(userId, planId, body.color, socketId); + return { success: true }; + } + + @Post('invite') + @HttpCode(200) + invite(@CurrentUser() user: User, @Body('user_id') userIdInput?: number | string) { + if (!userIdInput) { + throw new HttpException({ error: 'user_id required' }, 400); + } + const plan = this.vacay.getActivePlan(user.id); + const result = this.vacay.sendInvite(plan.id, user.id, user.username, user.email, userIdInput as number); + if (result.error) { + throw new HttpException({ error: result.error }, result.status!); + } + return { success: true }; + } + + @Post('invite/accept') + @HttpCode(200) + acceptInvite(@CurrentUser() user: User, @Body('plan_id') planId: number, @Headers('x-socket-id') socketId?: string) { + const result = this.vacay.acceptInvite(user.id, planId, socketId); + if (result.error) { + throw new HttpException({ error: result.error }, result.status!); + } + return { success: true }; + } + + @Post('invite/decline') + @HttpCode(200) + declineInvite(@CurrentUser() user: User, @Body('plan_id') planId: number, @Headers('x-socket-id') socketId?: string) { + this.vacay.declineInvite(user.id, planId, socketId); + return { success: true }; + } + + @Post('invite/cancel') + @HttpCode(200) + cancelInvite(@CurrentUser() user: User, @Body('user_id') targetUserId: number) { + const plan = this.vacay.getActivePlan(user.id); + this.vacay.cancelInvite(plan.id, targetUserId); + return { success: true }; + } + + @Post('dissolve') + @HttpCode(200) + dissolve(@CurrentUser() user: User, @Headers('x-socket-id') socketId?: string) { + this.vacay.dissolvePlan(user.id, socketId); + return { success: true }; + } + + @Get('available-users') + availableUsers(@CurrentUser() user: User) { + const planId = this.vacay.getActivePlanId(user.id); + return { users: this.vacay.getAvailableUsers(user.id, planId) }; + } + + @Get('years') + years(@CurrentUser() user: User) { + const planId = this.vacay.getActivePlanId(user.id); + return { years: this.vacay.listYears(planId) }; + } + + @Post('years') + @HttpCode(200) + addYear(@CurrentUser() user: User, @Body('year') year?: number, @Headers('x-socket-id') socketId?: string) { + if (!year) { + throw new HttpException({ error: 'Year required' }, 400); + } + const planId = this.vacay.getActivePlanId(user.id); + return { years: this.vacay.addYear(planId, year, socketId) }; + } + + @Delete('years/:year') + deleteYear(@CurrentUser() user: User, @Param('year') yearParam: string, @Headers('x-socket-id') socketId?: string) { + const year = parseInt(yearParam); + const planId = this.vacay.getActivePlanId(user.id); + return { years: this.vacay.deleteYear(planId, year, socketId) }; + } + + @Get('entries/:year') + entries(@CurrentUser() user: User, @Param('year') year: string) { + const planId = this.vacay.getActivePlanId(user.id); + return this.vacay.getEntries(planId, year); + } + + @Post('entries/toggle') + @HttpCode(200) + toggleEntry( + @CurrentUser() user: User, + @Body() body: { date?: string; target_user_id?: number | string }, + @Headers('x-socket-id') socketId?: string, + ) { + if (!body.date) { + throw new HttpException({ error: 'date required' }, 400); + } + const planId = this.vacay.getActivePlanId(user.id); + let userId = user.id; + if (body.target_user_id && parseInt(String(body.target_user_id)) !== user.id) { + const tid = parseInt(String(body.target_user_id)); + if (!this.vacay.getPlanUsers(planId).find((u) => u.id === tid)) { + throw new HttpException({ error: 'User not in plan' }, 403); + } + userId = tid; + } + return this.vacay.toggleEntry(userId, planId, body.date, socketId); + } + + @Post('entries/company-holiday') + @HttpCode(200) + companyHoliday( + @CurrentUser() user: User, + @Body() body: { date?: string; note?: string }, + @Headers('x-socket-id') socketId?: string, + ) { + const planId = this.vacay.getActivePlanId(user.id); + return this.vacay.toggleCompanyHoliday(planId, body.date as string, body.note, socketId); + } + + @Get('stats/:year') + stats(@CurrentUser() user: User, @Param('year') yearParam: string) { + const year = parseInt(yearParam); + const planId = this.vacay.getActivePlanId(user.id); + return { stats: this.vacay.getStats(planId, year) }; + } + + @Put('stats/:year') + updateStats( + @CurrentUser() user: User, + @Param('year') yearParam: string, + @Body() body: { vacation_days?: number; target_user_id?: number | string }, + @Headers('x-socket-id') socketId?: string, + ) { + const year = parseInt(yearParam); + const planId = this.vacay.getActivePlanId(user.id); + const userId = body.target_user_id ? parseInt(String(body.target_user_id)) : user.id; + if (!this.vacay.getPlanUsers(planId).find((u) => u.id === userId)) { + throw new HttpException({ error: 'User not in plan' }, 403); + } + this.vacay.updateStats(userId, planId, year, body.vacation_days as number, socketId); + return { success: true }; + } + + @Get('holidays/countries') + async holidayCountries() { + const result = await this.vacay.getCountries(); + if (result.error) { + throw new HttpException({ error: result.error }, 502); + } + return result.data; + } + + @Get('holidays/:year/:country') + async holidays(@Param('year') year: string, @Param('country') country: string) { + const result = await this.vacay.getHolidays(year, country); + if (result.error) { + throw new HttpException({ error: result.error }, 502); + } + return result.data; + } +} diff --git a/server/src/nest/vacay/vacay.module.ts b/server/src/nest/vacay/vacay.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..dec2befbc358dd9d2caf29a764d7738100dd863e --- /dev/null +++ b/server/src/nest/vacay/vacay.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { VacayController } from './vacay.controller'; +import { VacayService } from './vacay.service'; + +/** Vacay addon domain (S1 — Phase 2 trip sub-domain). Registered in AppModule. */ +@Module({ + controllers: [VacayController], + providers: [VacayService], +}) +export class VacayModule {} diff --git a/server/src/nest/vacay/vacay.service.ts b/server/src/nest/vacay/vacay.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..dd2fc81d29abe66fc5b4b8a9482f29c8006f0bb2 --- /dev/null +++ b/server/src/nest/vacay/vacay.service.ts @@ -0,0 +1,112 @@ +import { Injectable } from '@nestjs/common'; +import * as svc from '../../services/vacayService'; + +type UpdatePlanBody = Parameters[1]; + +/** + * Thin Nest wrapper around the existing vacay service. All plan logic, the + * holiday-calendar handling, invite flow and the WebSocket broadcasts (driven by + * the forwarded socket id) stay in vacayService, so behaviour is unchanged. + */ +@Injectable() +export class VacayService { + getPlanData(userId: number) { + return svc.getPlanData(userId); + } + + getActivePlanId(userId: number): number { + return svc.getActivePlanId(userId); + } + + getActivePlan(userId: number) { + return svc.getActivePlan(userId); + } + + updatePlan(planId: number, body: UpdatePlanBody, socketId: string | undefined) { + return svc.updatePlan(planId, body, socketId); + } + + addHolidayCalendar(planId: number, region: string, label: string | null, color: string | undefined, sortOrder: number | undefined, socketId: string | undefined) { + return svc.addHolidayCalendar(planId, region, label, color, sortOrder, socketId); + } + + updateHolidayCalendar(id: number, planId: number, body: Parameters[2], socketId: string | undefined) { + return svc.updateHolidayCalendar(id, planId, body, socketId); + } + + deleteHolidayCalendar(id: number, planId: number, socketId: string | undefined): boolean { + return svc.deleteHolidayCalendar(id, planId, socketId); + } + + getPlanUsers(planId: number) { + return svc.getPlanUsers(planId); + } + + setUserColor(userId: number, planId: number, color: string | undefined, socketId: string | undefined): void { + svc.setUserColor(userId, planId, color, socketId); + } + + sendInvite(planId: number, inviterId: number, inviterUsername: string, inviterEmail: string, targetUserId: number) { + return svc.sendInvite(planId, inviterId, inviterUsername, inviterEmail, targetUserId); + } + + acceptInvite(userId: number, planId: number, socketId: string | undefined) { + return svc.acceptInvite(userId, planId, socketId); + } + + declineInvite(userId: number, planId: number, socketId: string | undefined): void { + svc.declineInvite(userId, planId, socketId); + } + + cancelInvite(planId: number, targetUserId: number): void { + svc.cancelInvite(planId, targetUserId); + } + + dissolvePlan(userId: number, socketId: string | undefined): void { + svc.dissolvePlan(userId, socketId); + } + + getAvailableUsers(userId: number, planId: number) { + return svc.getAvailableUsers(userId, planId); + } + + listYears(planId: number): number[] { + return svc.listYears(planId); + } + + addYear(planId: number, year: number, socketId: string | undefined): number[] { + return svc.addYear(planId, year, socketId); + } + + deleteYear(planId: number, year: number, socketId: string | undefined): number[] { + return svc.deleteYear(planId, year, socketId); + } + + getEntries(planId: number, year: string) { + return svc.getEntries(planId, year); + } + + toggleEntry(userId: number, planId: number, date: string, socketId: string | undefined) { + return svc.toggleEntry(userId, planId, date, socketId); + } + + toggleCompanyHoliday(planId: number, date: string, note: string | undefined, socketId: string | undefined) { + return svc.toggleCompanyHoliday(planId, date, note, socketId); + } + + getStats(planId: number, year: number) { + return svc.getStats(planId, year); + } + + updateStats(userId: number, planId: number, year: number, vacationDays: number, socketId: string | undefined): void { + svc.updateStats(userId, planId, year, vacationDays, socketId); + } + + getCountries() { + return svc.getCountries(); + } + + getHolidays(year: string, country: string) { + return svc.getHolidays(year, country); + } +} diff --git a/server/src/nest/weather/weather.controller.ts b/server/src/nest/weather/weather.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..447606250925b88e480b1cd883ff9f609938d442 --- /dev/null +++ b/server/src/nest/weather/weather.controller.ts @@ -0,0 +1,66 @@ +import { Controller, Get, HttpException, Query, UseGuards } from '@nestjs/common'; +import type { WeatherResult } from '@trek/shared'; +import { WeatherService } from './weather.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { ApiError } from '../../services/weatherService'; + +/** + * /api/weather — first migrated leaf module (the pilot). + * + * Behaviour is byte-identical to the legacy Express route (server/src/routes/ + * weather.ts): same paths, query params, status codes and `{ error }` bodies. + * + * Parity note: the "X is required" 400s and the 500 fallback messages are bespoke + * strings, not the generic Zod-pipe envelope, so they are reproduced here exactly + * rather than derived from the schema. The Zod contract/types live in + * @trek/shared/weather and are used for typing; `lang` defaults to 'de' only when + * the param is absent, matching the Express destructuring default. + */ +@Controller('api/weather') +@UseGuards(JwtAuthGuard) +export class WeatherController { + constructor(private readonly weather: WeatherService) {} + + @Get() + async getWeather( + @Query('lat') lat?: string, + @Query('lng') lng?: string, + @Query('date') date?: string, + @Query('lang') lang?: string, + ): Promise { + if (!lat || !lng) { + throw new HttpException({ error: 'Latitude and longitude are required' }, 400); + } + try { + return await this.weather.get(lat, lng, date, lang ?? 'de'); + } catch (err: unknown) { + throw toHttp(err, 'Weather error:', 'Error fetching weather data'); + } + } + + @Get('detailed') + async getDetailed( + @Query('lat') lat?: string, + @Query('lng') lng?: string, + @Query('date') date?: string, + @Query('lang') lang?: string, + ): Promise { + if (!lat || !lng || !date) { + throw new HttpException({ error: 'Latitude, longitude, and date are required' }, 400); + } + try { + return await this.weather.getDetailed(lat, lng, date, lang ?? 'de'); + } catch (err: unknown) { + throw toHttp(err, 'Detailed weather error:', 'Error fetching detailed weather data'); + } + } +} + +/** Maps a thrown error to the same status + `{ error }` body the Express route sent. */ +function toHttp(err: unknown, logPrefix: string, fallback: string): HttpException { + if (err instanceof ApiError) { + return new HttpException({ error: err.message }, err.status); + } + console.error(logPrefix, err); + return new HttpException({ error: fallback }, 500); +} diff --git a/server/src/nest/weather/weather.module.ts b/server/src/nest/weather/weather.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..3615fa1a7bdf0d25bd3bd88eeae47f66b1c6c8c3 --- /dev/null +++ b/server/src/nest/weather/weather.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { WeatherController } from './weather.controller'; +import { WeatherService } from './weather.service'; + +/** Weather domain (pilot leaf module). Registered in AppModule. */ +@Module({ + controllers: [WeatherController], + providers: [WeatherService], +}) +export class WeatherModule {} diff --git a/server/src/nest/weather/weather.service.ts b/server/src/nest/weather/weather.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..a9319d3afea410a53f90427a3b6163986ab559bd --- /dev/null +++ b/server/src/nest/weather/weather.service.ts @@ -0,0 +1,21 @@ +import { Injectable } from '@nestjs/common'; +import type { WeatherResult } from '@trek/shared'; +import { getWeather, getDetailedWeather } from '../../services/weatherService'; + +/** + * Thin Nest wrapper around the existing weather service. It delegates to the + * exact same `getWeather` / `getDetailedWeather` functions the legacy route and + * the MCP tools use, so behaviour — including the shared in-memory cache and the + * Open-Meteo calls — is identical. No logic is duplicated; the upstream service + * stays the single source of truth (still consumed by the MCP weather tools). + */ +@Injectable() +export class WeatherService { + get(lat: string, lng: string, date: string | undefined, lang: string): Promise { + return getWeather(lat, lng, date, lang) as Promise; + } + + getDetailed(lat: string, lng: string, date: string, lang: string): Promise { + return getDetailedWeather(lat, lng, date, lang) as Promise; + } +} diff --git a/server/src/scheduler.ts b/server/src/scheduler.ts new file mode 100644 index 0000000000000000000000000000000000000000..b9f7fb8723982c7dbd11446ef6fa0b87fffdd34f --- /dev/null +++ b/server/src/scheduler.ts @@ -0,0 +1,422 @@ +import cron, { type ScheduledTask } from 'node-cron'; +import archiver from 'archiver'; +import path from 'node:path'; +import fs from 'node:fs'; +import { logInfo, logError } from './services/auditLog'; + +const dataDir = path.join(__dirname, '../data'); +const backupsDir = path.join(dataDir, 'backups'); +const uploadsDir = path.join(__dirname, '../uploads'); +const settingsFile = path.join(dataDir, 'backup-settings.json'); + +const VALID_INTERVALS = ['hourly', 'daily', 'weekly', 'monthly']; +const VALID_DAYS_OF_WEEK = new Set([0, 1, 2, 3, 4, 5, 6]); // 0=Sunday +const VALID_HOURS = new Set(Array.from({length: 24}, (_, i) => i)); + +interface BackupSettings { + enabled: boolean; + interval: string; + keep_days: number; + hour: number; + day_of_week: number; + day_of_month: number; +} + +export function buildCronExpression(settings: BackupSettings): string { + const hour = VALID_HOURS.has(settings.hour) ? settings.hour : 2; + const dow = VALID_DAYS_OF_WEEK.has(settings.day_of_week) ? settings.day_of_week : 0; + const dom = settings.day_of_month >= 1 && settings.day_of_month <= 28 ? settings.day_of_month : 1; + + switch (settings.interval) { + case 'hourly': return '0 * * * *'; + case 'daily': return `0 ${hour} * * *`; + case 'weekly': return `0 ${hour} * * ${dow}`; + case 'monthly': return `0 ${hour} ${dom} * *`; + default: return `0 ${hour} * * *`; + } +} + +let currentTask: ScheduledTask | null = null; + +function getDefaults(): BackupSettings { + return { enabled: false, interval: 'daily', keep_days: 7, hour: 2, day_of_week: 0, day_of_month: 1 }; +} + +function loadSettings(): BackupSettings { + let settings = getDefaults(); + try { + if (fs.existsSync(settingsFile)) { + const saved = JSON.parse(fs.readFileSync(settingsFile, 'utf8')); + settings = { ...settings, ...saved }; + } + } catch (e) {} + return settings; +} + +function saveSettings(settings: BackupSettings): void { + if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true }); + fs.writeFileSync(settingsFile, JSON.stringify(settings, null, 2)); +} + +async function runBackup(): Promise { + if (!fs.existsSync(backupsDir)) fs.mkdirSync(backupsDir, { recursive: true }); + + const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19); + const filename = `auto-backup-${timestamp}.zip`; + const outputPath = path.join(backupsDir, filename); + + try { + // Flush WAL to main DB file before archiving + try { const { db } = require('./db/database'); db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch (e) {} + + await new Promise((resolve, reject) => { + const output = fs.createWriteStream(outputPath); + const archive = archiver('zip', { zlib: { level: 9 } }); + output.on('close', resolve); + archive.on('error', reject); + archive.pipe(output); + const dbPath = path.join(dataDir, 'travel.db'); + if (fs.existsSync(dbPath)) archive.file(dbPath, { name: 'travel.db' }); + if (fs.existsSync(uploadsDir)) archive.directory(uploadsDir, 'uploads'); + archive.finalize(); + }); + logInfo(`Auto-Backup created: ${filename}`); + } catch (err: unknown) { + logError(`Auto-Backup: ${err instanceof Error ? err.message : err}`); + if (fs.existsSync(outputPath)) fs.unlinkSync(outputPath); + return; + } + + const settings = loadSettings(); + if (settings.keep_days > 0) { + cleanupOldBackups(settings.keep_days); + } +} + +function autoBackupTimestampMs(filename: string): number | null { + // auto-backup-2026-04-27T00-00-00.zip → 2026-04-27T00:00:00 + const stamp = filename.slice('auto-backup-'.length, -'.zip'.length); + const iso = stamp.replace(/T(\d{2})-(\d{2})-(\d{2})$/, 'T$1:$2:$3'); + const ms = Date.parse(iso); + return Number.isNaN(ms) ? null : ms; +} + +export function cleanupOldBackups(keepDays: number, now: number = Date.now()): void { + try { + const cutoff = now - keepDays * 24 * 60 * 60 * 1000; + const files = fs.readdirSync(backupsDir).filter(f => f.startsWith('auto-backup-') && f.endsWith('.zip')); + for (const file of files) { + const filePath = path.join(backupsDir, file); + const ageMs = autoBackupTimestampMs(file) ?? fs.statSync(filePath).mtimeMs; + if (ageMs < cutoff) { + fs.unlinkSync(filePath); + logInfo(`Auto-Backup old backup deleted: ${file}`); + } + } + } catch (err: unknown) { + logError(`Auto-Backup cleanup: ${err instanceof Error ? err.message : err}`); + } +} + +function start(): void { + if (currentTask) { + currentTask.stop(); + currentTask = null; + } + + const settings = loadSettings(); + if (!settings.enabled) { + logInfo('Auto-Backup disabled'); + return; + } + + const expression = buildCronExpression(settings); + const tz = process.env.TZ || 'UTC'; + currentTask = cron.schedule(expression, runBackup, { timezone: tz }); + logInfo(`Auto-Backup scheduled: ${settings.interval} (${expression}), tz: ${tz}, retention: ${settings.keep_days === 0 ? 'forever' : settings.keep_days + ' days'}`); +} + +// Demo mode: hourly reset of demo user data +let demoTask: ScheduledTask | null = null; + +function startDemoReset(): void { + if (demoTask) { demoTask.stop(); demoTask = null; } + if (process.env.DEMO_MODE?.toLowerCase() !== 'true') return; + + demoTask = cron.schedule('0 * * * *', () => { + try { + const { resetDemoUser } = require('./demo/demo-reset'); + resetDemoUser(); + } catch (err: unknown) { + logError(`Demo reset: ${err instanceof Error ? err.message : err}`); + } + }); + logInfo('Demo hourly reset scheduled'); +} + +// Trip reminders: daily check at 9 AM local time for trips starting tomorrow +let reminderTask: ScheduledTask | null = null; + +function startTripReminders(): void { + if (reminderTask) { reminderTask.stop(); reminderTask = null; } + + try { + const { db } = require('./db/database'); + const getSetting = (key: string) => (db.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as { value: string } | undefined)?.value; + const reminderEnabled = getSetting('notify_trip_reminder') !== 'false'; + const channelsRaw = getSetting('notification_channels') || getSetting('notification_channel') || 'none'; + const activeChannels = channelsRaw === 'none' ? [] : channelsRaw.split(',').map((c: string) => c.trim()); + if (!reminderEnabled) { + logInfo('Trip reminders: disabled in settings'); + return; + } + + const tripCount = (db.prepare('SELECT COUNT(*) as c FROM trips WHERE reminder_days > 0 AND start_date IS NOT NULL').get() as { c: number }).c; + logInfo(`Trip reminders: enabled via [${activeChannels.join(',')}]${tripCount > 0 ? `, ${tripCount} trip(s) with active reminders` : ''}`); + } catch { + return; + } + + const tz = process.env.TZ || 'UTC'; + reminderTask = cron.schedule('0 9 * * *', async () => { + try { + const { db } = require('./db/database'); + const { send } = require('./services/notificationService'); + + const trips = db.prepare(` + SELECT t.id, t.title, t.user_id, t.reminder_days FROM trips t + WHERE t.reminder_days > 0 + AND t.start_date IS NOT NULL + AND t.start_date = date('now', '+' || t.reminder_days || ' days') + `).all() as { id: number; title: string; user_id: number; reminder_days: number }[]; + + for (const trip of trips) { + await send({ event: 'trip_reminder', actorId: null, scope: 'trip', targetId: trip.id, params: { trip: trip.title, tripId: String(trip.id) } }).catch(() => {}); + } + + if (trips.length > 0) { + logInfo(`Trip reminders sent for ${trips.length} trip(s): ${trips.map(t => `"${t.title}" (${t.reminder_days}d)`).join(', ')}`); + } + } catch (err: unknown) { + logError(`Trip reminder check failed: ${err instanceof Error ? err.message : err}`); + } + }, { timezone: tz }); +} + +// Todo due-date reminders: daily check at 9 AM for unchecked todos +// whose due_date falls within the next TODO_REMINDER_LEAD_DAYS days. +// Each todo gets reminded at most once per 24 h (tracked via +// todo_items.reminded_at) so the scheduler doesn't spam the user every +// morning leading up to the deadline. +const TODO_REMINDER_LEAD_DAYS = 3; +let todoReminderTask: ScheduledTask | null = null; + +function startTodoReminders(): void { + if (todoReminderTask) { todoReminderTask.stop(); todoReminderTask = null; } + + const { db } = require('./db/database'); + const getSetting = (key: string) => (db.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as { value: string } | undefined)?.value; + const enabled = getSetting('notify_todo_due') !== 'false'; + if (!enabled) { + logInfo('Todo due reminders: disabled in settings'); + return; + } + logInfo(`Todo due reminders: enabled (lead ${TODO_REMINDER_LEAD_DAYS}d)`); + + const tz = process.env.TZ || 'UTC'; + todoReminderTask = cron.schedule('0 9 * * *', async () => { + try { + const { send } = require('./services/notificationService'); + + // Select unchecked todos with a due date inside the lead window + // that haven't been reminded in the last 24 hours. `due_date` is + // stored as a YYYY-MM-DD text; SQLite date() handles it directly. + const todos = db.prepare(` + SELECT ti.id, ti.trip_id, ti.name, ti.due_date, ti.assigned_user_id, + t.title AS trip_title, t.user_id AS trip_owner_id + FROM todo_items ti + JOIN trips t ON t.id = ti.trip_id + WHERE ti.checked = 0 + AND ti.due_date IS NOT NULL + AND ti.due_date <> '' + AND date(ti.due_date) <= date('now', '+' || ? || ' days') + AND date(ti.due_date) >= date('now') + AND (ti.reminded_at IS NULL OR ti.reminded_at <= datetime('now', '-20 hours')) + `).all(TODO_REMINDER_LEAD_DAYS) as { + id: number; trip_id: number; name: string; due_date: string; + assigned_user_id: number | null; trip_title: string; trip_owner_id: number; + }[]; + + for (const todo of todos) { + const targetScope: 'user' | 'trip' = todo.assigned_user_id ? 'user' : 'trip'; + const targetId = todo.assigned_user_id ?? todo.trip_id; + await send({ + event: 'todo_due', + actorId: null, + scope: targetScope, + targetId, + params: { + todo: todo.name, + trip: todo.trip_title, + tripId: String(todo.trip_id), + due: todo.due_date, + }, + }).catch(() => {}); + db.prepare('UPDATE todo_items SET reminded_at = CURRENT_TIMESTAMP WHERE id = ?').run(todo.id); + } + + if (todos.length > 0) { + logInfo(`Todo reminders sent for ${todos.length} item(s)`); + } + } catch (err: unknown) { + logError(`Todo reminder check failed: ${err instanceof Error ? err.message : err}`); + } + }, { timezone: tz }); +} + +// Version check: daily at 9 AM — notify admins if a new TREK release is available +let versionCheckTask: ScheduledTask | null = null; + +function startVersionCheck(): void { + if (versionCheckTask) { versionCheckTask.stop(); versionCheckTask = null; } + + const tz = process.env.TZ || 'UTC'; + versionCheckTask = cron.schedule('0 9 * * *', async () => { + try { + const { checkAndNotifyVersion } = require('./services/adminService'); + await checkAndNotifyVersion(); + } catch (err: unknown) { + logError(`Version check: ${err instanceof Error ? err.message : err}`); + } + }, { timezone: tz }); +} + +// Idempotency key cleanup: nightly at 3 AM — delete keys past their TTL. +// The TTL must exceed any realistic offline window: the TREK client replays +// queued mutations with their X-Idempotency-Key when it reconnects, so a key +// GC'd before the device comes back online would let the replay create a +// duplicate. 24h was far too short for a multi-day offline trip; default 30d, +// overridable via IDEMPOTENCY_TTL_SECONDS. +const DEFAULT_IDEMPOTENCY_TTL_SECONDS = 30 * 24 * 60 * 60; // 30 days +let idempotencyCleanupTask: ScheduledTask | null = null; + +function idempotencyTtlSeconds(): number { + const n = Number(process.env.IDEMPOTENCY_TTL_SECONDS); + return Number.isFinite(n) && n > 0 ? n : DEFAULT_IDEMPOTENCY_TTL_SECONDS; +} + +interface PurgeDb { + prepare(sql: string): { run(...args: unknown[]): { changes: number } }; +} + +/** Delete idempotency keys older than the configured TTL. Returns rows removed. + * The db is injectable for testing; the cron job uses the default. */ +function purgeExpiredIdempotencyKeys( + now: number = Date.now(), + ttlSeconds: number = idempotencyTtlSeconds(), + database: PurgeDb = require('./db/database').db, +): number { + const cutoff = Math.floor(now / 1000) - ttlSeconds; + const result = database.prepare('DELETE FROM idempotency_keys WHERE created_at < ?').run(cutoff); + return result.changes; +} + +function startIdempotencyCleanup(): void { + if (idempotencyCleanupTask) { idempotencyCleanupTask.stop(); idempotencyCleanupTask = null; } + + const tz = process.env.TZ || 'UTC'; + idempotencyCleanupTask = cron.schedule('0 3 * * *', () => { + try { + const removed = purgeExpiredIdempotencyKeys(); + if (removed > 0) { + logInfo(`Idempotency cleanup: removed ${removed} expired key(s)`); + } + } catch (err: unknown) { + logError(`Idempotency cleanup: ${err instanceof Error ? err.message : err}`); + } + }, { timezone: tz }); +} + +// Trek photo cache cleanup: every 2 hours — evict disk files and DB rows past their 1h TTL +let trekPhotoCacheTask: ScheduledTask | null = null; + +function startTrekPhotoCacheCleanup(): void { + if (trekPhotoCacheTask) { trekPhotoCacheTask.stop(); trekPhotoCacheTask = null; } + + // Run once immediately on startup to evict any entries left over from a previous run + try { + const { sweepExpired } = require('./services/memories/trekPhotoCache'); + sweepExpired(); + } catch { /* cache dir may not exist yet — harmless */ } + + trekPhotoCacheTask = cron.schedule('0 */2 * * *', () => { + try { + const { sweepExpired } = require('./services/memories/trekPhotoCache'); + sweepExpired(); + } catch (err: unknown) { + logError(`Trek photo cache cleanup: ${err instanceof Error ? err.message : err}`); + } + }); +} + +// Place-photo (Google/Wikimedia) cache cleanup: nightly — reclaim cached files and +// meta rows no place references anymore (deleted places/trips, overwritten image_url). +let placePhotoCacheTask: ScheduledTask | null = null; + +function startPlacePhotoCacheCleanup(): void { + if (placePhotoCacheTask) { placePhotoCacheTask.stop(); placePhotoCacheTask = null; } + + const sweep = () => { + try { + const { sweepOrphans } = require('./services/placePhotoCache'); + const removed = sweepOrphans(); + if (removed > 0) logInfo(`Place-photo cache cleanup: removed ${removed} orphaned file(s)/row(s)`); + } catch (err: unknown) { + logError(`Place-photo cache cleanup: ${err instanceof Error ? err.message : err}`); + } + }; + + // Run once on startup to reclaim orphans left over from before this sweeper existed. + sweep(); + + const tz = process.env.TZ || 'UTC'; + placePhotoCacheTask = cron.schedule('30 3 * * *', sweep, { timezone: tz }); +} + +// AirTrail sync: poll connected instances on an interval and reconcile linked +// flights both ways (#214). The per-tick enable gate (addon + setting) lives in +// runAirtrailSync, so toggling the addon takes effect without a restart. +let airtrailSyncTask: ScheduledTask | null = null; + +function startAirTrailSync(): void { + if (airtrailSyncTask) { airtrailSyncTask.stop(); airtrailSyncTask = null; } + + const { db } = require('./db/database'); + const getSetting = (key: string) => (db.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as { value: string } | undefined)?.value; + const raw = parseInt(getSetting('airtrail_poll_interval_minutes') || '5', 10); + const minutes = Number.isFinite(raw) && raw >= 1 && raw <= 59 ? raw : 5; + const tz = process.env.TZ || 'UTC'; + logInfo(`AirTrail sync: scheduled every ${minutes}m`); + + airtrailSyncTask = cron.schedule(`*/${minutes} * * * *`, async () => { + try { + const { runAirtrailSync } = require('./services/airtrail/airtrailSync'); + await runAirtrailSync(); + } catch (err: unknown) { + logError(`AirTrail sync tick failed: ${err instanceof Error ? err.message : err}`); + } + }, { timezone: tz }); +} + +function stop(): void { + if (currentTask) { currentTask.stop(); currentTask = null; } + if (demoTask) { demoTask.stop(); demoTask = null; } + if (reminderTask) { reminderTask.stop(); reminderTask = null; } + if (versionCheckTask) { versionCheckTask.stop(); versionCheckTask = null; } + if (idempotencyCleanupTask) { idempotencyCleanupTask.stop(); idempotencyCleanupTask = null; } + if (trekPhotoCacheTask) { trekPhotoCacheTask.stop(); trekPhotoCacheTask = null; } + if (placePhotoCacheTask) { placePhotoCacheTask.stop(); placePhotoCacheTask = null; } + if (airtrailSyncTask) { airtrailSyncTask.stop(); airtrailSyncTask = null; } +} + +export { start, stop, startDemoReset, startTripReminders, startTodoReminders, startVersionCheck, startIdempotencyCleanup, purgeExpiredIdempotencyKeys, startTrekPhotoCacheCleanup, startPlacePhotoCacheCleanup, startAirTrailSync, loadSettings, saveSettings, VALID_INTERVALS }; diff --git a/server/src/services/adminService.ts b/server/src/services/adminService.ts new file mode 100644 index 0000000000000000000000000000000000000000..7cce69c36740185d49f73d449909d9d3d8beabb3 --- /dev/null +++ b/server/src/services/adminService.ts @@ -0,0 +1,780 @@ +import bcrypt from 'bcryptjs'; +import crypto from 'crypto'; +import path from 'path'; +import fs from 'fs'; +import { db } from '../db/database'; +import { User, Addon } from '../types'; +import { updateJwtSecret } from '../config'; +import { maybe_encrypt_api_key, decrypt_api_key } from './apiKeyCrypto'; +import { getAllPermissions, savePermissions as savePerms, PERMISSION_ACTIONS } from './permissions'; +import { revokeUserSessions, revokeUserSessionsForClient } from '../mcp'; +import { deleteUserCompletely } from './userCleanupService'; +import { validatePassword } from './passwordPolicy'; +import { getPhotoProviderConfig } from './memories/helpersService'; +import { send as sendNotification } from './notificationService'; +import { resolveAuthToggles } from './authService'; + +// ── Helpers ──────────────────────────────────────────────────────────────── + +// bcrypt cost factor for user passwords — kept in sync with authService. +const BCRYPT_COST = 12; + +function utcSuffix(ts: string | null | undefined): string | null { + if (!ts) return null; + return ts.endsWith('Z') ? ts : ts.replace(' ', 'T') + 'Z'; +} + +export function compareVersions(a: string, b: string): number { + const parse = (v: string) => { + const [base, pre] = v.split('-pre.'); + const parts = base.split('.').map(Number); + const n = pre !== undefined ? parseInt(pre, 10) : null; + const preN = n !== null && Number.isFinite(n) ? n : null; + return { parts, preN }; + }; + const pa = parse(a), pb = parse(b); + for (let i = 0; i < Math.max(pa.parts.length, pb.parts.length); i++) { + const na = pa.parts[i] || 0, nb = pb.parts[i] || 0; + if (na > nb) return 1; + if (na < nb) return -1; + } + // Equal base: stable > prerelease; higher preN wins among prereleases + if (pa.preN === null && pb.preN !== null) return 1; + if (pa.preN !== null && pb.preN === null) return -1; + if (pa.preN !== null && pb.preN !== null) { + if (pa.preN > pb.preN) return 1; + if (pa.preN < pb.preN) return -1; + } + return 0; +} + +export const isDocker = (() => { + try { + return fs.existsSync('/.dockerenv') || (fs.existsSync('/proc/1/cgroup') && fs.readFileSync('/proc/1/cgroup', 'utf8').includes('docker')); + } catch { return false; } +})(); + +// ── User CRUD ────────────────────────────────────────────────────────────── + +export function listUsers() { + const users = db.prepare( + 'SELECT id, username, email, role, avatar, created_at, updated_at, last_login FROM users ORDER BY created_at DESC' + ).all() as (Pick & { avatar?: string | null })[]; + let onlineUserIds = new Set(); + try { + const { getOnlineUserIds } = require('../websocket'); + onlineUserIds = getOnlineUserIds(); + } catch { /* */ } + return users.map(u => ({ + ...u, + avatar_url: u.avatar ? `/uploads/avatars/${u.avatar}` : null, + created_at: utcSuffix(u.created_at), + updated_at: utcSuffix(u.updated_at as string), + last_login: utcSuffix(u.last_login), + online: onlineUserIds.has(u.id), + })); +} + +export function createUser(data: { username: string; email: string; password: string; role?: string }) { + const username = data.username?.trim(); + const email = data.email?.trim(); + const password = data.password?.trim(); + + if (!username || !email || !password) { + return { error: 'Username, email and password are required', status: 400 }; + } + + const pwCheck = validatePassword(password); + if (!pwCheck.ok) return { error: pwCheck.reason, status: 400 }; + + if (data.role && !['user', 'admin'].includes(data.role)) { + return { error: 'Invalid role', status: 400 }; + } + + const existingUsername = db.prepare('SELECT id FROM users WHERE username = ?').get(username); + if (existingUsername) return { error: 'Username already taken', status: 409 }; + + const existingEmail = db.prepare('SELECT id FROM users WHERE email = ?').get(email); + if (existingEmail) return { error: 'Email already taken', status: 409 }; + + const passwordHash = bcrypt.hashSync(password, BCRYPT_COST); + + const result = db.prepare( + 'INSERT INTO users (username, email, password_hash, role) VALUES (?, ?, ?, ?)' + ).run(username, email, passwordHash, data.role || 'user'); + + const user = db.prepare( + 'SELECT id, username, email, role, created_at, updated_at FROM users WHERE id = ?' + ).get(result.lastInsertRowid); + + return { + user, + insertedId: Number(result.lastInsertRowid), + auditDetails: { username, email, role: data.role || 'user' }, + }; +} + +export function updateUser(id: string, data: { username?: string; email?: string; role?: string; password?: string }) { + const username = typeof data.username === 'string' ? data.username.trim() : data.username; + const email = typeof data.email === 'string' ? data.email.trim() : data.email; + const { role, password } = data; + const user = db.prepare('SELECT * FROM users WHERE id = ?').get(id) as User | undefined; + + if (!user) return { error: 'User not found', status: 404 }; + + if (role && !['user', 'admin'].includes(role)) { + return { error: 'Invalid role', status: 400 }; + } + + if (username && username !== user.username) { + const conflict = db.prepare('SELECT id FROM users WHERE username = ? AND id != ?').get(username, id); + if (conflict) return { error: 'Username already taken', status: 409 }; + } + if (email && email !== user.email) { + const conflict = db.prepare('SELECT id FROM users WHERE email = ? AND id != ?').get(email, id); + if (conflict) return { error: 'Email already taken', status: 409 }; + } + + if (password) { + const pwCheck = validatePassword(password); + if (!pwCheck.ok) return { error: pwCheck.reason, status: 400 }; + } + const passwordHash = password ? bcrypt.hashSync(password, BCRYPT_COST) : null; + + db.prepare(` + UPDATE users SET + username = COALESCE(?, username), + email = COALESCE(?, email), + role = COALESCE(?, role), + password_hash = COALESCE(?, password_hash), + updated_at = CURRENT_TIMESTAMP + WHERE id = ? + `).run(username || null, email || null, role || null, passwordHash, id); + + const updated = db.prepare( + 'SELECT id, username, email, role, created_at, updated_at FROM users WHERE id = ?' + ).get(id); + + const changed: string[] = []; + if (username) changed.push('username'); + if (email) changed.push('email'); + if (role) changed.push('role'); + if (password) changed.push('password'); + + return { + user: updated, + previousEmail: user.email, + changed, + }; +} + +export function deleteUser(id: string, currentUserId: number) { + if (parseInt(id) === currentUserId) { + return { error: 'Cannot delete own account', status: 400 }; + } + + const userToDel = db.prepare('SELECT id, email FROM users WHERE id = ?').get(id) as { id: number; email: string } | undefined; + if (!userToDel) return { error: 'User not found', status: 404 }; + + deleteUserCompletely(userToDel.id); + return { email: userToDel.email }; +} + +// ── Stats ────────────────────────────────────────────────────────────────── + +export function getStats() { + const totalUsers = (db.prepare('SELECT COUNT(*) as count FROM users').get() as { count: number }).count; + const totalTrips = (db.prepare('SELECT COUNT(*) as count FROM trips').get() as { count: number }).count; + const totalPlaces = (db.prepare('SELECT COUNT(*) as count FROM places').get() as { count: number }).count; + const totalFiles = (db.prepare('SELECT COUNT(*) as count FROM trip_files').get() as { count: number }).count; + return { totalUsers, totalTrips, totalPlaces, totalFiles }; +} + +// ── Permissions ──────────────────────────────────────────────────────────── + +export function getPermissions() { + const current = getAllPermissions(); + const actions = PERMISSION_ACTIONS.map(a => ({ + key: a.key, + level: current[a.key], + defaultLevel: a.defaultLevel, + allowedLevels: a.allowedLevels, + })); + return { permissions: actions }; +} + +export function savePermissions(permissions: Record) { + const { skipped } = savePerms(permissions); + return { permissions: getAllPermissions(), skipped }; +} + +// ── Audit Log ────────────────────────────────────────────────────────────── + +export function getAuditLog(query: { limit?: string; offset?: string }) { + const limitRaw = parseInt(String(query.limit || '100'), 10); + const offsetRaw = parseInt(String(query.offset || '0'), 10); + const limit = Math.min(Math.max(Number.isFinite(limitRaw) ? limitRaw : 100, 1), 500); + const offset = Math.max(Number.isFinite(offsetRaw) ? offsetRaw : 0, 0); + + type Row = { + id: number; + created_at: string; + user_id: number | null; + username: string | null; + user_email: string | null; + action: string; + resource: string | null; + details: string | null; + ip: string | null; + }; + + const rows = db.prepare(` + SELECT a.id, a.created_at, a.user_id, u.username, u.email as user_email, a.action, a.resource, a.details, a.ip + FROM audit_log a + LEFT JOIN users u ON u.id = a.user_id + ORDER BY a.id DESC + LIMIT ? OFFSET ? + `).all(limit, offset) as Row[]; + + const total = (db.prepare('SELECT COUNT(*) as c FROM audit_log').get() as { c: number }).c; + + const entries = rows.map((r) => { + let details: Record | null = null; + if (r.details) { + try { + details = JSON.parse(r.details) as Record; + } catch { + details = { _parse_error: true }; + } + } + const created_at = r.created_at && !r.created_at.endsWith('Z') ? r.created_at.replace(' ', 'T') + 'Z' : r.created_at; + return { ...r, created_at, details }; + }); + + return { entries, total, limit, offset }; +} + +// ── OIDC Settings ────────────────────────────────────────────────────────── + +export function getOidcSettings() { + const get = (key: string) => (db.prepare("SELECT value FROM app_settings WHERE key = ?").get(key) as { value: string } | undefined)?.value || ''; + const secret = decrypt_api_key(get('oidc_client_secret')); + return { + issuer: get('oidc_issuer'), + client_id: get('oidc_client_id'), + client_secret_set: !!secret, + display_name: get('oidc_display_name'), + oidc_only: get('oidc_only') === 'true', + discovery_url: get('oidc_discovery_url'), + }; +} + +export function updateOidcSettings(data: { + issuer?: string; + client_id?: string; + client_secret?: string; + display_name?: string; + discovery_url?: string; +}): { error?: string; status?: number; success?: boolean } { + // Lockout prevention: can't remove OIDC config when password login is disabled + if ((data.issuer === '' || data.client_id === '') && !resolveAuthToggles().password_login) { + return { error: 'Cannot remove SSO configuration while password login is disabled. Enable password login first.', status: 400 }; + } + + const set = (key: string, val: string) => db.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)").run(key, val || ''); + set('oidc_issuer', data.issuer ?? ''); + set('oidc_client_id', data.client_id ?? ''); + if (data.client_secret !== undefined) set('oidc_client_secret', maybe_encrypt_api_key(data.client_secret) ?? ''); + set('oidc_display_name', data.display_name ?? ''); + set('oidc_discovery_url', data.discovery_url ?? ''); + return { success: true }; +} + +// ── Demo Baseline ────────────────────────────────────────────────────────── + +export function saveDemoBaseline(): { error?: string; status?: number; message?: string } { + if (process.env.DEMO_MODE?.toLowerCase() !== 'true') { + return { error: 'Not found', status: 404 }; + } + try { + const { saveBaseline } = require('../demo/demo-reset'); + saveBaseline(); + return { message: 'Demo baseline saved. Hourly resets will restore to this state.' }; + } catch (err: unknown) { + console.error(err); + return { error: 'Failed to save baseline', status: 500 }; + } +} + +// ── GitHub Integration ───────────────────────────────────────────────────── + +export async function getGithubReleases(perPage: string = '10', page: string = '1') { + try { + const resp = await fetch( + `https://api.github.com/repos/mauriceboe/TREK/releases?per_page=${perPage}&page=${page}`, + { headers: { 'Accept': 'application/vnd.github.v3+json', 'User-Agent': 'TREK-Server' } } + ); + if (!resp.ok) return []; + const data = await resp.json(); + return Array.isArray(data) ? data : []; + } catch { + return []; + } +} + +interface VersionInfo { + current: string; + latest: string; + update_available: boolean; + release_url?: string; + is_docker: boolean; + is_prerelease: boolean; +} + +const VERSION_CACHE_TTL = 5 * 60 * 1000; // 5 minutes +let _versionCache: { data: VersionInfo; expiresAt: number } | null = null; + +/** Test-only: clear the in-memory version cache. */ +export function __clearVersionCacheForTests(): void { + _versionCache = null; +} + +export async function checkVersion(): Promise { + if (_versionCache && Date.now() < _versionCache.expiresAt) { + return _versionCache.data; + } + + const currentVersion: string = process.env.APP_VERSION || require('../../package.json').version; + const isPrerelease = currentVersion.includes('-pre.'); + const fallback: VersionInfo = { current: currentVersion, latest: currentVersion, update_available: false, is_docker: isDocker, is_prerelease: isPrerelease }; + let result: VersionInfo; + try { + if (isPrerelease) { + // Fetch release list and find the newest prerelease + const resp = await fetch( + 'https://api.github.com/repos/mauriceboe/TREK/releases?per_page=100', + { headers: { 'Accept': 'application/vnd.github.v3+json', 'User-Agent': 'TREK-Server' } } + ); + if (!resp.ok) { + return fallback; + } + const data = await resp.json() as Array<{ tag_name?: string; html_url?: string; prerelease?: boolean }>; + const prereleases = Array.isArray(data) ? data.filter(r => r.prerelease) : []; + if (!prereleases.length) { + return fallback; + } + // Pre-compute stripped versions, then sort descending + const tagged = prereleases.map(r => ({ r, v: (r.tag_name || '').replace(/^v/, '') })); + tagged.sort((a, b) => compareVersions(b.v, a.v)); + const latest = tagged[0].v; + const update_available = !!latest && latest !== currentVersion && compareVersions(latest, currentVersion) > 0; + result = { current: currentVersion, latest, update_available, release_url: tagged[0].r.html_url || '', is_docker: isDocker, is_prerelease: true }; + } else { + const resp = await fetch( + 'https://api.github.com/repos/mauriceboe/TREK/releases/latest', + { headers: { 'Accept': 'application/vnd.github.v3+json', 'User-Agent': 'TREK-Server' } } + ); + if (!resp.ok) { + return fallback; + } + const data = await resp.json() as { tag_name?: string; html_url?: string }; + const latest = (data.tag_name || '').replace(/^v/, ''); + const update_available = !!latest && latest !== currentVersion && compareVersions(latest, currentVersion) > 0; + result = { current: currentVersion, latest, update_available, release_url: data.html_url || '', is_docker: isDocker, is_prerelease: false }; + } + } catch { + return fallback; + } + + _versionCache = { data: result, expiresAt: Date.now() + VERSION_CACHE_TTL }; + return result; +} + +export async function checkAndNotifyVersion(): Promise { + try { + const result = await checkVersion(); + if (!result.update_available) return; + + const lastNotified = (db.prepare('SELECT value FROM app_settings WHERE key = ?').get('last_notified_version') as { value: string } | undefined)?.value; + if (lastNotified === result.latest) return; + + db.prepare('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)').run('last_notified_version', result.latest); + + await sendNotification({ + event: 'version_available', + actorId: null, + scope: 'admin', + targetId: 0, + params: { version: result.latest }, + }); + } catch { + // Silently ignore — version check is non-critical + } +} + +// ── Invite Tokens ────────────────────────────────────────────────────────── + +export function listInvites() { + return db.prepare(` + SELECT i.*, u.username as created_by_name + FROM invite_tokens i + JOIN users u ON i.created_by = u.id + ORDER BY i.created_at DESC + `).all(); +} + +export function createInvite(createdBy: number, data: { max_uses?: string | number; expires_in_days?: string | number }) { + const rawUses = parseInt(String(data.max_uses)); + const uses = rawUses === 0 ? 0 : Math.min(Math.max(rawUses || 1, 1), 5); + const token = crypto.randomBytes(16).toString('hex'); + const expiresAt = data.expires_in_days + ? new Date(Date.now() + parseInt(String(data.expires_in_days)) * 86400000).toISOString() + : null; + + const ins = db.prepare( + 'INSERT INTO invite_tokens (token, max_uses, expires_at, created_by) VALUES (?, ?, ?, ?)' + ).run(token, uses, expiresAt, createdBy); + + const inviteId = Number(ins.lastInsertRowid); + const invite = db.prepare(` + SELECT i.*, u.username as created_by_name + FROM invite_tokens i + JOIN users u ON i.created_by = u.id + WHERE i.id = ? + `).get(inviteId); + + return { invite, inviteId, uses, expiresInDays: data.expires_in_days ?? null }; +} + +export function deleteInvite(id: string) { + const invite = db.prepare('SELECT id FROM invite_tokens WHERE id = ?').get(id); + if (!invite) return { error: 'Invite not found', status: 404 }; + db.prepare('DELETE FROM invite_tokens WHERE id = ?').run(id); + return {}; +} + +// ── Bag Tracking ─────────────────────────────────────────────────────────── + +export function getBagTracking() { + const row = db.prepare("SELECT value FROM app_settings WHERE key = 'bag_tracking_enabled'").get() as { value: string } | undefined; + return { enabled: row?.value === 'true' }; +} + +export function updateBagTracking(enabled: boolean) { + db.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('bag_tracking_enabled', ?)").run(enabled ? 'true' : 'false'); + return { enabled: !!enabled }; +} + +// ── Places Photos ───────────────────────────────────────────────────────── + +export function getPlacesPhotos() { + const row = db.prepare("SELECT value FROM app_settings WHERE key = 'places_photos_enabled'").get() as { value: string } | undefined; + return { enabled: row?.value !== 'false' }; +} + +export function updatePlacesPhotos(enabled: boolean) { + db.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('places_photos_enabled', ?)").run(enabled ? 'true' : 'false'); + return { enabled: !!enabled }; +} + +// ── Places Autocomplete ──────────────────────────────────────────────────── + +export function getPlacesAutocomplete() { + const row = db.prepare("SELECT value FROM app_settings WHERE key = 'places_autocomplete_enabled'").get() as { value: string } | undefined; + return { enabled: row?.value !== 'false' }; +} + +export function updatePlacesAutocomplete(enabled: boolean) { + db.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('places_autocomplete_enabled', ?)").run(enabled ? 'true' : 'false'); + return { enabled: !!enabled }; +} + +// ── Places Details ───────────────────────────────────────────────────────── + +export function getPlacesDetails() { + const row = db.prepare("SELECT value FROM app_settings WHERE key = 'places_details_enabled'").get() as { value: string } | undefined; + return { enabled: row?.value !== 'false' }; +} + +export function updatePlacesDetails(enabled: boolean) { + db.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('places_details_enabled', ?)").run(enabled ? 'true' : 'false'); + return { enabled: !!enabled }; +} + +// ── Collab Features ─────────────────────────────────────────────────────── + +const COLLAB_FEATURE_KEYS = ['collab_chat_enabled', 'collab_notes_enabled', 'collab_polls_enabled', 'collab_whatsnext_enabled'] as const; + +export function getCollabFeatures() { + const rows = db.prepare("SELECT key, value FROM app_settings WHERE key IN ('collab_chat_enabled', 'collab_notes_enabled', 'collab_polls_enabled', 'collab_whatsnext_enabled')").all() as { key: string; value: string }[]; + const map: Record = {}; + for (const r of rows) map[r.key] = r.value; + return { + chat: map['collab_chat_enabled'] !== 'false', + notes: map['collab_notes_enabled'] !== 'false', + polls: map['collab_polls_enabled'] !== 'false', + whatsnext: map['collab_whatsnext_enabled'] !== 'false', + }; +} + +export function updateCollabFeatures(features: { chat?: boolean; notes?: boolean; polls?: boolean; whatsnext?: boolean }) { + const mapping: Record = { chat: 'collab_chat_enabled', notes: 'collab_notes_enabled', polls: 'collab_polls_enabled', whatsnext: 'collab_whatsnext_enabled' }; + const stmt = db.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)"); + for (const [feat, key] of Object.entries(mapping)) { + if (features[feat] !== undefined) stmt.run(key, features[feat] ? 'true' : 'false'); + } + return getCollabFeatures(); +} + +// ── Packing Templates ────────────────────────────────────────────────────── + +export function listPackingTemplates() { + return db.prepare(` + SELECT pt.*, u.username as created_by_name, + (SELECT COUNT(*) FROM packing_template_items ti JOIN packing_template_categories tc ON ti.category_id = tc.id WHERE tc.template_id = pt.id) as item_count, + (SELECT COUNT(*) FROM packing_template_categories WHERE template_id = pt.id) as category_count + FROM packing_templates pt + JOIN users u ON pt.created_by = u.id + ORDER BY pt.created_at DESC + `).all(); +} + +export function getPackingTemplate(id: string) { + const template = db.prepare('SELECT * FROM packing_templates WHERE id = ?').get(id); + if (!template) return { error: 'Template not found', status: 404 }; + const categories = db.prepare('SELECT * FROM packing_template_categories WHERE template_id = ? ORDER BY sort_order, id').all(id) as any[]; + const items = db.prepare(` + SELECT ti.* FROM packing_template_items ti + JOIN packing_template_categories tc ON ti.category_id = tc.id + WHERE tc.template_id = ? ORDER BY ti.sort_order, ti.id + `).all(id); + return { template, categories, items }; +} + +export function createPackingTemplate(name: string, createdBy: number) { + if (!name?.trim()) return { error: 'Name is required', status: 400 }; + const result = db.prepare('INSERT INTO packing_templates (name, created_by) VALUES (?, ?)').run(name.trim(), createdBy); + const template = db.prepare('SELECT * FROM packing_templates WHERE id = ?').get(result.lastInsertRowid); + return { template }; +} + +export function updatePackingTemplate(id: string, data: { name?: string }) { + const template = db.prepare('SELECT * FROM packing_templates WHERE id = ?').get(id); + if (!template) return { error: 'Template not found', status: 404 }; + if (data.name?.trim()) db.prepare('UPDATE packing_templates SET name = ? WHERE id = ?').run(data.name.trim(), id); + return { template: db.prepare('SELECT * FROM packing_templates WHERE id = ?').get(id) }; +} + +export function deletePackingTemplate(id: string) { + const template = db.prepare('SELECT * FROM packing_templates WHERE id = ?').get(id) as { name?: string } | undefined; + if (!template) return { error: 'Template not found', status: 404 }; + db.prepare('DELETE FROM packing_templates WHERE id = ?').run(id); + return { name: template.name }; +} + +// Template categories + +export function createTemplateCategory(templateId: string, name: string) { + if (!name?.trim()) return { error: 'Category name is required', status: 400 }; + const template = db.prepare('SELECT * FROM packing_templates WHERE id = ?').get(templateId); + if (!template) return { error: 'Template not found', status: 404 }; + const maxOrder = db.prepare('SELECT MAX(sort_order) as max FROM packing_template_categories WHERE template_id = ?').get(templateId) as { max: number | null }; + const result = db.prepare('INSERT INTO packing_template_categories (template_id, name, sort_order) VALUES (?, ?, ?)').run(templateId, name.trim(), (maxOrder.max ?? -1) + 1); + return { category: db.prepare('SELECT * FROM packing_template_categories WHERE id = ?').get(result.lastInsertRowid) }; +} + +export function updateTemplateCategory(templateId: string, catId: string, data: { name?: string }) { + const cat = db.prepare('SELECT * FROM packing_template_categories WHERE id = ? AND template_id = ?').get(catId, templateId); + if (!cat) return { error: 'Category not found', status: 404 }; + if (data.name?.trim()) db.prepare('UPDATE packing_template_categories SET name = ? WHERE id = ?').run(data.name.trim(), catId); + return { category: db.prepare('SELECT * FROM packing_template_categories WHERE id = ?').get(catId) }; +} + +export function deleteTemplateCategory(templateId: string, catId: string) { + const cat = db.prepare('SELECT * FROM packing_template_categories WHERE id = ? AND template_id = ?').get(catId, templateId); + if (!cat) return { error: 'Category not found', status: 404 }; + db.prepare('DELETE FROM packing_template_categories WHERE id = ?').run(catId); + return {}; +} + +// Template items + +export function createTemplateItem(templateId: string, catId: string, name: string) { + if (!name?.trim()) return { error: 'Item name is required', status: 400 }; + const cat = db.prepare('SELECT * FROM packing_template_categories WHERE id = ? AND template_id = ?').get(catId, templateId); + if (!cat) return { error: 'Category not found', status: 404 }; + const maxOrder = db.prepare('SELECT MAX(sort_order) as max FROM packing_template_items WHERE category_id = ?').get(catId) as { max: number | null }; + const result = db.prepare('INSERT INTO packing_template_items (category_id, name, sort_order) VALUES (?, ?, ?)').run(catId, name.trim(), (maxOrder.max ?? -1) + 1); + return { item: db.prepare('SELECT * FROM packing_template_items WHERE id = ?').get(result.lastInsertRowid) }; +} + +export function updateTemplateItem(itemId: string, data: { name?: string }) { + const item = db.prepare('SELECT * FROM packing_template_items WHERE id = ?').get(itemId); + if (!item) return { error: 'Item not found', status: 404 }; + if (data.name?.trim()) db.prepare('UPDATE packing_template_items SET name = ? WHERE id = ?').run(data.name.trim(), itemId); + return { item: db.prepare('SELECT * FROM packing_template_items WHERE id = ?').get(itemId) }; +} + +export function deleteTemplateItem(itemId: string) { + const item = db.prepare('SELECT * FROM packing_template_items WHERE id = ?').get(itemId); + if (!item) return { error: 'Item not found', status: 404 }; + db.prepare('DELETE FROM packing_template_items WHERE id = ?').run(itemId); + return {}; +} + +// ── Addons ───────────────────────────────────────────────────────────────── + +export function isAddonEnabled(addonId: string): boolean { + const addon = db.prepare('SELECT enabled FROM addons WHERE id = ?').get(addonId) as { enabled: number } | undefined; + return !!addon?.enabled; +} + +export function listAddons() { + const addons = db.prepare('SELECT * FROM addons ORDER BY sort_order, id').all() as Addon[]; + const providers = db.prepare(` + SELECT id, name, description, icon, enabled, sort_order + FROM photo_providers + ORDER BY sort_order, id + `).all() as Array<{ id: string; name: string; description?: string | null; icon: string; enabled: number; sort_order: number }>; + const fields = db.prepare(` + SELECT provider_id, field_key, label, input_type, placeholder, required, secret, settings_key, payload_key, sort_order + FROM photo_provider_fields + ORDER BY sort_order, id + `).all() as Array<{ + provider_id: string; + field_key: string; + label: string; + input_type: string; + placeholder?: string | null; + required: number; + secret: number; + settings_key?: string | null; + payload_key?: string | null; + sort_order: number; + }>; + const fieldsByProvider = new Map(); + for (const field of fields) { + const arr = fieldsByProvider.get(field.provider_id) || []; + arr.push(field); + fieldsByProvider.set(field.provider_id, arr); + } + + return [ + ...addons.map(a => ({ ...a, enabled: !!a.enabled, config: JSON.parse(a.config || '{}') })), + ...providers.map(p => ({ + id: p.id, + name: p.name, + description: p.description, + type: 'photo_provider', + icon: p.icon, + enabled: !!p.enabled, + config: getPhotoProviderConfig(p.id), + fields: (fieldsByProvider.get(p.id) || []).map(f => ({ + key: f.field_key, + label: f.label, + input_type: f.input_type, + placeholder: f.placeholder || '', + required: !!f.required, + secret: !!f.secret, + settings_key: f.settings_key || null, + payload_key: f.payload_key || null, + sort_order: f.sort_order, + })), + sort_order: p.sort_order, + })), + ]; +} + +export function updateAddon(id: string, data: { enabled?: boolean; config?: Record }) { + const addon = db.prepare('SELECT * FROM addons WHERE id = ?').get(id) as Addon | undefined; + const provider = db.prepare('SELECT * FROM photo_providers WHERE id = ?').get(id) as { id: string; name: string; description?: string | null; icon: string; enabled: number; sort_order: number } | undefined; + if (!addon && !provider) return { error: 'Addon not found', status: 404 }; + + if (addon) { + if (data.enabled !== undefined) db.prepare('UPDATE addons SET enabled = ? WHERE id = ?').run(data.enabled ? 1 : 0, id); + if (data.config !== undefined) db.prepare('UPDATE addons SET config = ? WHERE id = ?').run(JSON.stringify(data.config), id); + } else { + if (data.enabled !== undefined) db.prepare('UPDATE photo_providers SET enabled = ? WHERE id = ?').run(data.enabled ? 1 : 0, id); + } + + const updatedAddon = db.prepare('SELECT * FROM addons WHERE id = ?').get(id) as Addon | undefined; + const updatedProvider = db.prepare('SELECT * FROM photo_providers WHERE id = ?').get(id) as { id: string; name: string; description?: string | null; icon: string; enabled: number; sort_order: number } | undefined; + const updated = updatedAddon + ? { ...updatedAddon, enabled: !!updatedAddon.enabled, config: JSON.parse(updatedAddon.config || '{}') } + : updatedProvider + ? { + id: updatedProvider.id, + name: updatedProvider.name, + description: updatedProvider.description, + type: 'photo_provider', + icon: updatedProvider.icon, + enabled: !!updatedProvider.enabled, + config: getPhotoProviderConfig(updatedProvider.id), + sort_order: updatedProvider.sort_order, + } + : null; + + return { + addon: updated, + auditDetails: { enabled: data.enabled !== undefined ? !!data.enabled : undefined, config_changed: data.config !== undefined }, + }; +} + +// ── MCP Tokens ───────────────────────────────────────────────────────────── + +export function listMcpTokens() { + return db.prepare(` + SELECT t.id, t.name, t.token_prefix, t.created_at, t.last_used_at, t.user_id, u.username + FROM mcp_tokens t + JOIN users u ON u.id = t.user_id + ORDER BY t.created_at DESC + `).all(); +} + +export function deleteMcpToken(id: string) { + const token = db.prepare('SELECT id, user_id FROM mcp_tokens WHERE id = ?').get(id) as { id: number; user_id: number } | undefined; + if (!token) return { error: 'Token not found', status: 404 }; + db.prepare('DELETE FROM mcp_tokens WHERE id = ?').run(id); + revokeUserSessions(token.user_id); + return {}; +} + +// ── OAuth Sessions ───────────────────────────────────────────────────────── + +export function listOAuthSessions() { + const rows = db.prepare(` + SELECT ot.id, ot.client_id, oc.name AS client_name, ot.user_id, u.username, + ot.scopes, ot.access_token_expires_at, ot.refresh_token_expires_at, ot.created_at + FROM oauth_tokens ot + JOIN oauth_clients oc ON ot.client_id = oc.client_id + JOIN users u ON u.id = ot.user_id + WHERE ot.revoked_at IS NULL + AND ot.refresh_token_expires_at > CURRENT_TIMESTAMP + ORDER BY ot.created_at DESC + `).all() as (Record & { scopes: string })[]; + return rows.map(r => ({ ...r, scopes: JSON.parse(r.scopes) })); +} + +export function revokeOAuthSession(id: string) { + const row = db.prepare('SELECT id, user_id, client_id FROM oauth_tokens WHERE id = ?').get(id) as { id: number; user_id: number; client_id: string } | undefined; + if (!row) return { error: 'Session not found', status: 404 }; + db.prepare('UPDATE oauth_tokens SET revoked_at = CURRENT_TIMESTAMP WHERE id = ?').run(id); + revokeUserSessionsForClient(row.user_id, row.client_id); + return {}; +} + +// ── JWT Rotation ─────────────────────────────────────────────────────────── + +export function rotateJwtSecret(): { error?: string; status?: number } { + const newSecret = crypto.randomBytes(32).toString('hex'); + const dataDir = path.resolve(__dirname, '../../data'); + const secretFile = path.join(dataDir, '.jwt_secret'); + try { + if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true }); + fs.writeFileSync(secretFile, newSecret, { mode: 0o600 }); + } catch (err: unknown) { + return { error: 'Failed to persist new JWT secret to disk', status: 500 }; + } + updateJwtSecret(newSecret); + return {}; +} diff --git a/server/src/services/airportService.ts b/server/src/services/airportService.ts new file mode 100644 index 0000000000000000000000000000000000000000..a5745d31bb66915f67220006995c5c8ecdbee3e0 --- /dev/null +++ b/server/src/services/airportService.ts @@ -0,0 +1,109 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { db } from '../db/database'; + +export interface Airport { + iata: string; + icao: string | null; + name: string; + city: string; + country: string; + lat: number; + lng: number; + tz: string; +} + +let cache: Airport[] | null = null; +let byIata: Map | null = null; + +function load(): Airport[] { + if (cache) return cache; + const file = path.join(__dirname, '..', '..', 'assets', 'airports.json'); + if (!fs.existsSync(file)) { + console.warn('[airports] airports.json missing — run `node scripts/build-airports.mjs`'); + cache = []; + byIata = new Map(); + return cache; + } + const raw = fs.readFileSync(file, 'utf8'); + cache = JSON.parse(raw) as Airport[]; + byIata = new Map(cache.map(a => [a.iata, a])); + return cache; +} + +export function findByIata(code: string): Airport | null { + load(); + return byIata!.get(code.toUpperCase()) ?? null; +} + +export function searchAirports(query: string, limit = 12): Airport[] { + const all = load(); + const q = query.trim().toLowerCase(); + if (!q) return []; + + const upper = q.toUpperCase(); + if (q.length === 3) { + const exact = byIata!.get(upper); + if (exact) return [exact]; + } + + const matches: Array<{ a: Airport; score: number }> = []; + for (const a of all) { + let score = 0; + if (a.iata === upper) score = 100; + else if (a.icao === upper) score = 90; + else if (a.iata.startsWith(upper)) score = 70; + else if (a.city.toLowerCase().startsWith(q)) score = 60; + else if (a.name.toLowerCase().startsWith(q)) score = 50; + else if (a.city.toLowerCase().includes(q)) score = 30; + else if (a.name.toLowerCase().includes(q)) score = 20; + if (score > 0) matches.push({ a, score }); + } + matches.sort((x, y) => y.score - x.score || x.a.iata.localeCompare(y.a.iata)); + return matches.slice(0, limit).map(m => m.a); +} + +export function backfillFlightEndpoints(): void { + const pending = db.prepare(` + SELECT r.id, r.metadata, r.reservation_time, r.reservation_end_time + FROM reservations r + WHERE r.type = 'flight' + AND NOT EXISTS (SELECT 1 FROM reservation_endpoints e WHERE e.reservation_id = r.id) + `).all() as { id: number; metadata: string | null; reservation_time: string | null; reservation_end_time: string | null }[]; + + if (pending.length === 0) return; + + load(); + const insert = db.prepare(` + INSERT INTO reservation_endpoints (reservation_id, role, sequence, name, code, lat, lng, timezone, local_time, local_date) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `); + const markReview = db.prepare('UPDATE reservations SET needs_review = 1 WHERE id = ?'); + + let filled = 0; + let flagged = 0; + for (const r of pending) { + if (!r.metadata) { markReview.run(r.id); flagged++; continue; } + let meta: any; + try { meta = JSON.parse(r.metadata); } catch { markReview.run(r.id); flagged++; continue; } + + const dep = meta.departure_airport ? findByIata(String(meta.departure_airport).slice(0, 3)) : null; + const arr = meta.arrival_airport ? findByIata(String(meta.arrival_airport).slice(0, 3)) : null; + + if (!dep || !arr) { markReview.run(r.id); flagged++; continue; } + + const split = (iso: string | null) => { + if (!iso) return { date: null as string | null, time: null as string | null }; + const [date, time] = iso.split('T'); + return { date: date || null, time: time ? time.slice(0, 5) : null }; + }; + const depParts = split(r.reservation_time); + const arrParts = split(r.reservation_end_time); + + insert.run(r.id, 'from', 0, dep.city ? `${dep.city} (${dep.iata})` : dep.name, dep.iata, dep.lat, dep.lng, dep.tz, depParts.time, depParts.date); + insert.run(r.id, 'to', 1, arr.city ? `${arr.city} (${arr.iata})` : arr.name, arr.iata, arr.lat, arr.lng, arr.tz, arrParts.time, arrParts.date); + filled++; + } + + console.log(`[airports] Backfill: ${filled} filled, ${flagged} flagged for review`); +} diff --git a/server/src/services/airtrail/airtrailClient.ts b/server/src/services/airtrail/airtrailClient.ts new file mode 100644 index 0000000000000000000000000000000000000000..fbab295acadbdd0eb25329b76fa99332066d9470 --- /dev/null +++ b/server/src/services/airtrail/airtrailClient.ts @@ -0,0 +1,197 @@ +import { safeFetch } from '../../utils/ssrfGuard'; + +/** + * Thin HTTP client for the AirTrail REST API (github.com/johanohly/AirTrail). + * This is the ONLY place that talks to a user's AirTrail instance. + * + * Verified against AirTrail source: + * - Auth: `Authorization: Bearer `; a key maps to exactly one user. + * - GET /api/flight/list — defaults to scope=mine. We NEVER send a scope + * param so the key only ever returns its owner's own flights (isolation + * holds even if an admin key is pasted). + * - GET /api/flight/get/{id} + * - POST /api/flight/save — `id` present => update, else create. seats[] is + * required (>=1). A seat with userId '' is attributed to the key + * owner server-side, so we never need the caller's AirTrail user id. + * - There is no webhook and no updated_at on a flight, so change detection is + * snapshot-hash based (see airtrailSync). + */ + +const TIMEOUT_MS = 12000; + +export interface AirtrailCreds { + /** Instance origin without a trailing /api. */ + baseUrl: string; + apiKey: string; + allowInsecureTls: boolean; +} + +export class AirtrailAuthError extends Error { + constructor(message = 'AirTrail rejected the API key') { + super(message); + this.name = 'AirtrailAuthError'; + } +} + +export class AirtrailRequestError extends Error { + status?: number; + constructor(message: string, status?: number) { + super(message); + this.name = 'AirtrailRequestError'; + this.status = status; + } +} + +export interface AirtrailAirport { + id: number; + icao: string | null; + iata: string | null; + name: string | null; + lat: number | null; + lon: number | null; + tz: string | null; + country: string | null; +} + +export interface AirtrailSeat { + userId: string | null; + guestName: string | null; + seat: string | null; + seatNumber: string | null; + seatClass: string | null; +} + +/** Airline/aircraft come back as joined objects (not bare codes) on a flight. */ +export interface AirtrailNamedCode { + id?: number; + icao?: string | null; + iata?: string | null; + name?: string | null; +} + +/** A flight as returned by list/get (the fields TREK consumes). */ +export interface AirtrailFlightRaw { + id: number; + from: AirtrailAirport | null; + to: AirtrailAirport | null; + date: string | null; + datePrecision: string | null; + departure: string | null; + arrival: string | null; + airline: AirtrailNamedCode | null; + flightNumber: string | null; + aircraft: AirtrailNamedCode | null; + aircraftReg: string | null; + flightReason: string | null; + note: string | null; + seats: AirtrailSeat[]; +} + +/** Write shape accepted by POST /flight/save (airports/airline/aircraft as codes). */ +export interface AirtrailSavePayload { + id?: number; + from: string; + to: string; + departure: string; + departureTime?: string | null; + arrival?: string | null; + arrivalTime?: string | null; + datePrecision?: string; + airline?: string | null; + flightNumber?: string | null; + aircraft?: string | null; + aircraftReg?: string | null; + flightReason?: string | null; + note?: string | null; + seats: Array<{ + userId: string | null; + guestName: string | null; + seat: string | null; + seatNumber: string | null; + seatClass: string | null; + }>; +} + +function apiBase(baseUrl: string): string { + // Tolerate a pasted trailing slash or '/api' suffix so we never build '/api/api'. + const origin = baseUrl.trim().replace(/\/+$/, '').replace(/\/api$/i, ''); + return origin + '/api'; +} + +/** + * Parse a response as JSON, but turn the cryptic "Unexpected token '<'" that a + * misconfigured URL produces (AirTrail serving its SPA / an auth-proxy login + * page) into an actionable message. + */ +async function parseJson(resp: Response): Promise { + const text = await resp.text(); + try { + return JSON.parse(text) as T; + } catch { + throw new AirtrailRequestError( + 'AirTrail returned a non-JSON response. Check the URL is your AirTrail base URL (e.g. https://airtrail.example.com, without /api) and that the instance is reachable without a separate login.', + ); + } +} + +async function request(creds: AirtrailCreds, path: string, init: RequestInit): Promise { + const url = apiBase(creds.baseUrl) + path; + let resp: Response; + try { + resp = await safeFetch( + url, + { + ...init, + headers: { + Authorization: `Bearer ${creds.apiKey}`, + Accept: 'application/json', + ...(init.headers || {}), + }, + signal: AbortSignal.timeout(TIMEOUT_MS) as any, + }, + { rejectUnauthorized: !creds.allowInsecureTls }, + ); + } catch (err: unknown) { + throw new AirtrailRequestError(err instanceof Error ? err.message : 'Could not reach AirTrail'); + } + if (resp.status === 401 || resp.status === 403) { + throw new AirtrailAuthError(); + } + return resp; +} + +export async function listFlights(creds: AirtrailCreds): Promise { + const resp = await request(creds, '/flight/list', { method: 'GET' }); + if (!resp.ok) throw new AirtrailRequestError(`AirTrail list failed (HTTP ${resp.status})`, resp.status); + const data = await parseJson<{ flights?: AirtrailFlightRaw[] }>(resp); + return data.flights ?? []; +} + +export async function getFlight(creds: AirtrailCreds, id: number): Promise { + const resp = await request(creds, `/flight/get/${id}`, { method: 'GET' }); + if (resp.status === 404) return null; + if (!resp.ok) throw new AirtrailRequestError(`AirTrail get failed (HTTP ${resp.status})`, resp.status); + const data = await parseJson<{ flight?: AirtrailFlightRaw }>(resp); + return data.flight ?? null; +} + +export async function saveFlight(creds: AirtrailCreds, payload: AirtrailSavePayload): Promise<{ id?: number }> { + const resp = await request(creds, '/flight/save', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload), + }); + if (!resp.ok) { + let msg = `AirTrail save failed (HTTP ${resp.status})`; + try { + const body = (await resp.json()) as { message?: string; errors?: unknown }; + if (body?.message) msg = body.message; + else if (body?.errors) msg = JSON.stringify(body.errors); + } catch { + /* keep the generic message */ + } + throw new AirtrailRequestError(msg, resp.status); + } + const data = await parseJson<{ id?: number }>(resp); + return { id: data.id }; +} diff --git a/server/src/services/airtrail/airtrailImport.ts b/server/src/services/airtrail/airtrailImport.ts new file mode 100644 index 0000000000000000000000000000000000000000..d6b387a3eecaf8f0eef50e83fa1564c18c6866a5 --- /dev/null +++ b/server/src/services/airtrail/airtrailImport.ts @@ -0,0 +1,132 @@ +import type { AirtrailImportResult } from '@trek/shared'; +import { db } from '../../db/database'; +import { broadcast } from '../../websocket'; +import { createReservation } from '../reservationService'; +import { getAirtrailCredentials } from './airtrailService'; +import { AirtrailRequestError, listFlights } from './airtrailClient'; +import { canonicalHash, mapFlightToReservation } from './airtrailMapper'; + +interface ExistingFlightRow { + id: number; + reservation_time: string | null; + metadata: string | null; + from_code: string | null; + to_code: string | null; +} + +function depDate(t: string | null): string | null { + return t && /^\d{4}-\d{2}-\d{2}/.test(t) ? t.slice(0, 10) : null; +} + +/** A loose "same physical flight" key: flight number + date, else route + date. */ +function softSignature( + date: string | null, + flightNumber: string | null, + fromCode: string | null, + toCode: string | null, +): string | null { + if (!date) return null; + if (flightNumber) return `fn:${flightNumber.toUpperCase()}@${date}`; + if (fromCode && toCode) return `rt:${fromCode.toUpperCase()}-${toCode.toUpperCase()}@${date}`; + return null; +} + +/** + * Import the given AirTrail flights into a trip as reservations (type:'flight'), + * recording the AirTrail linkage for two-way sync and broadcasting each one live. + * + * Dedup: a flight already linked to this trip is skipped ('already-imported'); a + * flight that looks like one already in the trip — e.g. the same flight another + * member already imported from their own AirTrail — is skipped ('already-in-trip'). + * The server re-fetches the flights by id with the caller's own key, so the client + * cannot inject arbitrary flight data. + */ +export async function importAirtrailFlights( + tripId: string | number, + userId: number, + flightIds: string[], + socketId: string | undefined, +): Promise { + const creds = getAirtrailCredentials(userId); + if (!creds) throw new AirtrailRequestError('AirTrail is not connected', 400); + + const wanted = new Set(flightIds.map(String)); + const selected = (await listFlights(creds)).filter(f => wanted.has(String(f.id))); + + const result: AirtrailImportResult = { imported: [], skipped: [] }; + + const linkedIds = new Set( + (db.prepare("SELECT external_id FROM reservations WHERE trip_id = ? AND external_source = 'airtrail'").all(tripId) as { + external_id: string | null; + }[]) + .map(r => r.external_id) + .filter((v): v is string => !!v), + ); + + const existing = db + .prepare( + `SELECT r.id, r.reservation_time, r.metadata, + (SELECT code FROM reservation_endpoints WHERE reservation_id = r.id AND role = 'from' LIMIT 1) AS from_code, + (SELECT code FROM reservation_endpoints WHERE reservation_id = r.id AND role = 'to' LIMIT 1) AS to_code + FROM reservations r WHERE r.trip_id = ? AND r.type = 'flight'`, + ) + .all(tripId) as ExistingFlightRow[]; + + const existingSigs = new Set(); + for (const row of existing) { + let fn: string | null = null; + try { + fn = row.metadata ? (JSON.parse(row.metadata).flight_number ?? null) : null; + } catch { + /* malformed metadata — ignore */ + } + const sig = softSignature(depDate(row.reservation_time), fn, row.from_code, row.to_code); + if (sig) existingSigs.add(sig); + } + + for (const flight of selected) { + const fid = String(flight.id); + if (linkedIds.has(fid)) { + result.skipped.push({ flightId: fid, reason: 'already-imported' }); + continue; + } + + const mapped = mapFlightToReservation(flight); + const sig = softSignature( + depDate(mapped.reservation_time), + (mapped.metadata.flight_number as string) ?? null, + mapped.endpoints.find(e => e.role === 'from')?.code ?? null, + mapped.endpoints.find(e => e.role === 'to')?.code ?? null, + ); + if (sig && existingSigs.has(sig)) { + result.skipped.push({ flightId: fid, reason: 'already-in-trip', detail: mapped.title }); + continue; + } + + try { + const { reservation } = createReservation(tripId, mapped as any); + const now = new Date().toISOString(); + db.prepare( + `UPDATE reservations SET external_source = 'airtrail', external_id = ?, external_owner_user_id = ?, + sync_enabled = 1, external_hash = ?, external_synced_at = ? WHERE id = ?`, + ).run(fid, userId, canonicalHash(flight), now, reservation.id); + + // Carry the linkage on the broadcast payload so members see the badge live. + reservation.external_source = 'airtrail'; + reservation.external_id = fid; + reservation.external_owner_user_id = userId; + reservation.sync_enabled = 1; + reservation.external_synced_at = now; + + broadcast(tripId, 'reservation:created', { reservation }, socketId); + if (sig) existingSigs.add(sig); + linkedIds.add(fid); + result.imported.push(fid); + } catch (err) { + console.error('[airtrail-import] failed to import flight', fid, err instanceof Error ? err.message : err); + result.skipped.push({ flightId: fid, reason: 'invalid', detail: err instanceof Error ? err.message : undefined }); + } + } + + return result; +} diff --git a/server/src/services/airtrail/airtrailMapper.ts b/server/src/services/airtrail/airtrailMapper.ts new file mode 100644 index 0000000000000000000000000000000000000000..392e31e1a51066856c318e01468497f2492b4f17 --- /dev/null +++ b/server/src/services/airtrail/airtrailMapper.ts @@ -0,0 +1,200 @@ +import * as crypto from 'node:crypto'; +import type { AirtrailAirport, AirtrailFlightRaw, AirtrailNamedCode } from './airtrailClient'; +import type { AirtrailFlight } from '@trek/shared'; + +/** Preferred display/lookup code for an airport. */ +function airportCode(a: AirtrailAirport | null): string | null { + return a?.iata || a?.icao || null; +} + +/** + * Airline/aircraft arrive as joined objects ({icao, iata, name, ...}); reduce + * them to a single code (ICAO preferred, matching AirTrail's save shape). + */ +function entityCode(e: AirtrailNamedCode | null | undefined): string | null { + return e?.icao || e?.iata || null; +} + +/** + * Local calendar date + clock time for an instant at a given IANA zone. + * AirTrail stores `departure`/`arrival` as instants (ISO w/ offset) plus a local + * `date`; the airport-local wall time is what TREK shows and files days by. + */ +function localParts(iso: string | null, tz: string | null): { date: string | null; time: string | null } { + if (!iso) return { date: null, time: null }; + try { + const d = new Date(iso); + if (isNaN(d.getTime())) return { date: null, time: null }; + const fmt = new Intl.DateTimeFormat('en-CA', { + timeZone: tz || 'UTC', + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + hour12: false, + }); + const parts = fmt.formatToParts(d); + const get = (t: string) => parts.find(p => p.type === t)?.value ?? ''; + const date = `${get('year')}-${get('month')}-${get('day')}`; + let hh = get('hour'); + if (hh === '24') hh = '00'; // some ICU builds emit 24:00 for midnight + const time = `${hh}:${get('minute')}`; + return { date: /^\d{4}-\d{2}-\d{2}$/.test(date) ? date : null, time }; + } catch { + return { date: null, time: null }; + } +} + +/** Raw AirTrail flight → the normalized shape the import picker consumes. */ +export function normalizeFlight(raw: AirtrailFlightRaw): AirtrailFlight { + return { + id: String(raw.id), + fromCode: airportCode(raw.from), + fromName: raw.from?.name ?? null, + toCode: airportCode(raw.to), + toName: raw.to?.name ?? null, + date: raw.date ?? null, + departure: raw.departure ?? null, + arrival: raw.arrival ?? null, + airline: entityCode(raw.airline), + flightNumber: raw.flightNumber ?? null, + aircraft: entityCode(raw.aircraft), + seatClass: (raw.seats?.find(s => s.userId) ?? raw.seats?.[0])?.seatClass ?? null, + }; +} + +export interface MappedEndpoint { + role: 'from' | 'to' | 'stop'; + sequence: number; + name: string; + code: string | null; + lat: number; + lng: number; + timezone: string | null; + local_time: string | null; + local_date: string | null; +} + +export interface MappedReservation { + title: string; + type: 'flight'; + status: 'confirmed'; + reservation_time: string | null; + reservation_end_time: string | null; + notes: string | null; + metadata: Record; + endpoints: MappedEndpoint[]; + needs_review: number; +} + +function hasCoords(a: AirtrailAirport | null): a is AirtrailAirport & { lat: number; lng: number } { + return !!a && typeof a.lat === 'number' && typeof a.lon === 'number'; +} + +/** Raw AirTrail flight → the data createReservation() expects (type:'flight'). */ +export function mapFlightToReservation(raw: AirtrailFlightRaw): MappedReservation { + const dep = localParts(raw.departure, raw.from?.tz ?? null); + const arr = localParts(raw.arrival, raw.to?.tz ?? null); + + const fromCode = airportCode(raw.from); + const toCode = airportCode(raw.to); + const datePrefix = raw.date || dep.date; + const reservation_time = datePrefix ? `${datePrefix}T${dep.time ?? '00:00'}` : null; + const reservation_end_time = arr.date ? `${arr.date}T${arr.time ?? '00:00'}` : null; + + const endpoints: MappedEndpoint[] = []; + let needsReview = raw.datePrecision && raw.datePrecision !== 'day' ? 1 : 0; + + if (hasCoords(raw.from)) { + endpoints.push({ + role: 'from', + sequence: 0, + name: raw.from.name || fromCode || 'Departure', + code: fromCode, + lat: raw.from.lat, + lng: raw.from.lon, + timezone: raw.from.tz, + local_time: dep.time, + local_date: datePrefix, + }); + } else { + needsReview = 1; + } + + if (hasCoords(raw.to)) { + endpoints.push({ + role: 'to', + sequence: 1, + name: raw.to.name || toCode || 'Arrival', + code: toCode, + lat: raw.to.lat, + lng: raw.to.lon, + timezone: raw.to.tz, + local_time: arr.time, + local_date: arr.date, + }); + } else { + needsReview = 1; + } + + const seat = raw.seats?.find(s => s.userId) ?? raw.seats?.[0]; + const airlineCode = entityCode(raw.airline); + const aircraftCode = entityCode(raw.aircraft); + const metadata: Record = {}; + if (airlineCode) metadata.airline = airlineCode; + if (raw.flightNumber) metadata.flight_number = raw.flightNumber; + if (aircraftCode) metadata.aircraft = aircraftCode; + if (raw.aircraftReg) metadata.aircraft_reg = raw.aircraftReg; + if (raw.flightReason) metadata.flight_reason = raw.flightReason; + if (seat?.seatNumber || seat?.seatClass) metadata.seat = seat.seatNumber || seat.seatClass; + + // The flight number already carries the airline prefix (e.g. "SAS983"), so it + // makes the clearest title; fall back to the route. + const title = raw.flightNumber?.trim() || `${fromCode || '?'} → ${toCode || '?'}`; + + return { + title, + type: 'flight', + status: 'confirmed', + reservation_time, + reservation_end_time, + notes: raw.note ?? null, + metadata, + endpoints, + needs_review: needsReview, + }; +} + +/** + * Stable snapshot hash of an AirTrail flight, used by the sync engine to detect + * remote changes (AirTrail exposes no updated_at/etag) and to suppress TREK's own + * writes from re-triggering a pull. Only fields that can meaningfully change are + * included, in a fixed key order. + */ +export function canonicalHash(raw: AirtrailFlightRaw): string { + const snapshot = { + from: airportCode(raw.from), + to: airportCode(raw.to), + date: raw.date ?? null, + datePrecision: raw.datePrecision ?? 'day', + departure: raw.departure ?? null, + arrival: raw.arrival ?? null, + airline: entityCode(raw.airline), + flightNumber: raw.flightNumber ?? null, + aircraft: entityCode(raw.aircraft), + aircraftReg: raw.aircraftReg ?? null, + flightReason: raw.flightReason ?? null, + note: raw.note ?? null, + seats: (raw.seats ?? []) + .map(s => ({ + userId: s.userId ?? null, + guestName: s.guestName ?? null, + seat: s.seat ?? null, + seatNumber: s.seatNumber ?? null, + seatClass: s.seatClass ?? null, + })) + .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))), + }; + return crypto.createHash('sha256').update(JSON.stringify(snapshot)).digest('hex'); +} diff --git a/server/src/services/airtrail/airtrailService.ts b/server/src/services/airtrail/airtrailService.ts new file mode 100644 index 0000000000000000000000000000000000000000..f4ed626477006937a996d57b3bab6400167f1966 --- /dev/null +++ b/server/src/services/airtrail/airtrailService.ts @@ -0,0 +1,153 @@ +import type { AirtrailFlight } from '@trek/shared'; +import { db } from '../../db/database'; +import { maybe_encrypt_api_key, decrypt_api_key } from '../apiKeyCrypto'; +import { checkSsrf } from '../../utils/ssrfGuard'; +import { writeAudit } from '../auditLog'; +import { AirtrailAuthError, AirtrailCreds, AirtrailRequestError, listFlights } from './airtrailClient'; +import { normalizeFlight } from './airtrailMapper'; + +const KEY_MASK = '••••••••'; + +interface UserConnRow { + airtrail_url?: string | null; + airtrail_api_key?: string | null; + airtrail_allow_insecure_tls?: number | null; +} + +function readRow(userId: number): UserConnRow | undefined { + return db + .prepare('SELECT airtrail_url, airtrail_api_key, airtrail_allow_insecure_tls FROM users WHERE id = ?') + .get(userId) as UserConnRow | undefined; +} + +/** Decrypted creds for outbound calls, or null when the user has no connection. */ +export function getAirtrailCredentials(userId: number): AirtrailCreds | null { + const row = readRow(userId); + if (!row?.airtrail_url || !row?.airtrail_api_key) return null; + const apiKey = decrypt_api_key(row.airtrail_api_key); + if (!apiKey) return null; + return { + baseUrl: row.airtrail_url, + apiKey, + allowInsecureTls: !!row.airtrail_allow_insecure_tls, + }; +} + +/** Settings as shown in the UI — the key is never echoed, only masked. */ +export function getConnectionSettings(userId: number) { + const row = readRow(userId); + return { + url: row?.airtrail_url || '', + apiKeyMasked: row?.airtrail_api_key ? KEY_MASK : '', + allowInsecureTls: !!row?.airtrail_allow_insecure_tls, + connected: !!(row?.airtrail_url && row?.airtrail_api_key), + }; +} + +export async function saveSettings( + userId: number, + url: string | undefined, + apiKey: string | undefined, + allowInsecureTls: boolean, + clientIp: string | null, +): Promise<{ success: boolean; warning?: string; error?: string }> { + const trimmedUrl = (url || '').trim(); + let warning: string | undefined; + + if (trimmedUrl) { + const ssrf = await checkSsrf(trimmedUrl); + // Reject only genuinely unusable URLs (malformed, unresolvable, non-http, + // loopback). Private/LAN instances are the common self-hosted case, so we + // persist them with a warning rather than blocking — the outbound calls + // still need ALLOW_INTERNAL_NETWORK=true to actually reach them. + if (!ssrf.allowed && !ssrf.isPrivate) { + return { success: false, error: ssrf.error ?? 'Invalid AirTrail URL' }; + } + if (ssrf.isPrivate) { + writeAudit({ + userId, + action: 'airtrail.private_ip_configured', + ip: clientIp, + details: { airtrail_url: trimmedUrl, resolved_ip: ssrf.resolvedIp }, + }); + warning = `AirTrail URL resolves to a private IP (${ssrf.resolvedIp}). Make sure this is intentional — the server may need ALLOW_INTERNAL_NETWORK=true to reach it.`; + } + } + + // Only overwrite the stored key when a genuinely new value is supplied; + // a blank field or the mask means "keep the existing key". + const provided = (apiKey || '').trim(); + const newKey = provided && provided !== KEY_MASK ? maybe_encrypt_api_key(provided) : undefined; + + if (newKey !== undefined) { + db.prepare( + 'UPDATE users SET airtrail_url = ?, airtrail_api_key = ?, airtrail_allow_insecure_tls = ? WHERE id = ?', + ).run(trimmedUrl || null, newKey, allowInsecureTls ? 1 : 0, userId); + } else { + db.prepare( + 'UPDATE users SET airtrail_url = ?, airtrail_allow_insecure_tls = ? WHERE id = ?', + ).run(trimmedUrl || null, allowInsecureTls ? 1 : 0, userId); + // Clearing the URL with no key left makes the connection meaningless — drop the key too. + if (!trimmedUrl) { + db.prepare('UPDATE users SET airtrail_api_key = NULL WHERE id = ?').run(userId); + } + } + + return { success: true, warning }; +} + +async function probe(creds: AirtrailCreds): Promise<{ connected: boolean; flightCount?: number; error?: string }> { + try { + const flights = await listFlights(creds); + return { connected: true, flightCount: flights.length }; + } catch (err: unknown) { + if (err instanceof AirtrailAuthError) return { connected: false, error: 'Invalid API key' }; + return { connected: false, error: err instanceof Error ? err.message : 'Connection failed' }; + } +} + +/** Live check using the stored connection. */ +export async function getConnectionStatus( + userId: number, +): Promise<{ connected: boolean; flightCount?: number; error?: string }> { + const creds = getAirtrailCredentials(userId); + if (!creds) return { connected: false, error: 'Not configured' }; + return probe(creds); +} + +/** + * "Test connection" from the settings form. Uses the typed URL/key when given; + * falls back to the stored key when the key field still shows the mask. + */ +export async function testConnection( + userId: number, + url: string | undefined, + apiKey: string | undefined, + allowInsecureTls: boolean, +): Promise<{ connected: boolean; flightCount?: number; error?: string }> { + const trimmedUrl = (url || '').trim(); + const provided = (apiKey || '').trim(); + + const stored = getAirtrailCredentials(userId); + const effectiveUrl = trimmedUrl || stored?.baseUrl; + const effectiveKey = provided && provided !== KEY_MASK ? provided : stored?.apiKey; + + if (!effectiveUrl || !effectiveKey) { + return { connected: false, error: 'URL and API key required' }; + } + + const ssrf = await checkSsrf(effectiveUrl); + if (!ssrf.allowed && !ssrf.isPrivate) { + return { connected: false, error: ssrf.error ?? 'Invalid AirTrail URL' }; + } + + return probe({ baseUrl: effectiveUrl, apiKey: effectiveKey, allowInsecureTls }); +} + +/** The user's AirTrail flights, normalized for the import picker. */ +export async function getFlightsForPicker(userId: number): Promise { + const creds = getAirtrailCredentials(userId); + if (!creds) throw new AirtrailRequestError('AirTrail is not connected', 400); + const raw = await listFlights(creds); + return raw.map(normalizeFlight); +} diff --git a/server/src/services/airtrail/airtrailSync.ts b/server/src/services/airtrail/airtrailSync.ts new file mode 100644 index 0000000000000000000000000000000000000000..c53f86fd4af0cae690e1e14f44643655a371763f --- /dev/null +++ b/server/src/services/airtrail/airtrailSync.ts @@ -0,0 +1,264 @@ +import { ADDON_IDS } from '../../addons'; +import { db } from '../../db/database'; +import { broadcast } from '../../websocket'; +import { isAddonEnabled } from '../adminService'; +import { logError, logInfo } from '../auditLog'; +import { getReservation, getReservationWithJoins, updateReservation } from '../reservationService'; +import { + AirtrailAuthError, + AirtrailCreds, + AirtrailFlightRaw, + AirtrailSavePayload, + getFlight, + listFlights, + saveFlight, +} from './airtrailClient'; +import { canonicalHash, mapFlightToReservation } from './airtrailMapper'; +import { getAirtrailCredentials } from './airtrailService'; + +/** Global on/off: the addon must be enabled and sync not explicitly turned off. */ +export function syncGloballyEnabled(): boolean { + if (!isAddonEnabled(ADDON_IDS.AIRTRAIL)) return false; + const row = db.prepare("SELECT value FROM app_settings WHERE key = 'airtrail_sync_enabled'").get() as + | { value: string } + | undefined; + return row?.value !== 'false'; +} + +function broadcastUpdated(tripId: number, reservationId: number): void { + try { + const reservation = getReservationWithJoins(reservationId); + if (reservation) broadcast(tripId, 'reservation:updated', { reservation }); + } catch { + /* broadcast failure is non-fatal */ + } +} + +function detach(tripId: number, reservationId: number): void { + db.prepare('UPDATE reservations SET sync_enabled = 0 WHERE id = ?').run(reservationId); + broadcastUpdated(tripId, reservationId); +} + +// ── AirTrail → TREK (poll) ─────────────────────────────────────────────────── + +/** + * Reconcile one owner's linked reservations against their current AirTrail + * flights: apply field changes (detected by snapshot hash, since AirTrail has no + * updated_at) and, when a flight is gone from AirTrail, keep the TREK row but + * stop syncing it. Only already-imported flights are touched — new AirTrail + * flights are never auto-added to a trip. Returns how many rows changed. + */ +async function syncOwner(uid: number): Promise { + const creds = getAirtrailCredentials(uid); + if (!creds) return 0; // owner disconnected — leave their linked rows as-is + + let flights: AirtrailFlightRaw[]; + try { + flights = await listFlights(creds); + } catch (err) { + if (err instanceof AirtrailAuthError) logError(`AirTrail sync: invalid API key for user ${uid}`); + return 0; + } + const byId = new Map(flights.map((f) => [String(f.id), f])); + + const linked = db + .prepare( + "SELECT id, trip_id, external_id, external_hash FROM reservations WHERE external_source = 'airtrail' AND sync_enabled = 1 AND external_owner_user_id = ?", + ) + .all(uid) as { id: number; trip_id: number; external_id: string; external_hash: string | null }[]; + + let changed = 0; + for (const row of linked) { + const flight = byId.get(String(row.external_id)); + if (!flight) { + detach(row.trip_id, row.id); // deleted in AirTrail → keep row, stop syncing + changed++; + continue; + } + + const hash = canonicalHash(flight); + if (hash === row.external_hash) continue; + + const current = getReservation(row.id, row.trip_id); + if (!current) continue; + try { + updateReservation(row.id, row.trip_id, mapFlightToReservation(flight) as any, current as any); + db.prepare('UPDATE reservations SET external_hash = ?, external_synced_at = ? WHERE id = ?').run( + hash, + new Date().toISOString(), + row.id, + ); + broadcastUpdated(row.trip_id, row.id); + changed++; + } catch (err) { + logError(`AirTrail sync: failed to update reservation ${row.id}: ${err instanceof Error ? err.message : err}`); + } + } + return changed; +} + +let running = false; + +/** Background poll across every connected owner (scheduler). */ +export async function runAirtrailSync(): Promise { + if (running) return; + if (!syncGloballyEnabled()) return; + running = true; + let changed = 0; + try { + const owners = db + .prepare( + "SELECT DISTINCT external_owner_user_id AS uid FROM reservations WHERE external_source = 'airtrail' AND sync_enabled = 1 AND external_owner_user_id IS NOT NULL", + ) + .all() as { uid: number }[]; + for (const { uid } of owners) changed += await syncOwner(uid); + if (changed > 0) logInfo(`AirTrail sync: applied ${changed} change(s)`); + } catch (err) { + logError(`AirTrail sync failed: ${err instanceof Error ? err.message : err}`); + } finally { + running = false; + } +} + +/** + * On-demand sync of just this user's linked flights — called when the user opens + * a trip so AirTrail-side edits show up immediately instead of waiting for the + * background poll. + */ +export async function runAirtrailSyncForUser(userId: number): Promise<{ changed: number }> { + if (!syncGloballyEnabled()) return { changed: 0 }; + try { + return { changed: await syncOwner(userId) }; + } catch (err) { + logError(`AirTrail sync (user ${userId}) failed: ${err instanceof Error ? err.message : err}`); + return { changed: 0 }; + } +} + +// ── TREK → AirTrail (push) ─────────────────────────────────────────────────── + +function splitLocal(dt: string | null | undefined): { date: string | null; time: string | null } { + if (!dt) return { date: null, time: null }; + const date = dt.slice(0, 10); + const m = dt.slice(10).match(/(\d{2}:\d{2})/); + return { date: /^\d{4}-\d{2}-\d{2}$/.test(date) ? date : null, time: m ? m[1] : null }; +} + +function buildSavePayload(reservation: any, existing: AirtrailFlightRaw): AirtrailSavePayload | null { + let meta: Record; + try { + meta = reservation.metadata ? JSON.parse(reservation.metadata) : {}; + } catch { + meta = {}; + } + const endpoints: any[] = reservation.endpoints || []; + const fromEp = endpoints.find((e) => e.role === 'from'); + const toEp = endpoints.find((e) => e.role === 'to'); + const fromCode = fromEp?.code || existing.from?.iata || existing.from?.icao || null; + const toCode = toEp?.code || existing.to?.iata || existing.to?.icao || null; + if (!fromCode || !toCode) return null; + + const dep = splitLocal(reservation.reservation_time); + const arr = splitLocal(reservation.reservation_end_time); + if (!dep.date) return null; + + // Preserve the existing seat manifest (an update replaces all seats); fall back + // to the key-owner placeholder so AirTrail attributes it to the connecting user. + const seats = (existing.seats ?? []).map((s) => ({ + userId: s.userId, + guestName: s.guestName, + seat: s.seat, + seatNumber: s.seatNumber, + seatClass: s.seatClass, + })); + if (seats.length === 0) { + seats.push({ userId: '', guestName: null, seat: null, seatNumber: null, seatClass: null }); + } + + // Push the seat the user set in TREK onto their own AirTrail seat (the one with + // a userId), leaving any co-passenger seats untouched. + const seatNumber = typeof meta.seat === 'string' && meta.seat.trim() ? meta.seat.trim() : null; + if (seatNumber) { + const ownSeat = seats.find((s) => s.userId) ?? seats[0]; + if (ownSeat) ownSeat.seatNumber = seatNumber; + } + + return { + id: Number(reservation.external_id), + from: fromCode, + to: toCode, + departure: dep.date, + departureTime: dep.time, + arrival: arr.date, + arrivalTime: arr.time, + airline: meta.airline ?? null, + flightNumber: meta.flight_number ?? null, + aircraft: meta.aircraft ?? null, + aircraftReg: meta.aircraft_reg ?? null, + flightReason: meta.flight_reason ?? null, + note: reservation.notes ?? null, + seats, + }; +} + +/** + * Push a locally-edited linked reservation back to AirTrail using the importer's + * (owner's) credentials — even if a different member made the edit. If the owner + * is gone or the flight no longer exists in AirTrail, the link is detached so the + * next pull's AirTrail-wins policy can't silently revert the local edit. + */ +export async function pushReservationToAirtrail(reservationId: number, tripId: number): Promise { + if (!syncGloballyEnabled()) return; + + const row = db + .prepare( + "SELECT id, trip_id, external_id, external_owner_user_id, sync_enabled FROM reservations WHERE id = ? AND external_source = 'airtrail'", + ) + .get(reservationId) as + | { id: number; trip_id: number; external_id: string; external_owner_user_id: number | null; sync_enabled: number } + | undefined; + if (!row || !row.sync_enabled) return; + + const creds: AirtrailCreds | null = row.external_owner_user_id + ? getAirtrailCredentials(row.external_owner_user_id) + : null; + if (!creds) { + detach(tripId, row.id); // owner disconnected — cannot push, so stop syncing + return; + } + + let existing: AirtrailFlightRaw | null; + try { + existing = await getFlight(creds, Number(row.external_id)); + } catch (err) { + if (err instanceof AirtrailAuthError) detach(tripId, row.id); + else logError(`AirTrail push: get failed for reservation ${row.id}: ${err instanceof Error ? err.message : err}`); + return; + } + if (!existing) { + detach(tripId, row.id); // gone in AirTrail → treat like a remote delete + return; + } + + const reservation = getReservationWithJoins(row.id); + if (!reservation) return; + + const payload = buildSavePayload(reservation, existing); + if (!payload) return; + + try { + await saveFlight(creds, payload); + // Self-write suppression: re-read the saved flight and store its hash so the + // next poll doesn't treat our own write as an inbound change. + const saved = await getFlight(creds, Number(row.external_id)); + if (saved) { + db.prepare('UPDATE reservations SET external_hash = ?, external_synced_at = ? WHERE id = ?').run( + canonicalHash(saved), + new Date().toISOString(), + row.id, + ); + } + } catch (err) { + logError(`AirTrail push failed for reservation ${row.id}: ${err instanceof Error ? err.message : err}`); + } +} diff --git a/server/src/services/apiKeyCrypto.ts b/server/src/services/apiKeyCrypto.ts new file mode 100644 index 0000000000000000000000000000000000000000..6dc0b0bdf353f1e2803d6e72a03cf7ebdc675cb5 --- /dev/null +++ b/server/src/services/apiKeyCrypto.ts @@ -0,0 +1,43 @@ +import * as crypto from 'node:crypto'; +import { ENCRYPTION_KEY } from '../config'; + +const ENCRYPTED_PREFIX = 'enc:v1:'; + +function get_key() { + return crypto.createHash('sha256').update(`${ENCRYPTION_KEY}:api_keys:v1`).digest(); +} + +export function encrypt_api_key(plain: unknown) { + const iv = crypto.randomBytes(12); + const cipher = crypto.createCipheriv('aes-256-gcm', get_key(), iv); + const enc = Buffer.concat([cipher.update(String(plain), 'utf8'), cipher.final()]); + const tag = cipher.getAuthTag(); + const blob = Buffer.concat([iv, tag, enc]).toString('base64'); + return `${ENCRYPTED_PREFIX}${blob}`; +} + +export function decrypt_api_key(value: unknown) { + if (!value) return null; + if (typeof value !== 'string') return null; + if (!value.startsWith(ENCRYPTED_PREFIX)) return value; // legacy plaintext + const blob = value.slice(ENCRYPTED_PREFIX.length); + try { + const buf = Buffer.from(blob, 'base64'); + const iv = buf.subarray(0, 12); + const tag = buf.subarray(12, 28); + const enc = buf.subarray(28); + const decipher = crypto.createDecipheriv('aes-256-gcm', get_key(), iv); + decipher.setAuthTag(tag); + return Buffer.concat([decipher.update(enc), decipher.final()]).toString('utf8'); + } catch { + return null; + } +} + +export function maybe_encrypt_api_key(value: unknown) { + const trimmed = String(value || '').trim(); + if (!trimmed) return null; + if (trimmed.startsWith(ENCRYPTED_PREFIX)) return trimmed; + return encrypt_api_key(trimmed); +} + diff --git a/server/src/services/assignmentService.ts b/server/src/services/assignmentService.ts new file mode 100644 index 0000000000000000000000000000000000000000..b7579ea980ff9022059ca4279b0ac5adc79c5c74 --- /dev/null +++ b/server/src/services/assignmentService.ts @@ -0,0 +1,215 @@ +import { db } from '../db/database'; +import { loadTagsByPlaceIds, loadParticipantsByAssignmentIds, formatAssignmentWithPlace } from './queryHelpers'; +import { AssignmentRow, DayAssignment } from '../types'; + +export function getAssignmentWithPlace(assignmentId: number | bigint) { + const a = db.prepare(` + SELECT da.*, p.id as place_id, p.name as place_name, p.description as place_description, + p.lat, p.lng, p.address, p.category_id, p.price, p.currency as place_currency, + COALESCE(da.assignment_time, p.place_time) as place_time, + COALESCE(da.assignment_end_time, p.end_time) as end_time, + p.duration_minutes, p.notes as place_notes, + p.image_url, p.transport_mode, p.google_place_id, p.website, p.phone, + c.name as category_name, c.color as category_color, c.icon as category_icon + FROM day_assignments da + JOIN places p ON da.place_id = p.id + LEFT JOIN categories c ON p.category_id = c.id + WHERE da.id = ? + `).get(assignmentId) as AssignmentRow | undefined; + + if (!a) 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(a.place_id); + + const participants = db.prepare(` + SELECT ap.user_id, u.username, u.avatar + FROM assignment_participants ap + JOIN users u ON ap.user_id = u.id + WHERE ap.assignment_id = ? + `).all(a.id); + + return { + id: a.id, + day_id: a.day_id, + place_id: a.place_id, + order_index: a.order_index, + notes: a.notes, + assignment_time: a.assignment_time ?? null, + assignment_end_time: a.assignment_end_time ?? null, + participants, + created_at: a.created_at, + place: { + id: a.place_id, + name: a.place_name, + description: a.place_description, + lat: a.lat, + lng: a.lng, + address: a.address, + category_id: a.category_id, + price: a.price, + currency: a.place_currency, + place_time: a.place_time, + end_time: a.end_time, + duration_minutes: a.duration_minutes, + notes: a.place_notes, + image_url: a.image_url, + transport_mode: a.transport_mode, + google_place_id: a.google_place_id, + website: a.website, + phone: a.phone, + category: a.category_id ? { + id: a.category_id, + name: a.category_name, + color: a.category_color, + icon: a.category_icon, + } : null, + tags, + } + }; +} + +export function listDayAssignments(dayId: string | number) { + const assignments = db.prepare(` + SELECT da.*, p.id as place_id, p.name as place_name, p.description as place_description, + p.lat, p.lng, p.address, p.category_id, p.price, p.currency as place_currency, + COALESCE(da.assignment_time, p.place_time) as place_time, + COALESCE(da.assignment_end_time, p.end_time) as end_time, + p.duration_minutes, p.notes as place_notes, + p.image_url, p.transport_mode, p.google_place_id, p.website, p.phone, + c.name as category_name, c.color as category_color, c.icon as category_icon + FROM day_assignments da + JOIN places p ON da.place_id = p.id + LEFT JOIN categories c ON p.category_id = c.id + WHERE da.day_id = ? + ORDER BY da.order_index ASC, da.created_at ASC + `).all(dayId) as AssignmentRow[]; + + const placeIds = [...new Set(assignments.map(a => a.place_id))]; + const tagsByPlaceId = loadTagsByPlaceIds(placeIds, { compact: true }); + + const assignmentIds = assignments.map(a => a.id); + const participantsByAssignment = loadParticipantsByAssignmentIds(assignmentIds); + + return assignments.map(a => { + return formatAssignmentWithPlace(a, tagsByPlaceId[a.place_id] || [], participantsByAssignment[a.id] || []); + }); +} + +export function dayExists(dayId: string | number, tripId: string | number) { + return !!db.prepare('SELECT id FROM days WHERE id = ? AND trip_id = ?').get(dayId, tripId); +} + +export function placeExists(placeId: string | number, tripId: string | number) { + return !!db.prepare('SELECT id FROM places WHERE id = ? AND trip_id = ?').get(placeId, tripId); +} + +export function createAssignment(dayId: string | number, placeId: string | number, notes: string | null) { + const maxOrder = db.prepare('SELECT MAX(order_index) as max FROM day_assignments WHERE day_id = ?').get(dayId) as { max: number | null }; + const orderIndex = (maxOrder.max !== null ? maxOrder.max : -1) + 1; + + const result = db.prepare( + 'INSERT INTO day_assignments (day_id, place_id, order_index, notes) VALUES (?, ?, ?, ?)' + ).run(dayId, placeId, orderIndex, notes || null); + + return getAssignmentWithPlace(result.lastInsertRowid); +} + +export function assignmentExistsInDay(id: string | number, dayId: string | number, tripId: string | number) { + return !!db.prepare( + 'SELECT da.id FROM day_assignments da JOIN days d ON da.day_id = d.id WHERE da.id = ? AND da.day_id = ? AND d.trip_id = ?' + ).get(id, dayId, tripId); +} + +export function deleteAssignment(id: string | number) { + db.prepare('DELETE FROM day_assignments WHERE id = ?').run(id); +} + +export function reorderAssignments(dayId: string | number, orderedIds: number[]) { + const update = db.prepare('UPDATE day_assignments SET order_index = ? WHERE id = ? AND day_id = ?'); + db.exec('BEGIN'); + try { + orderedIds.forEach((id: number, index: number) => { + update.run(index, id, dayId); + }); + db.exec('COMMIT'); + } catch (e) { + db.exec('ROLLBACK'); + throw e; + } +} + +export function getAssignmentForTrip(id: string | number, tripId: string | number) { + return db.prepare(` + SELECT da.* FROM day_assignments da + JOIN days d ON da.day_id = d.id + WHERE da.id = ? AND d.trip_id = ? + `).get(id, tripId) as DayAssignment | undefined; +} + +export function moveAssignment(id: string | number, newDayId: string | number, orderIndex: number, oldDayId: number) { + db.prepare('UPDATE day_assignments SET day_id = ?, order_index = ? WHERE id = ?').run(newDayId, orderIndex || 0, id); + const updated = getAssignmentWithPlace(Number(id)); + return { assignment: updated, oldDayId }; +} + +export function getParticipants(assignmentId: string | number) { + return db.prepare(` + SELECT ap.user_id, u.username, u.avatar + FROM assignment_participants ap + JOIN users u ON ap.user_id = u.id + WHERE ap.assignment_id = ? + `).all(assignmentId); +} + +export function updateTime(id: string | number, placeTime: string | null, endTime: string | null) { + db.prepare('UPDATE day_assignments SET assignment_time = ?, assignment_end_time = ? WHERE id = ?') + .run(placeTime ?? null, endTime ?? null, id); + + // Auto-sort: reorder timed assignments chronologically within the day + if (placeTime) { + const assignment = db.prepare('SELECT day_id FROM day_assignments WHERE id = ?').get(id) as { day_id: number } | undefined; + if (assignment) { + const dayAssignments = db.prepare(` + SELECT da.id, COALESCE(da.assignment_time, p.place_time) as effective_time + FROM day_assignments da + JOIN places p ON da.place_id = p.id + WHERE da.day_id = ? + ORDER BY da.order_index ASC + `).all(assignment.day_id) as { id: number; effective_time: string | null }[]; + + // Separate timed and untimed, sort timed by time + const timed = dayAssignments.filter(a => a.effective_time).sort((a, b) => { + const ta = a.effective_time!.includes(':') ? a.effective_time! : '99:99'; + const tb = b.effective_time!.includes(':') ? b.effective_time! : '99:99'; + return ta.localeCompare(tb); + }); + const untimed = dayAssignments.filter(a => !a.effective_time); + + // Interleave: timed in chronological order, untimed keep relative position + const reordered = [...timed, ...untimed]; + const update = db.prepare('UPDATE day_assignments SET order_index = ? WHERE id = ?'); + reordered.forEach((a, i) => update.run(i, a.id)); + } + } + + return getAssignmentWithPlace(Number(id)); +} + +export function setParticipants(assignmentId: string | number, userIds: number[]) { + db.prepare('DELETE FROM assignment_participants WHERE assignment_id = ?').run(assignmentId); + if (userIds.length > 0) { + const insert = db.prepare('INSERT OR IGNORE INTO assignment_participants (assignment_id, user_id) VALUES (?, ?)'); + for (const userId of userIds) insert.run(assignmentId, userId); + } + + return db.prepare(` + SELECT ap.user_id, u.username, u.avatar + FROM assignment_participants ap + JOIN users u ON ap.user_id = u.id + WHERE ap.assignment_id = ? + `).all(assignmentId); +} diff --git a/server/src/services/atlasService.ts b/server/src/services/atlasService.ts new file mode 100644 index 0000000000000000000000000000000000000000..48a6df7a7000efa70f62b161431ce7a802696a30 --- /dev/null +++ b/server/src/services/atlasService.ts @@ -0,0 +1,719 @@ +import fs from 'fs'; +import path from 'path'; +import zlib from 'zlib'; +import { db } from '../db/database'; +import { Trip, Place } from '../types'; + +// ── Bundled boundary GeoJSON (admin-0 countries + admin-1 regions) ───────── +// +// Sourced from geoBoundaries (CC BY 4.0), normalized + quantized offline by +// scripts/build-atlas-geo.mjs into gzipped FeatureCollections under server/assets. +// They are read + decompressed once and cached in memory — no network at runtime. +// (Replaces the previous runtime fetch of Natural Earth, which was stale for recent +// sub-national reforms and depicts some contested borders in unwanted ways.) +// +// __dirname is server/dist/services at runtime and server/src/services under vitest; +// both resolve ../../assets to server/assets. + +const geoBundleCache = new Map(); + +function loadGeoBundle(name: 'admin0' | 'admin1'): any { + const cached = geoBundleCache.get(name); + if (cached) return cached; + const file = path.join(__dirname, '..', '..', 'assets', 'atlas', `${name}.geojson.gz`); + if (!fs.existsSync(file)) { + console.warn(`[Atlas] ${name}.geojson.gz missing — run \`node scripts/build-atlas-geo.mjs\``); + const empty = { type: 'FeatureCollection', features: [] }; + geoBundleCache.set(name, empty); + return empty; + } + const geo = JSON.parse(zlib.gunzipSync(fs.readFileSync(file)).toString('utf8')); + geoBundleCache.set(name, geo); + console.log(`[Atlas] Loaded ${name} GeoJSON: ${geo.features?.length || 0} features`); + return geo; +} + +/** Full admin-0 country-border FeatureCollection (for the client map's country layer). */ +export function getCountryGeo(): any { + return loadGeoBundle('admin0'); +} + +export async function getRegionGeo(countryCodes: string[]): Promise { + const geo = loadGeoBundle('admin1'); + if (!geo) return { type: 'FeatureCollection', features: [] }; + const codes = new Set(countryCodes.map(c => c.toUpperCase())); + const features = geo.features.filter((f: any) => codes.has(f.properties?.iso_a2?.toUpperCase())); + return { type: 'FeatureCollection', features }; +} + +// ── Geocode cache ─────────────────────────────────────────────────────────── + +const geocodeCache = new Map(); + +function roundKey(lat: number, lng: number): string { + return `${lat.toFixed(3)},${lng.toFixed(3)}`; +} + +function cacheKey(lat: number, lng: number): string { + return roundKey(lat, lng); +} + +export function getCached(lat: number, lng: number): string | null | undefined { + const key = cacheKey(lat, lng); + if (geocodeCache.has(key)) return geocodeCache.get(key)!; + return undefined; +} + +export function setCache(lat: number, lng: number, code: string | null): void { + geocodeCache.set(cacheKey(lat, lng), code); +} + +// Periodically trim the cache so it doesn't grow unbounded +const CACHE_MAX = 50_000; +const CACHE_CLEANUP_MS = 10 * 60 * 1000; +setInterval(() => { + if (geocodeCache.size > CACHE_MAX) { + const keys = [...geocodeCache.keys()]; + const toDelete = keys.slice(0, keys.length - CACHE_MAX); + for (const k of toDelete) geocodeCache.delete(k); + } +}, CACHE_CLEANUP_MS).unref(); + +// ── Bounding-box lookup tables ────────────────────────────────────────────── + +export const COUNTRY_BOXES: Record = { + AF:[60.5,29.4,75,38.5],AL:[19,39.6,21.1,42.7],DZ:[-8.7,19,12,37.1],AD:[1.4,42.4,1.8,42.7],AO:[11.7,-18.1,24.1,-4.4], + AR:[-73.6,-55.1,-53.6,-21.8],AM:[43.4,38.8,46.6,41.3],AU:[112.9,-43.6,153.6,-10.7],AT:[9.5,46.4,17.2,49],AZ:[44.8,38.4,50.4,41.9], + BA:[15.7,42.6,19.6,45.3],BD:[88.0,20.7,92.7,26.6],BF:[-5.5,9.4,2.4,15.1],BH:[50.4,25.8,50.7,26.2],BI:[29.0,-4.5,30.8,-2.3], + BJ:[0.8,6.2,3.8,12.4],BN:[114.1,4.0,115.4,5.1],BO:[-69.7,-22.9,-57.5,-9.7],BR:[-73.9,-33.8,-34.8,5.3],BE:[2.5,49.5,6.4,51.5], + BG:[22.4,41.2,28.6,44.2],BW:[20.0,-26.9,29.4,-17.8],CA:[-141,41.7,-52.6,83.1],CD:[12.2,-13.5,31.3,5.4],CG:[11.2,-5.0,18.7,3.7], + CI:[-8.6,4.3,-2.5,10.7],CL:[-75.6,-55.9,-66.9,-17.5],CM:[8.4,1.7,16.2,13.1],CN:[73.6,18.2,134.8,53.6],CO:[-79.1,-4.3,-66.9,12.5], + CR:[-85.9,8.0,-82.5,11.2],CU:[-85.0,19.8,-74.1,23.2],CV:[-25.4,14.8,-22.7,17.2],CY:[32.3,34.5,34.1,35.7],HR:[13.5,42.4,19.5,46.6], + CZ:[12.1,48.6,18.9,51.1],DJ:[41.8,11.0,43.4,12.7],DK:[8,54.6,15.2,57.8],DO:[-72.0,17.5,-68.3,19.9],EC:[-81.0,-5.0,-75.2,1.5], + EG:[24.7,22,37,31.7],EE:[21.8,57.5,28.2,59.7],ER:[36.4,12.4,43.1,18.0],ET:[33.0,3.4,47.9,14.9],FI:[20.6,59.8,31.6,70.1], + FR:[-5.1,41.3,9.6,51.1],DE:[5.9,47.3,15.1,55.1],GE:[40.0,41.0,46.7,43.6],GH:[-3.3,4.7,1.2,11.2],GN:[-15.1,7.2,-7.6,12.7], + GR:[19.4,34.8,29.7,41.8],GT:[-92.2,13.7,-88.2,17.8],HN:[-89.4,12.9,-83.2,16.5],HT:[-74.5,18.0,-71.6,20.1],HU:[16,45.7,22.9,48.6], + IS:[-24.5,63.4,-13.5,66.6],IN:[68.2,6.7,97.4,35.5],ID:[95.3,-11,141,5.9],IR:[44.1,25.1,63.3,39.8],IQ:[38.8,29.1,48.6,37.4], + IE:[-10.5,51.4,-6,55.4],IL:[34.3,29.5,35.9,33.3],IT:[6.6,36.6,18.5,47.1],JM:[-78.4,17.7,-76.2,18.5],JO:[34.9,29.2,39.3,33.4], + JP:[129.4,31.1,145.5,45.5],KE:[33.9,-4.7,41.9,5.5],KG:[69.2,39.2,80.3,43.2],KH:[102.3,10.4,107.6,14.7],KR:[126,33.2,129.6,38.6], + KW:[46.5,28.5,48.4,30.1],KZ:[50.3,40.6,87.4,55.4],LA:[100.1,13.9,107.7,22.5],LB:[35.1,33.1,36.6,34.7],LK:[79.7,5.9,81.9,9.8], + LV:[21,55.7,28.2,58.1],LT:[21,53.9,26.8,56.5],LU:[5.7,49.4,6.5,50.2],LY:[9.5,19.5,25.2,33.3],MA:[-13.2,27.7,-1,35.9], + MD:[26.6,45.5,30.2,48.5],ME:[18.4,41.8,20.4,43.6],MG:[43.2,-25.6,50.5,-11.9],MK:[20.5,40.8,23.0,42.4],ML:[-4.8,10.1,4.3,25.0], + MM:[92.2,9.8,101.2,28.5],MN:[87.8,41.6,119.9,52.1],MR:[-17.1,14.7,-4.8,27.3],MT:[14.1,35.8,14.6,36.1],MU:[57.3,-20.5,57.8,-19.9], + MV:[72.7,-0.7,73.8,7.1],MW:[32.7,-17.1,35.9,-9.4],MY:[99.6,0.9,119.3,7.4],MX:[-118.4,14.5,-86.7,32.7],MZ:[30.2,-26.9,40.8,-10.5], + NA:[11.7,-28.9,25.3,-17.0],NE:[0.2,11.7,15.9,23.5],NI:[-87.7,10.7,-83.1,15.0],NL:[3.4,50.8,7.2,53.5],NP:[80.1,26.4,88.2,30.4], + NZ:[166.4,-47.3,178.5,-34.4],NO:[4.6,58,31.1,71.2],OM:[51.9,16.6,59.8,26.4],PA:[-83.0,7.2,-77.2,9.6],PG:[140.8,-11.7,155.7,-1.3], + PK:[60.9,23.7,77.1,37.1],PE:[-81.3,-18.4,-68.7,-0.1],PH:[117,5,126.6,18.5],PL:[14.1,49,24.1,54.9],PS:[34.2,29.5,35.6,32.6], + PT:[-9.5,36.8,-6.2,42.2],PY:[-62.6,-27.6,-54.3,-19.3],QA:[50.7,24.5,51.6,26.2],RO:[20.2,43.6,29.7,48.3],RU:[19.6,41.2,180,81.9], + RW:[29.0,-2.8,30.9,-1.0],SA:[34.6,16.4,55.7,32.2],SC:[55.3,-9.7,55.8,-3.7],SD:[21.8,3.4,38.6,22.2],SG:[103.6,1.2,104.1,1.5], + SI:[13.4,45.4,16.6,46.9],SK:[16.8,47.7,22.6,49.6],SN:[-17.5,12.3,-11.4,15.0],SO:[40.9,-1.7,51.4,11.9],RS:[18.8,42.2,23,46.2], + SV:[-90.1,13.2,-87.7,14.5],SY:[35.7,32.3,42.4,37.3],TG:[-0.2,6.1,1.8,11.2],TJ:[67.3,36.7,75.2,41.0],TM:[52.4,35.1,66.7,42.8], + TN:[7.5,30.2,11.6,37.5],TT:[-61.9,10.0,-60.5,11.3],TW:[120.1,21.9,122.0,25.3],TZ:[29.3,-11.7,40.4,-1.0],ZA:[16.5,-34.8,32.9,-22.1], + SE:[11.1,55.3,24.2,69.1],CH:[6,45.8,10.5,47.8],TH:[97.3,5.6,105.6,20.5],TR:[26,36,44.8,42.1],UA:[22.1,44.4,40.2,52.4], + UG:[29.6,-1.5,35.0,4.2],UY:[-58.4,-34.9,-53.1,-30.1],UZ:[55.9,37.2,73.1,45.6],VE:[-73.4,0.7,-59.8,12.2], + AE:[51.6,22.6,56.4,26.1],GB:[-8,49.9,2,60.9],US:[-125,24.5,-66.9,49.4],VN:[102.1,8.6,109.5,23.4],XK:[20.0,41.9,21.8,43.3], + YE:[42.5,12.1,54.0,19.0],ZM:[21.9,-18.1,33.7,-8.2],ZW:[25.2,-22.4,33.1,-15.6], + // Territories with their own ISO code that sit inside a larger country's box. + // Listed so getCountryFromCoords()'s smallest-box match picks them over the host + // (e.g. Hong Kong/Macau over China, San Marino/Vatican over Italy). + HK:[113.83,22.15,114.43,22.56],MO:[113.53,22.10,113.60,22.21],SM:[12.40,43.89,12.52,43.99], + VA:[12.44,41.90,12.46,41.91],MC:[7.40,43.72,7.44,43.75],LI:[9.47,47.05,9.64,47.27], + GI:[-5.36,36.11,-5.33,36.16],PR:[-67.30,17.88,-65.22,18.53], +}; + +export const NAME_TO_CODE: Record = { + 'germany':'DE','deutschland':'DE','france':'FR','frankreich':'FR','spain':'ES','spanien':'ES', + 'italy':'IT','italien':'IT','united kingdom':'GB','uk':'GB','england':'GB','united states':'US', + 'usa':'US','netherlands':'NL','niederlande':'NL','austria':'AT','osterreich':'AT','switzerland':'CH', + 'schweiz':'CH','portugal':'PT','greece':'GR','griechenland':'GR','turkey':'TR','turkei':'TR', + 'croatia':'HR','kroatien':'HR','czech republic':'CZ','tschechien':'CZ','czechia':'CZ', + 'poland':'PL','polen':'PL','sweden':'SE','schweden':'SE','norway':'NO','norwegen':'NO', + 'denmark':'DK','danemark':'DK','finland':'FI','finnland':'FI','belgium':'BE','belgien':'BE', + 'ireland':'IE','irland':'IE','hungary':'HU','ungarn':'HU','romania':'RO','rumanien':'RO', + 'bulgaria':'BG','bulgarien':'BG','japan':'JP','china':'CN','australia':'AU','australien':'AU', + 'canada':'CA','kanada':'CA','mexico':'MX','mexiko':'MX','brazil':'BR','brasilien':'BR', + 'argentina':'AR','argentinien':'AR','thailand':'TH','indonesia':'ID','indonesien':'ID', + 'india':'IN','indien':'IN','egypt':'EG','agypten':'EG','morocco':'MA','marokko':'MA', + 'south africa':'ZA','sudafrika':'ZA','new zealand':'NZ','neuseeland':'NZ','iceland':'IS','island':'IS', + 'luxembourg':'LU','luxemburg':'LU','slovenia':'SI','slowenien':'SI','slovakia':'SK','slowakei':'SK', + 'estonia':'EE','estland':'EE','latvia':'LV','lettland':'LV','lithuania':'LT','litauen':'LT', + 'serbia':'RS','serbien':'RS','israel':'IL','russia':'RU','russland':'RU','ukraine':'UA', + 'vietnam':'VN','south korea':'KR','sudkorea':'KR','philippines':'PH','philippinen':'PH', + 'malaysia':'MY','colombia':'CO','kolumbien':'CO','peru':'PE','chile':'CL','iran':'IR', + 'iraq':'IQ','irak':'IQ','pakistan':'PK','kenya':'KE','kenia':'KE','nigeria':'NG', + 'saudi arabia':'SA','saudi-arabien':'SA','albania':'AL','albanien':'AL', + 'georgia':'GE','georgien':'GE','montenegro':'ME','north macedonia':'MK','nordmazedonien':'MK', + 'macedonia':'MK','bosnia':'BA','bosnia and herzegovina':'BA','bosnien':'BA','kosovo':'XK', + 'cyprus':'CY','zypern':'CY','malta':'MT','tunisia':'TN','tunesien':'TN','jordan':'JO','jordanien':'JO', + 'lebanon':'LB','libanon':'LB','ghana':'GH','ethiopia':'ET','athiopien':'ET','tanzania':'TZ','uganda':'UG', + 'singapore':'SG','taiwan':'TW','nepal':'NP','sri lanka':'LK','cambodia':'KH','kambodscha':'KH', + 'myanmar':'MM','burma':'MM','laos':'LA','mongolia':'MN','mongolei':'MN','kazakhstan':'KZ','kasachstan':'KZ', + 'uzbekistan':'UZ','usbekistan':'UZ','kyrgyzstan':'KG','kirgisistan':'KG','tajikistan':'TJ','tadschikistan':'TJ', + 'turkmenistan':'TM','costa rica':'CR','panama':'PA','ecuador':'EC','uruguay':'UY','cuba':'CU','kuba':'CU', + 'dominican republic':'DO','dominikanische republik':'DO','jamaica':'JM','haiti':'HT','honduras':'HN', + 'guatemala':'GT','el salvador':'SV','nicaragua':'NI','bolivia':'BO','bolivia plurinational state of':'BO', + 'paraguay':'PY','venezuela':'VE','trinidad and tobago':'TT','trinidad':'TT', + 'oman':'OM','kuwait':'KW','qatar':'QA','bahrain':'BH', + 'syria':'SY','syrien':'SY','yemen':'YE','jemen':'YE','palestine':'PS','palastina':'PS', + 'moldova':'MD','republic of moldova':'MD','moldawien':'MD', + 'libya':'LY','libyen':'LY','sudan':'SD','eritrea':'ER','djibouti':'DJ', + 'senegal':'SN','cameroon':'CM','kamerun':'CM','ivory coast':'CI','cote d\'ivoire':'CI', + 'mali':'ML','niger':'NE','burkina faso':'BF','togo':'TG','benin':'BJ','guinea':'GN', + 'dr congo':'CD','democratic republic of the congo':'CD','republic of the congo':'CG','congo':'CG', + 'angola':'AO','namibia':'NA','botswana':'BW','zimbabwe':'ZW','zambia':'ZM','malawi':'MW', + 'mozambique':'MZ','mozambik':'MZ','madagascar':'MG','rwanda':'RW','burundi':'BI', + 'somalia':'SO','papua new guinea':'PG','brunei':'BN', + 'hong kong':'HK','hong kong sar':'HK','macau':'MO','macao':'MO','macau sar':'MO', + 'san marino':'SM','vatican':'VA','vatican city':'VA','holy see':'VA','monaco':'MC', + 'liechtenstein':'LI','gibraltar':'GI','puerto rico':'PR', +}; + +export const CONTINENT_MAP: Record = { + AF:'Asia',AL:'Europe',DZ:'Africa',AD:'Europe',AO:'Africa',AR:'South America',AM:'Asia',AU:'Oceania',AT:'Europe',AZ:'Asia', + BA:'Europe',BD:'Asia',BF:'Africa',BH:'Asia',BI:'Africa',BJ:'Africa',BN:'Asia',BO:'South America', + BR:'South America',BE:'Europe',BG:'Europe',BW:'Africa', + CA:'North America',CD:'Africa',CG:'Africa',CI:'Africa',CL:'South America',CM:'Africa',CN:'Asia',CO:'South America', + CR:'North America',CU:'North America',CV:'Africa',CY:'Europe',HR:'Europe',CZ:'Europe', + DJ:'Africa',DK:'Europe',DO:'North America',EC:'South America',EG:'Africa',EE:'Europe',ER:'Africa',ET:'Africa', + FI:'Europe',FR:'Europe',DE:'Europe',GE:'Asia',GH:'Africa',GN:'Africa',GR:'Europe',GT:'North America', + HN:'North America',HT:'North America',HU:'Europe',IS:'Europe',IN:'Asia',ID:'Asia',IR:'Asia',IQ:'Asia', + IE:'Europe',IL:'Asia',IT:'Europe',JM:'North America',JO:'Asia',JP:'Asia',KE:'Africa',KG:'Asia',KH:'Asia', + KR:'Asia',KW:'Asia',KZ:'Asia',LA:'Asia',LB:'Asia',LK:'Asia',LV:'Europe',LT:'Europe',LU:'Europe',LY:'Africa', + MA:'Africa',MD:'Europe',ME:'Europe',MG:'Africa',MK:'Europe',ML:'Africa',MM:'Asia',MN:'Asia',MR:'Africa', + MT:'Europe',MU:'Africa',MV:'Asia',MW:'Africa',MY:'Asia',MX:'North America',MZ:'Africa', + NA:'Africa',NE:'Africa',NI:'North America',NL:'Europe',NP:'Asia',NZ:'Oceania',NO:'Europe',OM:'Asia', + PA:'North America',PG:'Oceania',PK:'Asia',PE:'South America',PH:'Asia',PL:'Europe',PS:'Asia', + PT:'Europe',PY:'South America',QA:'Asia',RO:'Europe',RU:'Europe',RW:'Africa',SA:'Asia',SC:'Africa', + SD:'Africa',SG:'Asia',SI:'Europe',SK:'Europe',SN:'Africa',SO:'Africa',RS:'Europe',SV:'North America', + SY:'Asia',TG:'Africa',TJ:'Asia',TM:'Asia',TN:'Africa',TT:'North America',TW:'Asia',TZ:'Africa', + ZA:'Africa',SE:'Europe',CH:'Europe',TH:'Asia',TR:'Europe',UA:'Europe',UG:'Africa',UY:'South America', + UZ:'Asia',VE:'South America',AE:'Asia',GB:'Europe',US:'North America',VN:'Asia',XK:'Europe', + YE:'Asia',ZM:'Africa',ZW:'Africa',NG:'Africa', + HK:'Asia',MO:'Asia',SM:'Europe',VA:'Europe',MC:'Europe',LI:'Europe',GI:'Europe',PR:'North America', +}; + +// ── Geocoding helpers ─────────────────────────────────────────────────────── + +let lastNominatimCall = 0; + +// Shared throttle: enforces ≥1.1s between any Nominatim request, across all callers. +async function throttleNominatim() { + const elapsed = Date.now() - lastNominatimCall; + if (elapsed < 1100) await new Promise(r => setTimeout(r, 1100 - elapsed)); + lastNominatimCall = Date.now(); +} + +export async function reverseGeocodeCountry(lat: number, lng: number): Promise { + const key = roundKey(lat, lng); + if (geocodeCache.has(key)) return geocodeCache.get(key)!; + await throttleNominatim(); + try { + const res = await fetch(`https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lng}&format=json&zoom=3&accept-language=en`, { + headers: { 'User-Agent': 'TREK Travel Planner (https://github.com/mauriceboe/TREK)' }, + signal: AbortSignal.timeout(10_000), + }); + if (!res.ok) return null; + const data = await res.json() as { address?: { country_code?: string } }; + const code = data.address?.country_code?.toUpperCase() || null; + geocodeCache.set(key, code); + return code; + } catch { + return null; + } +} + +export function getCountryFromCoords(lat: number, lng: number): string | null { + let bestCode: string | null = null; + let bestArea = Infinity; + for (const [code, [minLng, minLat, maxLng, maxLat]] of Object.entries(COUNTRY_BOXES)) { + if (lat >= minLat && lat <= maxLat && lng >= minLng && lng <= maxLng) { + const area = (maxLng - minLng) * (maxLat - minLat); + if (area < bestArea) { + bestArea = area; + bestCode = code; + } + } + } + return bestCode; +} + +export function getCountryFromAddress(address: string | null): string | null { + if (!address) return null; + const parts = address.split(',').map(s => s.trim()).filter(Boolean); + if (parts.length === 0) return null; + const last = parts[parts.length - 1]; + const normalized = last.toLowerCase(); + if (NAME_TO_CODE[normalized]) return NAME_TO_CODE[normalized]; + if (NAME_TO_CODE[last]) return NAME_TO_CODE[last]; + if (last.length === 2 && last === last.toUpperCase()) return last; + return null; +} + +// ── Resolve a place to a country code (address -> bbox -> geocode) ────────── + +async function resolveCountryCode(place: Place): Promise { + let code = getCountryFromAddress(place.address); + if (!code && place.lat && place.lng) { + code = getCountryFromCoords(place.lat, place.lng); + } + if (!code && place.lat && place.lng) { + code = await reverseGeocodeCountry(place.lat, place.lng); + } + return code; +} + +function resolveCountryCodeSync(place: Place): string | null { + let code = getCountryFromAddress(place.address); + if (!code && place.lat && place.lng) { + code = getCountryFromCoords(place.lat, place.lng); + } + return code; +} + +// ── Shared query: all trips the user owns or is a member of ───────────────── + +function getUserTrips(userId: number): Trip[] { + return db.prepare(` + SELECT DISTINCT t.* FROM trips t + LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ? + WHERE t.user_id = ? OR m.user_id = ? + ORDER BY t.start_date DESC + `).all(userId, userId, userId) as Trip[]; +} + +function getPlacesForTrips(tripIds: number[]): Place[] { + if (tripIds.length === 0) return []; + const placeholders = tripIds.map(() => '?').join(','); + return db.prepare(`SELECT * FROM places WHERE trip_id IN (${placeholders})`).all(...tripIds) as Place[]; +} + +// ── Country resolution (batch DB cache + sync fallback + background geocoding) ── + +function resolvePlaceCountries(places: Place[]): Map { + const out = new Map(); + const geoPlaces = places.filter(p => p.lat && p.lng); + const placeIds = geoPlaces.map(p => p.id); + + const cached = placeIds.length > 0 + ? (db.prepare( + `SELECT place_id, country_code FROM place_regions WHERE place_id IN (${placeIds.map(() => '?').join(',')})` + ).all(...placeIds) as { place_id: number; country_code: string }[]) + : []; + const cachedMap = new Map(cached.map(r => [r.place_id, r.country_code])); + + const uncachedForGeocode: Place[] = []; + for (const p of places) { + const fromDb = cachedMap.get(p.id); + if (fromDb) { out.set(p.id, fromDb); continue; } + const sync = resolveCountryCodeSync(p); + if (sync) { out.set(p.id, sync); continue; } + if (p.lat && p.lng && !geocodingInFlight.has(p.id)) { + uncachedForGeocode.push(p); + } + } + + if (uncachedForGeocode.length > 0) { + const insertStmt = db.prepare( + 'INSERT OR REPLACE INTO place_regions (place_id, country_code, region_code, region_name) VALUES (?, ?, ?, ?)' + ); + for (const p of uncachedForGeocode) geocodingInFlight.add(p.id); + void (async () => { + try { + for (const place of uncachedForGeocode) { + try { + const info = await reverseGeocodeRegion(place.lat!, place.lng!); + if (info) insertStmt.run(place.id, info.country_code, info.region_code, info.region_name); + } catch { /* continue */ } + finally { geocodingInFlight.delete(place.id); } + } + } catch { + for (const p of uncachedForGeocode) geocodingInFlight.delete(p.id); + } + })(); + } + + return out; +} + +// ── getStats ──────────────────────────────────────────────────────────────── + +export async function getStats(userId: number) { + const trips = getUserTrips(userId); + const tripIds = trips.map(t => t.id); + + if (tripIds.length === 0) { + const manualCountries = db.prepare('SELECT country_code FROM visited_countries WHERE user_id = ?').all(userId) as { country_code: string }[]; + const countries = manualCountries.map(mc => ({ code: mc.country_code, placeCount: 0, tripCount: 0, firstVisit: null, lastVisit: null })); + return { countries, trips: [], stats: { totalTrips: 0, totalPlaces: 0, totalCountries: countries.length, totalDays: 0 } }; + } + + const places = getPlacesForTrips(tripIds); + + interface CountryEntry { code: string; places: { id: number; name: string; lat: number | null; lng: number | null }[]; tripIds: Set } + const placeCountries = resolvePlaceCountries(places); + const countrySet = new Map(); + for (const place of places) { + const code = placeCountries.get(place.id); + if (code) { + if (!countrySet.has(code)) { + countrySet.set(code, { code, places: [], tripIds: new Set() }); + } + countrySet.get(code)!.places.push({ id: place.id, name: place.name, lat: place.lat ?? null, lng: place.lng ?? null }); + countrySet.get(code)!.tripIds.add(place.trip_id); + } + } + + let totalDays = 0; + for (const trip of trips) { + if (trip.start_date && trip.end_date) { + const start = new Date(trip.start_date); + const end = new Date(trip.end_date); + const diff = Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24)) + 1; + if (diff > 0) totalDays += diff; + } + } + + const countries = [...countrySet.values()].map(c => { + const countryTrips = trips.filter(t => c.tripIds.has(t.id)); + const dates = countryTrips.map(t => t.start_date).filter(Boolean).sort(); + return { + code: c.code, + placeCount: c.places.length, + tripCount: c.tripIds.size, + firstVisit: dates[0] || null, + lastVisit: dates[dates.length - 1] || null, + }; + }); + + const citySet = new Set(); + for (const place of places) { + if (place.address) { + const parts = place.address.split(',').map((s: string) => s.trim()).filter(Boolean); + // The last part is the country; the city is usually right before it, but a + // full formatted address can have a postal code sitting between them + // (e.g. "Bucharest, 010071, Romania"). Walk back from the country and take + // the first part that still has letters once digits/postal noise is stripped. + const candidates = parts.length >= 2 ? parts.slice(0, -1) : parts; + let city = ''; + for (let i = candidates.length - 1; i >= 0; i--) { + const cleaned = candidates[i].replace(/[\d\-\u2212\u3012]+/g, '').trim(); + if (cleaned) { city = cleaned.toLowerCase(); break; } + } + if (city) citySet.add(city); + } + } + const totalCities = citySet.size; + + // Merge manually marked countries + const manualCountries = db.prepare('SELECT country_code FROM visited_countries WHERE user_id = ?').all(userId) as { country_code: string }[]; + for (const mc of manualCountries) { + if (!countries.find(c => c.code === mc.country_code)) { + countries.push({ code: mc.country_code, placeCount: 0, tripCount: 0, firstVisit: null, lastVisit: null }); + } + } + + const mostVisited = countries.length > 0 ? countries.reduce((a, b) => a.placeCount > b.placeCount ? a : b) : null; + + const continents: Record = {}; + countries.forEach(c => { + const cont = CONTINENT_MAP[c.code] || 'Other'; + continents[cont] = (continents[cont] || 0) + 1; + }); + + const now = new Date().toISOString().split('T')[0]; + const pastTrips = trips.filter(t => t.end_date && t.end_date <= now).sort((a, b) => b.end_date!.localeCompare(a.end_date!)); + const lastTrip: { id: number; title: string; start_date?: string | null; end_date?: string | null; countryCode?: string } | null = pastTrips[0] + ? { id: pastTrips[0].id, title: pastTrips[0].title, start_date: pastTrips[0].start_date, end_date: pastTrips[0].end_date } + : null; + if (lastTrip) { + const lastTripPlaces = places.filter(p => p.trip_id === lastTrip.id); + for (const p of lastTripPlaces) { + const code = resolveCountryCodeSync(p); + if (code) { lastTrip.countryCode = code; break; } + } + } + + const futureTrips = trips.filter(t => t.start_date && t.start_date > now).sort((a, b) => a.start_date!.localeCompare(b.start_date!)); + const nextTrip: { id: number; title: string; start_date?: string | null; daysUntil?: number } | null = futureTrips[0] + ? { id: futureTrips[0].id, title: futureTrips[0].title, start_date: futureTrips[0].start_date } + : null; + if (nextTrip) { + const diff = Math.ceil((new Date(nextTrip.start_date!).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24)); + nextTrip.daysUntil = Math.max(0, diff); + } + + const tripYears = new Set(trips.filter(t => t.start_date).map(t => parseInt(t.start_date!.split('-')[0]))); + let streak = 0; + const currentYear = new Date().getFullYear(); + for (let y = currentYear; y >= 2000; y--) { + if (tripYears.has(y)) streak++; + else break; + } + const firstYear = tripYears.size > 0 ? Math.min(...tripYears) : null; + + return { + countries, + stats: { + totalTrips: trips.length, + totalPlaces: places.length, + totalCountries: countries.length, + totalDays, + totalCities, + }, + mostVisited, + continents, + lastTrip, + nextTrip, + streak, + firstYear, + tripsThisYear: trips.filter(t => t.start_date && t.start_date.startsWith(String(currentYear))).length, + }; +} + +// ── getCountryPlaces ──────────────────────────────────────────────────────── + +export function getCountryPlaces(userId: number, code: string) { + const trips = getUserTrips(userId); + const tripIds = trips.map(t => t.id); + if (tripIds.length === 0) return { places: [], trips: [], manually_marked: false }; + + const places = getPlacesForTrips(tripIds); + + const matchingPlaces: { id: number; name: string; address: string | null; lat: number | null; lng: number | null; trip_id: number }[] = []; + const matchingTripIds = new Set(); + + for (const place of places) { + const pCode = resolveCountryCodeSync(place); + if (pCode === code) { + matchingPlaces.push({ id: place.id, name: place.name, address: place.address ?? null, lat: place.lat ?? null, lng: place.lng ?? null, trip_id: place.trip_id }); + matchingTripIds.add(place.trip_id); + } + } + + const matchingTrips = trips.filter(t => matchingTripIds.has(t.id)).map(t => ({ id: t.id, title: t.title, start_date: t.start_date, end_date: t.end_date })); + + const isManuallyMarked = !!(db.prepare('SELECT 1 FROM visited_countries WHERE user_id = ? AND country_code = ?').get(userId, code)); + return { places: matchingPlaces, trips: matchingTrips, manually_marked: isManuallyMarked }; +} + +// ── Mark / unmark country ─────────────────────────────────────────────────── + +export function listVisitedCountries(userId: number): { country_code: string; created_at: string }[] { + return db.prepare( + 'SELECT country_code, created_at FROM visited_countries WHERE user_id = ? ORDER BY created_at DESC' + ).all(userId) as { country_code: string; created_at: string }[]; +} + +export function markCountryVisited(userId: number, code: string): void { + db.prepare('INSERT OR IGNORE INTO visited_countries (user_id, country_code) VALUES (?, ?)').run(userId, code); +} + +export function unmarkCountryVisited(userId: number, code: string): void { + db.prepare('DELETE FROM visited_countries WHERE user_id = ? AND country_code = ?').run(userId, code); + db.prepare('DELETE FROM visited_regions WHERE user_id = ? AND country_code = ?').run(userId, code); +} + +// ── Mark / unmark region ──────────────────────────────────────────────────── + +export function listManuallyVisitedRegions(userId: number): { region_code: string; region_name: string; country_code: string }[] { + return db.prepare( + 'SELECT region_code, region_name, country_code FROM visited_regions WHERE user_id = ? ORDER BY created_at DESC' + ).all(userId) as { region_code: string; region_name: string; country_code: string }[]; +} + +export function markRegionVisited(userId: number, regionCode: string, regionName: string, countryCode: string): void { + db.prepare('INSERT OR IGNORE INTO visited_regions (user_id, region_code, region_name, country_code) VALUES (?, ?, ?, ?)').run(userId, regionCode, regionName, countryCode); + // Auto-mark parent country if not already visited + db.prepare('INSERT OR IGNORE INTO visited_countries (user_id, country_code) VALUES (?, ?)').run(userId, countryCode); +} + +export function unmarkRegionVisited(userId: number, regionCode: string): void { + const region = db.prepare('SELECT country_code FROM visited_regions WHERE user_id = ? AND region_code = ?').get(userId, regionCode) as { country_code: string } | undefined; + db.prepare('DELETE FROM visited_regions WHERE user_id = ? AND region_code = ?').run(userId, regionCode); + if (region) { + const remaining = db.prepare('SELECT COUNT(*) as count FROM visited_regions WHERE user_id = ? AND country_code = ?').get(userId, region.country_code) as { count: number }; + if (remaining.count === 0) { + db.prepare('DELETE FROM visited_countries WHERE user_id = ? AND country_code = ?').run(userId, region.country_code); + } + } +} + +// ── Sub-national region resolution ──────────────────────────────────────── + +interface RegionInfo { country_code: string; region_code: string; region_name: string } + +// Tracks place IDs currently being geocoded in the background to prevent duplicate enqueuing. +const geocodingInFlight = new Set(); + +const regionCache = new Map(); + +// A zoom-8 reverse geocode of a GB place only resolves to the constituent country +// (England/Scotland/Wales/Northern Ireland). Natural Earth's admin-1 polygons for GB +// are counties and boroughs, so those four codes match no polygon and never highlight. +const GB_CONSTITUENT_CODES = new Set(['GB-ENG', 'GB-SCT', 'GB-WLS', 'GB-NIR']); + +// Returns the OSM address object, {} for an "ok but empty" response (so it is cached as +// a definitive miss), or null for a transient failure (so it is retried next time). +async function fetchNominatimAddress(lat: number, lng: number, zoom: number): Promise | null> { + await throttleNominatim(); + try { + const res = await fetch( + `https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lng}&format=json&zoom=${zoom}&accept-language=en`, + { + headers: { 'User-Agent': 'TREK Travel Planner (https://github.com/mauriceboe/TREK)' }, + signal: AbortSignal.timeout(10_000), + } + ); + if (!res.ok) return null; + const data = await res.json() as { address?: Record }; + return data.address ?? {}; + } catch { + return null; + } +} + +function buildRegionInfo(address: Record, preferFinest: boolean): RegionInfo | null { + const countryCode = address.country_code?.toUpperCase() || null; + // Coarse path (almost every country) lands on the admin-1 level that matches Natural + // Earth directly; the finest path is used only to rescue codes that are too broad. + let regionCode = preferFinest + ? (address['ISO3166-2-lvl8'] || address['ISO3166-2-lvl7'] || address['ISO3166-2-lvl6'] || address['ISO3166-2-lvl5'] || null) + : (address['ISO3166-2-lvl6'] || address['ISO3166-2-lvl5'] || address['ISO3166-2-lvl4'] || null); + // Normalize: FR-75C → FR-75 (strip trailing letter suffixes for GeoJSON compatibility) + if (regionCode && /^[A-Z]{2}-\d+[A-Z]$/i.test(regionCode)) { + regionCode = regionCode.replace(/[A-Z]$/i, ''); + } + const regionName = preferFinest + ? (address.city || address.county || address.state_district || address.borough || address.state || address.province || address.region || null) + : (address.state || address.province || address.region || address.county || address.city || null); + if (!countryCode || !regionName) return null; + return { + country_code: countryCode, + region_code: regionCode || `${countryCode}-${regionName.substring(0, 3).toUpperCase()}`, + region_name: regionName, + }; +} + +async function reverseGeocodeRegion(lat: number, lng: number): Promise { + const key = roundKey(lat, lng); + if (regionCache.has(key)) return regionCache.get(key)!; + const address = await fetchNominatimAddress(lat, lng, 8); + if (!address) return null; // transient failure — leave uncached so a later call retries + let info = buildRegionInfo(address, false); + // GB constituent-country codes map to no admin-1 polygon, so re-resolve them at a finer + // zoom where Nominatim exposes the county/borough code (GB-LND, GB-MAN, GB-CON, …) that + // the polygons actually carry. + if (info && info.country_code === 'GB' && GB_CONSTITUENT_CODES.has(info.region_code)) { + const finerAddress = await fetchNominatimAddress(lat, lng, 10); + const finer = finerAddress ? buildRegionInfo(finerAddress, true) : null; + if (finer && !GB_CONSTITUENT_CODES.has(finer.region_code)) info = finer; + } + regionCache.set(key, info); + return info; +} + +export async function getVisitedRegions(userId: number): Promise<{ regions: Record }> { + const trips = getUserTrips(userId); + const tripIds = trips.map(t => t.id); + const places = getPlacesForTrips(tripIds); + + // Check DB cache first + const placeIds = places.filter(p => p.lat && p.lng).map(p => p.id); + const cached = placeIds.length > 0 + ? db.prepare(`SELECT * FROM place_regions WHERE place_id IN (${placeIds.map(() => '?').join(',')})`).all(...placeIds) as { place_id: number; country_code: string; region_code: string; region_name: string }[] + : []; + const cachedMap = new Map(cached.map(c => [c.place_id, c])); + + // Kick off background geocoding for uncached places; return cached data immediately. + const uncached = places.filter(p => p.lat && p.lng && !cachedMap.has(p.id) && !geocodingInFlight.has(p.id)); + if (uncached.length > 0) { + const insertStmt = db.prepare('INSERT OR REPLACE INTO place_regions (place_id, country_code, region_code, region_name) VALUES (?, ?, ?, ?)'); + for (const p of uncached) geocodingInFlight.add(p.id); + void (async () => { + try { + for (const place of uncached) { + try { + const info = await reverseGeocodeRegion(place.lat!, place.lng!); + if (info) insertStmt.run(place.id, info.country_code, info.region_code, info.region_name); + } catch { + // individual failure — continue with remaining places + } finally { + geocodingInFlight.delete(place.id); + } + } + } catch { + for (const p of uncached) geocodingInFlight.delete(p.id); + } + })(); + } + + // Group by country → regions with place counts + const regionMap: Record> = {}; + for (const [, entry] of cachedMap) { + if (!regionMap[entry.country_code]) regionMap[entry.country_code] = new Map(); + const existing = regionMap[entry.country_code].get(entry.region_code); + if (existing) { + existing.placeCount++; + } else { + regionMap[entry.country_code].set(entry.region_code, { code: entry.region_code, name: entry.region_name, placeCount: 1 }); + } + } + + const result: Record = {}; + for (const [country, regions] of Object.entries(regionMap)) { + result[country] = [...regions.values()]; + } + + // Merge manually marked regions + const manualRegions = listManuallyVisitedRegions(userId); + for (const r of manualRegions) { + if (!result[r.country_code]) result[r.country_code] = []; + if (!result[r.country_code].find(x => x.code === r.region_code)) { + result[r.country_code].push({ code: r.region_code, name: r.region_name, placeCount: 0, manuallyMarked: true }); + } + } + + return { regions: result }; +} + +// ── Bucket list CRUD ──────────────────────────────────────────────────────── + +export function listBucketList(userId: number) { + return db.prepare('SELECT * FROM bucket_list WHERE user_id = ? ORDER BY created_at DESC').all(userId); +} + +export function createBucketItem(userId: number, data: { name: string; lat?: number | null; lng?: number | null; country_code?: string | null; notes?: string | null; target_date?: string | null }) { + const result = db.prepare('INSERT INTO bucket_list (user_id, name, lat, lng, country_code, notes, target_date) VALUES (?, ?, ?, ?, ?, ?, ?)').run( + userId, data.name.trim(), data.lat ?? null, data.lng ?? null, data.country_code ?? null, data.notes ?? null, data.target_date ?? null + ); + return db.prepare('SELECT * FROM bucket_list WHERE id = ?').get(result.lastInsertRowid); +} + +export function updateBucketItem(userId: number, itemId: string | number, data: { name?: string; notes?: string; lat?: number | null; lng?: number | null; country_code?: string | null; target_date?: string | null }) { + const item = db.prepare('SELECT * FROM bucket_list WHERE id = ? AND user_id = ?').get(itemId, userId); + if (!item) return null; + db.prepare(`UPDATE bucket_list SET + name = COALESCE(?, name), + notes = CASE WHEN ? THEN ? ELSE notes END, + lat = CASE WHEN ? THEN ? ELSE lat END, + lng = CASE WHEN ? THEN ? ELSE lng END, + country_code = CASE WHEN ? THEN ? ELSE country_code END, + target_date = CASE WHEN ? THEN ? ELSE target_date END + WHERE id = ?`).run( + data.name?.trim() || null, + data.notes !== undefined ? 1 : 0, data.notes !== undefined ? (data.notes || null) : null, + data.lat !== undefined ? 1 : 0, data.lat !== undefined ? (data.lat || null) : null, + data.lng !== undefined ? 1 : 0, data.lng !== undefined ? (data.lng || null) : null, + data.country_code !== undefined ? 1 : 0, data.country_code !== undefined ? (data.country_code || null) : null, + data.target_date !== undefined ? 1 : 0, data.target_date !== undefined ? (data.target_date || null) : null, + itemId + ); + return db.prepare('SELECT * FROM bucket_list WHERE id = ?').get(itemId); +} + +export function deleteBucketItem(userId: number, itemId: string | number): boolean { + const item = db.prepare('SELECT * FROM bucket_list WHERE id = ? AND user_id = ?').get(itemId, userId); + if (!item) return false; + db.prepare('DELETE FROM bucket_list WHERE id = ?').run(itemId); + return true; +} diff --git a/server/src/services/auditLog.ts b/server/src/services/auditLog.ts new file mode 100644 index 0000000000000000000000000000000000000000..03476ecdde725788af8b5c658c613483aea60ecf --- /dev/null +++ b/server/src/services/auditLog.ts @@ -0,0 +1,168 @@ +import { Request } from 'express'; +import { db } from '../db/database'; +import fs from 'fs'; +import path from 'path'; + +const LOG_LEVEL = (process.env.LOG_LEVEL || 'info').toLowerCase(); +const MAX_LOG_SIZE = 10 * 1024 * 1024; // 10 MB +const MAX_LOG_FILES = 5; + +const C = { + blue: '\x1b[34m', + cyan: '\x1b[36m', + red: '\x1b[31m', + yellow: '\x1b[33m', + reset: '\x1b[0m', +}; + +// ── File logger with rotation ───────────────────────────────────────────── + +const logsDir = path.join(process.cwd(), 'data/logs'); +try { fs.mkdirSync(logsDir, { recursive: true }); } catch {} +const logFilePath = path.join(logsDir, 'trek.log'); + +function rotateIfNeeded(): void { + try { + if (!fs.existsSync(logFilePath)) return; + const stat = fs.statSync(logFilePath); + if (stat.size < MAX_LOG_SIZE) return; + + for (let i = MAX_LOG_FILES - 1; i >= 1; i--) { + const src = i === 1 ? logFilePath : `${logFilePath}.${i - 1}`; + const dst = `${logFilePath}.${i}`; + if (fs.existsSync(src)) fs.renameSync(src, dst); + } + } catch {} +} + +function writeToFile(line: string): void { + try { + rotateIfNeeded(); + fs.appendFileSync(logFilePath, line + '\n'); + } catch {} +} + +// ── Public log helpers ──────────────────────────────────────────────────── + +function formatTs(): string { + const tz = process.env.TZ || 'UTC'; + return new Date().toLocaleString('sv-SE', { timeZone: tz }).replace(' ', 'T'); +} + +function logInfo(msg: string): void { + const ts = formatTs(); + console.log(`${C.blue}[INFO]${C.reset} ${ts} ${msg}`); + writeToFile(`[INFO] ${ts} ${msg}`); +} + +function logDebug(msg: string): void { + if (LOG_LEVEL !== 'debug') return; + const ts = formatTs(); + console.log(`${C.cyan}[DEBUG]${C.reset} ${ts} ${msg}`); + writeToFile(`[DEBUG] ${ts} ${msg}`); +} + +function logError(msg: string): void { + const ts = formatTs(); + console.error(`${C.red}[ERROR]${C.reset} ${ts} ${msg}`); + writeToFile(`[ERROR] ${ts} ${msg}`); +} + +function logWarn(msg: string): void { + const ts = formatTs(); + console.warn(`${C.yellow}[WARN]${C.reset} ${ts} ${msg}`); + writeToFile(`[WARN] ${ts} ${msg}`); +} + +// ── IP + audit ──────────────────────────────────────────────────────────── + +export function getClientIp(req: Request): string | null { + const xff = req.headers['x-forwarded-for']; + if (typeof xff === 'string') { + const first = xff.split(',')[0]?.trim(); + return first || null; + } + if (Array.isArray(xff) && xff[0]) return String(xff[0]).trim() || null; + return req.socket?.remoteAddress || null; +} + +function resolveUserEmail(userId: number | null): string { + if (!userId) return 'anonymous'; + try { + const row = db.prepare('SELECT email FROM users WHERE id = ?').get(userId) as { email: string } | undefined; + return row?.email || `uid:${userId}`; + } catch { return `uid:${userId}`; } +} + +const ACTION_LABELS: Record = { + 'user.register': 'registered', + 'user.login': 'logged in', + 'user.login_failed': 'login failed', + 'user.password_change': 'changed password', + 'user.account_delete': 'deleted account', + 'user.mfa_enable': 'enabled MFA', + 'user.mfa_disable': 'disabled MFA', + 'settings.app_update': 'updated settings', + 'trip.create': 'created trip', + 'trip.delete': 'deleted trip', + 'admin.user_role_change': 'changed user role', + 'admin.user_delete': 'deleted user', + 'admin.invite_create': 'created invite', + 'immich.private_ip_configured': 'configured Immich with private IP', +}; + +/** Best-effort; never throws — failures are logged only. */ +export function writeAudit(entry: { + userId: number | null; + action: string; + resource?: string | null; + details?: Record; + debugDetails?: Record; + ip?: string | null; +}): void { + try { + const detailsJson = entry.details && Object.keys(entry.details).length > 0 ? JSON.stringify(entry.details) : null; + db.prepare( + `INSERT INTO audit_log (user_id, action, resource, details, ip) VALUES (?, ?, ?, ?, ?)` + ).run(entry.userId, entry.action, entry.resource ?? null, detailsJson, entry.ip ?? null); + + const email = resolveUserEmail(entry.userId); + const label = ACTION_LABELS[entry.action] || entry.action; + const brief = buildInfoSummary(entry.action, entry.details); + logInfo(`${email} ${label}${brief} ip=${entry.ip || '-'}`); + + if (entry.debugDetails && Object.keys(entry.debugDetails).length > 0) { + logDebug(`AUDIT ${entry.action} userId=${entry.userId} ${JSON.stringify(entry.debugDetails)}`); + } else if (detailsJson) { + logDebug(`AUDIT ${entry.action} userId=${entry.userId} ${detailsJson}`); + } + } catch (e) { + logError(`Audit write failed: ${e instanceof Error ? e.message : e}`); + } +} + +function buildInfoSummary(action: string, details?: Record): string { + if (!details || Object.keys(details).length === 0) return ''; + if (action === 'trip.create') return ` "${details.title}"`; + if (action === 'trip.delete') return ` tripId=${details.tripId}`; + if (action === 'user.register') return ` ${details.email}`; + if (action === 'user.login') return ''; + if (action === 'user.login_failed') return ` reason=${details.reason}`; + if (action === 'settings.app_update') { + const parts: string[] = []; + if (details.notification_channel) parts.push(`channel=${details.notification_channel}`); + if (details.smtp_settings_updated) parts.push('smtp'); + if (details.notification_events_updated) parts.push('events'); + if (details.webhook_url_updated) parts.push('webhook_url'); + if (details.allowed_file_types_updated) parts.push('file_types'); + if (details.allow_registration !== undefined) parts.push(`registration=${details.allow_registration}`); + if (details.require_mfa !== undefined) parts.push(`mfa=${details.require_mfa}`); + return parts.length ? ` (${parts.join(', ')})` : ''; + } + if (action === 'immich.private_ip_configured') { + return details.resolved_ip ? ` url=${details.immich_url} ip=${details.resolved_ip}` : ''; + } + return ''; +} + +export { LOG_LEVEL, logInfo, logDebug, logError, logWarn }; diff --git a/server/src/services/authService.ts b/server/src/services/authService.ts new file mode 100644 index 0000000000000000000000000000000000000000..bc516577d497e720f9edaf4c7cd7239f8c3219dc --- /dev/null +++ b/server/src/services/authService.ts @@ -0,0 +1,1445 @@ +import bcrypt from 'bcryptjs'; +import jwt from 'jsonwebtoken'; +import crypto from 'crypto'; +import path from 'path'; +import fs from 'fs'; +import { authenticator } from 'otplib'; +import QRCode from 'qrcode'; +import { randomBytes, createHash } from 'crypto'; +import { db } from '../db/database'; +import { JWT_SECRET, SESSION_DURATION_SECONDS, SESSION_DURATION_REMEMBER_SECONDS } from '../config'; +import { validatePassword } from './passwordPolicy'; +import { encryptMfaSecret, decryptMfaSecret } from './mfaCrypto'; +import { getAllPermissions } from './permissions'; +import { decrypt_api_key, maybe_encrypt_api_key, encrypt_api_key } from './apiKeyCrypto'; +import { createEphemeralToken } from './ephemeralTokens'; +import { revokeUserSessions } from '../mcp'; +import { startTripReminders } from '../scheduler'; +import { deleteUserCompletely } from './userCleanupService'; +import { getFlightDistanceKm } from './distanceService'; +import { verifyJwtAndLoadUser } from '../middleware/auth'; +import { User } from '../types'; +import { DEMO_EMAIL_PRIMARY, isDemoEmail } from './demo'; +import { avatarUrl } from './avatarUrl'; +import { isPasskeyConfigured } from './webauthnConfig'; + +export { avatarUrl }; + +// --------------------------------------------------------------------------- +// Constants +// --------------------------------------------------------------------------- + +authenticator.options = { window: 1 }; + +// bcrypt cost factor for user passwords. Shared by register/changePassword/ +// resetPassword and the dummy-hash timing equaliser below — must stay in sync. +const BCRYPT_COST = 12; + +// Shape check for email input on register and profile update. +const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + +// Pre-computed bcrypt hash to equalise timing of "unknown email" and +// "OIDC-only account" branches with the real verification path (CWE-208). +const DUMMY_PASSWORD_HASH = bcrypt.hashSync('__trek_no_such_user__', BCRYPT_COST); + +const MFA_SETUP_TTL_MS = 15 * 60 * 1000; +const mfaSetupPending = new Map(); +const MFA_BACKUP_CODE_COUNT = 10; + +const ADMIN_SETTINGS_KEYS = [ + 'allow_registration', 'allowed_file_types', 'require_mfa', + 'smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_from', 'smtp_skip_tls_verify', + 'notification_channels', 'admin_webhook_url', 'admin_ntfy_server', 'admin_ntfy_topic', 'admin_ntfy_token', + 'notify_trip_reminder', + 'password_login', 'password_registration', 'oidc_login', 'oidc_registration', + 'passkey_login', 'webauthn_rp_id', 'webauthn_origins', +]; + +const avatarDir = path.join(__dirname, '../../uploads/avatars'); +if (!fs.existsSync(avatarDir)) fs.mkdirSync(avatarDir, { recursive: true }); + +const KNOWN_COUNTRIES = new Set([ + 'Japan', 'Germany', 'Deutschland', 'France', 'Frankreich', 'Italy', 'Italien', 'Spain', 'Spanien', + 'United States', 'USA', 'United Kingdom', 'UK', 'Thailand', 'Australia', 'Australien', + 'Canada', 'Kanada', 'Mexico', 'Mexiko', 'Brazil', 'Brasilien', 'China', 'India', 'Indien', + 'South Korea', 'Sudkorea', 'Indonesia', 'Indonesien', 'Turkey', 'Turkei', 'Turkiye', + 'Greece', 'Griechenland', 'Portugal', 'Netherlands', 'Niederlande', 'Belgium', 'Belgien', + 'Switzerland', 'Schweiz', 'Austria', 'Osterreich', 'Sweden', 'Schweden', 'Norway', 'Norwegen', + 'Denmark', 'Danemark', 'Finland', 'Finnland', 'Poland', 'Polen', 'Czech Republic', 'Tschechien', + 'Czechia', 'Hungary', 'Ungarn', 'Croatia', 'Kroatien', 'Romania', 'Rumanien', + 'Ireland', 'Irland', 'Iceland', 'Island', 'New Zealand', 'Neuseeland', + 'Singapore', 'Singapur', 'Malaysia', 'Vietnam', 'Philippines', 'Philippinen', + 'Egypt', 'Agypten', 'Morocco', 'Marokko', 'South Africa', 'Sudafrika', 'Kenya', 'Kenia', + 'Argentina', 'Argentinien', 'Chile', 'Colombia', 'Kolumbien', 'Peru', + 'Russia', 'Russland', 'United Arab Emirates', 'UAE', 'Vereinigte Arabische Emirate', + 'Israel', 'Jordan', 'Jordanien', 'Taiwan', 'Hong Kong', 'Hongkong', + 'Cuba', 'Kuba', 'Costa Rica', 'Panama', 'Ecuador', 'Bolivia', 'Bolivien', 'Uruguay', 'Paraguay', + 'Luxembourg', 'Luxemburg', 'Malta', 'Cyprus', 'Zypern', 'Estonia', 'Estland', + 'Latvia', 'Lettland', 'Lithuania', 'Litauen', 'Slovakia', 'Slowakei', 'Slovenia', 'Slowenien', + 'Bulgaria', 'Bulgarien', 'Serbia', 'Serbien', 'Montenegro', 'Albania', 'Albanien', + 'Sri Lanka', 'Nepal', 'Cambodia', 'Kambodscha', 'Laos', 'Myanmar', 'Mongolia', 'Mongolei', + 'Saudi Arabia', 'Saudi-Arabien', 'Qatar', 'Katar', 'Oman', 'Bahrain', 'Kuwait', + 'Tanzania', 'Tansania', 'Ethiopia', 'Athiopien', 'Nigeria', 'Ghana', 'Tunisia', 'Tunesien', + 'Dominican Republic', 'Dominikanische Republik', 'Jamaica', 'Jamaika', + 'Ukraine', 'Georgia', 'Georgien', 'Armenia', 'Armenien', 'Pakistan', 'Bangladesh', 'Bangladesch', + 'Senegal', 'Mozambique', 'Mosambik', 'Moldova', 'Moldawien', 'Belarus', 'Weissrussland', +]); + +// --------------------------------------------------------------------------- +// Helpers (exported for route-level use where needed) +// --------------------------------------------------------------------------- + +export function utcSuffix(ts: string | null | undefined): string | null { + if (!ts) return null; + return ts.endsWith('Z') ? ts : ts.replace(' ', 'T') + 'Z'; +} + +export function stripUserForClient(user: User): Record { + const { + password_hash: _p, + maps_api_key: _m, + openweather_api_key: _o, + unsplash_api_key: _u, + mfa_secret: _mf, + mfa_backup_codes: _mbc, + ...rest + } = user; + return { + ...rest, + created_at: utcSuffix(rest.created_at), + updated_at: utcSuffix(rest.updated_at), + last_login: utcSuffix(rest.last_login), + mfa_enabled: !!(user.mfa_enabled === 1 || user.mfa_enabled === true), + must_change_password: !!(user.must_change_password === 1 || user.must_change_password === true), + }; +} + +export function maskKey(key: string | null | undefined): string | null { + if (!key) return null; + if (key.length <= 8) return '--------'; + return '----' + key.slice(-4); +} + +export function mask_stored_api_key(key: string | null | undefined): string | null { + const plain = decrypt_api_key(key); + return maskKey(plain); +} + +export function resolveAuthToggles(): { + password_login: boolean; + password_registration: boolean; + oidc_login: boolean; + oidc_registration: boolean; + passkey_login: boolean; +} { + const get = (key: string) => + (db.prepare("SELECT value FROM app_settings WHERE key = ?").get(key) as { value: string } | undefined)?.value ?? null; + + // Passkey login is independent of the password/OIDC "new keys" probe, so it + // must be resolved OUTSIDE the branch below — otherwise on a fresh install + // that never touched the password/OIDC toggles it would silently read false + // even after an admin enabled it. Default OFF (opt-in). + const passkey_login = get('passkey_login') === 'true'; + + const hasNewKeys = ['password_login', 'password_registration', 'oidc_login', 'oidc_registration'] + .some(k => get(k) !== null); + + if (hasNewKeys) { + const result = { + password_login: get('password_login') !== 'false', + password_registration: get('password_registration') !== 'false', + oidc_login: get('oidc_login') !== 'false', + oidc_registration: get('oidc_registration') !== 'false', + passkey_login, + }; + if (process.env.OIDC_ONLY?.toLowerCase() === 'true') { + result.password_login = false; + result.password_registration = false; + } + return result; + } + + // Legacy fallback + const oidcOnlyEnabled = process.env.OIDC_ONLY?.toLowerCase() === 'true' || get('oidc_only') === 'true'; + const oidcConfigured = !!( + (process.env.OIDC_ISSUER || get('oidc_issuer')) && + (process.env.OIDC_CLIENT_ID || get('oidc_client_id')) + ); + const oidcOnly = oidcOnlyEnabled && oidcConfigured; + const allowReg = (get('allow_registration') ?? 'true') === 'true'; + + return { + password_login: !oidcOnly, + password_registration: !oidcOnly && allowReg, + oidc_login: true, + oidc_registration: allowReg, + passkey_login, + }; +} + +export function isOidcOnlyMode(): boolean { + return !resolveAuthToggles().password_login; +} + +export function generateToken(user: { id: number | bigint; password_version?: number }, rememberMe = false) { + const pv = typeof user.password_version === 'number' + ? user.password_version + : ((db.prepare('SELECT password_version FROM users WHERE id = ?').get(user.id) as { password_version?: number } | undefined)?.password_version ?? 0); + // "Remember me" extends the JWT lifetime to match the persistent cookie maxAge; + // the cookie service decides session-vs-persistent off the same flag. + const expiresIn = rememberMe ? SESSION_DURATION_REMEMBER_SECONDS : SESSION_DURATION_SECONDS; + return jwt.sign( + { id: user.id, pv }, + JWT_SECRET, + { expiresIn, algorithm: 'HS256' } + ); +} + +// --------------------------------------------------------------------------- +// MFA helpers +// --------------------------------------------------------------------------- + +export function normalizeBackupCode(input: string): string { + return String(input || '').toUpperCase().replace(/[^A-Z0-9]/g, ''); +} + +// Legacy SHA-256 hex hash. Kept so existing stored hashes (from before +// the bcrypt migration) can still be verified in `matchBackupCode` +// without forcing every user to re-enrol their MFA device. New hashes +// are produced by `hashBackupCodeBcrypt` below. +export function hashBackupCode(input: string): string { + return crypto.createHash('sha256').update(normalizeBackupCode(input)).digest('hex'); +} + +const BCRYPT_BACKUP_COST = 10; + +/** + * Hash a backup code with bcrypt for at-rest storage. Backup codes only + * have ~40 bits of entropy (8 hex chars) so a plain SHA-256 rainbow + * table cracks them in minutes if the DB ever leaks. bcrypt with a + * moderate cost raises that cost by ~3-4 orders of magnitude. + */ +export function hashBackupCodeBcrypt(input: string): string { + return bcrypt.hashSync(normalizeBackupCode(input), BCRYPT_BACKUP_COST); +} + +/** + * Constant-time match of a plaintext backup code against a stored hash + * in either format (bcrypt or legacy SHA-256 hex). Used by login and + * password-reset flows; callers that need to CONSUME the matching + * entry should use this to find the index, then splice it out. + */ +export function matchBackupCode(plaintext: string, storedHash: string): boolean { + if (!storedHash) return false; + if (storedHash.startsWith('$2')) { + // bcrypt hash — compareSync is constant-time internally. + try { return bcrypt.compareSync(normalizeBackupCode(plaintext), storedHash); } + catch { return false; } + } + // Legacy SHA-256 hex. Compare the SHA-256 of the input against the + // stored hex with a constant-time comparator so timing can't leak. + const candidate = hashBackupCode(plaintext); + if (candidate.length !== storedHash.length) return false; + return crypto.timingSafeEqual(Buffer.from(candidate), Buffer.from(storedHash)); +} + +export function generateBackupCodes(count = MFA_BACKUP_CODE_COUNT): string[] { + const codes: string[] = []; + while (codes.length < count) { + const raw = crypto.randomBytes(4).toString('hex').toUpperCase(); + const code = `${raw.slice(0, 4)}-${raw.slice(4)}`; + if (!codes.includes(code)) codes.push(code); + } + return codes; +} + +export function parseBackupCodeHashes(raw: string | null | undefined): string[] { + if (!raw) return []; + try { + const parsed = JSON.parse(raw); + return Array.isArray(parsed) ? parsed.filter(v => typeof v === 'string') : []; + } catch { + return []; + } +} + +export function getPendingMfaSecret(userId: number): string | null { + const row = mfaSetupPending.get(userId); + if (!row || Date.now() > row.exp) { + mfaSetupPending.delete(userId); + return null; + } + return row.secret; +} + +// --------------------------------------------------------------------------- +// App config (public) +// --------------------------------------------------------------------------- + +export function getAppConfig(authenticatedUser: { id: number } | null) { + const userCount = (db.prepare('SELECT COUNT(*) as count FROM users').get() as { count: number }).count; + const isDemo = process.env.DEMO_MODE?.toLowerCase() === 'true'; + const toggles = resolveAuthToggles(); + const version: string = process.env.APP_VERSION ?? require('../../package.json').version; + const hasGoogleKey = !!db.prepare("SELECT maps_api_key FROM users WHERE role = 'admin' AND maps_api_key IS NOT NULL AND maps_api_key != '' LIMIT 1").get(); + const oidcDisplayName = process.env.OIDC_DISPLAY_NAME || + (db.prepare("SELECT value FROM app_settings WHERE key = 'oidc_display_name'").get() as { value: string } | undefined)?.value || null; + const oidcConfigured = !!( + (process.env.OIDC_ISSUER || (db.prepare("SELECT value FROM app_settings WHERE key = 'oidc_issuer'").get() as { value: string } | undefined)?.value) && + (process.env.OIDC_CLIENT_ID || (db.prepare("SELECT value FROM app_settings WHERE key = 'oidc_client_id'").get() as { value: string } | undefined)?.value) + ); + const requireMfaRow = db.prepare("SELECT value FROM app_settings WHERE key = 'require_mfa'").get() as { value: string } | undefined; + const notifChannel = (db.prepare("SELECT value FROM app_settings WHERE key = 'notification_channel'").get() as { value: string } | undefined)?.value || 'none'; + const tripReminderSetting = (db.prepare("SELECT value FROM app_settings WHERE key = 'notify_trip_reminder'").get() as { value: string } | undefined)?.value; + const hasSmtpHost = !!(process.env.SMTP_HOST || (db.prepare("SELECT value FROM app_settings WHERE key = 'smtp_host'").get() as { value: string } | undefined)?.value); + const notifChannelsRaw = (db.prepare("SELECT value FROM app_settings WHERE key = 'notification_channels'").get() as { value: string } | undefined)?.value || notifChannel; + const activeChannels = notifChannelsRaw === 'none' ? [] : notifChannelsRaw.split(',').map((c: string) => c.trim()).filter(Boolean); + const hasWebhookEnabled = activeChannels.includes('webhook'); + const tripRemindersEnabled = tripReminderSetting !== 'false'; + const placesPhotosSetting = (db.prepare("SELECT value FROM app_settings WHERE key = 'places_photos_enabled'").get() as { value: string } | undefined)?.value; + const placesPhotosEnabled = placesPhotosSetting !== 'false'; + const placesAutocompleteSetting = (db.prepare("SELECT value FROM app_settings WHERE key = 'places_autocomplete_enabled'").get() as { value: string } | undefined)?.value; + const placesAutocompleteEnabled = placesAutocompleteSetting !== 'false'; + const placesDetailsSetting = (db.prepare("SELECT value FROM app_settings WHERE key = 'places_details_enabled'").get() as { value: string } | undefined)?.value; + const placesDetailsEnabled = placesDetailsSetting !== 'false'; + const setupComplete = userCount > 0 && !(db.prepare("SELECT id FROM users WHERE role = 'admin' AND must_change_password = 1 LIMIT 1").get()); + + return { + // Legacy fields (backward compat) + allow_registration: isDemo ? false : (toggles.password_registration || toggles.oidc_registration), + oidc_only_mode: !toggles.password_login && !toggles.password_registration, + // Granular toggles + password_login: toggles.password_login, + password_registration: isDemo ? false : toggles.password_registration, + oidc_login: toggles.oidc_login, + oidc_registration: isDemo ? false : toggles.oidc_registration, + // Passkey login: the instance toggle + whether a usable RP ID resolves for + // this deployment. The login page shows the passkey button only when both + // are true. `passkey_configured` stays a pure boolean — it never leaks the + // resolved RP ID / origin / APP_URL on this unauthenticated endpoint. + passkey_login: toggles.passkey_login, + passkey_configured: isPasskeyConfigured(), + env_override_oidc_only: process.env.OIDC_ONLY === 'true', + has_users: userCount > 0, + setup_complete: setupComplete, + version, + is_prerelease: version.includes('-pre.'), + has_maps_key: hasGoogleKey, + oidc_configured: oidcConfigured, + oidc_display_name: oidcConfigured ? (oidcDisplayName || 'SSO') : undefined, + require_mfa: requireMfaRow?.value === 'true', + allowed_file_types: (db.prepare("SELECT value FROM app_settings WHERE key = 'allowed_file_types'").get() as { value: string } | undefined)?.value || 'jpg,jpeg,png,gif,webp,heic,pdf,doc,docx,xls,xlsx,txt,csv', + demo_mode: isDemo, + demo_email: isDemo ? DEMO_EMAIL_PRIMARY : undefined, + demo_password: isDemo ? 'demo12345' : undefined, + timezone: process.env.TZ || Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC', + notification_channel: notifChannel, + notification_channels: activeChannels, + available_channels: { email: hasSmtpHost, webhook: hasWebhookEnabled, inapp: true }, + trip_reminders_enabled: tripRemindersEnabled, + places_photos_enabled: placesPhotosEnabled, + places_autocomplete_enabled: placesAutocompleteEnabled, + places_details_enabled: placesDetailsEnabled, + permissions: authenticatedUser ? getAllPermissions() : undefined, + dev_mode: process.env.NODE_ENV === 'development', + }; +} + +// --------------------------------------------------------------------------- +// Auth: register, login, demo +// --------------------------------------------------------------------------- + +export function demoLogin(): { error?: string; status?: number; token?: string; user?: Record } { + if (process.env.DEMO_MODE !== 'true') { + return { error: 'Not found', status: 404 }; + } + const user = db.prepare('SELECT * FROM users WHERE email = ?').get(DEMO_EMAIL_PRIMARY) as User | undefined; + if (!user) return { error: 'Demo user not found', status: 500 }; + const token = generateToken(user); + const safe = stripUserForClient(user) as Record; + return { token, user: { ...safe, avatar_url: avatarUrl(user) } }; +} + +export function validateInviteToken(token: string): { error?: string; status?: number; valid?: boolean; max_uses?: number; used_count?: number; expires_at?: string } { + const invite = db.prepare('SELECT * FROM invite_tokens WHERE token = ?').get(token) as any; + if (!invite) return { error: 'Invalid invite link', status: 404 }; + if (invite.max_uses > 0 && invite.used_count >= invite.max_uses) return { error: 'Invite link has been fully used', status: 410 }; + if (invite.expires_at && new Date(invite.expires_at) < new Date()) return { error: 'Invite link has expired', status: 410 }; + return { valid: true, max_uses: invite.max_uses, used_count: invite.used_count, expires_at: invite.expires_at }; +} + +export function registerUser(body: { + username?: string; + email?: string; + password?: string; + invite_token?: string; +}): { error?: string; status?: number; token?: string; user?: Record; auditUserId?: number; auditDetails?: Record } { + const username = typeof body.username === 'string' ? body.username.trim() : ''; + const email = typeof body.email === 'string' ? body.email.trim() : ''; + const { password, invite_token } = body; + + const userCount = (db.prepare('SELECT COUNT(*) as count FROM users').get() as { count: number }).count; + + let validInvite: any = null; + if (invite_token) { + validInvite = db.prepare('SELECT * FROM invite_tokens WHERE token = ?').get(invite_token); + if (!validInvite) return { error: 'Invalid invite link', status: 400 }; + if (validInvite.max_uses > 0 && validInvite.used_count >= validInvite.max_uses) return { error: 'Invite link has been fully used', status: 410 }; + if (validInvite.expires_at && new Date(validInvite.expires_at) < new Date()) return { error: 'Invite link has expired', status: 410 }; + } + + if (userCount > 0 && !validInvite) { + const toggles = resolveAuthToggles(); + if (!toggles.password_registration) { + return { error: 'Password registration is disabled. Contact your administrator.', status: 403 }; + } + } + + if (!username || !email || !password) { + return { error: 'Username, email and password are required', status: 400 }; + } + + const pwCheck = validatePassword(password); + if (!pwCheck.ok) return { error: pwCheck.reason, status: 400 }; + + if (!EMAIL_REGEX.test(email)) { + return { error: 'Invalid email format', status: 400 }; + } + + const existingUser = db.prepare('SELECT id FROM users WHERE LOWER(email) = LOWER(?) OR LOWER(username) = LOWER(?)').get(email, username); + if (existingUser) { + return { error: 'Registration failed. Please try different credentials.', status: 409 }; + } + + const password_hash = bcrypt.hashSync(password, BCRYPT_COST); + const isFirstUser = userCount === 0; + const role = isFirstUser ? 'admin' : 'user'; + + try { + const result = db.prepare( + 'INSERT INTO users (username, email, password_hash, role, first_seen_version, login_count) VALUES (?, ?, ?, ?, ?, 0)' + ).run(username, email, password_hash, role, process.env.APP_VERSION || '0.0.0'); + + const user = { id: result.lastInsertRowid, username, email, role, avatar: null, mfa_enabled: false }; + const token = generateToken(user); + + if (validInvite) { + const updated = db.prepare( + 'UPDATE invite_tokens SET used_count = used_count + 1 WHERE id = ? AND (max_uses = 0 OR used_count < max_uses) RETURNING used_count' + ).get(validInvite.id); + if (!updated) { + console.warn(`[Auth] Invite token ${validInvite.token.slice(0, 8)}... exceeded max_uses due to race condition`); + } + } + + return { + token, + user: { ...user, avatar_url: null }, + auditUserId: Number(result.lastInsertRowid), + auditDetails: { username, email, role }, + }; + } catch { + return { error: 'Error creating user', status: 500 }; + } +} + +export function loginUser(body: { + email?: string; + password?: string; + remember_me?: boolean; +}): { + error?: string; + status?: number; + token?: string; + user?: Record; + mfa_required?: boolean; + mfa_token?: string; + remember?: boolean; + auditUserId?: number | null; + auditAction?: string; + auditDetails?: Record; +} { + if (isOidcOnlyMode()) { + return { error: 'Password authentication is disabled. Please sign in with SSO.', status: 403 }; + } + + const { email, password, remember_me } = body; + const remember = remember_me === true; + if (!email || !password) { + return { error: 'Email and password are required', status: 400 }; + } + + const user = db.prepare('SELECT * FROM users WHERE LOWER(email) = LOWER(?)').get(email) as User | undefined; + + // Always run bcrypt — even for unknown/OIDC-only users — so response time + // does not reveal whether the email exists in the database (CWE-203/208). + const hashToCheck = user?.password_hash ?? DUMMY_PASSWORD_HASH; + const validPassword = bcrypt.compareSync(password, hashToCheck); + + if (!user) { + return { + error: 'Invalid email or password', status: 401, + auditUserId: null, auditAction: 'user.login_failed', auditDetails: { email, reason: 'unknown_email' }, + }; + } + if (!user.password_hash) { + return { + error: 'Invalid email or password', status: 401, + auditUserId: Number(user.id), auditAction: 'user.login_failed', auditDetails: { email, reason: 'oidc_only' }, + }; + } + if (!validPassword) { + return { + error: 'Invalid email or password', status: 401, + auditUserId: Number(user.id), auditAction: 'user.login_failed', auditDetails: { email, reason: 'wrong_password' }, + }; + } + + if (user.mfa_enabled === 1 || user.mfa_enabled === true) { + const pv = (user as User & { password_version?: number }).password_version ?? 0; + const mfa_token = jwt.sign( + { id: Number(user.id), purpose: 'mfa_login', pv }, + JWT_SECRET, + { expiresIn: '5m', algorithm: 'HS256' } + ); + return { mfa_required: true, mfa_token }; + } + + db.prepare('UPDATE users SET last_login = CURRENT_TIMESTAMP, login_count = login_count + 1 WHERE id = ?').run(user.id); + const token = generateToken(user, remember); + const userSafe = stripUserForClient(user) as Record; + + return { + token, + user: { ...userSafe, avatar_url: avatarUrl(user) }, + remember, + auditUserId: Number(user.id), + auditAction: 'user.login', + auditDetails: { email }, + }; +} + +// --------------------------------------------------------------------------- +// Session +// --------------------------------------------------------------------------- + +export function getCurrentUser( + userId: number +): (Record & Pick & { avatar_url: string }) | null { + const user = db.prepare( + 'SELECT id, username, email, role, avatar, oidc_issuer, created_at, mfa_enabled, must_change_password FROM users WHERE id = ?' + ).get(userId) as User | undefined; + if (!user) return null; + const base = stripUserForClient(user as User) as Record; + return { ...base, id: user.id, username: user.username, email: user.email, role: user.role, avatar_url: avatarUrl(user) }; +} + +// --------------------------------------------------------------------------- +// Password & account +// --------------------------------------------------------------------------- + +export function changePassword( + userId: number, + userEmail: string, + body: { current_password?: string; new_password?: string } +): { error?: string; status?: number; success?: boolean; token?: string } { + if (isOidcOnlyMode()) { + return { error: 'Password authentication is disabled.', status: 403 }; + } + if (process.env.DEMO_MODE === 'true' && isDemoEmail(userEmail)) { + return { error: 'Password change is disabled in demo mode.', status: 403 }; + } + + const { current_password, new_password } = body; + if (!current_password) return { error: 'Current password is required', status: 400 }; + if (!new_password) return { error: 'New password is required', status: 400 }; + + const pwCheck = validatePassword(new_password); + if (!pwCheck.ok) return { error: pwCheck.reason, status: 400 }; + + const user = db.prepare('SELECT password_hash, password_version FROM users WHERE id = ?').get(userId) as { password_hash: string; password_version?: number } | undefined; + if (!user || !bcrypt.compareSync(current_password, user.password_hash)) { + return { error: 'Current password is incorrect', status: 401 }; + } + + const hash = bcrypt.hashSync(new_password, BCRYPT_COST); + const newPv = (user.password_version ?? 0) + 1; + + db.transaction(() => { + db.prepare('UPDATE users SET password_hash = ?, must_change_password = 0, password_version = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?').run(hash, newPv, userId); + // A password change rotates the user's sessions: bumping password_version + // invalidates existing JWT cookie sessions, and the separate MCP static + // token and OAuth bearer-token stores are pruned to match (same set the + // password-reset path already revokes). + db.prepare('DELETE FROM mcp_tokens WHERE user_id = ?').run(userId); + try { + db.prepare("UPDATE oauth_tokens SET revoked_at = CURRENT_TIMESTAMP WHERE user_id = ? AND revoked_at IS NULL").run(userId); + } catch { /* oauth_tokens table may not exist in very old installs */ } + })(); + + try { revokeUserSessions?.(userId); } catch { /* best-effort */ } + + // Re-issue a session bound to the new password_version so the current device + // stays logged in while other existing sessions are rotated out by the pv gate. + const token = generateToken({ id: userId, password_version: newPv }); + return { success: true, token }; +} + +export function deleteAccount(userId: number, userEmail: string, userRole: string): { error?: string; status?: number; success?: boolean } { + if (process.env.DEMO_MODE === 'true' && isDemoEmail(userEmail)) { + return { error: 'Account deletion is disabled in demo mode.', status: 403 }; + } + if (userRole === 'admin') { + const adminCount = (db.prepare("SELECT COUNT(*) as count FROM users WHERE role = 'admin'").get() as { count: number }).count; + if (adminCount <= 1) { + return { error: 'Cannot delete the last admin account', status: 400 }; + } + } + deleteUserCompletely(userId); + return { success: true }; +} + +// --------------------------------------------------------------------------- +// API keys +// --------------------------------------------------------------------------- + +export function updateMapsKey(userId: number, maps_api_key: string | null | undefined) { + db.prepare( + 'UPDATE users SET maps_api_key = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?' + ).run(maybe_encrypt_api_key(maps_api_key), userId); + return { success: true, maps_api_key: mask_stored_api_key(maps_api_key) }; +} + +export function updateApiKeys( + userId: number, + body: { maps_api_key?: string; openweather_api_key?: string } +) { + const current = db.prepare('SELECT maps_api_key, openweather_api_key FROM users WHERE id = ?').get(userId) as Pick | undefined; + + db.prepare( + 'UPDATE users SET maps_api_key = ?, openweather_api_key = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?' + ).run( + body.maps_api_key !== undefined ? maybe_encrypt_api_key(body.maps_api_key) : current!.maps_api_key, + body.openweather_api_key !== undefined ? maybe_encrypt_api_key(body.openweather_api_key) : current!.openweather_api_key, + userId + ); + + const updated = db.prepare( + 'SELECT id, username, email, role, maps_api_key, openweather_api_key, avatar, mfa_enabled FROM users WHERE id = ?' + ).get(userId) as Pick | undefined; + + const u = updated ? { ...updated, mfa_enabled: !!(updated.mfa_enabled === 1 || updated.mfa_enabled === true) } : undefined; + return { + success: true, + user: { ...u, maps_api_key: mask_stored_api_key(u?.maps_api_key), openweather_api_key: mask_stored_api_key(u?.openweather_api_key), avatar_url: avatarUrl(updated || {}) }, + }; +} + +export function updateSettings( + userId: number, + body: { maps_api_key?: string; openweather_api_key?: string; username?: string; email?: string } +): { error?: string; status?: number; success?: boolean; user?: Record } { + const { maps_api_key, openweather_api_key, username, email } = body; + + if (username !== undefined) { + const trimmed = username.trim(); + if (!trimmed || trimmed.length < 2 || trimmed.length > 50) { + return { error: 'Username must be between 2 and 50 characters', status: 400 }; + } + if (!/^[a-zA-Z0-9_.-]+$/.test(trimmed)) { + return { error: 'Username can only contain letters, numbers, underscores, dots and hyphens', status: 400 }; + } + const conflict = db.prepare('SELECT id FROM users WHERE LOWER(username) = LOWER(?) AND id != ?').get(trimmed, userId); + if (conflict) return { error: 'Username already taken', status: 409 }; + } + + if (email !== undefined) { + const trimmed = email.trim(); + if (!trimmed || !EMAIL_REGEX.test(trimmed)) { + return { error: 'Invalid email format', status: 400 }; + } + const conflict = db.prepare('SELECT id FROM users WHERE LOWER(email) = LOWER(?) AND id != ?').get(trimmed, userId); + if (conflict) return { error: 'Email already taken', status: 409 }; + } + + const updates: string[] = []; + const params: (string | number | null)[] = []; + + if (maps_api_key !== undefined) { updates.push('maps_api_key = ?'); params.push(maybe_encrypt_api_key(maps_api_key)); } + if (openweather_api_key !== undefined) { updates.push('openweather_api_key = ?'); params.push(maybe_encrypt_api_key(openweather_api_key)); } + if (username !== undefined) { updates.push('username = ?'); params.push(username.trim()); } + if (email !== undefined) { updates.push('email = ?'); params.push(email.trim()); } + + if (updates.length > 0) { + updates.push('updated_at = CURRENT_TIMESTAMP'); + params.push(userId); + db.prepare(`UPDATE users SET ${updates.join(', ')} WHERE id = ?`).run(...params); + } + + const updated = db.prepare( + 'SELECT id, username, email, role, maps_api_key, openweather_api_key, avatar, mfa_enabled FROM users WHERE id = ?' + ).get(userId) as Pick | undefined; + + const u = updated ? { ...updated, mfa_enabled: !!(updated.mfa_enabled === 1 || updated.mfa_enabled === true) } : undefined; + return { + success: true, + user: { ...u, maps_api_key: mask_stored_api_key(u?.maps_api_key), openweather_api_key: mask_stored_api_key(u?.openweather_api_key), avatar_url: avatarUrl(updated || {}) }, + }; +} + +export function getSettings(userId: number): { error?: string; status?: number; settings?: Record } { + const user = db.prepare( + 'SELECT role, maps_api_key, openweather_api_key FROM users WHERE id = ?' + ).get(userId) as Pick | undefined; + if (user?.role !== 'admin') return { error: 'Admin access required', status: 403 }; + + return { + settings: { + maps_api_key: decrypt_api_key(user.maps_api_key), + openweather_api_key: decrypt_api_key(user.openweather_api_key), + }, + }; +} + +// --------------------------------------------------------------------------- +// Avatar +// --------------------------------------------------------------------------- + +export async function saveAvatar(userId: number, filename: string) { + const current = db.prepare('SELECT avatar FROM users WHERE id = ?').get(userId) as { avatar: string | null } | undefined; + if (current && current.avatar) { + // Fire-and-forget: leftover files are harmless; the DB update is + // the source of truth for which avatar is current. + const oldPath = path.join(avatarDir, current.avatar); + await fs.promises.rm(oldPath, { force: true }).catch(() => {}); + } + + db.prepare('UPDATE users SET avatar = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?').run(filename, userId); + + const updated = db.prepare('SELECT id, username, email, role, avatar FROM users WHERE id = ?').get(userId) as Pick | undefined; + return { success: true, avatar_url: avatarUrl(updated || {}) }; +} + +export async function deleteAvatar(userId: number) { + const current = db.prepare('SELECT avatar FROM users WHERE id = ?').get(userId) as { avatar: string | null } | undefined; + if (current && current.avatar) { + const filePath = path.join(avatarDir, current.avatar); + await fs.promises.rm(filePath, { force: true }).catch(() => {}); + } + db.prepare('UPDATE users SET avatar = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?').run(userId); + return { success: true }; +} + +// --------------------------------------------------------------------------- +// User directory +// --------------------------------------------------------------------------- + +export function listUsers(excludeUserId: number) { + const users = db.prepare( + 'SELECT id, username, avatar FROM users WHERE id != ? ORDER BY username ASC' + ).all(excludeUserId) as Pick[]; + return users.map(u => ({ ...u, avatar_url: avatarUrl(u) })); +} + +// --------------------------------------------------------------------------- +// Key validation +// --------------------------------------------------------------------------- + +export async function validateKeys(userId: number): Promise<{ error?: string; status?: number; maps: boolean; weather: boolean; maps_details: null | { ok: boolean; status: number | null; status_text: string | null; error_message: string | null; error_status: string | null; error_raw: string | null } }> { + const user = db.prepare('SELECT role, maps_api_key, openweather_api_key FROM users WHERE id = ?').get(userId) as Pick | undefined; + if (user?.role !== 'admin') return { error: 'Admin access required', status: 403, maps: false, weather: false, maps_details: null }; + + const result: { + maps: boolean; + weather: boolean; + maps_details: null | { + ok: boolean; + status: number | null; + status_text: string | null; + error_message: string | null; + error_status: string | null; + error_raw: string | null; + }; + } = { maps: false, weather: false, maps_details: null }; + + const maps_api_key = decrypt_api_key(user.maps_api_key); + if (maps_api_key) { + try { + const mapsRes = await fetch( + `https://places.googleapis.com/v1/places:searchText`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Goog-Api-Key': maps_api_key, + 'X-Goog-FieldMask': 'places.displayName', + }, + body: JSON.stringify({ textQuery: 'test' }), + } + ); + result.maps = mapsRes.status === 200; + let error_text: string | null = null; + let error_json: any = null; + if (!result.maps) { + try { + error_text = await mapsRes.text(); + try { error_json = JSON.parse(error_text); } catch { error_json = null; } + } catch { error_text = null; error_json = null; } + } + result.maps_details = { + ok: result.maps, + status: mapsRes.status, + status_text: mapsRes.statusText || null, + error_message: error_json?.error?.message || null, + error_status: error_json?.error?.status || null, + error_raw: error_text, + }; + } catch (err: unknown) { + result.maps = false; + result.maps_details = { + ok: false, + status: null, + status_text: null, + error_message: err instanceof Error ? err.message : 'Request failed', + error_status: 'FETCH_ERROR', + error_raw: null, + }; + } + } + + const openweather_api_key = decrypt_api_key(user.openweather_api_key); + if (openweather_api_key) { + try { + const weatherRes = await fetch( + `https://api.openweathermap.org/data/2.5/weather?q=London&appid=${openweather_api_key}` + ); + result.weather = weatherRes.status === 200; + } catch { + result.weather = false; + } + } + + return result; +} + +// --------------------------------------------------------------------------- +// Admin settings +// --------------------------------------------------------------------------- + +export function getAppSettings(userId: number): { error?: string; status?: number; data?: Record } { + const user = db.prepare('SELECT role FROM users WHERE id = ?').get(userId) as { role: string } | undefined; + if (user?.role !== 'admin') return { error: 'Admin access required', status: 403 }; + + const result: Record = {}; + for (const key of ADMIN_SETTINGS_KEYS) { + const row = db.prepare("SELECT value FROM app_settings WHERE key = ?").get(key) as { value: string } | undefined; + if (row) result[key] = (key === 'smtp_pass' || key === 'admin_webhook_url' || key === 'admin_ntfy_token') ? '••••••••' : row.value; + } + return { data: result }; +} + +export function updateAppSettings( + userId: number, + body: Record +): { + error?: string; + status?: number; + success?: boolean; + auditSummary?: Record; + auditDebugDetails?: Record; + shouldRestartScheduler?: boolean; +} { + const user = db.prepare('SELECT role FROM users WHERE id = ?').get(userId) as { role: string } | undefined; + if (user?.role !== 'admin') return { error: 'Admin access required', status: 403 }; + + const { require_mfa } = body; + if (require_mfa === true || require_mfa === 'true') { + const adminMfa = db.prepare('SELECT mfa_enabled FROM users WHERE id = ?').get(userId) as { mfa_enabled: number } | undefined; + // A user-verified passkey satisfies the MFA policy, so an admin who secured + // their own account with a passkey may enable it too (not only TOTP). + const adminHasPasskey = !!db.prepare('SELECT 1 FROM webauthn_credentials WHERE user_id = ? LIMIT 1').get(userId); + if (!(adminMfa?.mfa_enabled === 1) && !adminHasPasskey) { + return { + error: 'Secure your own account with two-factor authentication or a passkey before requiring it for all users.', + status: 400, + }; + } + } + + // Lockout prevention: can't disable all login methods + if (body.password_login !== undefined || body.oidc_login !== undefined) { + const current = resolveAuthToggles(); + const oidcConfigured = !!( + (process.env.OIDC_ISSUER || (db.prepare("SELECT value FROM app_settings WHERE key = 'oidc_issuer'").get() as { value: string } | undefined)?.value) && + (process.env.OIDC_CLIENT_ID || (db.prepare("SELECT value FROM app_settings WHERE key = 'oidc_client_id'").get() as { value: string } | undefined)?.value) + ); + const nextPasswordLogin = body.password_login !== undefined ? (String(body.password_login) === 'true') : current.password_login; + const nextOidcLogin = body.oidc_login !== undefined ? (String(body.oidc_login) === 'true') : current.oidc_login; + if (!nextPasswordLogin && (!nextOidcLogin || !oidcConfigured)) { + return { error: 'Cannot disable all login methods. At least one must remain enabled.', status: 400 }; + } + } + + for (const key of ADMIN_SETTINGS_KEYS) { + if (body[key] !== undefined) { + let val = String(body[key]); + if (key === 'require_mfa') { + val = body[key] === true || val === 'true' ? 'true' : 'false'; + } + if (key === 'smtp_pass' && val === '••••••••') continue; + if (key === 'smtp_pass') val = encrypt_api_key(val); + if (key === 'admin_webhook_url' && val === '••••••••') continue; + if (key === 'admin_webhook_url' && val) val = maybe_encrypt_api_key(val) ?? val; + if (key === 'admin_ntfy_token' && val === '••••••••') continue; + if (key === 'admin_ntfy_token' && val) val = maybe_encrypt_api_key(val) ?? val; + db.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)").run(key, val); + } + } + + const changedKeys = ADMIN_SETTINGS_KEYS.filter(k => body[k] !== undefined && !(k === 'smtp_pass' && String(body[k]) === '••••••••')); + + const summary: Record = {}; + const smtpChanged = changedKeys.some(k => k.startsWith('smtp_')); + if (changedKeys.includes('notification_channels')) summary.notification_channels = body.notification_channels; + if (changedKeys.includes('admin_webhook_url')) summary.admin_webhook_url_updated = true; + if (changedKeys.some(k => k.startsWith('admin_ntfy_'))) summary.admin_ntfy_updated = true; + if (smtpChanged) summary.smtp_settings_updated = true; + if (changedKeys.includes('allow_registration')) summary.allow_registration = body.allow_registration; + if (changedKeys.includes('allowed_file_types')) summary.allowed_file_types_updated = true; + if (changedKeys.includes('require_mfa')) summary.require_mfa = body.require_mfa; + + const debugDetails: Record = {}; + for (const k of changedKeys) { + debugDetails[k] = k === 'smtp_pass' ? '***' : body[k]; + } + + const notifRelated = ['notification_channels', 'smtp_host']; + const shouldRestartScheduler = changedKeys.some(k => notifRelated.includes(k)); + if (shouldRestartScheduler) { + startTripReminders(); + } + + return { success: true, auditSummary: summary, auditDebugDetails: debugDetails, shouldRestartScheduler }; +} + +// --------------------------------------------------------------------------- +// Travel stats +// --------------------------------------------------------------------------- + +export function getTravelStats(userId: number) { + const places = db.prepare(` + SELECT DISTINCT p.address, p.lat, p.lng + FROM places p + JOIN trips t ON p.trip_id = t.id + LEFT JOIN trip_members tm ON t.id = tm.trip_id + WHERE t.user_id = ? OR tm.user_id = ? + `).all(userId, userId) as { address: string | null; lat: number | null; lng: number | null }[]; + + const tripStats = db.prepare(` + SELECT COUNT(DISTINCT t.id) as trips, + COUNT(DISTINCT d.id) as days + FROM trips t + LEFT JOIN days d ON d.trip_id = t.id + LEFT JOIN trip_members tm ON t.id = tm.trip_id + WHERE (t.user_id = ? OR tm.user_id = ?) AND t.is_archived = 0 + `).get(userId, userId) as { trips: number; days: number } | undefined; + + const cities = new Set(); + const coords: { lat: number; lng: number }[] = []; + + places.forEach(p => { + if (p.lat && p.lng) coords.push({ lat: p.lat, lng: p.lng }); + if (p.address) { + const parts = p.address.split(',').map(s => s.trim().replace(/\d{3,}/g, '').trim()); + const cityPart = parts.find(s => !KNOWN_COUNTRIES.has(s) && /^[A-Za-z\u00C0-\u00FF\s-]{2,}$/.test(s)); + if (cityPart) cities.add(cityPart); + } + }); + + // Visited countries \u2014 same source the Atlas page uses: ISO-2 codes from + // auto-resolved place regions plus countries the user marked manually. + const countryCodes = new Set(); + const manualCountries = db.prepare( + 'SELECT country_code FROM visited_countries WHERE user_id = ?' + ).all(userId) as { country_code: string }[]; + manualCountries.forEach(m => { if (m.country_code) countryCodes.add(m.country_code.toUpperCase()); }); + + const placeRegionCodes = db.prepare(` + SELECT DISTINCT pr.country_code + FROM place_regions pr + JOIN places p ON p.id = pr.place_id + JOIN trips t ON p.trip_id = t.id + LEFT JOIN trip_members tm ON t.id = tm.trip_id + WHERE (t.user_id = ? OR tm.user_id = ?) AND pr.country_code IS NOT NULL + `).all(userId, userId) as { country_code: string }[]; + placeRegionCodes.forEach(r => { if (r.country_code) countryCodes.add(r.country_code.toUpperCase()); }); + + return { + countries: [...countryCodes], + cities: [...cities], + coords, + totalTrips: tripStats?.trips || 0, + totalDays: tripStats?.days || 0, + totalPlaces: places.length, + totalDistanceKm: getFlightDistanceKm(userId), + }; +} + +// --------------------------------------------------------------------------- +// MFA +// --------------------------------------------------------------------------- + +export function setupMfa(userId: number, userEmail: string): { error?: string; status?: number; secret?: string; otpauth_url?: string; qrPromise?: Promise } { + if (process.env.DEMO_MODE === 'true' && isDemoEmail(userEmail)) { + return { error: 'MFA is not available in demo mode.', status: 403 }; + } + const row = db.prepare('SELECT mfa_enabled FROM users WHERE id = ?').get(userId) as { mfa_enabled: number } | undefined; + if (row?.mfa_enabled) { + return { error: 'MFA is already enabled', status: 400 }; + } + let secret: string, otpauth_url: string; + try { + secret = authenticator.generateSecret(); + mfaSetupPending.set(userId, { secret, exp: Date.now() + MFA_SETUP_TTL_MS }); + otpauth_url = authenticator.keyuri(userEmail, 'TREK', secret); + } catch (err) { + console.error('[MFA] Setup error:', err); + return { error: 'MFA setup failed', status: 500 }; + } + return { secret, otpauth_url, qrPromise: QRCode.toString(otpauth_url, { type: 'svg', width: 250 }) }; +} + +export function enableMfa(userId: number, code?: string): { error?: string; status?: number; success?: boolean; mfa_enabled?: boolean; backup_codes?: string[] } { + if (!code) { + return { error: 'Verification code is required', status: 400 }; + } + const pending = getPendingMfaSecret(userId); + if (!pending) { + return { error: 'No MFA setup in progress. Start the setup again.', status: 400 }; + } + const tokenStr = String(code).replace(/\s/g, ''); + const ok = authenticator.verify({ token: tokenStr, secret: pending }); + if (!ok) { + return { error: 'Invalid verification code', status: 401 }; + } + const backupCodes = generateBackupCodes(); + const backupHashes = backupCodes.map(hashBackupCodeBcrypt); + const enc = encryptMfaSecret(pending); + db.prepare('UPDATE users SET mfa_enabled = 1, mfa_secret = ?, mfa_backup_codes = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?').run( + enc, + JSON.stringify(backupHashes), + userId + ); + mfaSetupPending.delete(userId); + return { success: true, mfa_enabled: true, backup_codes: backupCodes }; +} + +export function disableMfa( + userId: number, + userEmail: string, + body: { password?: string; code?: string } +): { error?: string; status?: number; success?: boolean; mfa_enabled?: boolean } { + if (process.env.DEMO_MODE === 'true' && isDemoEmail(userEmail)) { + return { error: 'MFA cannot be changed in demo mode.', status: 403 }; + } + const policy = db.prepare("SELECT value FROM app_settings WHERE key = 'require_mfa'").get() as { value: string } | undefined; + if (policy?.value === 'true') { + return { error: 'Two-factor authentication cannot be disabled while it is required for all users.', status: 403 }; + } + const { password, code } = body; + if (!password || !code) { + return { error: 'Password and authenticator code are required', status: 400 }; + } + const user = db.prepare('SELECT * FROM users WHERE id = ?').get(userId) as User | undefined; + if (!user?.mfa_enabled || !user.mfa_secret) { + return { error: 'MFA is not enabled', status: 400 }; + } + if (!user.password_hash || !bcrypt.compareSync(password, user.password_hash)) { + return { error: 'Incorrect password', status: 401 }; + } + const secret = decryptMfaSecret(user.mfa_secret); + const tokenStr = String(code).replace(/\s/g, ''); + const ok = authenticator.verify({ token: tokenStr, secret }); + if (!ok) { + return { error: 'Invalid verification code', status: 401 }; + } + db.prepare('UPDATE users SET mfa_enabled = 0, mfa_secret = NULL, mfa_backup_codes = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?').run( + userId + ); + mfaSetupPending.delete(userId); + return { success: true, mfa_enabled: false }; +} + +export function verifyMfaLogin(body: { + mfa_token?: string; + code?: string; + remember_me?: boolean; +}): { + error?: string; + status?: number; + token?: string; + user?: Record; + remember?: boolean; + auditUserId?: number; +} { + const { mfa_token, code, remember_me } = body; + const remember = remember_me === true; + if (!mfa_token || !code) { + return { error: 'Verification token and code are required', status: 400 }; + } + try { + const decoded = jwt.verify(mfa_token, JWT_SECRET, { algorithms: ['HS256'] }) as { id: number; purpose?: string }; + if (decoded.purpose !== 'mfa_login') { + return { error: 'Invalid verification token', status: 401 }; + } + const user = db.prepare('SELECT * FROM users WHERE id = ?').get(decoded.id) as User | undefined; + if (!user || !(user.mfa_enabled === 1 || user.mfa_enabled === true) || !user.mfa_secret) { + return { error: 'Invalid session', status: 401 }; + } + const secret = decryptMfaSecret(user.mfa_secret); + const tokenStr = String(code).trim(); + const okTotp = authenticator.verify({ token: tokenStr.replace(/\s/g, ''), secret }); + if (!okTotp) { + const hashes = parseBackupCodeHashes(user.mfa_backup_codes); + // matchBackupCode handles both bcrypt and legacy SHA-256 hashes; + // any store older than the bcrypt migration keeps working. + const idx = hashes.findIndex((h) => matchBackupCode(tokenStr, h)); + if (idx === -1) { + return { error: 'Invalid verification code', status: 401 }; + } + hashes.splice(idx, 1); + db.prepare('UPDATE users SET mfa_backup_codes = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?').run( + JSON.stringify(hashes), + user.id + ); + } + db.prepare('UPDATE users SET last_login = CURRENT_TIMESTAMP, login_count = login_count + 1 WHERE id = ?').run(user.id); + const sessionToken = generateToken(user, remember); + const userSafe = stripUserForClient(user) as Record; + return { + token: sessionToken, + user: { ...userSafe, avatar_url: avatarUrl(user) }, + remember, + auditUserId: Number(user.id), + }; + } catch { + return { error: 'Invalid or expired verification token', status: 401 }; + } +} + +// --------------------------------------------------------------------------- +// Password reset +// --------------------------------------------------------------------------- + +// 60 min; long enough to read the email in a second tab, short enough +// that a leaked link is unlikely to still be valid when someone tries it. +const PASSWORD_RESET_TTL_MS = 60 * 60 * 1000; +const PASSWORD_RESET_TOKEN_BYTES = 32; // 256-bit entropy + +/** + * Returns the SHA-256 hex hash of a reset token. Raw tokens are never + * persisted — we only store and compare their hashes. + */ +function hashResetToken(raw: string): string { + return createHash('sha256').update(raw).digest('hex'); +} + +/** + * Shape returned by requestPasswordReset. For enumeration-safety the + * route ALWAYS returns the same response to the client regardless of + * whether a user existed — this struct is only consumed internally by + * the route handler to decide whether to send an email / log a link. + */ +export interface PasswordResetRequestOutcome { + tokenForDelivery: string | null; // raw token — send via email or log, never return to client + userId: number | null; + userEmail: string | null; + reason: 'issued' | 'no_user' | 'oidc_only' | 'throttled_per_email' | 'password_login_disabled'; +} + +// Per-email throttle (defence-in-depth on top of the per-IP limiter). +const perEmailResetAttempts = new Map(); +const PASSWORD_RESET_PER_EMAIL_WINDOW_MS = 15 * 60 * 1000; +const PASSWORD_RESET_PER_EMAIL_MAX = 3; +setInterval(() => { + const now = Date.now(); + for (const [key, record] of perEmailResetAttempts) { + if (now - record.first >= PASSWORD_RESET_PER_EMAIL_WINDOW_MS) perEmailResetAttempts.delete(key); + } +}, 5 * 60 * 1000).unref?.(); + +export function requestPasswordReset(rawEmail: string, createdIp: string | null): PasswordResetRequestOutcome { + const email = String(rawEmail || '').trim().toLowerCase(); + // Basic shape check — a fully empty / malformed email is treated like + // "no user" so we still spend the same time internally. + const looksLikeEmail = email.length > 0 && /.+@.+\..+/.test(email); + + // Global policy check: password login disabled → no reset possible. + const toggles = resolveAuthToggles(); + if (!toggles.password_login) { + return { tokenForDelivery: null, userId: null, userEmail: null, reason: 'password_login_disabled' }; + } + + // Per-email throttle. We check this BEFORE the DB lookup so the timing + // is identical regardless of whether the account exists. + const throttleKey = email || '__noemail__'; + const now = Date.now(); + const record = perEmailResetAttempts.get(throttleKey); + if (record && record.count >= PASSWORD_RESET_PER_EMAIL_MAX && now - record.first < PASSWORD_RESET_PER_EMAIL_WINDOW_MS) { + return { tokenForDelivery: null, userId: null, userEmail: null, reason: 'throttled_per_email' }; + } + if (!record || now - record.first >= PASSWORD_RESET_PER_EMAIL_WINDOW_MS) { + perEmailResetAttempts.set(throttleKey, { count: 1, first: now }); + } else { + record.count++; + } + + if (!looksLikeEmail) { + return { tokenForDelivery: null, userId: null, userEmail: null, reason: 'no_user' }; + } + + const user = db.prepare('SELECT id, email, password_hash, oidc_sub FROM users WHERE email = ?').get(email) as + | { id: number; email: string; password_hash: string | null; oidc_sub: string | null } + | undefined; + + if (!user) { + return { tokenForDelivery: null, userId: null, userEmail: null, reason: 'no_user' }; + } + // SSO-linked account — refuse a reset. OIDC users are created with a random + // bcrypt hash (so password_hash is never empty), which is why we must key off + // oidc_sub rather than a missing hash. Letting the reset proceed would set a + // local password and revoke session/credential state, which breaks the SSO + // login; admins (or the user, with their current password) can still set one. + // The client still gets the generic "if that email exists…" response. + if (user.oidc_sub) { + return { tokenForDelivery: null, userId: user.id, userEmail: user.email, reason: 'oidc_only' }; + } + + // Invalidate any prior unconsumed tokens for this user so there is + // always at most one live reset link in flight. + db.prepare( + "UPDATE password_reset_tokens SET consumed_at = CURRENT_TIMESTAMP WHERE user_id = ? AND consumed_at IS NULL" + ).run(user.id); + + const raw = randomBytes(PASSWORD_RESET_TOKEN_BYTES).toString('base64url'); + const token_hash = hashResetToken(raw); + const expires_at = new Date(Date.now() + PASSWORD_RESET_TTL_MS).toISOString(); + + db.prepare( + 'INSERT INTO password_reset_tokens (user_id, token_hash, expires_at, created_ip) VALUES (?, ?, ?, ?)' + ).run(user.id, token_hash, expires_at, createdIp); + + return { tokenForDelivery: raw, userId: user.id, userEmail: user.email, reason: 'issued' }; +} + +export interface ResetPasswordOutcome { + error?: string; + status?: number; + success?: boolean; + /** When true the client must collect a TOTP/backup code and call again. */ + mfa_required?: boolean; + userId?: number; +} + +/** + * Consume a reset token and set a new password. If the target user has + * MFA enabled, a valid TOTP code or backup code must be supplied — a + * compromised email alone therefore does NOT allow taking over a + * 2FA-protected account. + */ +export function resetPassword(body: { + token?: string; + new_password?: string; + mfa_code?: string; +}): ResetPasswordOutcome { + const { token, new_password, mfa_code } = body; + if (!token || typeof token !== 'string') { + return { error: 'Reset token is required', status: 400 }; + } + if (!new_password || typeof new_password !== 'string') { + return { error: 'New password is required', status: 400 }; + } + // Check the policy BEFORE touching the token so an invalid password + // does not burn the user's one-time link. + const pwCheck = validatePassword(new_password); + if (!pwCheck.ok) return { error: pwCheck.reason!, status: 400 }; + + const tokenHash = hashResetToken(token); + const row = db.prepare( + 'SELECT id, user_id, expires_at, consumed_at FROM password_reset_tokens WHERE token_hash = ?' + ).get(tokenHash) as + | { id: number; user_id: number; expires_at: string; consumed_at: string | null } + | undefined; + + if (!row) return { error: 'Invalid or expired reset link', status: 400 }; + if (row.consumed_at) return { error: 'This reset link has already been used', status: 400 }; + if (new Date(row.expires_at).getTime() < Date.now()) { + return { error: 'Reset link has expired. Please request a new one.', status: 400 }; + } + + const user = db.prepare( + 'SELECT id, email, mfa_enabled, mfa_secret, mfa_backup_codes, password_version FROM users WHERE id = ?' + ).get(row.user_id) as + | { id: number; email: string; mfa_enabled: number | boolean; mfa_secret: string | null; mfa_backup_codes: string | null; password_version: number } + | undefined; + + if (!user) return { error: 'Invalid or expired reset link', status: 400 }; + + // MFA gate. If enabled, require a valid TOTP or backup code. + const mfaOn = user.mfa_enabled === 1 || user.mfa_enabled === true; + let backupCodeConsumedIndex: number | null = null; + if (mfaOn) { + if (!user.mfa_secret) { + // Data inconsistency — fail closed. + return { error: 'MFA is enabled but not configured. Contact your administrator.', status: 500 }; + } + const supplied = typeof mfa_code === 'string' ? mfa_code.trim() : ''; + if (!supplied) return { mfa_required: true, status: 200 }; + + const secret = decryptMfaSecret(user.mfa_secret); + const okTotp = authenticator.verify({ token: supplied.replace(/\s/g, ''), secret }); + if (!okTotp) { + const hashes = parseBackupCodeHashes(user.mfa_backup_codes); + const idx = hashes.findIndex((h) => matchBackupCode(supplied, h)); + if (idx === -1) return { error: 'Invalid MFA code', status: 401 }; + backupCodeConsumedIndex = idx; + } + } + + const newHash = bcrypt.hashSync(new_password, BCRYPT_COST); + const newPv = (user.password_version ?? 0) + 1; + + db.transaction(() => { + // Burn the token first to keep it atomic with the password change. + db.prepare('UPDATE password_reset_tokens SET consumed_at = CURRENT_TIMESTAMP WHERE id = ?').run(row.id); + // Also burn every OTHER live token for this user — a fresh login + // should not leave a second door open. + db.prepare( + "UPDATE password_reset_tokens SET consumed_at = CURRENT_TIMESTAMP WHERE user_id = ? AND consumed_at IS NULL AND id != ?" + ).run(user.id, row.id); + db.prepare( + 'UPDATE users SET password_hash = ?, must_change_password = 0, password_version = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?' + ).run(newHash, newPv, user.id); + // Consume backup code if one was used. + if (backupCodeConsumedIndex !== null) { + const hashes = parseBackupCodeHashes(user.mfa_backup_codes); + hashes.splice(backupCodeConsumedIndex, 1); + db.prepare('UPDATE users SET mfa_backup_codes = ? WHERE id = ?').run(JSON.stringify(hashes), user.id); + } + // Revoke every other credential class the user had. The + // password_version bump alone invalidates JWT cookie sessions, but + // MCP static tokens and OAuth 2.1 bearer tokens are separate stores + // that survive the bump unless we prune them here. + db.prepare('DELETE FROM mcp_tokens WHERE user_id = ?').run(user.id); + try { + db.prepare( + "UPDATE oauth_tokens SET revoked_at = CURRENT_TIMESTAMP WHERE user_id = ? AND revoked_at IS NULL" + ).run(user.id); + } catch { /* oauth_tokens table may not exist in very old installs */ } + })(); + + // Kick off any MCP/WS session cleanup — same hook the account-delete path uses. + try { revokeUserSessions?.(user.id); } catch { /* best-effort */ } + + return { success: true, userId: user.id }; +} + +// --------------------------------------------------------------------------- +// MCP tokens +// --------------------------------------------------------------------------- + +export function listMcpTokens(userId: number) { + return db.prepare( + 'SELECT id, name, token_prefix, created_at, last_used_at FROM mcp_tokens WHERE user_id = ? ORDER BY created_at DESC' + ).all(userId); +} + +export function createMcpToken(userId: number, name?: string): { error?: string; status?: number; token?: Record } { + if (!name?.trim()) return { error: 'Token name is required', status: 400 }; + if (name.trim().length > 100) return { error: 'Token name must be 100 characters or less', status: 400 }; + + const tokenCount = (db.prepare('SELECT COUNT(*) as count FROM mcp_tokens WHERE user_id = ?').get(userId) as { count: number }).count; + if (tokenCount >= 10) return { error: 'Maximum of 10 tokens per user reached', status: 400 }; + + const rawToken = 'trek_' + randomBytes(24).toString('hex'); + const tokenHash = createHash('sha256').update(rawToken).digest('hex'); + const tokenPrefix = rawToken.slice(0, 13); + + const result = db.prepare( + 'INSERT INTO mcp_tokens (user_id, name, token_hash, token_prefix) VALUES (?, ?, ?, ?)' + ).run(userId, name.trim(), tokenHash, tokenPrefix); + + const token = db.prepare( + 'SELECT id, name, token_prefix, created_at, last_used_at FROM mcp_tokens WHERE id = ?' + ).get(result.lastInsertRowid); + + return { token: { ...(token as object), raw_token: rawToken } }; +} + +export function deleteMcpToken(userId: number, tokenId: string): { error?: string; status?: number; success?: boolean } { + const token = db.prepare('SELECT id FROM mcp_tokens WHERE id = ? AND user_id = ?').get(tokenId, userId); + if (!token) return { error: 'Token not found', status: 404 }; + db.prepare('DELETE FROM mcp_tokens WHERE id = ?').run(tokenId); + revokeUserSessions(userId); + return { success: true }; +} + +// --------------------------------------------------------------------------- +// Ephemeral tokens +// --------------------------------------------------------------------------- + +export function createWsToken(userId: number): { error?: string; status?: number; token?: string } { + // Bind the ws-token to the user's current password_version so a token minted + // before a password reset is rejected on connect (defence-in-depth session gate). + const pv = (db.prepare('SELECT password_version FROM users WHERE id = ?').get(userId) as { password_version?: number } | undefined)?.password_version ?? 0; + const token = createEphemeralToken(userId, 'ws', { pv }); + if (!token) return { error: 'Service unavailable', status: 503 }; + return { token }; +} + +export function createResourceToken(userId: number, purpose?: string): { error?: string; status?: number; token?: string } { + if (purpose !== 'download') { + return { error: 'Invalid purpose', status: 400 }; + } + const token = createEphemeralToken(userId, purpose); + if (!token) return { error: 'Service unavailable', status: 503 }; + return { token }; +} + +// --------------------------------------------------------------------------- +// MCP auth helpers +// --------------------------------------------------------------------------- + +export function isDemoUser(userId: number): boolean { + if (process.env.DEMO_MODE !== 'true') return false; + const user = db.prepare('SELECT email FROM users WHERE id = ?').get(userId) as { email: string } | undefined; + return isDemoEmail(user?.email); +} + +export function verifyMcpToken(rawToken: string): User | null { + const hash = createHash('sha256').update(rawToken).digest('hex'); + const row = db.prepare(` + SELECT u.id, u.username, u.email, u.role + FROM mcp_tokens mt + JOIN users u ON mt.user_id = u.id + WHERE mt.token_hash = ? + `).get(hash) as User | undefined; + if (row) { + db.prepare('UPDATE mcp_tokens SET last_used_at = CURRENT_TIMESTAMP WHERE token_hash = ?').run(hash); + return row; + } + return null; +} + +/** + * Verify a JWT the same way `middleware/auth.ts#verifyJwtAndLoadUser` + * does — including the `password_version` check — so that stolen tokens + * lose access the moment the victim resets their password. + * + * This is the single entry point every non-cookie JWT verification path + * (MCP bearer, WebSocket handshake, file-download query tokens, photo + * route) should go through. + */ +export function verifyJwtToken(token: string): User | null { + return verifyJwtAndLoadUser(token); +} diff --git a/server/src/services/avatarUrl.ts b/server/src/services/avatarUrl.ts new file mode 100644 index 0000000000000000000000000000000000000000..d3919f5f0faed55a48f28b735796003fb47f37f6 --- /dev/null +++ b/server/src/services/avatarUrl.ts @@ -0,0 +1,3 @@ +export function avatarUrl(user: { avatar?: string | null }): string | null { + return user.avatar ? `/uploads/avatars/${user.avatar}` : null; +} diff --git a/server/src/services/backupService.ts b/server/src/services/backupService.ts new file mode 100644 index 0000000000000000000000000000000000000000..282c61ac2e263f004b76faf9d7e9eeb84c8b16a6 --- /dev/null +++ b/server/src/services/backupService.ts @@ -0,0 +1,363 @@ +import archiver from 'archiver'; +import unzipper from 'unzipper'; +import path from 'path'; +import fs from 'fs'; +import Database from 'better-sqlite3'; +import { db, closeDb, reinitialize } from '../db/database'; +import * as scheduler from '../scheduler'; +import { invalidatePermissionsCache } from './permissions'; + +// --------------------------------------------------------------------------- +// Paths +// --------------------------------------------------------------------------- + +const dataDir = path.join(__dirname, '../../data'); +const backupsDir = path.join(dataDir, 'backups'); +const uploadsDir = path.join(__dirname, '../../uploads'); + +export const MAX_BACKUP_UPLOAD_SIZE = 500 * 1024 * 1024; // 500 MB compressed +// Upper bound on the TOTAL decompressed size of a restore archive (the upload +// limit only caps the compressed bytes). Generous enough for any real backup. +export const MAX_BACKUP_DECOMPRESSED_SIZE = 5 * 1024 * 1024 * 1024; // 5 GB + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +export function ensureBackupsDir(): void { + if (!fs.existsSync(backupsDir)) fs.mkdirSync(backupsDir, { recursive: true }); +} + +export function formatSize(bytes: number): string { + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; + return `${(bytes / 1024 / 1024).toFixed(1)} MB`; +} + +export function parseIntField(raw: unknown, fallback: number): number { + if (typeof raw === 'number' && Number.isFinite(raw)) return Math.floor(raw); + if (typeof raw === 'string' && raw.trim() !== '') { + const n = parseInt(raw, 10); + if (Number.isFinite(n)) return n; + } + return fallback; +} + +export function parseAutoBackupBody(body: Record): { + enabled: boolean; + interval: string; + keep_days: number; + hour: number; + day_of_week: number; + day_of_month: number; +} { + const enabled = body.enabled === true || body.enabled === 'true' || body.enabled === 1; + const rawInterval = body.interval; + const interval = + typeof rawInterval === 'string' && scheduler.VALID_INTERVALS.includes(rawInterval) + ? rawInterval + : 'daily'; + const keep_days = Math.max(0, parseIntField(body.keep_days, 7)); + const hour = Math.min(23, Math.max(0, parseIntField(body.hour, 2))); + const day_of_week = Math.min(6, Math.max(0, parseIntField(body.day_of_week, 0))); + const day_of_month = Math.min(28, Math.max(1, parseIntField(body.day_of_month, 1))); + return { enabled, interval, keep_days, hour, day_of_week, day_of_month }; +} + +export function isValidBackupFilename(filename: string): boolean { + return /^(?:auto-)?backup-[\w-]+\.zip$/.test(filename); +} + +export function backupFilePath(filename: string): string { + return path.join(backupsDir, filename); +} + +export function backupFileExists(filename: string): boolean { + return fs.existsSync(path.join(backupsDir, filename)); +} + +// --------------------------------------------------------------------------- +// Rate limiter state (shared across requests) +// --------------------------------------------------------------------------- + +export const BACKUP_RATE_WINDOW = 60 * 60 * 1000; // 1 hour + +const backupAttempts = new Map(); + +/** Returns true if the request is allowed, false if rate-limited. */ +export function checkRateLimit(key: string, maxAttempts: number, windowMs: number): boolean { + const now = Date.now(); + const record = backupAttempts.get(key); + if (record && record.count >= maxAttempts && now - record.first < windowMs) { + return false; + } + if (!record || now - record.first >= windowMs) { + backupAttempts.set(key, { count: 1, first: now }); + } else { + record.count++; + } + return true; +} + +// --------------------------------------------------------------------------- +// List backups +// --------------------------------------------------------------------------- + +export interface BackupInfo { + filename: string; + size: number; + sizeText: string; + created_at: string; +} + +export function listBackups(): BackupInfo[] { + ensureBackupsDir(); + return fs.readdirSync(backupsDir) + .filter(f => f.endsWith('.zip')) + .map(filename => { + const filePath = path.join(backupsDir, filename); + const stat = fs.statSync(filePath); + return { + filename, + size: stat.size, + sizeText: formatSize(stat.size), + created_at: stat.mtime.toISOString(), + }; + }) + .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()); +} + +// --------------------------------------------------------------------------- +// Create backup +// --------------------------------------------------------------------------- + +export async function createBackup(): Promise { + ensureBackupsDir(); + + const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19); + const filename = `backup-${timestamp}.zip`; + const outputPath = path.join(backupsDir, filename); + + try { + try { db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch (e) {} + + await new Promise((resolve, reject) => { + const output = fs.createWriteStream(outputPath); + const archive = archiver('zip', { zlib: { level: 9 } }); + + output.on('close', resolve); + archive.on('error', reject); + + archive.pipe(output); + + const dbPath = path.join(dataDir, 'travel.db'); + if (fs.existsSync(dbPath)) { + archive.file(dbPath, { name: 'travel.db' }); + } + + // Bundle the at-rest encryption key so the backup is self-contained: the + // DB stores secrets (API keys, MFA, SMTP/OIDC) encrypted with this key, so + // a restore onto a different install would otherwise be unable to decrypt + // them. NOTE: this makes the backup file as sensitive as the key itself — + // store/transfer it securely. Skipped when ENCRYPTION_KEY is provided via + // env, since in that case the file is not the source of truth. + const encKeyPath = path.join(dataDir, '.encryption_key'); + if (!process.env.ENCRYPTION_KEY && fs.existsSync(encKeyPath)) { + archive.file(encKeyPath, { name: '.encryption_key' }); + } + + if (fs.existsSync(uploadsDir)) { + // Exclude the place-photo and trek-memory caches: both are re-derivable + // (re-fetched on demand, keyed on stable ids) and would otherwise dominate + // backup size. Restores self-heal — the cache dirs are recreated at startup. + archive.glob( + '**/*', + { cwd: uploadsDir, ignore: ['photos/google/**', 'photos/trek/**'], nodir: true, dot: true }, + { prefix: 'uploads' }, + ); + } + + archive.finalize(); + }); + + const stat = fs.statSync(outputPath); + return { + filename, + size: stat.size, + sizeText: formatSize(stat.size), + created_at: stat.birthtime.toISOString(), + }; + } catch (err: unknown) { + console.error('Backup error:', err); + if (fs.existsSync(outputPath)) fs.unlinkSync(outputPath); + throw err; + } +} + +// --------------------------------------------------------------------------- +// Restore from ZIP +// --------------------------------------------------------------------------- + +export interface RestoreResult { + success: boolean; + error?: string; + status?: number; +} + +export async function restoreFromZip(zipPath: string): Promise { + const extractDir = path.join(dataDir, `restore-${Date.now()}`); + let reinitFailed: unknown = null; + try { + // Check the declared uncompressed size from the central directory and bail + // if it exceeds the cap, before extracting anything. + const directory = await unzipper.Open.file(zipPath); + const claimedSize = directory.files.reduce((sum, f) => sum + (f.uncompressedSize || 0), 0); + if (claimedSize > MAX_BACKUP_DECOMPRESSED_SIZE) { + return { success: false, error: 'Backup exceeds the maximum decompressed size.', status: 400 }; + } + + await fs.createReadStream(zipPath) + .pipe(unzipper.Extract({ path: extractDir })) + .promise(); + + const extractedDb = path.join(extractDir, 'travel.db'); + if (!fs.existsSync(extractedDb)) { + fs.rmSync(extractDir, { recursive: true, force: true }); + return { success: false, error: 'Invalid backup: travel.db not found', status: 400 }; + } + + let uploadedDb: InstanceType | null = null; + try { + uploadedDb = new Database(extractedDb, { readonly: true }); + + const integrityResult = uploadedDb.prepare('PRAGMA integrity_check').get() as { integrity_check: string }; + if (integrityResult.integrity_check !== 'ok') { + fs.rmSync(extractDir, { recursive: true, force: true }); + return { success: false, error: `Uploaded database failed integrity check: ${integrityResult.integrity_check}`, status: 400 }; + } + + const requiredTables = ['users', 'trips', 'trip_members', 'places', 'days']; + const existingTables = uploadedDb + .prepare("SELECT name FROM sqlite_master WHERE type='table'") + .all() as { name: string }[]; + const tableNames = new Set(existingTables.map(t => t.name)); + for (const table of requiredTables) { + if (!tableNames.has(table)) { + fs.rmSync(extractDir, { recursive: true, force: true }); + return { success: false, error: `Uploaded database is missing required table: ${table}. This does not appear to be a TREK backup.`, status: 400 }; + } + } + } catch (err) { + fs.rmSync(extractDir, { recursive: true, force: true }); + return { success: false, error: 'Uploaded file is not a valid SQLite database', status: 400 }; + } finally { + uploadedDb?.close(); + } + + closeDb(); + + try { + const dbDest = path.join(dataDir, 'travel.db'); + for (const ext of ['', '-wal', '-shm']) { + try { fs.unlinkSync(dbDest + ext); } catch (e) {} + } + fs.copyFileSync(extractedDb, dbDest); + + // Restore the bundled at-rest encryption key (if the archive carries one) + // so the restored DB's encrypted secrets can be decrypted. Only the file + // is swapped here; the in-memory key was read at startup, so a restart is + // required for it to take effect (and an explicit ENCRYPTION_KEY env var + // still overrides the file). + const extractedEncKey = path.join(extractDir, '.encryption_key'); + if (fs.existsSync(extractedEncKey)) { + fs.copyFileSync(extractedEncKey, path.join(dataDir, '.encryption_key')); + } + + const extractedUploads = path.join(extractDir, 'uploads'); + if (fs.existsSync(extractedUploads)) { + for (const sub of fs.readdirSync(uploadsDir)) { + const subPath = path.join(uploadsDir, sub); + if (fs.statSync(subPath).isDirectory()) { + for (const file of fs.readdirSync(subPath)) { + try { fs.unlinkSync(path.join(subPath, file)); } catch (e) {} + } + } + } + // Copy into the real directory behind uploadsDir. In Docker, uploadsDir + // (/app/server/uploads) is a symlink to the mounted /app/uploads volume; + // cpSync(dereference:false) would otherwise try to overwrite the symlink + // node with a directory and throw ERR_FS_CP_DIR_TO_NON_DIR. realpathSync + // is a no-op when uploadsDir is a plain directory (dev/non-Docker). + fs.cpSync(extractedUploads, fs.realpathSync(uploadsDir), { recursive: true, force: true }); + } + } finally { + // Reopening the DB must always run (even if the copy above threw) so the + // process is never left without a connection. Capture a reopen failure + // instead of letting it propagate as a generic error — a backup whose + // files already landed on disk but whose connection failed to reopen + // needs to be reported as "restart required", not swallowed. + try { + reinitialize(); + } catch (reinitErr) { + reinitFailed = reinitErr; + } + // The restored DB has different permission-override rows from + // the pre-restore DB, but our process-local permissions cache + // still holds the pre-restore state. Any request using a cached + // permission would decide against the wrong grants until the + // next restart. Dropping the cache forces a fresh read. + invalidatePermissionsCache(); + } + + fs.rmSync(extractDir, { recursive: true, force: true }); + if (reinitFailed) { + console.error('Restore: database reopen failed after file swap:', reinitFailed); + return { success: false, error: 'Backup files were restored but the database connection could not be reopened. Restart the server to finish the restore.', status: 500 }; + } + return { success: true }; + } catch (err: unknown) { + console.error('Restore error:', err); + if (fs.existsSync(extractDir)) fs.rmSync(extractDir, { recursive: true, force: true }); + // Belt-and-braces: the inner `finally` already drops the permissions + // cache after a successful swap, but if the extraction/copy step + // itself threw before the DB swap even started, the cache wasn't + // stale anyway. Invalidating here too costs nothing and guarantees + // we never serve cached permissions that don't match the DB state + // we leave the process in after a failed restore. + try { invalidatePermissionsCache(); } catch { /* best-effort */ } + throw err; + } +} + +// --------------------------------------------------------------------------- +// Auto-backup settings +// --------------------------------------------------------------------------- + +export function getAutoSettings(): { settings: ReturnType; timezone: string } { + const tz = process.env.TZ || Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'; + return { settings: scheduler.loadSettings(), timezone: tz }; +} + +export function updateAutoSettings(body: Record): ReturnType { + const settings = parseAutoBackupBody(body); + scheduler.saveSettings(settings); + scheduler.start(); + return settings; +} + +// --------------------------------------------------------------------------- +// Delete backup +// --------------------------------------------------------------------------- + +export function deleteBackup(filename: string): void { + const filePath = path.join(backupsDir, filename); + fs.unlinkSync(filePath); +} + +// --------------------------------------------------------------------------- +// Upload config (multer dest) +// --------------------------------------------------------------------------- + +export function getUploadTmpDir(): string { + return path.join(dataDir, 'tmp/'); +} diff --git a/server/src/services/budgetService.ts b/server/src/services/budgetService.ts new file mode 100644 index 0000000000000000000000000000000000000000..8bffe9349f03436415798321ca6fdfc465438a46 --- /dev/null +++ b/server/src/services/budgetService.ts @@ -0,0 +1,479 @@ +import { db } from '../db/database'; +import { BudgetItem, BudgetItemMember, BudgetItemPayer } from '../types'; +import { avatarUrl } from './avatarUrl'; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +export { avatarUrl }; +export { verifyTripAccess } from './tripAccess'; + +function loadItemMembers(itemId: number | string) { + const rows = db.prepare(` + SELECT bm.user_id, bm.paid, u.username, u.avatar + FROM budget_item_members bm + JOIN users u ON bm.user_id = u.id + WHERE bm.budget_item_id = ? + `).all(itemId) as BudgetItemMember[]; + return rows.map(m => ({ ...m, avatar_url: avatarUrl(m) })); +} + +function loadItemPayers(itemId: number | string) { + const rows = db.prepare(` + SELECT bp.user_id, bp.amount, u.username, u.avatar + FROM budget_item_payers bp + JOIN users u ON bp.user_id = u.id + WHERE bp.budget_item_id = ? + `).all(itemId) as BudgetItemPayer[]; + return rows.map(p => ({ ...p, avatar_url: avatarUrl(p) })); +} + +/** Replace the payer rows of an item and keep total_price = sum of payer amounts. */ +function writeItemPayers(itemId: number | string, payers: { user_id: number; amount: number }[]) { + db.prepare('DELETE FROM budget_item_payers WHERE budget_item_id = ?').run(itemId); + const insert = db.prepare('INSERT OR IGNORE INTO budget_item_payers (budget_item_id, user_id, amount) VALUES (?, ?, ?)'); + let total = 0; + for (const p of payers) { + if (!(p.amount > 0)) continue; + insert.run(itemId, p.user_id, p.amount); + total += p.amount; + } + db.prepare('UPDATE budget_items SET total_price = ? WHERE id = ?').run(total, itemId); + return total; +} + +// --------------------------------------------------------------------------- +// CRUD +// --------------------------------------------------------------------------- + +export function listBudgetItems(tripId: string | number) { + const items = db.prepare(` + SELECT bi.* FROM budget_items bi + LEFT JOIN budget_category_order bco ON bco.trip_id = bi.trip_id AND bco.category = bi.category + WHERE bi.trip_id = ? + ORDER BY COALESCE(bco.sort_order, 999999) ASC, bi.sort_order ASC + `).all(tripId) as BudgetItem[]; + + const itemIds = items.map(i => i.id); + const membersByItem: Record = {}; + + if (itemIds.length > 0) { + const allMembers = db.prepare(` + SELECT bm.budget_item_id, bm.user_id, bm.paid, u.username, u.avatar + FROM budget_item_members bm + JOIN users u ON bm.user_id = u.id + WHERE bm.budget_item_id IN (${itemIds.map(() => '?').join(',')}) + `).all(...itemIds) as (BudgetItemMember & { budget_item_id: number })[]; + + for (const m of allMembers) { + if (!membersByItem[m.budget_item_id]) membersByItem[m.budget_item_id] = []; + membersByItem[m.budget_item_id].push({ + user_id: m.user_id, paid: m.paid, username: m.username, avatar_url: avatarUrl(m), + }); + } + } + + const payersByItem: Record = {}; + if (itemIds.length > 0) { + const allPayers = db.prepare(` + SELECT bp.budget_item_id, bp.user_id, bp.amount, u.username, u.avatar + FROM budget_item_payers bp + JOIN users u ON bp.user_id = u.id + WHERE bp.budget_item_id IN (${itemIds.map(() => '?').join(',')}) + `).all(...itemIds) as (BudgetItemPayer & { budget_item_id: number })[]; + + for (const p of allPayers) { + if (!payersByItem[p.budget_item_id]) payersByItem[p.budget_item_id] = []; + payersByItem[p.budget_item_id].push({ + user_id: p.user_id, amount: p.amount, username: p.username, avatar_url: avatarUrl(p), + }); + } + } + + items.forEach(item => { + item.members = membersByItem[item.id] || []; + item.payers = payersByItem[item.id] || []; + }); + return items; +} + +export function createBudgetItem( + tripId: string | number, + data: { + category?: string; name: string; total_price?: number; + currency?: string | null; exchange_rate?: number; + payers?: { user_id: number; amount: number }[]; member_ids?: number[]; + persons?: number | null; days?: number | null; note?: string | null; expense_date?: string | null; + }, +) { + const maxOrder = db.prepare( + 'SELECT MAX(sort_order) as max FROM budget_items WHERE trip_id = ?' + ).get(tripId) as { max: number | null }; + const sortOrder = (maxOrder.max !== null ? maxOrder.max : -1) + 1; + + const cat = data.category || 'other'; + + // Ensure category has a sort_order entry + const catExists = db.prepare('SELECT 1 FROM budget_category_order WHERE trip_id = ? AND category = ?').get(tripId, cat); + if (!catExists) { + const maxCatOrder = db.prepare('SELECT MAX(sort_order) as max FROM budget_category_order WHERE trip_id = ?').get(tripId) as { max: number | null }; + const catOrder = (maxCatOrder?.max !== null && maxCatOrder?.max !== undefined ? maxCatOrder.max : -1) + 1; + db.prepare('INSERT OR IGNORE INTO budget_category_order (trip_id, category, sort_order) VALUES (?, ?, ?)').run(tripId, cat, catOrder); + } + + // total_price is derived from explicit payers when given; otherwise the caller + // value (planning entries, or a bill no one has paid yet). + const payerTotal = (data.payers || []).reduce((a, p) => a + (p.amount > 0 ? p.amount : 0), 0); + const total = data.payers && data.payers.length > 0 ? payerTotal : (data.total_price || 0); + + const result = db.prepare( + 'INSERT INTO budget_items (trip_id, category, name, total_price, currency, exchange_rate, persons, days, note, sort_order, expense_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' + ).run( + tripId, + cat, + data.name, + total, + data.currency || null, + data.exchange_rate != null ? data.exchange_rate : 1, + data.member_ids ? data.member_ids.length : (data.persons != null ? data.persons : null), + data.days !== undefined && data.days !== null ? data.days : null, + data.note || null, + sortOrder, + data.expense_date || null, + ); + + const itemId = result.lastInsertRowid as number; + if (data.payers && data.payers.length > 0) writeItemPayers(itemId, data.payers); + if (data.member_ids && data.member_ids.length > 0) { + const insert = db.prepare('INSERT OR IGNORE INTO budget_item_members (budget_item_id, user_id, paid) VALUES (?, ?, 0)'); + for (const uid of data.member_ids) insert.run(itemId, uid); + } + + const item = db.prepare('SELECT * FROM budget_items WHERE id = ?').get(itemId) as BudgetItem; + item.members = loadItemMembers(itemId); + item.payers = loadItemPayers(itemId); + return item; +} + +export function linkBudgetItemToReservation( + tripId: string | number, + reservationId: number, + data: { name: string; category?: string; total_price: number }, +) { + const item = createBudgetItem(tripId, data) as BudgetItem & { reservation_id?: number | null }; + db.prepare('UPDATE budget_items SET reservation_id = ? WHERE id = ?').run(reservationId, item.id); + item.reservation_id = reservationId; + return item; +} + +export function updateBudgetItem( + id: string | number, + tripId: string | number, + data: { + category?: string; name?: string; total_price?: number; + currency?: string | null; exchange_rate?: number; + payers?: { user_id: number; amount: number }[]; member_ids?: number[]; + persons?: number | null; days?: number | null; note?: string | null; sort_order?: number; expense_date?: string | null; + }, +) { + const item = db.prepare('SELECT * FROM budget_items WHERE id = ? AND trip_id = ?').get(id, tripId); + if (!item) return null; + + db.prepare(` + UPDATE budget_items SET + category = COALESCE(?, category), + name = COALESCE(?, name), + total_price = CASE WHEN ? IS NOT NULL THEN ? ELSE total_price END, + currency = CASE WHEN ? THEN ? ELSE currency END, + exchange_rate = CASE WHEN ? IS NOT NULL THEN ? ELSE exchange_rate END, + persons = CASE WHEN ? IS NOT NULL THEN ? ELSE persons END, + days = CASE WHEN ? THEN ? ELSE days END, + note = CASE WHEN ? THEN ? ELSE note END, + sort_order = CASE WHEN ? IS NOT NULL THEN ? ELSE sort_order END, + expense_date = CASE WHEN ? THEN ? ELSE expense_date END + WHERE id = ? + `).run( + data.category || null, + data.name || null, + data.total_price !== undefined ? 1 : null, data.total_price !== undefined ? data.total_price : 0, + data.currency !== undefined ? 1 : 0, data.currency !== undefined ? (data.currency || null) : null, + data.exchange_rate !== undefined ? 1 : null, data.exchange_rate !== undefined ? data.exchange_rate : 1, + data.persons !== undefined ? 1 : null, data.persons !== undefined ? data.persons : null, + data.days !== undefined ? 1 : 0, data.days !== undefined ? data.days : null, + data.note !== undefined ? 1 : 0, data.note !== undefined ? data.note : null, + data.sort_order !== undefined ? 1 : null, data.sort_order !== undefined ? data.sort_order : 0, + data.expense_date !== undefined ? 1 : 0, data.expense_date !== undefined ? (data.expense_date || null) : null, + id, + ); + + // Optional inline payer/member replacement (the edit modal saves all at once). + if (data.payers !== undefined) writeItemPayers(id, data.payers); + if (data.member_ids !== undefined) { + db.prepare('DELETE FROM budget_item_members WHERE budget_item_id = ?').run(id); + const insert = db.prepare('INSERT OR IGNORE INTO budget_item_members (budget_item_id, user_id, paid) VALUES (?, ?, 0)'); + for (const uid of data.member_ids) insert.run(id, uid); + db.prepare('UPDATE budget_items SET persons = ? WHERE id = ?').run(data.member_ids.length || null, id); + } + + // If category changed, update category order table + if (data.category) { + const catExists = db.prepare('SELECT 1 FROM budget_category_order WHERE trip_id = ? AND category = ?').get(tripId, data.category); + if (!catExists) { + const maxCatOrder = db.prepare('SELECT MAX(sort_order) as max FROM budget_category_order WHERE trip_id = ?').get(tripId) as { max: number | null }; + const catOrder = (maxCatOrder?.max !== null && maxCatOrder?.max !== undefined ? maxCatOrder.max : -1) + 1; + db.prepare('INSERT OR IGNORE INTO budget_category_order (trip_id, category, sort_order) VALUES (?, ?, ?)').run(tripId, data.category, catOrder); + } + } + + const updated = db.prepare('SELECT * FROM budget_items WHERE id = ?').get(id) as BudgetItem; + updated.members = loadItemMembers(id); + updated.payers = loadItemPayers(id); + return updated; +} + +// --------------------------------------------------------------------------- +// Payers +// --------------------------------------------------------------------------- + +export function setItemPayers(id: string | number, tripId: string | number, payers: { user_id: number; amount: number }[]) { + const item = db.prepare('SELECT id FROM budget_items WHERE id = ? AND trip_id = ?').get(id, tripId); + if (!item) return null; + writeItemPayers(id, payers); + const updated = db.prepare('SELECT * FROM budget_items WHERE id = ?').get(id) as BudgetItem; + updated.members = loadItemMembers(id); + updated.payers = loadItemPayers(id); + return updated; +} + +export function deleteBudgetItem(id: string | number, tripId: string | number): boolean { + const item = db.prepare('SELECT id FROM budget_items WHERE id = ? AND trip_id = ?').get(id, tripId); + if (!item) return false; + db.prepare('DELETE FROM budget_items WHERE id = ?').run(id); + return true; +} + +// --------------------------------------------------------------------------- +// Members +// --------------------------------------------------------------------------- + +export function updateMembers(id: string | number, tripId: string | number, userIds: number[]) { + const item = db.prepare('SELECT * FROM budget_items WHERE id = ? AND trip_id = ?').get(id, tripId); + if (!item) return null; + + const existingPaid: Record = {}; + const existing = db.prepare('SELECT user_id, paid FROM budget_item_members WHERE budget_item_id = ?').all(id) as { user_id: number; paid: number }[]; + for (const e of existing) existingPaid[e.user_id] = e.paid; + + db.prepare('DELETE FROM budget_item_members WHERE budget_item_id = ?').run(id); + + if (userIds.length > 0) { + const insert = db.prepare('INSERT OR IGNORE INTO budget_item_members (budget_item_id, user_id, paid) VALUES (?, ?, ?)'); + for (const userId of userIds) insert.run(id, userId, existingPaid[userId] || 0); + db.prepare('UPDATE budget_items SET persons = ? WHERE id = ?').run(userIds.length, id); + } else { + db.prepare('UPDATE budget_items SET persons = NULL WHERE id = ?').run(id); + } + + const members = loadItemMembers(id).map(m => ({ ...m, avatar_url: avatarUrl(m) })); + const updated = db.prepare('SELECT * FROM budget_items WHERE id = ?').get(id) as BudgetItem; + return { members, item: updated }; +} + +export function toggleMemberPaid(id: string | number, tripId: string | number, userId: string | number, paid: boolean) { + // Resolve the item within the caller's trip before updating. + const item = db.prepare('SELECT id FROM budget_items WHERE id = ? AND trip_id = ?').get(id, tripId); + if (!item) return null; + + db.prepare('UPDATE budget_item_members SET paid = ? WHERE budget_item_id = ? AND user_id = ?') + .run(paid ? 1 : 0, id, userId); + + const member = db.prepare(` + SELECT bm.user_id, bm.paid, u.username, u.avatar + FROM budget_item_members bm JOIN users u ON bm.user_id = u.id + WHERE bm.budget_item_id = ? AND bm.user_id = ? + `).get(id, userId) as BudgetItemMember | undefined; + + return member ? { ...member, avatar_url: avatarUrl(member) } : null; +} + +// --------------------------------------------------------------------------- +// Per-person summary +// --------------------------------------------------------------------------- + +export function getPerPersonSummary(tripId: string | number) { + const summary = db.prepare(` + SELECT bm.user_id, u.username, u.avatar, + SUM(bi.total_price * 1.0 / (SELECT COUNT(*) FROM budget_item_members WHERE budget_item_id = bi.id)) as total_assigned, + SUM(CASE WHEN bm.paid = 1 THEN bi.total_price * 1.0 / (SELECT COUNT(*) FROM budget_item_members WHERE budget_item_id = bi.id) ELSE 0 END) as total_paid, + COUNT(bi.id) as items_count + FROM budget_item_members bm + JOIN budget_items bi ON bm.budget_item_id = bi.id + JOIN users u ON bm.user_id = u.id + WHERE bi.trip_id = ? + GROUP BY bm.user_id + `).all(tripId) as { user_id: number; username: string; avatar: string | null; total_assigned: number; total_paid: number; items_count: number }[]; + + return summary.map(s => ({ ...s, avatar_url: avatarUrl(s) })); +} + +// --------------------------------------------------------------------------- +// Settlement calculation (greedy debt matching) +// --------------------------------------------------------------------------- + +export function calculateSettlement( + tripId: string | number, + opts: { base?: string; rates?: Record | null; tripCurrency?: string } = {}, +) { + const base = (opts.base || opts.tripCurrency || 'EUR').toUpperCase(); + const tripCurrency = (opts.tripCurrency || base).toUpperCase(); + const rates = opts.rates ?? null; + // Amount in some currency → base. Pre-rework rows store currency = NULL, which + // means "the trip's own currency". rates[X] = units of X per 1 base. + const toBase = (amount: number, itemCurrency: string | null | undefined): number => { + const cur = (itemCurrency || tripCurrency).toUpperCase(); + if (cur === base || !rates) return amount; + const r = rates[cur]; + return r && r > 0 ? amount / r : amount; + }; + + const items = db.prepare('SELECT * FROM budget_items WHERE trip_id = ?').all(tripId) as BudgetItem[]; + const allMembers = db.prepare(` + SELECT bm.budget_item_id, bm.user_id, u.username, u.avatar + FROM budget_item_members bm + JOIN users u ON bm.user_id = u.id + WHERE bm.budget_item_id IN (SELECT id FROM budget_items WHERE trip_id = ?) + `).all(tripId) as (BudgetItemMember & { budget_item_id: number })[]; + const allPayers = db.prepare(` + SELECT bp.budget_item_id, bp.user_id, bp.amount, u.username, u.avatar + FROM budget_item_payers bp + JOIN users u ON bp.user_id = u.id + WHERE bp.budget_item_id IN (SELECT id FROM budget_items WHERE trip_id = ?) + `).all(tripId) as (BudgetItemPayer & { budget_item_id: number })[]; + + // Net balance per user, in the requested base currency: positive = is owed + // money, negative = owes money. Each expense's amounts are converted from their + // own currency to the base with live rates, so mixed-currency trips net correctly. + const balances: Record = {}; + const ensure = (id: number, src: { username?: string; avatar?: string | null }) => { + if (!balances[id]) balances[id] = { user_id: id, username: src.username || '', avatar_url: avatarUrl(src), balance: 0 }; + return balances[id]; + }; + + for (const item of items) { + const members = allMembers.filter(m => m.budget_item_id === item.id); + const payers = allPayers.filter(p => p.budget_item_id === item.id); + if (members.length === 0) continue; // planning-only entry → doesn't affect balances + + const paidBase = payers.reduce((a, p) => a + toBase(p.amount > 0 ? p.amount : 0, item.currency), 0); + const sharePerMember = paidBase / members.length; + + // Payers are credited what they actually paid (converted to base)… + for (const p of payers) ensure(p.user_id, p).balance += toBase(p.amount > 0 ? p.amount : 0, item.currency); + // …and every split participant owes an equal share of the base total. + for (const m of members) ensure(m.user_id, m).balance -= sharePerMember; + } + + // Persisted settle-up transfers already moved money: the payer's debt shrinks, + // the receiver's credit shrinks, so the corresponding flow disappears. + const settlements = listSettlements(tripId); + for (const s of settlements) { + if (balances[s.from_user_id]) balances[s.from_user_id].balance += s.amount; + if (balances[s.to_user_id]) balances[s.to_user_id].balance -= s.amount; + } + + // Calculate optimized payment flows (greedy algorithm) + const people = Object.values(balances).filter(b => Math.abs(b.balance) > 0.01); + const debtors = people.filter(p => p.balance < -0.01).map(p => ({ ...p, amount: -p.balance })); + const creditors = people.filter(p => p.balance > 0.01).map(p => ({ ...p, amount: p.balance })); + + // Sort by amount descending for efficient matching + debtors.sort((a, b) => b.amount - a.amount); + creditors.sort((a, b) => b.amount - a.amount); + + const flows: { from: { user_id: number; username: string; avatar_url: string | null }; to: { user_id: number; username: string; avatar_url: string | null }; amount: number }[] = []; + + let di = 0, ci = 0; + while (di < debtors.length && ci < creditors.length) { + const transfer = Math.min(debtors[di].amount, creditors[ci].amount); + if (transfer > 0.01) { + flows.push({ + from: { user_id: debtors[di].user_id, username: debtors[di].username, avatar_url: debtors[di].avatar_url }, + to: { user_id: creditors[ci].user_id, username: creditors[ci].username, avatar_url: creditors[ci].avatar_url }, + amount: Math.round(transfer * 100) / 100, + }); + } + debtors[di].amount -= transfer; + creditors[ci].amount -= transfer; + if (debtors[di].amount < 0.01) di++; + if (creditors[ci].amount < 0.01) ci++; + } + + return { + balances: Object.values(balances).map(b => ({ ...b, balance: Math.round(b.balance * 100) / 100 })), + flows, + settlements, + }; +} + +// --------------------------------------------------------------------------- +// Settlements (persisted settle-up transfers — history + undo) +// --------------------------------------------------------------------------- + +export function listSettlements(tripId: string | number) { + const rows = db.prepare(` + SELECT s.id, s.trip_id, s.from_user_id, s.to_user_id, s.amount, s.created_at, s.created_by_user_id, + fu.username AS from_username, fu.avatar AS from_avatar, + tu.username AS to_username, tu.avatar AS to_avatar + FROM budget_settlements s + JOIN users fu ON s.from_user_id = fu.id + JOIN users tu ON s.to_user_id = tu.id + WHERE s.trip_id = ? + ORDER BY s.created_at DESC, s.id DESC + `).all(tripId) as any[]; + return rows.map(r => ({ + id: r.id, trip_id: r.trip_id, + from_user_id: r.from_user_id, to_user_id: r.to_user_id, + amount: r.amount, created_at: r.created_at, created_by_user_id: r.created_by_user_id, + from_username: r.from_username, from_avatar_url: avatarUrl({ avatar: r.from_avatar }), + to_username: r.to_username, to_avatar_url: avatarUrl({ avatar: r.to_avatar }), + })); +} + +export function createSettlement( + tripId: string | number, + data: { from_user_id: number; to_user_id: number; amount: number }, + createdByUserId?: number, +) { + const result = db.prepare( + 'INSERT INTO budget_settlements (trip_id, from_user_id, to_user_id, amount, created_by_user_id) VALUES (?, ?, ?, ?, ?)' + ).run(tripId, data.from_user_id, data.to_user_id, Math.round(data.amount * 100) / 100, createdByUserId ?? null); + return listSettlements(tripId).find(s => s.id === Number(result.lastInsertRowid)) || null; +} + +export function deleteSettlement(id: string | number, tripId: string | number): boolean { + const row = db.prepare('SELECT id FROM budget_settlements WHERE id = ? AND trip_id = ?').get(id, tripId); + if (!row) return false; + db.prepare('DELETE FROM budget_settlements WHERE id = ?').run(id); + return true; +} + +// --------------------------------------------------------------------------- +// Reorder +// --------------------------------------------------------------------------- + +export function reorderBudgetItems(tripId: string | number, orderedIds: number[]) { + const update = db.prepare('UPDATE budget_items SET sort_order = ? WHERE id = ? AND trip_id = ?'); + db.transaction(() => { + orderedIds.forEach((id, index) => update.run(index, id, tripId)); + })(); +} + +export function reorderBudgetCategories(tripId: string | number, orderedCategories: string[]) { + const upsert = db.prepare( + 'INSERT INTO budget_category_order (trip_id, category, sort_order) VALUES (?, ?, ?) ON CONFLICT(trip_id, category) DO UPDATE SET sort_order = excluded.sort_order' + ); + db.transaction(() => { + orderedCategories.forEach((cat, index) => upsert.run(tripId, cat, index)); + })(); +} diff --git a/server/src/services/categoryService.ts b/server/src/services/categoryService.ts new file mode 100644 index 0000000000000000000000000000000000000000..a533d1a864624230fae491da0bc4dc400adf8bd4 --- /dev/null +++ b/server/src/services/categoryService.ts @@ -0,0 +1,31 @@ +import { db } from '../db/database'; + +export function listCategories() { + return db.prepare('SELECT * FROM categories ORDER BY name ASC').all(); +} + +export function createCategory(userId: number, name: string, color?: string, icon?: string) { + const result = db.prepare( + 'INSERT INTO categories (name, color, icon, user_id) VALUES (?, ?, ?, ?)' + ).run(name, color || '#6366f1', icon || '\uD83D\uDCCD', userId); + return db.prepare('SELECT * FROM categories WHERE id = ?').get(result.lastInsertRowid); +} + +export function getCategoryById(categoryId: number | string) { + return db.prepare('SELECT * FROM categories WHERE id = ?').get(categoryId); +} + +export function updateCategory(categoryId: number | string, name?: string, color?: string, icon?: string) { + db.prepare(` + UPDATE categories SET + name = COALESCE(?, name), + color = COALESCE(?, color), + icon = COALESCE(?, icon) + WHERE id = ? + `).run(name || null, color || null, icon || null, categoryId); + return db.prepare('SELECT * FROM categories WHERE id = ?').get(categoryId); +} + +export function deleteCategory(categoryId: number | string) { + db.prepare('DELETE FROM categories WHERE id = ?').run(categoryId); +} diff --git a/server/src/services/collabService.ts b/server/src/services/collabService.ts new file mode 100644 index 0000000000000000000000000000000000000000..2b6b0b7184848842920d1d30e81452d77aa0d7ca --- /dev/null +++ b/server/src/services/collabService.ts @@ -0,0 +1,442 @@ +import path from 'path'; +import fs from 'fs'; +import { db } from '../db/database'; +import { CollabNote, CollabPoll, CollabMessage, TripFile } from '../types'; +import { checkSsrf, createPinnedDispatcher } from '../utils/ssrfGuard'; +import { avatarUrl } from './avatarUrl'; + +/* ------------------------------------------------------------------ */ +/* Internal row types */ +/* ------------------------------------------------------------------ */ + +export interface ReactionRow { + emoji: string; + user_id: number; + username: string; + message_id?: number; +} + +export interface PollVoteRow { + option_index: number; + user_id: number; + username: string; + avatar: string | null; +} + +export interface NoteFileRow { + id: number; + filename: string; + original_name?: string; + file_size?: number; + mime_type?: string; +} + +export interface GroupedReaction { + emoji: string; + users: { user_id: number; username: string }[]; + count: number; +} + +export interface LinkPreviewResult { + title: string | null; + description: string | null; + image: string | null; + site_name?: string | null; + url: string; +} + +/* ------------------------------------------------------------------ */ +/* Helpers */ +/* ------------------------------------------------------------------ */ + +export { avatarUrl }; +export { verifyTripAccess } from './tripAccess'; + +/* ------------------------------------------------------------------ */ +/* Reactions */ +/* ------------------------------------------------------------------ */ + +export function loadReactions(messageId: number | string): ReactionRow[] { + return db.prepare(` + SELECT r.emoji, r.user_id, u.username + FROM collab_message_reactions r + JOIN users u ON r.user_id = u.id + WHERE r.message_id = ? + `).all(messageId) as ReactionRow[]; +} + +export function groupReactions(reactions: ReactionRow[]): GroupedReaction[] { + const map: Record = {}; + for (const r of reactions) { + if (!map[r.emoji]) map[r.emoji] = []; + map[r.emoji].push({ user_id: r.user_id, username: r.username }); + } + return Object.entries(map).map(([emoji, users]) => ({ emoji, users, count: users.length })); +} + +export function addOrRemoveReaction(messageId: number | string, tripId: number | string, userId: number, emoji: string): { found: boolean; reactions: GroupedReaction[] } { + const msg = db.prepare('SELECT id FROM collab_messages WHERE id = ? AND trip_id = ?').get(messageId, tripId); + if (!msg) return { found: false, reactions: [] }; + + const existing = db.prepare('SELECT id FROM collab_message_reactions WHERE message_id = ? AND user_id = ? AND emoji = ?').get(messageId, userId, emoji) as { id: number } | undefined; + if (existing) { + db.prepare('DELETE FROM collab_message_reactions WHERE id = ?').run(existing.id); + } else { + db.prepare('INSERT INTO collab_message_reactions (message_id, user_id, emoji) VALUES (?, ?, ?)').run(messageId, userId, emoji); + } + + return { found: true, reactions: groupReactions(loadReactions(messageId)) }; +} + +/* ------------------------------------------------------------------ */ +/* Notes */ +/* ------------------------------------------------------------------ */ + +export function formatNote(note: CollabNote) { + const attachments = db.prepare('SELECT id, filename, original_name, file_size, mime_type FROM trip_files WHERE note_id = ?').all(note.id) as NoteFileRow[]; + return { + ...note, + avatar_url: avatarUrl(note), + attachments: attachments.map(a => ({ ...a, url: `/api/trips/${note.trip_id}/files/${a.id}/download` })), + }; +} + +export function listNotes(tripId: string | number) { + const notes = db.prepare(` + SELECT n.*, u.username, u.avatar + FROM collab_notes n + JOIN users u ON n.user_id = u.id + WHERE n.trip_id = ? + ORDER BY n.pinned DESC, n.updated_at DESC + `).all(tripId) as CollabNote[]; + + return notes.map(formatNote); +} + +export function createNote(tripId: string | number, userId: number, data: { title: string; content?: string; category?: string; color?: string; website?: string; pinned?: boolean }) { + const pinned = data.pinned ? 1 : 0; + const result = db.prepare(` + INSERT INTO collab_notes (trip_id, user_id, title, content, category, color, website, pinned) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + `).run(tripId, userId, data.title, data.content || null, data.category || 'General', data.color || '#6366f1', data.website || null, pinned); + + const note = db.prepare(` + SELECT n.*, u.username, u.avatar FROM collab_notes n JOIN users u ON n.user_id = u.id WHERE n.id = ? + `).get(result.lastInsertRowid) as CollabNote; + + return formatNote(note); +} + +export function updateNote(tripId: string | number, noteId: string | number, data: { title?: string; content?: string; category?: string; color?: string; pinned?: number | boolean; website?: string }): ReturnType | null { + const existing = db.prepare('SELECT * FROM collab_notes WHERE id = ? AND trip_id = ?').get(noteId, tripId); + if (!existing) return null; + + db.prepare(` + UPDATE collab_notes SET + title = COALESCE(?, title), + content = CASE WHEN ? THEN ? ELSE content END, + category = COALESCE(?, category), + color = COALESCE(?, color), + pinned = CASE WHEN ? IS NOT NULL THEN ? ELSE pinned END, + website = CASE WHEN ? THEN ? ELSE website END, + updated_at = CURRENT_TIMESTAMP + WHERE id = ? + `).run( + data.title || null, + data.content !== undefined ? 1 : 0, data.content !== undefined ? data.content : null, + data.category || null, + data.color || null, + data.pinned !== undefined ? 1 : null, data.pinned ? 1 : 0, + data.website !== undefined ? 1 : 0, data.website !== undefined ? data.website : null, + noteId + ); + + const note = db.prepare(` + SELECT n.*, u.username, u.avatar FROM collab_notes n JOIN users u ON n.user_id = u.id WHERE n.id = ? + `).get(noteId) as CollabNote; + + return formatNote(note); +} + +export function deleteNote(tripId: string | number, noteId: string | number): boolean { + const existing = db.prepare('SELECT id FROM collab_notes WHERE id = ? AND trip_id = ?').get(noteId, tripId); + if (!existing) return false; + + // Clean up attached files from disk + const noteFiles = db.prepare('SELECT id, filename FROM trip_files WHERE note_id = ?').all(noteId) as NoteFileRow[]; + for (const f of noteFiles) { + const filePath = path.join(__dirname, '../../uploads', f.filename); + try { fs.unlinkSync(filePath); } catch { /* ignore */ } + } + db.prepare('DELETE FROM trip_files WHERE note_id = ?').run(noteId); + + db.prepare('DELETE FROM collab_notes WHERE id = ?').run(noteId); + return true; +} + +/* ------------------------------------------------------------------ */ +/* Note files */ +/* ------------------------------------------------------------------ */ + +export function addNoteFile(tripId: string | number, noteId: string | number, file: { filename: string; originalname: string; size: number; mimetype: string }): { file: TripFile & { url: string } } | null { + const note = db.prepare('SELECT id FROM collab_notes WHERE id = ? AND trip_id = ?').get(noteId, tripId); + if (!note) return null; + + const result = db.prepare( + 'INSERT INTO trip_files (trip_id, note_id, filename, original_name, file_size, mime_type) VALUES (?, ?, ?, ?, ?, ?)' + ).run(tripId, noteId, `files/${file.filename}`, file.originalname, file.size, file.mimetype); + + const saved = db.prepare('SELECT * FROM trip_files WHERE id = ?').get(result.lastInsertRowid) as TripFile; + return { file: { ...saved, url: `/api/trips/${tripId}/files/${saved.id}/download` } }; +} + +export function getFormattedNoteById(noteId: string | number) { + const note = db.prepare('SELECT n.*, u.username, u.avatar FROM collab_notes n JOIN users u ON n.user_id = u.id WHERE n.id = ?').get(noteId) as CollabNote; + return formatNote(note); +} + +export function deleteNoteFile(noteId: string | number, fileId: string | number): boolean { + const file = db.prepare('SELECT * FROM trip_files WHERE id = ? AND note_id = ?').get(fileId, noteId) as TripFile | undefined; + if (!file) return false; + + const filePath = path.join(__dirname, '../../uploads', file.filename); + try { fs.unlinkSync(filePath); } catch { /* ignore */ } + + db.prepare('DELETE FROM trip_files WHERE id = ?').run(fileId); + return true; +} + +/* ------------------------------------------------------------------ */ +/* Polls */ +/* ------------------------------------------------------------------ */ + +export function getPollWithVotes(pollId: number | bigint | string) { + const poll = db.prepare(` + SELECT p.*, u.username, u.avatar + FROM collab_polls p + JOIN users u ON p.user_id = u.id + WHERE p.id = ? + `).get(pollId) as CollabPoll | undefined; + + if (!poll) return null; + + const options: (string | { label: string })[] = JSON.parse(poll.options); + + const votes = db.prepare(` + SELECT v.option_index, v.user_id, u.username, u.avatar + FROM collab_poll_votes v + JOIN users u ON v.user_id = u.id + WHERE v.poll_id = ? + `).all(pollId) as PollVoteRow[]; + + const formattedOptions = options.map((label: string | { label: string }, idx: number) => ({ + label: typeof label === 'string' ? label : label.label || label, + voters: votes + .filter(v => v.option_index === idx) + .map(v => ({ id: v.user_id, user_id: v.user_id, username: v.username, avatar: v.avatar, avatar_url: avatarUrl(v) })), + })); + + return { + ...poll, + avatar_url: avatarUrl(poll), + options: formattedOptions, + is_closed: !!poll.closed, + multiple_choice: !!poll.multiple, + }; +} + +export function listPolls(tripId: string | number) { + const rows = db.prepare(` + SELECT id FROM collab_polls WHERE trip_id = ? ORDER BY created_at DESC + `).all(tripId) as { id: number }[]; + + return rows.map(row => getPollWithVotes(row.id)).filter(Boolean); +} + +export function createPoll(tripId: string | number, userId: number, data: { question: string; options: unknown[]; multiple?: boolean; multiple_choice?: boolean; deadline?: string }) { + const isMultiple = data.multiple || data.multiple_choice; + + const result = db.prepare(` + INSERT INTO collab_polls (trip_id, user_id, question, options, multiple, deadline) + VALUES (?, ?, ?, ?, ?, ?) + `).run(tripId, userId, data.question, JSON.stringify(data.options), isMultiple ? 1 : 0, data.deadline || null); + + return getPollWithVotes(result.lastInsertRowid); +} + +export function votePoll(tripId: string | number, pollId: string | number, userId: number, optionIndex: number): { error?: string; poll?: ReturnType } { + const poll = db.prepare('SELECT * FROM collab_polls WHERE id = ? AND trip_id = ?').get(pollId, tripId) as CollabPoll | undefined; + if (!poll) return { error: 'not_found' }; + if (poll.closed) return { error: 'closed' }; + + const options = JSON.parse(poll.options); + if (optionIndex < 0 || optionIndex >= options.length) { + return { error: 'invalid_index' }; + } + + const existingVote = db.prepare( + 'SELECT id FROM collab_poll_votes WHERE poll_id = ? AND user_id = ? AND option_index = ?' + ).get(pollId, userId, optionIndex) as { id: number } | undefined; + + if (existingVote) { + db.prepare('DELETE FROM collab_poll_votes WHERE id = ?').run(existingVote.id); + } else { + if (!poll.multiple) { + db.prepare('DELETE FROM collab_poll_votes WHERE poll_id = ? AND user_id = ?').run(pollId, userId); + } + db.prepare('INSERT INTO collab_poll_votes (poll_id, user_id, option_index) VALUES (?, ?, ?)').run(pollId, userId, optionIndex); + } + + return { poll: getPollWithVotes(pollId) }; +} + +export function closePoll(tripId: string | number, pollId: string | number): ReturnType | null { + const poll = db.prepare('SELECT * FROM collab_polls WHERE id = ? AND trip_id = ?').get(pollId, tripId); + if (!poll) return null; + + db.prepare('UPDATE collab_polls SET closed = 1 WHERE id = ?').run(pollId); + return getPollWithVotes(pollId); +} + +export function deletePoll(tripId: string | number, pollId: string | number): boolean { + const poll = db.prepare('SELECT id FROM collab_polls WHERE id = ? AND trip_id = ?').get(pollId, tripId); + if (!poll) return false; + + db.prepare('DELETE FROM collab_polls WHERE id = ?').run(pollId); + return true; +} + +/* ------------------------------------------------------------------ */ +/* Messages */ +/* ------------------------------------------------------------------ */ + +export function formatMessage(msg: CollabMessage, reactions?: GroupedReaction[]) { + return { ...msg, user_avatar: avatarUrl(msg), avatar_url: avatarUrl(msg), reactions: reactions || [] }; +} + +export function countMessages(tripId: string | number): number { + const row = db.prepare('SELECT COUNT(*) as cnt FROM collab_messages WHERE trip_id = ?').get(tripId) as { cnt: number }; + return row.cnt; +} + +export function listMessages(tripId: string | number, before?: string | number) { + const query = ` + SELECT m.*, u.username, u.avatar, + rm.text AS reply_text, ru.username AS reply_username + FROM collab_messages m + JOIN users u ON m.user_id = u.id + LEFT JOIN collab_messages rm ON m.reply_to = rm.id + LEFT JOIN users ru ON rm.user_id = ru.id + WHERE m.trip_id = ?${before ? ' AND m.id < ?' : ''} + ORDER BY m.id DESC + LIMIT 100 + `; + + const messages = before + ? db.prepare(query).all(tripId, before) as CollabMessage[] + : db.prepare(query).all(tripId) as CollabMessage[]; + + messages.reverse(); + + const msgIds = messages.map(m => m.id); + const reactionsByMsg: Record = {}; + if (msgIds.length > 0) { + const allReactions = db.prepare(` + SELECT r.message_id, r.emoji, r.user_id, u.username + FROM collab_message_reactions r + JOIN users u ON r.user_id = u.id + WHERE r.message_id IN (${msgIds.map(() => '?').join(',')}) + `).all(...msgIds) as (ReactionRow & { message_id: number })[]; + for (const r of allReactions) { + if (!reactionsByMsg[r.message_id]) reactionsByMsg[r.message_id] = []; + reactionsByMsg[r.message_id].push(r); + } + } + + return messages.map(m => formatMessage(m, groupReactions(reactionsByMsg[m.id] || []))); +} + +export function createMessage(tripId: string | number, userId: number, text: string, replyTo?: number | null): { error?: string; message?: ReturnType } { + if (replyTo) { + const replyMsg = db.prepare('SELECT id FROM collab_messages WHERE id = ? AND trip_id = ?').get(replyTo, tripId); + if (!replyMsg) return { error: 'reply_not_found' }; + } + + const result = db.prepare(` + INSERT INTO collab_messages (trip_id, user_id, text, reply_to) VALUES (?, ?, ?, ?) + `).run(tripId, userId, text.trim(), replyTo || null); + + const message = db.prepare(` + SELECT m.*, u.username, u.avatar, + rm.text AS reply_text, ru.username AS reply_username + FROM collab_messages m + JOIN users u ON m.user_id = u.id + LEFT JOIN collab_messages rm ON m.reply_to = rm.id + LEFT JOIN users ru ON rm.user_id = ru.id + WHERE m.id = ? + `).get(result.lastInsertRowid) as CollabMessage; + + return { message: formatMessage(message) }; +} + +export function deleteMessage(tripId: string | number, messageId: string | number, userId: number): { error?: string; username?: string } { + const message = db.prepare('SELECT * FROM collab_messages WHERE id = ? AND trip_id = ?').get(messageId, tripId) as CollabMessage | undefined; + if (!message) return { error: 'not_found' }; + if (Number(message.user_id) !== Number(userId)) return { error: 'not_owner' }; + + db.prepare('UPDATE collab_messages SET deleted = 1 WHERE id = ?').run(messageId); + return { username: message.username }; +} + +/* ------------------------------------------------------------------ */ +/* Link preview */ +/* ------------------------------------------------------------------ */ + +export async function fetchLinkPreview(url: string): Promise { + const fallback: LinkPreviewResult = { title: null, description: null, image: null, url }; + + const parsed = new URL(url); + const ssrf = await checkSsrf(url, true); + if (!ssrf.allowed) { + return { ...fallback, error: ssrf.error } as LinkPreviewResult & { error?: string }; + } + + try { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 5000); + + try { + const r = await fetch(url, { + redirect: 'error', + signal: controller.signal, + dispatcher: createPinnedDispatcher(ssrf.resolvedIp!), + headers: { 'User-Agent': 'Mozilla/5.0 (compatible; NOMAD/1.0; +https://github.com/mauriceboe/NOMAD)' }, + } as any); + clearTimeout(timeout); + if (!r.ok) throw new Error('Fetch failed'); + + const html = await r.text(); + const get = (prop: string) => { + const m = html.match(new RegExp(`]*property=["']og:${prop}["'][^>]*content=["']([^"']*)["']`, 'i')) + || html.match(new RegExp(`]*content=["']([^"']*)["'][^>]*property=["']og:${prop}["']`, 'i')); + return m ? m[1] : null; + }; + const titleTag = html.match(/]*>([^<]*)<\/title>/i); + const descMeta = html.match(/]*name=["']description["'][^>]*content=["']([^"']*)["']/i) + || html.match(/]*content=["']([^"']*)["'][^>]*name=["']description["']/i); + + return { + title: get('title') || (titleTag ? titleTag[1].trim() : null), + description: get('description') || (descMeta ? descMeta[1].trim() : null), + image: get('image') || null, + site_name: get('site_name') || null, + url, + }; + } catch { + clearTimeout(timeout); + return fallback; + } + } catch { + return fallback; + } +} diff --git a/server/src/services/cookie.ts b/server/src/services/cookie.ts new file mode 100644 index 0000000000000000000000000000000000000000..e8532e3e0f7b16b9737b611f5ffa7268d5c525f1 --- /dev/null +++ b/server/src/services/cookie.ts @@ -0,0 +1,63 @@ +import { Request, Response } from 'express'; +import { SESSION_DURATION_MS, SESSION_DURATION_REMEMBER_MS } from '../config'; + +const COOKIE_NAME = 'trek_session'; + +/** + * Controls the cookie lifetime for a login: + * - `undefined` → persistent `maxAge: SESSION_DURATION_MS` (the historical + * default, used by register/demo and anything that doesn't opt in). + * - `true` → persistent `maxAge: SESSION_DURATION_REMEMBER_MS` ("Remember me"). + * - `false` → no `maxAge` — a browser-session cookie cleared on browser close. + */ +export type RememberOption = boolean | undefined; + +/** + * Decide whether the session cookie should carry the `Secure` flag. + * + * We previously only derived this from `NODE_ENV=production` or + * `FORCE_HTTPS=true`. That left behind a common self-host setup: + * TREK running behind Traefik / Caddy / Cloudflare Tunnel with + * `NODE_ENV=development` locally and no `FORCE_HTTPS` — the cookie + * went out without `Secure`, even though the public leg was https. + * + * Now we also honour `req.secure`, which Express derives from + * `X-Forwarded-Proto` once `trust proxy` is set (TREK sets it to `1` + * in production automatically). If Express sees the request was TLS + * on the outermost hop, the cookie is `Secure`. `COOKIE_SECURE=false` + * remains the explicit escape hatch for plain-HTTP LAN testing. + */ +export function cookieOptions(clear = false, req?: Request, remember?: RememberOption) { + if (process.env.COOKIE_SECURE?.toLowerCase() === 'false') { + return buildOptions(clear, false, remember); + } + const envSecure = process.env.NODE_ENV?.toLowerCase() === 'production' || process.env.FORCE_HTTPS?.toLowerCase() === 'true'; + const requestSecure = req?.secure === true; + return buildOptions(clear, envSecure || requestSecure, remember); +} + +function resolveMaxAge(remember: RememberOption): { maxAge: number } | Record { + // false → session cookie (omit maxAge); true → the longer "remember me" + // window; undefined → the historical default. Each maxAge matches the JWT exp. + if (remember === false) return {}; + if (remember === true) return { maxAge: SESSION_DURATION_REMEMBER_MS }; + return { maxAge: SESSION_DURATION_MS }; +} + +function buildOptions(clear: boolean, secure: boolean, remember?: RememberOption) { + return { + httpOnly: true, + secure, + sameSite: 'lax' as const, + path: '/', + ...(clear ? {} : resolveMaxAge(remember)), + }; +} + +export function setAuthCookie(res: Response, token: string, req?: Request, remember?: RememberOption): void { + res.cookie(COOKIE_NAME, token, cookieOptions(false, req, remember)); +} + +export function clearAuthCookie(res: Response, req?: Request): void { + res.clearCookie(COOKIE_NAME, cookieOptions(true, req)); +} diff --git a/server/src/services/dayNoteService.ts b/server/src/services/dayNoteService.ts new file mode 100644 index 0000000000000000000000000000000000000000..3758678a3061b1102ca7379922fe324549f35897 --- /dev/null +++ b/server/src/services/dayNoteService.ts @@ -0,0 +1,42 @@ +import { db } from '../db/database'; +import { DayNote } from '../types'; + +export { verifyTripAccess } from './tripAccess'; + +export function listNotes(dayId: string | number, tripId: string | number) { + return db.prepare( + 'SELECT * FROM day_notes WHERE day_id = ? AND trip_id = ? ORDER BY sort_order ASC, created_at ASC' + ).all(dayId, tripId); +} + +export function dayExists(dayId: string | number, tripId: string | number) { + return db.prepare('SELECT id FROM days WHERE id = ? AND trip_id = ?').get(dayId, tripId); +} + +export function createNote(dayId: string | number, tripId: string | number, text: string, time?: string, icon?: string, sort_order?: number) { + const result = db.prepare( + 'INSERT INTO day_notes (day_id, trip_id, text, time, icon, sort_order) VALUES (?, ?, ?, ?, ?, ?)' + ).run(dayId, tripId, text.trim(), time || null, icon || '\uD83D\uDCDD', sort_order ?? 9999); + return db.prepare('SELECT * FROM day_notes WHERE id = ?').get(result.lastInsertRowid); +} + +export function getNote(id: string | number, dayId: string | number, tripId: string | number) { + return db.prepare('SELECT * FROM day_notes WHERE id = ? AND day_id = ? AND trip_id = ?').get(id, dayId, tripId) as DayNote | undefined; +} + +export function updateNote(id: string | number, current: DayNote, fields: { text?: string; time?: string; icon?: string; sort_order?: number }) { + db.prepare( + 'UPDATE day_notes SET text = ?, time = ?, icon = ?, sort_order = ? WHERE id = ?' + ).run( + fields.text !== undefined ? fields.text.trim() : current.text, + fields.time !== undefined ? fields.time : current.time, + fields.icon !== undefined ? fields.icon : current.icon, + fields.sort_order !== undefined ? fields.sort_order : current.sort_order, + id + ); + return db.prepare('SELECT * FROM day_notes WHERE id = ?').get(id); +} + +export function deleteNote(id: string | number) { + db.prepare('DELETE FROM day_notes WHERE id = ?').run(id); +} diff --git a/server/src/services/dayService.ts b/server/src/services/dayService.ts new file mode 100644 index 0000000000000000000000000000000000000000..d1d0d1e2ac74f1859780cf944586cf847a460aa4 --- /dev/null +++ b/server/src/services/dayService.ts @@ -0,0 +1,522 @@ +import { db } from '../db/database'; +import { loadTagsByPlaceIds, loadParticipantsByAssignmentIds, formatAssignmentWithPlace } from './queryHelpers'; +import { AssignmentRow, Day, DayNote } from '../types'; + +export { verifyTripAccess } from './tripAccess'; + +// --------------------------------------------------------------------------- +// Day assignment helpers +// --------------------------------------------------------------------------- + +export function getAssignmentsForDay(dayId: number | string) { + const assignments = db.prepare(` + SELECT da.*, p.id as place_id, p.name as place_name, p.description as place_description, + p.lat, p.lng, p.address, p.category_id, p.price, p.currency as place_currency, + COALESCE(da.assignment_time, p.place_time) as place_time, + COALESCE(da.assignment_end_time, p.end_time) as end_time, + p.duration_minutes, p.notes as place_notes, + p.image_url, p.transport_mode, p.google_place_id, p.website, p.phone, + c.name as category_name, c.color as category_color, c.icon as category_icon + FROM day_assignments da + JOIN places p ON da.place_id = p.id + LEFT JOIN categories c ON p.category_id = c.id + WHERE da.day_id = ? + ORDER BY da.order_index ASC, da.created_at ASC + `).all(dayId) as AssignmentRow[]; + + return assignments.map(a => { + const tags = db.prepare(` + SELECT t.* FROM tags t + JOIN place_tags pt ON t.id = pt.tag_id + WHERE pt.place_id = ? + `).all(a.place_id); + + return { + id: a.id, + day_id: a.day_id, + order_index: a.order_index, + notes: a.notes, + created_at: a.created_at, + place: { + id: a.place_id, + name: a.place_name, + description: a.place_description, + lat: a.lat, + lng: a.lng, + address: a.address, + category_id: a.category_id, + price: a.price, + currency: a.place_currency, + place_time: a.place_time, + end_time: a.end_time, + duration_minutes: a.duration_minutes, + notes: a.place_notes, + image_url: a.image_url, + transport_mode: a.transport_mode, + google_place_id: a.google_place_id, + website: a.website, + phone: a.phone, + category: a.category_id ? { + id: a.category_id, + name: a.category_name, + color: a.category_color, + icon: a.category_icon, + } : null, + tags, + } + }; + }); +} + +// --------------------------------------------------------------------------- +// Day CRUD +// --------------------------------------------------------------------------- + +export function listDays(tripId: string | number) { + const days = db.prepare('SELECT * FROM days WHERE trip_id = ? ORDER BY day_number ASC').all(tripId) as Day[]; + + if (days.length === 0) { + return { days: [] }; + } + + const dayIds = days.map(d => d.id); + const dayPlaceholders = dayIds.map(() => '?').join(','); + + const allAssignments = db.prepare(` + SELECT da.*, p.id as place_id, p.name as place_name, p.description as place_description, + p.lat, p.lng, p.address, p.category_id, p.price, p.currency as place_currency, + COALESCE(da.assignment_time, p.place_time) as place_time, + COALESCE(da.assignment_end_time, p.end_time) as end_time, + p.duration_minutes, p.notes as place_notes, + p.image_url, p.transport_mode, p.google_place_id, p.website, p.phone, + c.name as category_name, c.color as category_color, c.icon as category_icon + FROM day_assignments da + JOIN places p ON da.place_id = p.id + LEFT JOIN categories c ON p.category_id = c.id + WHERE da.day_id IN (${dayPlaceholders}) + ORDER BY da.order_index ASC, da.created_at ASC + `).all(...dayIds) as AssignmentRow[]; + + const placeIds = [...new Set(allAssignments.map(a => a.place_id))]; + const tagsByPlaceId = loadTagsByPlaceIds(placeIds, { compact: true }); + + const allAssignmentIds = allAssignments.map(a => a.id); + const participantsByAssignment = loadParticipantsByAssignmentIds(allAssignmentIds); + + const assignmentsByDayId: Record[]> = {}; + for (const a of allAssignments) { + if (!assignmentsByDayId[a.day_id]) assignmentsByDayId[a.day_id] = []; + assignmentsByDayId[a.day_id].push(formatAssignmentWithPlace(a, tagsByPlaceId[a.place_id] || [], participantsByAssignment[a.id] || [])); + } + + const allNotes = db.prepare( + `SELECT * FROM day_notes WHERE day_id IN (${dayPlaceholders}) ORDER BY sort_order ASC, created_at ASC` + ).all(...dayIds) as DayNote[]; + const notesByDayId: Record = {}; + for (const note of allNotes) { + if (!notesByDayId[note.day_id]) notesByDayId[note.day_id] = []; + notesByDayId[note.day_id].push(note); + } + + const daysWithAssignments = days.map(day => ({ + ...day, + assignments: assignmentsByDayId[day.id] || [], + notes_items: notesByDayId[day.id] || [], + })); + + return { days: daysWithAssignments }; +} + +export function createDay(tripId: string | number, date?: string, notes?: string) { + const maxDay = db.prepare('SELECT MAX(day_number) as max FROM days WHERE trip_id = ?').get(tripId) as { max: number | null }; + const dayNumber = (maxDay.max || 0) + 1; + + const result = db.prepare( + 'INSERT INTO days (trip_id, day_number, date, notes) VALUES (?, ?, ?, ?)' + ).run(tripId, dayNumber, date || null, notes || null); + + const day = db.prepare('SELECT * FROM days WHERE id = ?').get(result.lastInsertRowid) as Day; + return { ...day, assignments: [] }; +} + +export function getDay(id: string | number, tripId: string | number) { + return db.prepare('SELECT * FROM days WHERE id = ? AND trip_id = ?').get(id, tripId) as Day | undefined; +} + +export function updateDay(id: string | number, current: Day, fields: { notes?: string; title?: string | null }) { + db.prepare('UPDATE days SET notes = ?, title = ? WHERE id = ?').run( + fields.notes || null, + 'title' in fields ? (fields.title ?? null) : current.title, + id + ); + const updatedDay = db.prepare('SELECT * FROM days WHERE id = ?').get(id) as Day; + return { ...updatedDay, assignments: getAssignmentsForDay(id) }; +} + +export function deleteDay(id: string | number) { + db.prepare('DELETE FROM days WHERE id = ?').run(id); +} + +// --------------------------------------------------------------------------- +// Day reorder / insert (#589) +// +// Reordering keeps every day ROW stable (so assignments, notes, accommodations, +// photos and multi-day reservation positions ride along by id) and only changes +// each row's day_number — its position. On a dated trip the calendar dates stay +// pinned to their slots (position i keeps the i-th date) and the day's content +// moves across them. Because a booking's day is derived from the date part of +// reservation_time, every booking on a day whose date changed gets that date +// re-stamped onto the day's new date (time-of-day preserved), so day_id stays +// consistent and the booking moves with its day. +// --------------------------------------------------------------------------- + +const MS_PER_DAY = 24 * 60 * 60 * 1000; + +function addDays(date: string, n: number): string { + const [y, m, d] = date.split('-').map(Number); + const t = Date.UTC(y, m - 1, d) + n * MS_PER_DAY; + const dt = new Date(t); + const yyyy = dt.getUTCFullYear(); + const mm = String(dt.getUTCMonth() + 1).padStart(2, '0'); + const dd = String(dt.getUTCDate()).padStart(2, '0'); + return `${yyyy}-${mm}-${dd}`; +} + +function dayDelta(from: string, to: string): number { + const [fy, fm, fd] = from.split('-').map(Number); + const [ty, tm, td] = to.split('-').map(Number); + return Math.round((Date.UTC(ty, tm - 1, td) - Date.UTC(fy, fm - 1, fd)) / MS_PER_DAY); +} + +/** Replace the date part of an ISO-ish timestamp, keeping any time suffix. */ +function withDatePart(timestamp: string, date: string): string { + return date + (timestamp.length > 10 ? timestamp.slice(10) : ''); +} + +/** + * After day dates have been re-pinned, re-stamp the date of every booking on a + * moved day so reservation_time/reservation_end_time follow their day's new + * date (time-of-day preserved). Transport endpoints (flight legs) shift by the + * same per-booking day delta so multi-leg timing stays internally consistent. + */ +function restampReservationDates( + tripId: string | number, + oldDateById: Map, + newDateById: Map, +): void { + const reservations = db.prepare( + 'SELECT id, day_id, end_day_id, reservation_time, reservation_end_time FROM reservations WHERE trip_id = ?' + ).all(tripId) as { + id: number; day_id: number | null; end_day_id: number | null; + reservation_time: string | null; reservation_end_time: string | null; + }[]; + + const setTime = db.prepare('UPDATE reservations SET reservation_time = ? WHERE id = ?'); + const setEndTime = db.prepare('UPDATE reservations SET reservation_end_time = ? WHERE id = ?'); + const endpoints = db.prepare('SELECT id, local_date FROM reservation_endpoints WHERE reservation_id = ?'); + const setEndpointDate = db.prepare('UPDATE reservation_endpoints SET local_date = ? WHERE id = ?'); + + for (const r of reservations) { + if (r.day_id != null && r.reservation_time) { + const oldDate = oldDateById.get(r.day_id); + const newDate = newDateById.get(r.day_id); + if (oldDate && newDate && oldDate !== newDate) { + setTime.run(withDatePart(r.reservation_time, newDate), r.id); + // Shift each transport leg's local_date by the same number of days. + const delta = dayDelta(oldDate, newDate); + if (delta !== 0) { + for (const ep of endpoints.all(r.id) as { id: number; local_date: string | null }[]) { + if (ep.local_date) setEndpointDate.run(addDays(ep.local_date, delta), ep.id); + } + } + } + } + if (r.end_day_id != null && r.reservation_end_time) { + const oldDate = oldDateById.get(r.end_day_id); + const newDate = newDateById.get(r.end_day_id); + if (oldDate && newDate && oldDate !== newDate) { + setEndTime.run(withDatePart(r.reservation_end_time, newDate), r.id); + } + } + } +} + +/** A stay must not end before it begins after a reorder/insert. */ +function assertNoInvertedAccommodation(tripId: string | number): void { + const spans = db.prepare(` + SELECT a.id, s.day_number AS start_no, e.day_number AS end_no + FROM day_accommodations a + JOIN days s ON a.start_day_id = s.id + JOIN days e ON a.end_day_id = e.id + WHERE a.trip_id = ? + `).all(tripId) as { id: number; start_no: number; end_no: number }[]; + for (const span of spans) { + if (span.start_no > span.end_no) { + throw new DayReorderError('This move would make an accommodation end before it starts.'); + } + } +} + +/** Thrown for invalid reorder/insert requests; mapped to HTTP 400 by the controller. */ +export class DayReorderError extends Error {} + +/** + * Reorder whole days. `orderedIds` is the desired full sequence of this trip's + * day ids (a permutation of the current ids). + */ +export function reorderDays(tripId: string | number, orderedIds: number[]) { + const rows = db.prepare( + 'SELECT id, day_number, date FROM days WHERE trip_id = ? ORDER BY day_number' + ).all(tripId) as { id: number; day_number: number; date: string | null }[]; + + const existingIds = new Set(rows.map(r => r.id)); + if (orderedIds.length !== rows.length || !orderedIds.every(id => existingIds.has(id))) { + throw new DayReorderError('orderedIds must be a permutation of the trip day ids.'); + } + + const oldDateById = new Map(rows.map(r => [r.id, r.date])); + // Dates stay pinned to slots: position i keeps the i-th date (ascending). + const sortedDates = rows.map(r => r.date).filter((d): d is string => !!d).sort(); + const isDated = sortedDates.length > 0; + + const setDayNumber = db.prepare('UPDATE days SET day_number = ? WHERE id = ?'); + const setDayNumberAndDate = db.prepare('UPDATE days SET day_number = ?, date = ? WHERE id = ?'); + + db.exec('BEGIN'); + try { + // Two-phase renumber to dodge UNIQUE(trip_id, day_number) collisions. + orderedIds.forEach((id, i) => setDayNumber.run(-(i + 1), id)); + const newDateById = new Map(); + orderedIds.forEach((id, i) => { + const date = isDated ? (sortedDates[i] ?? null) : null; + setDayNumberAndDate.run(i + 1, date, id); + newDateById.set(id, date); + }); + + if (isDated) restampReservationDates(tripId, oldDateById, newDateById); + assertNoInvertedAccommodation(tripId); + + db.exec('COMMIT'); + } catch (e) { + db.exec('ROLLBACK'); + throw e; + } + + return listDays(tripId); +} + +/** + * Insert a new empty day at a 1-based position (default: append at the end). + * On a dated trip the trip gains one calendar day: dates re-pin so the slots + * stay contiguous, the trip's end_date extends by one day, and bookings on + * shifted days have their dates re-stamped (same rules as reorderDays). + */ +export function insertDay(tripId: string | number, position?: number) { + const rows = db.prepare( + 'SELECT id, day_number, date FROM days WHERE trip_id = ? ORDER BY day_number' + ).all(tripId) as { id: number; day_number: number; date: string | null }[]; + const n = rows.length; + const pos = Math.min(Math.max(position ?? n + 1, 1), n + 1); + const datedRows = rows.filter(r => r.date) as { id: number; day_number: number; date: string }[]; + const isDated = datedRows.length > 0; + + const setDayNumber = db.prepare('UPDATE days SET day_number = ? WHERE id = ?'); + + if (!isDated) { + db.exec('BEGIN'); + try { + const toShift = rows.filter(r => r.day_number >= pos); + toShift.forEach(r => setDayNumber.run(-r.day_number, r.id)); + const result = db.prepare('INSERT INTO days (trip_id, day_number, date) VALUES (?, ?, NULL)').run(tripId, pos); + toShift.forEach(r => setDayNumber.run(r.day_number + 1, r.id)); + db.exec('COMMIT'); + const day = db.prepare('SELECT * FROM days WHERE id = ?').get(result.lastInsertRowid) as Day; + return { ...day, assignments: [], notes_items: [] }; + } catch (e) { + db.exec('ROLLBACK'); + throw e; + } + } + + // Dated trip: rebuild N+1 contiguous dates from the earliest date. + const start = datedRows.map(r => r.date).sort()[0]; + const dates = Array.from({ length: n + 1 }, (_, i) => addDays(start, i)); + const oldDateById = new Map(rows.map(r => [r.id, r.date])); + const setDayNumberAndDate = db.prepare('UPDATE days SET day_number = ?, date = ? WHERE id = ?'); + + db.exec('BEGIN'); + try { + rows.forEach((r, i) => setDayNumber.run(-(i + 1), r.id)); + const result = db.prepare('INSERT INTO days (trip_id, day_number, date) VALUES (?, ?, ?)').run(tripId, pos, dates[pos - 1]); + const newId = Number(result.lastInsertRowid); + + const orderedIds = rows.map(r => r.id); + orderedIds.splice(pos - 1, 0, newId); + const newDateById = new Map(); + orderedIds.forEach((id, i) => { + setDayNumberAndDate.run(i + 1, dates[i], id); + newDateById.set(id, dates[i]); + }); + + restampReservationDates(tripId, oldDateById, newDateById); + assertNoInvertedAccommodation(tripId); + db.prepare('UPDATE trips SET end_date = ? WHERE id = ?').run(dates[dates.length - 1], tripId); + + db.exec('COMMIT'); + const day = db.prepare('SELECT * FROM days WHERE id = ?').get(newId) as Day; + return { ...day, assignments: [], notes_items: [] }; + } catch (e) { + db.exec('ROLLBACK'); + throw e; + } +} + +// --------------------------------------------------------------------------- +// Accommodation helpers +// --------------------------------------------------------------------------- + +export interface DayAccommodation { + id: number; + trip_id: number; + place_id: number | null; + start_day_id: number; + end_day_id: number; + check_in: string | null; + check_in_end: string | null; + check_out: string | null; + confirmation: string | null; + notes: string | null; +} + +function getAccommodationWithPlace(id: number | bigint) { + return db.prepare(` + SELECT a.*, p.name as place_name, p.address as place_address, p.image_url as place_image, p.lat as place_lat, p.lng as place_lng + FROM day_accommodations a + LEFT JOIN places p ON a.place_id = p.id + WHERE a.id = ? + `).get(id); +} + +// --------------------------------------------------------------------------- +// Accommodation CRUD +// --------------------------------------------------------------------------- + +export function listAccommodations(tripId: string | number) { + return db.prepare(` + SELECT a.*, p.name as place_name, p.address as place_address, p.image_url as place_image, p.lat as place_lat, p.lng as place_lng, + r.title as reservation_title + FROM day_accommodations a + LEFT JOIN places p ON a.place_id = p.id + LEFT JOIN reservations r ON r.accommodation_id = a.id + WHERE a.trip_id = ? + ORDER BY a.created_at ASC + `).all(tripId); +} + +export function validateAccommodationRefs(tripId: string | number, placeId?: number, startDayId?: number, endDayId?: number) { + const errors: { field: string; message: string }[] = []; + if (placeId !== undefined) { + const place = db.prepare('SELECT id FROM places WHERE id = ? AND trip_id = ?').get(placeId, tripId); + if (!place) errors.push({ field: 'place_id', message: 'Place not found' }); + } + if (startDayId !== undefined) { + const startDay = db.prepare('SELECT id FROM days WHERE id = ? AND trip_id = ?').get(startDayId, tripId); + if (!startDay) errors.push({ field: 'start_day_id', message: 'Start day not found' }); + } + if (endDayId !== undefined) { + const endDay = db.prepare('SELECT id FROM days WHERE id = ? AND trip_id = ?').get(endDayId, tripId); + if (!endDay) errors.push({ field: 'end_day_id', message: 'End day not found' }); + } + return errors; +} + +interface CreateAccommodationData { + place_id: number; + start_day_id: number; + end_day_id: number; + check_in?: string; + check_in_end?: string; + check_out?: string; + confirmation?: string; + notes?: string; +} + +export function createAccommodation(tripId: string | number, data: CreateAccommodationData) { + const { place_id, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, notes } = data; + + const result = db.prepare( + 'INSERT INTO day_accommodations (trip_id, place_id, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)' + ).run(tripId, place_id, start_day_id, end_day_id, check_in || null, check_in_end || null, check_out || null, confirmation || null, notes || null); + + const accommodationId = result.lastInsertRowid; + + // Auto-create linked reservation for this accommodation + const placeName = (db.prepare('SELECT name FROM places WHERE id = ?').get(place_id) as { name: string } | undefined)?.name || 'Hotel'; + const startDayDate = (db.prepare('SELECT date FROM days WHERE id = ?').get(start_day_id) as { date: string } | undefined)?.date || null; + const meta: Record = {}; + if (check_in) meta.check_in_time = check_in; + if (check_in_end) meta.check_in_end_time = check_in_end; + if (check_out) meta.check_out_time = check_out; + db.prepare(` + INSERT INTO reservations (trip_id, day_id, title, reservation_time, location, confirmation_number, notes, status, type, accommodation_id, metadata) + VALUES (?, ?, ?, ?, ?, ?, ?, 'confirmed', 'hotel', ?, ?) + `).run( + tripId, start_day_id, placeName, startDayDate || null, null, + confirmation || null, notes || null, accommodationId, + Object.keys(meta).length > 0 ? JSON.stringify(meta) : null + ); + + return getAccommodationWithPlace(accommodationId); +} + +export function getAccommodation(id: string | number, tripId: string | number) { + return db.prepare('SELECT * FROM day_accommodations WHERE id = ? AND trip_id = ?').get(id, tripId) as DayAccommodation | undefined; +} + +export function updateAccommodation(id: string | number, existing: DayAccommodation, fields: { + place_id?: number; start_day_id?: number; end_day_id?: number; + check_in?: string; check_in_end?: string; check_out?: string; confirmation?: string; notes?: string; +}) { + const newPlaceId = fields.place_id !== undefined ? fields.place_id : existing.place_id; + const newStartDayId = fields.start_day_id !== undefined ? fields.start_day_id : existing.start_day_id; + const newEndDayId = fields.end_day_id !== undefined ? fields.end_day_id : existing.end_day_id; + const newCheckIn = fields.check_in !== undefined ? fields.check_in : existing.check_in; + const newCheckInEnd = fields.check_in_end !== undefined ? fields.check_in_end : existing.check_in_end; + const newCheckOut = fields.check_out !== undefined ? fields.check_out : existing.check_out; + const newConfirmation = fields.confirmation !== undefined ? fields.confirmation : existing.confirmation; + const newNotes = fields.notes !== undefined ? fields.notes : existing.notes; + + db.prepare( + 'UPDATE day_accommodations SET place_id = ?, start_day_id = ?, end_day_id = ?, check_in = ?, check_in_end = ?, check_out = ?, confirmation = ?, notes = ? WHERE id = ?' + ).run(newPlaceId, newStartDayId, newEndDayId, newCheckIn, newCheckInEnd, newCheckOut, newConfirmation, newNotes, id); + + // Sync check-in/out/confirmation to linked reservation + const linkedRes = db.prepare('SELECT id, metadata FROM reservations WHERE accommodation_id = ?').get(Number(id)) as { id: number; metadata: string | null } | undefined; + if (linkedRes) { + const meta = linkedRes.metadata ? JSON.parse(linkedRes.metadata) : {}; + if (newCheckIn) meta.check_in_time = newCheckIn; + if (newCheckInEnd) meta.check_in_end_time = newCheckInEnd; + if (newCheckOut) meta.check_out_time = newCheckOut; + db.prepare('UPDATE reservations SET metadata = ?, confirmation_number = COALESCE(?, confirmation_number) WHERE id = ?') + .run(JSON.stringify(meta), newConfirmation || null, linkedRes.id); + } + + return getAccommodationWithPlace(Number(id)); +} + +/** Delete accommodation and its linked reservation (and any linked budget item). */ +export function deleteAccommodation(id: string | number): { linkedReservationId: number | null; deletedBudgetItemId: number | null } { + const linkedRes = db.prepare('SELECT id FROM reservations WHERE accommodation_id = ?').get(Number(id)) as { id: number } | undefined; + let deletedBudgetItemId: number | null = null; + if (linkedRes) { + const linkedBudget = db.prepare('SELECT id FROM budget_items WHERE reservation_id = ?').get(linkedRes.id) as { id: number } | undefined; + if (linkedBudget) { + db.prepare('DELETE FROM budget_items WHERE id = ?').run(linkedBudget.id); + deletedBudgetItemId = linkedBudget.id; + } + db.prepare('DELETE FROM reservations WHERE id = ?').run(linkedRes.id); + } + + db.prepare('DELETE FROM day_accommodations WHERE id = ?').run(id); + return { linkedReservationId: linkedRes ? linkedRes.id : null, deletedBudgetItemId }; +} diff --git a/server/src/services/demo.ts b/server/src/services/demo.ts new file mode 100644 index 0000000000000000000000000000000000000000..7cbf6a3dea28baabc5885afb22cd0172e1e45f6f --- /dev/null +++ b/server/src/services/demo.ts @@ -0,0 +1,24 @@ +// Central registry of demo-user email addresses. +// +// Historical: the demo account was seeded as "demo@trek.app" (see +// authService.demoLogin), but several guards — demoUploadBlock in +// middleware/auth.ts, the MFA/backup-code bypasses in authService — +// were still checking the pre-rename "demo@nomad.app" string, so they +// either never fired or silently diverged between call sites. Routing +// every check through this constant keeps them aligned. + +export const DEMO_EMAIL_PRIMARY = 'demo@trek.app'; + +/** + * All email addresses that should be treated as the demo account. + * Includes the historical `demo@nomad.app` identifier so instances that + * upgraded in place without resetting the DB still hit demo-mode guards. + */ +export const DEMO_EMAILS: ReadonlySet = new Set([ + DEMO_EMAIL_PRIMARY, + 'demo@nomad.app', +]); + +export function isDemoEmail(email: string | null | undefined): boolean { + return !!email && DEMO_EMAILS.has(email); +} diff --git a/server/src/services/distanceService.ts b/server/src/services/distanceService.ts new file mode 100644 index 0000000000000000000000000000000000000000..559b815951aa6b06768e5d84e7bfeedb5106ce53 --- /dev/null +++ b/server/src/services/distanceService.ts @@ -0,0 +1,43 @@ +import { db } from '../db/database'; + +// Great-circle distance between two points in kilometres. +function haversineKm(lat1: number, lng1: number, lat2: number, lng2: number): number { + const R = 6371; + const toRad = (deg: number) => (deg * Math.PI) / 180; + const dLat = toRad(lat2 - lat1); + const dLng = toRad(lng2 - lng1); + const a = + Math.sin(dLat / 2) ** 2 + + Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLng / 2) ** 2; + return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); +} + +/** + * Total flight distance a user has covered, summed across every non-cancelled + * flight reservation in their trips. Each flight stores its waypoints in + * reservation_endpoints (from → stops → to, ordered by sequence); we add up the + * legs between consecutive points so multi-stop flights count correctly. + */ +export function getFlightDistanceKm(userId: number): number { + const rows = db.prepare(` + SELECT re.reservation_id, re.lat, re.lng + FROM reservation_endpoints re + JOIN reservations r ON r.id = re.reservation_id + JOIN trips t ON t.id = r.trip_id + LEFT JOIN trip_members tm ON tm.trip_id = t.id AND tm.user_id = ? + WHERE (t.user_id = ? OR tm.user_id IS NOT NULL) + AND r.type = 'flight' + AND r.status != 'cancelled' + ORDER BY re.reservation_id, re.sequence + `).all(userId, userId) as { reservation_id: number; lat: number; lng: number }[]; + + let total = 0; + let prev: { id: number; lat: number; lng: number } | null = null; + for (const point of rows) { + if (prev && prev.id === point.reservation_id) { + total += haversineKm(prev.lat, prev.lng, point.lat, point.lng); + } + prev = { id: point.reservation_id, lat: point.lat, lng: point.lng }; + } + return Math.round(total); +} diff --git a/server/src/services/ephemeralTokens.ts b/server/src/services/ephemeralTokens.ts new file mode 100644 index 0000000000000000000000000000000000000000..aed77d614e0f2fac928b31335db9130f8f96fb04 --- /dev/null +++ b/server/src/services/ephemeralTokens.ts @@ -0,0 +1,85 @@ +import crypto from 'crypto'; + +const TTL: Record = { + ws: 30_000, + download: 60_000, +}; + +const MAX_STORE_SIZE = 10_000; + +interface TokenEntry { + userId: number; + purpose: string; + expiresAt: number; + /** + * Snapshot of the user's `password_version` at mint time, used for the + * defence-in-depth session gate on WebSocket connects. `undefined` for + * tokens minted without a version (legacy/other purposes), which callers + * treat as version 0 — mirroring the JWT `pv` claim semantics. + */ + pv?: number; +} + +export interface EphemeralTokenMeta { + /** Bind the token to the user's current password_version (session gate). */ + pv?: number; +} + +const store = new Map(); + +export function createEphemeralToken( + userId: number, + purpose: string, + meta?: EphemeralTokenMeta, +): string | null { + if (store.size >= MAX_STORE_SIZE) return null; + const token = crypto.randomBytes(32).toString('hex'); + const ttl = TTL[purpose] ?? 60_000; + store.set(token, { userId, purpose, expiresAt: Date.now() + ttl, pv: meta?.pv }); + return token; +} + +export function consumeEphemeralToken(token: string, purpose: string): number | null { + const entry = store.get(token); + if (!entry) return null; + store.delete(token); + if (entry.purpose !== purpose || Date.now() > entry.expiresAt) return null; + return entry.userId; +} + +/** + * Like `consumeEphemeralToken`, but also returns the `password_version` the + * token was minted with. Used by the WebSocket handshake so a token issued + * before a password change can be rejected even within its short TTL. + */ +export function consumeEphemeralTokenWithMeta( + token: string, + purpose: string, +): { userId: number; pv?: number } | null { + const entry = store.get(token); + if (!entry) return null; + store.delete(token); + if (entry.purpose !== purpose || Date.now() > entry.expiresAt) return null; + return { userId: entry.userId, pv: entry.pv }; +} + +let cleanupInterval: ReturnType | null = null; + +export function startTokenCleanup(): void { + if (cleanupInterval) return; + cleanupInterval = setInterval(() => { + const now = Date.now(); + for (const [token, entry] of store) { + if (now > entry.expiresAt) store.delete(token); + } + }, 60_000); + // Allow process to exit even if interval is active + if (cleanupInterval.unref) cleanupInterval.unref(); +} + +export function stopTokenCleanup(): void { + if (cleanupInterval) { + clearInterval(cleanupInterval); + cleanupInterval = null; + } +} diff --git a/server/src/services/exchangeRateService.ts b/server/src/services/exchangeRateService.ts new file mode 100644 index 0000000000000000000000000000000000000000..184431332efaa1a6c0390c958c4680ad223678f0 --- /dev/null +++ b/server/src/services/exchangeRateService.ts @@ -0,0 +1,75 @@ +/** + * Live exchange rates for the Costs/Budget money conversion. + * + * Fetches from api.frankfurter.dev (no key, already CSP-allowlisted for the + * dashboard widget) and caches per base currency in-memory for a few hours so a + * settlement request never hammers the upstream. Rates are "units of X per 1 + * base", so an amount in currency C converts to base as `amount / rates[C]`. + * + * Everything degrades gracefully: if the fetch fails (offline, upstream down), + * callers get `null`/identity conversion and amounts are treated as already in + * the base currency rather than throwing. + */ + +const TTL_MS = 6 * 60 * 60 * 1000; // 6h +const cache = new Map; ts: number }>(); +const inflight = new Map | null>>(); + +async function fetchRates(base: string): Promise | null> { + try { + const res = await fetch(`https://api.frankfurter.dev/v2/rates?base=${encodeURIComponent(base)}`); + if (!res.ok) return null; + // Frankfurter returns an array of { date, base, quote, rate } and omits the + // base's own self-rate, so seed the map with `base = 1` then index by quote. + const data = (await res.json()) as Array<{ quote?: string; rate?: number }>; + if (!Array.isArray(data)) return null; + const rates: Record = { [base.toUpperCase()]: 1 }; + for (const r of data) { + if (r && typeof r.quote === 'string' && typeof r.rate === 'number') rates[r.quote] = r.rate; + } + return Object.keys(rates).length > 1 ? rates : null; + } catch { + return null; + } +} + +/** Rates map for `base` (cached). Returns null if unavailable. */ +export async function getRates(base: string): Promise | null> { + const key = (base || 'EUR').toUpperCase(); + const hit = cache.get(key); + const now = Date.now(); + if (hit && now - hit.ts < TTL_MS) return hit.rates; + + // Coalesce concurrent fetches for the same base. + let p = inflight.get(key); + if (!p) { + p = fetchRates(key).then(rates => { + if (rates) cache.set(key, { rates, ts: Date.now() }); + inflight.delete(key); + return rates; + }); + inflight.set(key, p); + } + const rates = await p; + // On failure fall back to the last cached value if we have one. + if (!rates && hit) return hit.rates; + return rates; +} + +/** + * Convert `amount` from `from` currency into `base` using a rates map obtained + * from getRates(base). Identity when same currency or the rate is missing. + */ +export function convertWithRates( + amount: number, + from: string | null | undefined, + base: string, + rates: Record | null, +): number { + const fromCur = (from || base).toUpperCase(); + const baseCur = base.toUpperCase(); + if (fromCur === baseCur || !rates) return amount; + const r = rates[fromCur]; + if (!r || r <= 0) return amount; + return amount / r; +} diff --git a/server/src/services/fileService.ts b/server/src/services/fileService.ts new file mode 100644 index 0000000000000000000000000000000000000000..f119344ccc20dfdff856a0ae9eb45e7b7c22c918 --- /dev/null +++ b/server/src/services/fileService.ts @@ -0,0 +1,275 @@ +import path from 'path'; +import fs from 'fs'; +import type { Request } from 'express'; +import { db } from '../db/database'; +import { consumeEphemeralToken } from './ephemeralTokens'; +import { verifyJwtAndLoadUser } from '../middleware/auth'; +import { TripFile } from '../types'; + +// --------------------------------------------------------------------------- +// Constants +// --------------------------------------------------------------------------- + +export const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50 MB +export const DEFAULT_ALLOWED_EXTENSIONS = 'jpg,jpeg,png,gif,webp,heic,pdf,doc,docx,xls,xlsx,txt,csv,pkpass'; +// Single authoritative blocklist for every file-upload surface (main +// file manager + collab attachments). When the admin setting +// `allowed_file_types` is `*`, this list is still enforced so the +// wildcard doesn't silently admit executables/scripts. +export const BLOCKED_EXTENSIONS = [ + // Server-rendered / scripted content that could XSS a viewer + '.svg', '.html', '.htm', '.xml', '.xhtml', + // Scripts + '.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.php', '.py', '.rb', '.pl', + // Executables + '.exe', '.bat', '.sh', '.cmd', '.msi', '.dll', '.com', '.vbs', '.ps1', '.app', +]; +export const filesDir = path.join(__dirname, '../../uploads/files'); + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +export { verifyTripAccess } from './tripAccess'; + +export function getAllowedExtensions(): string { + try { + const row = db.prepare("SELECT value FROM app_settings WHERE key = 'allowed_file_types'").get() as { value: string } | undefined; + return row?.value || DEFAULT_ALLOWED_EXTENSIONS; + } catch { return DEFAULT_ALLOWED_EXTENSIONS; } +} + +const FILE_SELECT = ` + SELECT f.*, r.title as reservation_title, u.username as uploaded_by_name, u.avatar as uploaded_by_avatar + FROM trip_files f + LEFT JOIN reservations r ON f.reservation_id = r.id + LEFT JOIN users u ON f.uploaded_by = u.id +`; + +export function formatFile(file: TripFile & { trip_id?: number; uploaded_by_avatar?: string | null }) { + const tripId = file.trip_id; + return { + ...file, + url: `/api/trips/${tripId}/files/${file.id}/download`, + uploaded_by_avatar: file.uploaded_by_avatar ? `/uploads/avatars/${file.uploaded_by_avatar}` : null, + }; +} + +// --------------------------------------------------------------------------- +// File path resolution & validation +// --------------------------------------------------------------------------- + +export function resolveFilePath(filename: string): { resolved: string; safe: boolean } { + const safeName = path.basename(filename); + const filePath = path.join(filesDir, safeName); + const resolved = path.resolve(filePath); + const safe = resolved.startsWith(path.resolve(filesDir)); + return { resolved, safe }; +} + +// --------------------------------------------------------------------------- +// Token-based download auth +// --------------------------------------------------------------------------- + +export function authenticateDownload(req: Request): { userId: number } | { error: string; status: number } { + const cookieToken = (req as any).cookies?.trek_session as string | undefined; + const authHeader = req.headers['authorization']; + const bearerToken = authHeader ? (authHeader.split(' ')[1] || undefined) : undefined; + const queryToken = req.query.token as string | undefined; + + // Cookie and Bearer both carry a full JWT — try them first (cookie wins). + const jwtToken = cookieToken || bearerToken; + if (jwtToken) { + // Use the shared helper so the password_version gate applies here too; + // previously this bypassed the check and stolen download tokens stayed + // valid across a password reset. + const user = verifyJwtAndLoadUser(jwtToken); + if (!user) return { error: 'Invalid or expired token', status: 401 }; + return { userId: user.id }; + } + + if (queryToken) { + const uid = consumeEphemeralToken(queryToken, 'download'); + if (!uid) return { error: 'Invalid or expired token', status: 401 }; + return { userId: uid }; + } + + return { error: 'Authentication required', status: 401 }; +} + +// --------------------------------------------------------------------------- +// CRUD +// --------------------------------------------------------------------------- + +export interface FileLink { + file_id: number; + reservation_id: number | null; + place_id: number | null; +} + +export function getFileById(id: string | number, tripId: string | number): TripFile | undefined { + return db.prepare('SELECT * FROM trip_files WHERE id = ? AND trip_id = ?').get(id, tripId) as TripFile | undefined; +} + +export function getDeletedFile(id: string | number, tripId: string | number): TripFile | undefined { + return db.prepare('SELECT * FROM trip_files WHERE id = ? AND trip_id = ? AND deleted_at IS NOT NULL').get(id, tripId) as TripFile | undefined; +} + +export function listFiles(tripId: string | number, showTrash: boolean) { + const where = showTrash ? 'f.trip_id = ? AND f.deleted_at IS NOT NULL' : 'f.trip_id = ? AND f.deleted_at IS NULL'; + const files = db.prepare(`${FILE_SELECT} WHERE ${where} ORDER BY f.starred DESC, f.created_at DESC`).all(tripId) as TripFile[]; + + const fileIds = files.map(f => f.id); + let linksMap: Record = {}; + if (fileIds.length > 0) { + const placeholders = fileIds.map(() => '?').join(','); + const links = db.prepare(`SELECT file_id, reservation_id, place_id FROM file_links WHERE file_id IN (${placeholders})`).all(...fileIds) as FileLink[]; + for (const link of links) { + if (!linksMap[link.file_id]) linksMap[link.file_id] = []; + linksMap[link.file_id].push(link); + } + } + + return files.map(f => { + const fileLinks = linksMap[f.id] || []; + return { + ...formatFile(f), + linked_reservation_ids: fileLinks.filter(l => l.reservation_id).map(l => l.reservation_id), + linked_place_ids: fileLinks.filter(l => l.place_id).map(l => l.place_id), + }; + }); +} + +export function createFile( + tripId: string | number, + file: { filename: string; originalname: string; size: number; mimetype: string }, + uploadedBy: number, + opts: { place_id?: string | null; reservation_id?: string | null; description?: string | null } +) { + const result = db.prepare(` + INSERT INTO trip_files (trip_id, place_id, reservation_id, filename, original_name, file_size, mime_type, description, uploaded_by) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + `).run( + tripId, + opts.place_id || null, + opts.reservation_id || null, + file.filename, + file.originalname, + file.size, + file.mimetype, + opts.description || null, + uploadedBy + ); + + const created = db.prepare(`${FILE_SELECT} WHERE f.id = ?`).get(result.lastInsertRowid) as TripFile; + return formatFile(created); +} + +export function updateFile( + id: string | number, + current: TripFile, + updates: { description?: string; place_id?: string | null; reservation_id?: string | null } +) { + db.prepare(` + UPDATE trip_files SET + description = ?, + place_id = ?, + reservation_id = ? + WHERE id = ? + `).run( + updates.description !== undefined ? updates.description : current.description, + updates.place_id !== undefined ? (updates.place_id || null) : current.place_id, + updates.reservation_id !== undefined ? (updates.reservation_id || null) : current.reservation_id, + id + ); + + const updated = db.prepare(`${FILE_SELECT} WHERE f.id = ?`).get(id) as TripFile; + return formatFile(updated); +} + +export function toggleStarred(id: string | number, currentStarred: number | undefined) { + const newStarred = currentStarred ? 0 : 1; + db.prepare('UPDATE trip_files SET starred = ? WHERE id = ?').run(newStarred, id); + + const updated = db.prepare(`${FILE_SELECT} WHERE f.id = ?`).get(id) as TripFile; + return formatFile(updated); +} + +export function softDeleteFile(id: string | number) { + db.prepare('UPDATE trip_files SET deleted_at = CURRENT_TIMESTAMP WHERE id = ?').run(id); +} + +export function restoreFile(id: string | number) { + db.prepare('UPDATE trip_files SET deleted_at = NULL WHERE id = ?').run(id); + const restored = db.prepare(`${FILE_SELECT} WHERE f.id = ?`).get(id) as TripFile; + return formatFile(restored); +} + +export async function permanentDeleteFile(file: TripFile): Promise { + const { resolved } = resolveFilePath(file.filename); + // `force: true` swallows ENOENT, replacing the prior existsSync+unlink + // double-call that blocked the event loop twice per deletion. Only + // drop the DB row when the on-disk unlink either succeeded or the + // file was already gone — otherwise a permission / ENOSPC failure + // would orphan the bytes on disk with no DB pointer left to clean it. + try { + await fs.promises.rm(resolved, { force: true }); + } catch (e) { + console.error(`[files] unlink failed for ${file.filename}, keeping DB row:`, e); + throw e; + } + db.prepare('DELETE FROM trip_files WHERE id = ?').run(file.id); +} + +export async function emptyTrash(tripId: string | number): Promise { + const trashed = db.prepare('SELECT * FROM trip_files WHERE trip_id = ? AND deleted_at IS NOT NULL').all(tripId) as TripFile[]; + // Collect successful IDs separately so we only DELETE rows whose disk + // content was actually removed — failing unlinks keep their DB row + // and a retry via the single-file delete path can try again. + const successfullyUnlinked: number[] = []; + await Promise.all(trashed.map(async (file) => { + const { resolved } = resolveFilePath(file.filename); + try { + await fs.promises.rm(resolved, { force: true }); + successfullyUnlinked.push(Number(file.id)); + } catch (e) { + console.error(`[files] unlink failed for ${file.filename}, keeping DB row:`, e); + } + })); + if (successfullyUnlinked.length > 0) { + const placeholders = successfullyUnlinked.map(() => '?').join(','); + db.prepare(`DELETE FROM trip_files WHERE id IN (${placeholders})`).run(...successfullyUnlinked); + } + return successfullyUnlinked.length; +} + +// --------------------------------------------------------------------------- +// File links (many-to-many) +// --------------------------------------------------------------------------- + +export function createFileLink( + fileId: string | number, + opts: { reservation_id?: string | null; assignment_id?: string | null; place_id?: string | null } +) { + try { + db.prepare('INSERT OR IGNORE INTO file_links (file_id, reservation_id, assignment_id, place_id) VALUES (?, ?, ?, ?)').run( + fileId, opts.reservation_id || null, opts.assignment_id || null, opts.place_id || null + ); + } catch (err) { + console.error('[Files] Error creating file link:', err instanceof Error ? err.message : err); + } + return db.prepare('SELECT * FROM file_links WHERE file_id = ?').all(fileId); +} + +export function deleteFileLink(linkId: string | number, fileId: string | number) { + db.prepare('DELETE FROM file_links WHERE id = ? AND file_id = ?').run(linkId, fileId); +} + +export function getFileLinks(fileId: string | number) { + return db.prepare(` + SELECT fl.*, r.title as reservation_title + FROM file_links fl + LEFT JOIN reservations r ON fl.reservation_id = r.id + WHERE fl.file_id = ? + `).all(fileId); +} diff --git a/server/src/services/inAppNotificationActions.ts b/server/src/services/inAppNotificationActions.ts new file mode 100644 index 0000000000000000000000000000000000000000..991ad7832ec3a12125a590b7755f537d0ac11c16 --- /dev/null +++ b/server/src/services/inAppNotificationActions.ts @@ -0,0 +1,22 @@ +type ActionHandler = (payload: Record, respondingUserId: number) => Promise; + +const actionRegistry = new Map(); + +function registerAction(actionType: string, handler: ActionHandler): void { + actionRegistry.set(actionType, handler); +} + +function getAction(actionType: string): ActionHandler | undefined { + return actionRegistry.get(actionType); +} + +// Dev/test actions +registerAction('test_approve', async () => { + console.log('[notifications] Test approve action executed'); +}); + +registerAction('test_deny', async () => { + console.log('[notifications] Test deny action executed'); +}); + +export { registerAction, getAction }; diff --git a/server/src/services/inAppNotifications.ts b/server/src/services/inAppNotifications.ts new file mode 100644 index 0000000000000000000000000000000000000000..4dca62b93eec0351b650cb3a589e27838d2a2f97 --- /dev/null +++ b/server/src/services/inAppNotifications.ts @@ -0,0 +1,365 @@ +import { db } from '../db/database'; +import { broadcastToUser } from '../websocket'; +import { getAction } from './inAppNotificationActions'; +import { isEnabledForEvent, type NotifEventType } from './notificationPreferencesService'; + +// SQLite's CURRENT_TIMESTAMP is UTC but the string ('YYYY-MM-DD HH:MM:SS') has +// no 'T'/'Z', so `new Date(...)` parses it as LOCAL time. Normalize to ISO-UTC +// so the client renders notification times in the viewer's own timezone (#1149). +function toUtcIso(ts: string): string { + return ts.endsWith('Z') ? ts : ts.replace(' ', 'T') + 'Z'; +} + +type NotificationType = 'simple' | 'boolean' | 'navigate'; +type NotificationScope = 'trip' | 'user' | 'admin'; +type NotificationResponse = 'positive' | 'negative'; + +interface BaseNotificationInput { + type: NotificationType; + scope: NotificationScope; + target: number; + sender_id: number | null; + event_type?: NotifEventType; + title_key: string; + title_params?: Record; + text_key: string; + text_params?: Record; +} + +interface SimpleNotificationInput extends BaseNotificationInput { + type: 'simple'; +} + +interface BooleanNotificationInput extends BaseNotificationInput { + type: 'boolean'; + positive_text_key: string; + negative_text_key: string; + positive_callback: { action: string; payload: Record }; + negative_callback: { action: string; payload: Record }; +} + +interface NavigateNotificationInput extends BaseNotificationInput { + type: 'navigate'; + navigate_text_key: string; + navigate_target: string; +} + +type NotificationInput = SimpleNotificationInput | BooleanNotificationInput | NavigateNotificationInput; + +interface NotificationRow { + id: number; + type: NotificationType; + scope: NotificationScope; + target: number; + sender_id: number | null; + sender_username?: string | null; + sender_avatar?: string | null; + recipient_id: number; + title_key: string; + title_params: string; + text_key: string; + text_params: string; + positive_text_key: string | null; + negative_text_key: string | null; + positive_callback: string | null; + negative_callback: string | null; + response: NotificationResponse | null; + navigate_text_key: string | null; + navigate_target: string | null; + is_read: number; + created_at: string; +} + +export function resolveRecipients(scope: NotificationScope, target: number, excludeUserId?: number | null): number[] { + let userIds: number[] = []; + + if (scope === 'trip') { + const owner = db.prepare('SELECT user_id FROM trips WHERE id = ?').get(target) as { user_id: number } | undefined; + const members = db.prepare('SELECT user_id FROM trip_members WHERE trip_id = ?').all(target) as { user_id: number }[]; + const ids = new Set(); + if (owner) ids.add(owner.user_id); + for (const m of members) ids.add(m.user_id); + userIds = Array.from(ids); + } else if (scope === 'user') { + userIds = [target]; + } else if (scope === 'admin') { + const admins = db.prepare('SELECT id FROM users WHERE role = ?').all('admin') as { id: number }[]; + userIds = admins.map(a => a.id); + } + + // Only exclude sender for group scopes (trip/admin) — for user scope, the target is explicit + if (excludeUserId != null && scope !== 'user') { + userIds = userIds.filter(id => id !== excludeUserId); + } + + return userIds; +} + +function createNotification(input: NotificationInput): number[] { + const recipients = resolveRecipients(input.scope, input.target, input.sender_id); + if (recipients.length === 0) return []; + + const titleParams = JSON.stringify(input.title_params ?? {}); + const textParams = JSON.stringify(input.text_params ?? {}); + + // Track inserted id → recipientId pairs (some recipients may be skipped by pref check) + const insertedPairs: Array<{ id: number; recipientId: number }> = []; + + const insert = db.transaction(() => { + const stmt = db.prepare(` + INSERT INTO notifications ( + type, scope, target, sender_id, recipient_id, + title_key, title_params, text_key, text_params, + positive_text_key, negative_text_key, positive_callback, negative_callback, + navigate_text_key, navigate_target + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `); + + for (const recipientId of recipients) { + // Check per-user in-app preference if an event_type is provided + if (input.event_type && !isEnabledForEvent(recipientId, input.event_type, 'inapp')) { + continue; + } + + let positiveTextKey: string | null = null; + let negativeTextKey: string | null = null; + let positiveCallback: string | null = null; + let negativeCallback: string | null = null; + let navigateTextKey: string | null = null; + let navigateTarget: string | null = null; + + if (input.type === 'boolean') { + positiveTextKey = input.positive_text_key; + negativeTextKey = input.negative_text_key; + positiveCallback = JSON.stringify(input.positive_callback); + negativeCallback = JSON.stringify(input.negative_callback); + } else if (input.type === 'navigate') { + navigateTextKey = input.navigate_text_key; + navigateTarget = input.navigate_target; + } + + const result = stmt.run( + input.type, input.scope, input.target, input.sender_id, recipientId, + input.title_key, titleParams, input.text_key, textParams, + positiveTextKey, negativeTextKey, positiveCallback, negativeCallback, + navigateTextKey, navigateTarget + ); + + insertedPairs.push({ id: result.lastInsertRowid as number, recipientId }); + } + }); + + insert(); + + // Fetch sender info once for WS payloads + const sender = input.sender_id + ? (db.prepare('SELECT username, avatar FROM users WHERE id = ?').get(input.sender_id) as { username: string; avatar: string | null } | undefined) + : null; + + // Broadcast to each recipient + for (const { id: notificationId, recipientId } of insertedPairs) { + const row = db.prepare('SELECT * FROM notifications WHERE id = ?').get(notificationId) as NotificationRow; + if (!row) continue; + + broadcastToUser(recipientId, { + type: 'notification:new', + notification: { + ...row, + sender_username: sender?.username ?? null, + sender_avatar: sender?.avatar ? `/uploads/avatars/${sender.avatar}` : null, + }, + }); + } + + return insertedPairs.map(p => p.id); +} + +/** + * Insert a single in-app notification for one pre-resolved recipient and broadcast via WebSocket. + * Used by notificationService.send() which handles recipient resolution externally. + */ +export function createNotificationForRecipient( + input: NotificationInput, + recipientId: number, + sender: { username: string; avatar: string | null } | null +): number | null { + const titleParams = JSON.stringify(input.title_params ?? {}); + const textParams = JSON.stringify(input.text_params ?? {}); + + let positiveTextKey: string | null = null; + let negativeTextKey: string | null = null; + let positiveCallback: string | null = null; + let negativeCallback: string | null = null; + let navigateTextKey: string | null = null; + let navigateTarget: string | null = null; + + if (input.type === 'boolean') { + positiveTextKey = input.positive_text_key; + negativeTextKey = input.negative_text_key; + positiveCallback = JSON.stringify(input.positive_callback); + negativeCallback = JSON.stringify(input.negative_callback); + } else if (input.type === 'navigate') { + navigateTextKey = input.navigate_text_key; + navigateTarget = input.navigate_target; + } + + const result = db.prepare(` + INSERT INTO notifications ( + type, scope, target, sender_id, recipient_id, + title_key, title_params, text_key, text_params, + positive_text_key, negative_text_key, positive_callback, negative_callback, + navigate_text_key, navigate_target + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `).run( + input.type, input.scope, input.target, input.sender_id, recipientId, + input.title_key, titleParams, input.text_key, textParams, + positiveTextKey, negativeTextKey, positiveCallback, negativeCallback, + navigateTextKey, navigateTarget + ); + + const notificationId = result.lastInsertRowid as number; + const row = db.prepare('SELECT * FROM notifications WHERE id = ?').get(notificationId) as NotificationRow | undefined; + if (!row) return null; + + broadcastToUser(recipientId, { + type: 'notification:new', + notification: { + ...row, + created_at: toUtcIso(row.created_at), + sender_username: sender?.username ?? null, + sender_avatar: sender?.avatar ? `/uploads/avatars/${sender.avatar}` : null, + }, + }); + + return notificationId; +} + +function getNotifications( + userId: number, + options: { limit?: number; offset?: number; unreadOnly?: boolean } = {} +): { notifications: NotificationRow[]; total: number; unread_count: number } { + const limit = Math.min(options.limit ?? 20, 50); + const offset = options.offset ?? 0; + const unreadOnly = options.unreadOnly ?? false; + + const whereAliased = unreadOnly ? 'WHERE n.recipient_id = ? AND n.is_read = 0' : 'WHERE n.recipient_id = ?'; + const wherePlain = unreadOnly ? 'WHERE recipient_id = ? AND is_read = 0' : 'WHERE recipient_id = ?'; + + const rows = db.prepare(` + SELECT n.*, u.username AS sender_username, u.avatar AS sender_avatar + FROM notifications n + LEFT JOIN users u ON n.sender_id = u.id + ${whereAliased} + ORDER BY n.created_at DESC + LIMIT ? OFFSET ? + `).all(userId, limit, offset) as NotificationRow[]; + + const { total } = db.prepare(`SELECT COUNT(*) as total FROM notifications ${wherePlain}`).get(userId) as { total: number }; + const { unread_count } = db.prepare('SELECT COUNT(*) as unread_count FROM notifications WHERE recipient_id = ? AND is_read = 0').get(userId) as { unread_count: number }; + + const mapped = rows.map(r => ({ + ...r, + created_at: toUtcIso(r.created_at), + sender_avatar: r.sender_avatar ? `/uploads/avatars/${r.sender_avatar}` : null, + })); + + return { notifications: mapped, total, unread_count }; +} + +function getUnreadCount(userId: number): number { + const row = db.prepare('SELECT COUNT(*) as count FROM notifications WHERE recipient_id = ? AND is_read = 0').get(userId) as { count: number }; + return row.count; +} + +function markRead(notificationId: number, userId: number): boolean { + const result = db.prepare('UPDATE notifications SET is_read = 1 WHERE id = ? AND recipient_id = ?').run(notificationId, userId); + return result.changes > 0; +} + +function markUnread(notificationId: number, userId: number): boolean { + const result = db.prepare('UPDATE notifications SET is_read = 0 WHERE id = ? AND recipient_id = ?').run(notificationId, userId); + return result.changes > 0; +} + +function markAllRead(userId: number): number { + const result = db.prepare('UPDATE notifications SET is_read = 1 WHERE recipient_id = ? AND is_read = 0').run(userId); + return result.changes; +} + +function deleteNotification(notificationId: number, userId: number): boolean { + const result = db.prepare('DELETE FROM notifications WHERE id = ? AND recipient_id = ?').run(notificationId, userId); + return result.changes > 0; +} + +function deleteAll(userId: number): number { + const result = db.prepare('DELETE FROM notifications WHERE recipient_id = ?').run(userId); + return result.changes; +} + +async function respondToBoolean( + notificationId: number, + userId: number, + response: NotificationResponse +): Promise<{ success: boolean; error?: string; notification?: NotificationRow }> { + const notification = db.prepare('SELECT * FROM notifications WHERE id = ? AND recipient_id = ?').get(notificationId, userId) as NotificationRow | undefined; + + if (!notification) return { success: false, error: 'Notification not found' }; + if (notification.type !== 'boolean') return { success: false, error: 'Not a boolean notification' }; + if (notification.response !== null) return { success: false, error: 'Already responded' }; + + const callbackJson = response === 'positive' ? notification.positive_callback : notification.negative_callback; + if (!callbackJson) return { success: false, error: 'No callback defined' }; + + let callback: { action: string; payload: Record }; + try { + callback = JSON.parse(callbackJson); + } catch { + return { success: false, error: 'Invalid callback format' }; + } + + const handler = getAction(callback.action); + if (!handler) return { success: false, error: `Unknown action: ${callback.action}` }; + + try { + await handler(callback.payload, userId); + } catch (err) { + return { success: false, error: err instanceof Error ? err.message : 'Action failed' }; + } + + // Atomic update — only updates if response is still NULL (prevents double-response) + const result = db.prepare( + 'UPDATE notifications SET response = ?, is_read = 1 WHERE id = ? AND recipient_id = ? AND response IS NULL' + ).run(response, notificationId, userId); + + if (result.changes === 0) return { success: false, error: 'Already responded' }; + + const updated = db.prepare(` + SELECT n.*, u.username AS sender_username, u.avatar AS sender_avatar + FROM notifications n + LEFT JOIN users u ON n.sender_id = u.id + WHERE n.id = ? + `).get(notificationId) as NotificationRow; + + const mappedUpdated = { + ...updated, + sender_avatar: updated.sender_avatar ? `/uploads/avatars/${updated.sender_avatar}` : null, + }; + + broadcastToUser(userId, { type: 'notification:updated', notification: mappedUpdated }); + + return { success: true, notification: mappedUpdated }; +} + +export { + createNotification, + getNotifications, + getUnreadCount, + markRead, + markUnread, + markAllRead, + deleteNotification, + deleteAll, + respondToBoolean, +}; + +export type { NotificationInput, NotificationRow, NotificationType, NotificationScope, NotificationResponse }; diff --git a/server/src/services/journeyService.ts b/server/src/services/journeyService.ts new file mode 100644 index 0000000000000000000000000000000000000000..3bc9b73c43e431aacaa9355829a55b05113d8a22 --- /dev/null +++ b/server/src/services/journeyService.ts @@ -0,0 +1,1143 @@ +import { db, canAccessTrip } from '../db/database'; +import type { Journey, JourneyEntry, JourneyPhoto, JourneyContributor } from '../types'; +import { broadcastToUser } from '../websocket'; +import { + getOrCreateTrekPhoto, + getOrCreateLocalTrekPhoto, + setTrekPhotoProvider, + deleteTrekPhotoIfOrphan, +} from './memories/photoResolverService'; + +function ts(): number { + return Date.now(); +} + +// Per-entry photo view: join journey_entry_photos → journey_photos (gallery) → trek_photos. +// id = gp.id (gallery photo id) — used by clients for linkPhoto/updatePhoto/unlink/delete. +const JP_SELECT = ` + gp.id, jep.entry_id, gp.photo_id, gp.caption, jep.sort_order, gp.shared, gp.created_at, + tp.provider, tp.asset_id, tp.owner_id, tp.file_path, tp.thumbnail_path, tp.width, tp.height +`; +const JP_JOIN = `journey_entry_photos jep + JOIN journey_photos gp ON gp.id = jep.journey_photo_id + JOIN trek_photos tp ON tp.id = gp.photo_id`; + +// Per-journey gallery view: journey_photos → trek_photos (no entry context). +const GALLERY_SELECT = ` + gp.id, gp.journey_id, gp.photo_id, gp.caption, gp.shared, gp.sort_order, gp.created_at, + tp.provider, tp.asset_id, tp.owner_id, tp.file_path, tp.thumbnail_path, tp.width, tp.height +`; +const GALLERY_JOIN = 'journey_photos gp JOIN trek_photos tp ON tp.id = gp.photo_id'; + +function broadcastJourneyEvent( + journeyId: number, + event: string, + data: Record, + excludeSocketId?: string | number, +) { + const contributors = db.prepare('SELECT user_id FROM journey_contributors WHERE journey_id = ?').all(journeyId) as { + user_id: number; + }[]; + const owner = db.prepare('SELECT user_id FROM journeys WHERE id = ?').get(journeyId) as + | { user_id: number } + | undefined; + + const userIds = new Set(contributors.map((c) => c.user_id)); + if (owner) userIds.add(owner.user_id); + + for (const uid of userIds) { + broadcastToUser(uid, { type: event, journeyId, ...data }, excludeSocketId); + } +} + +// ── Access control ─────────────────────────────────────────────────────── + +export function canAccessJourney(journeyId: number, userId: number): Journey | null { + const own = db.prepare('SELECT * FROM journeys WHERE id = ? AND user_id = ?').get(journeyId, userId) as + | Journey + | undefined; + if (own) return own; + const contrib = db + .prepare('SELECT 1 FROM journey_contributors WHERE journey_id = ? AND user_id = ?') + .get(journeyId, userId); + if (contrib) return (db.prepare('SELECT * FROM journeys WHERE id = ?').get(journeyId) as Journey) || null; + return null; +} + +export function isOwner(journeyId: number, userId: number): boolean { + return !!db.prepare('SELECT 1 FROM journeys WHERE id = ? AND user_id = ?').get(journeyId, userId); +} + +export function canEdit(journeyId: number, userId: number): boolean { + if (isOwner(journeyId, userId)) return true; + const c = db + .prepare('SELECT role FROM journey_contributors WHERE journey_id = ? AND user_id = ?') + .get(journeyId, userId) as { role: string } | undefined; + return c?.role === 'editor' || c?.role === 'owner'; +} + +// ── Journey CRUD ───────────────────────────────────────────────────────── + +export function listJourneys(userId: number) { + return db + .prepare( + ` + SELECT DISTINCT j.*, + (SELECT COUNT(*) FROM journey_entries je WHERE je.journey_id = j.id AND je.type != 'skeleton') as entry_count, + (SELECT COUNT(*) FROM journey_photos jp WHERE jp.journey_id = j.id) as photo_count, + (SELECT COUNT(DISTINCT je3.location_name) FROM journey_entries je3 WHERE je3.journey_id = j.id AND je3.location_name IS NOT NULL AND je3.location_name != '') as place_count, + (SELECT MIN(t.start_date) FROM journey_trips jt JOIN trips t ON jt.trip_id = t.id WHERE jt.journey_id = j.id) as trip_date_min, + (SELECT MAX(t.end_date) FROM journey_trips jt JOIN trips t ON jt.trip_id = t.id WHERE jt.journey_id = j.id) as trip_date_max + FROM journeys j + LEFT JOIN journey_contributors jc ON j.id = jc.journey_id AND jc.user_id = ? + WHERE j.user_id = ? OR jc.user_id = ? + ORDER BY j.updated_at DESC + `, + ) + .all(userId, userId, userId) as (Journey & { + entry_count: number; + photo_count: number; + place_count: number; + trip_date_min: string | null; + trip_date_max: string | null; + })[]; +} + +export function createJourney( + userId: number, + data: { + title: string; + subtitle?: string; + trip_ids?: number[]; + }, +): Journey { + const now = ts(); + const res = db + .prepare( + ` + INSERT INTO journeys (user_id, title, subtitle, status, created_at, updated_at) + VALUES (?, ?, ?, 'active', ?, ?) + `, + ) + .run(userId, data.title, data.subtitle || null, now, now); + + const journeyId = Number(res.lastInsertRowid); + + // add owner as contributor + db.prepare('INSERT INTO journey_contributors (journey_id, user_id, role, added_at) VALUES (?, ?, ?, ?)').run( + journeyId, + userId, + 'owner', + now, + ); + + // link trips and sync skeleton entries + if (data.trip_ids?.length) { + for (const tripId of data.trip_ids) { + addTripToJourney(journeyId, tripId, userId); + } + + // inherit cover image from first selected trip + const firstTrip = db.prepare('SELECT cover_image FROM trips WHERE id = ?').get(data.trip_ids[0]) as + | { cover_image: string | null } + | undefined; + if (firstTrip?.cover_image) { + // trip stores full path (/uploads/covers/x.jpg), journey stores relative (covers/x.jpg) + const relativePath = firstTrip.cover_image.replace(/^\/uploads\//, ''); + db.prepare('UPDATE journeys SET cover_image = ? WHERE id = ?').run(relativePath, journeyId); + } + } + + return db.prepare('SELECT * FROM journeys WHERE id = ?').get(journeyId) as Journey; +} + +export function getJourneyFull(journeyId: number, userId: number) { + const journey = canAccessJourney(journeyId, userId); + if (!journey) return null; + + const entries = db + .prepare('SELECT * FROM journey_entries WHERE journey_id = ? ORDER BY entry_date ASC, sort_order ASC, id ASC') + .all(journeyId) as JourneyEntry[]; + + const photos = db + .prepare( + `SELECT ${JP_SELECT} FROM ${JP_JOIN} WHERE jep.entry_id IN (SELECT id FROM journey_entries WHERE journey_id = ?) ORDER BY jep.sort_order ASC`, + ) + .all(journeyId) as JourneyPhoto[]; + + // group photos by entry + const photosByEntry: Record = {}; + for (const p of photos) { + (photosByEntry[p.entry_id] ||= []).push(p); + } + + const gallery = db + .prepare( + `SELECT ${GALLERY_SELECT} FROM ${GALLERY_JOIN} WHERE gp.journey_id = ? ORDER BY gp.sort_order ASC, gp.id ASC`, + ) + .all(journeyId); + + const enrichedEntries = entries.map((e) => ({ + ...e, + tags: e.tags ? JSON.parse(e.tags) : [], + pros_cons: e.pros_cons ? JSON.parse(e.pros_cons) : null, + photos: photosByEntry[e.id] || [], + source_trip_name: e.source_trip_id + ? (db.prepare('SELECT title FROM trips WHERE id = ?').get(e.source_trip_id) as { title: string } | undefined) + ?.title || null + : null, + })); + + // linked trips + const trips = db + .prepare( + ` + SELECT jt.trip_id, jt.added_at, t.title, t.start_date, t.end_date, t.cover_image, t.currency, + (SELECT COUNT(*) FROM places WHERE trip_id = t.id) as place_count + FROM journey_trips jt JOIN trips t ON jt.trip_id = t.id + WHERE jt.journey_id = ? ORDER BY t.start_date ASC + `, + ) + .all(journeyId); + + // contributors + const contributorsRaw = db + .prepare( + ` + SELECT jc.journey_id, jc.user_id, jc.role, jc.added_at, u.username, u.avatar + FROM journey_contributors jc JOIN users u ON jc.user_id = u.id + WHERE jc.journey_id = ? ORDER BY jc.added_at + `, + ) + .all(journeyId) as any[]; + const contributors = contributorsRaw.map((c) => ({ + ...c, + avatar_url: c.avatar ? `/uploads/avatars/${c.avatar}` : null, + })); + + // stats + const entryCount = entries.filter((e) => e.type === 'entry').length; + const photoCount = (gallery as any[]).length; + const places = [...new Set(entries.map((e) => e.location_name).filter(Boolean))]; + + const userPrefs = db + .prepare('SELECT hide_skeletons FROM journey_contributors WHERE journey_id = ? AND user_id = ?') + .get(journeyId, userId) as { hide_skeletons: number } | undefined; + + // Determine the viewer's role on this journey so the UI can gate edit/settings + // actions. 'owner' = creator, 'editor' | 'viewer' = from journey_contributors. + const journeyRow = journey as unknown as { user_id?: number }; + let myRole: 'owner' | 'editor' | 'viewer' | null; + if (journeyRow.user_id === userId) { + myRole = 'owner'; + } else { + const contribRow = db + .prepare('SELECT role FROM journey_contributors WHERE journey_id = ? AND user_id = ?') + .get(journeyId, userId) as { role: 'editor' | 'viewer' } | undefined; + myRole = contribRow?.role ?? null; + } + + return { + ...journey, + entries: enrichedEntries, + gallery, + trips, + contributors, + stats: { entries: entryCount, photos: photoCount, places: places.length }, + hide_skeletons: !!userPrefs?.hide_skeletons, + my_role: myRole, + }; +} + +export function updateJourney( + journeyId: number, + userId: number, + data: Partial<{ + title: string; + subtitle: string; + cover_gradient: string; + cover_image: string; + status: string; + }>, +): Journey | null { + // Journey-level settings (title, cover, status) are owner-only — editors + // may only edit entries and photos, not reshape the journey itself. + if (!isOwner(journeyId, userId)) return null; + + const ALLOWED_STATUSES = ['draft', 'active', 'completed', 'archived']; + const allowed = ['title', 'subtitle', 'cover_gradient', 'cover_image', 'status']; + const fields: string[] = []; + const values: unknown[] = []; + for (const [key, val] of Object.entries(data)) { + if (val !== undefined && allowed.includes(key)) { + if (key === 'status' && !ALLOWED_STATUSES.includes(val as string)) continue; + fields.push(`${key} = ?`); + values.push(val); + } + } + if (fields.length === 0) return db.prepare('SELECT * FROM journeys WHERE id = ?').get(journeyId) as Journey; + + fields.push('updated_at = ?'); + values.push(ts()); + values.push(journeyId); + db.prepare(`UPDATE journeys SET ${fields.join(', ')} WHERE id = ?`).run(...values); + return db.prepare('SELECT * FROM journeys WHERE id = ?').get(journeyId) as Journey; +} + +export function updateJourneyPreferences(journeyId: number, userId: number, data: { hide_skeletons?: boolean }) { + if (!canAccessJourney(journeyId, userId)) return null; + if (data.hide_skeletons !== undefined) { + db.prepare('UPDATE journey_contributors SET hide_skeletons = ? WHERE journey_id = ? AND user_id = ?').run( + data.hide_skeletons ? 1 : 0, + journeyId, + userId, + ); + } + const row = db + .prepare('SELECT hide_skeletons FROM journey_contributors WHERE journey_id = ? AND user_id = ?') + .get(journeyId, userId) as { hide_skeletons: number }; + return { hide_skeletons: !!row.hide_skeletons }; +} + +export function deleteJourney(journeyId: number, userId: number): boolean { + if (!isOwner(journeyId, userId)) return false; + db.prepare('DELETE FROM journeys WHERE id = ?').run(journeyId); + return true; +} + +// ── Trip management ────────────────────────────────────────────────────── + +export function addTripToJourney(journeyId: number, tripId: number, userId: number): boolean { + // Only attach a trip the caller can actually access — otherwise a journey + // owner could pull an arbitrary trip's places + photos into their journey + // (cross-tenant leak). Mirrors the trip-access gate every other trip-scoped + // path enforces. + if (!canAccessTrip(tripId, userId)) return false; + const now = ts(); + try { + db.prepare('INSERT OR IGNORE INTO journey_trips (journey_id, trip_id, added_at) VALUES (?, ?, ?)').run( + journeyId, + tripId, + now, + ); + } catch { + return false; + } + + // sync skeleton entries for all places in this trip + syncTripPlaces(journeyId, tripId, userId); + // import existing trip photos (Immich/Synology) with sharing settings + syncTripPhotos(journeyId, tripId); + broadcastJourneyEvent(journeyId, 'journey:trip:synced', { tripId }); + return true; +} + +export function removeTripFromJourney(journeyId: number, tripId: number, userId: number): boolean { + if (!isOwner(journeyId, userId)) return false; + + // remove skeleton entries that haven't been filled in + db.prepare( + ` + DELETE FROM journey_entries + WHERE journey_id = ? AND source_trip_id = ? AND type = 'skeleton' + `, + ).run(journeyId, tripId); + + // detach filled entries from this trip + db.prepare( + ` + UPDATE journey_entries SET source_trip_id = NULL, source_place_id = NULL + WHERE journey_id = ? AND source_trip_id = ? AND type != 'skeleton' + `, + ).run(journeyId, tripId); + + db.prepare('DELETE FROM journey_trips WHERE journey_id = ? AND trip_id = ?').run(journeyId, tripId); + return true; +} + +// ── Sync engine ────────────────────────────────────────────────────────── + +export function syncTripPlaces(journeyId: number, tripId: number, authorId: number) { + const places = db + .prepare( + ` + SELECT p.*, da.day_id, d.date as day_date, da.assignment_time, da.assignment_end_time, d.day_number + FROM places p + INNER JOIN day_assignments da ON da.place_id = p.id + INNER JOIN days d ON da.day_id = d.id + WHERE p.trip_id = ? + ORDER BY d.day_number ASC, da.order_index ASC + `, + ) + .all(tripId) as any[]; + + const now = ts(); + const existing = db + .prepare('SELECT source_place_id FROM journey_entries WHERE journey_id = ? AND source_trip_id = ?') + .all(journeyId, tripId) as { source_place_id: number }[]; + const existingPlaceIds = new Set(existing.map((e) => e.source_place_id)); + + // Track next sort_order per date so synced skeletons get unique, sequential positions. + const dateMaxOrder = new Map(); + const maxRows = db + .prepare( + 'SELECT entry_date, COALESCE(MAX(sort_order), -1) AS m FROM journey_entries WHERE journey_id = ? GROUP BY entry_date', + ) + .all(journeyId) as { entry_date: string; m: number }[]; + for (const row of maxRows) dateMaxOrder.set(row.entry_date, row.m); + + for (const place of places) { + if (existingPlaceIds.has(place.id)) continue; + existingPlaceIds.add(place.id); + + const entryDate = place.day_date || new Date().toISOString().split('T')[0]; + const entryTime = place.assignment_time || place.place_time || null; + const nextOrder = (dateMaxOrder.get(entryDate) ?? -1) + 1; + dateMaxOrder.set(entryDate, nextOrder); + + db.prepare( + ` + INSERT INTO journey_entries (journey_id, source_trip_id, source_place_id, author_id, type, title, entry_date, entry_time, location_name, location_lat, location_lng, sort_order, created_at, updated_at) + VALUES (?, ?, ?, ?, 'skeleton', ?, ?, ?, ?, ?, ?, ?, ?, ?) + `, + ).run( + journeyId, + tripId, + place.id, + authorId, + place.name, + entryDate, + entryTime, + place.address || place.name, + place.lat || null, + place.lng || null, + nextOrder, + now, + now, + ); + } +} + +// import trip_photos into journey gallery when a trip is linked +function syncTripPhotos(journeyId: number, tripId: number) { + const tripPhotos = db + .prepare('SELECT tp.photo_id, tp.shared FROM trip_photos tp WHERE tp.trip_id = ?') + .all(tripId) as { photo_id: number; shared: number }[]; + if (!tripPhotos.length) return; + + const now = ts(); + const maxOrderRow = db + .prepare('SELECT MAX(sort_order) as m FROM journey_photos WHERE journey_id = ?') + .get(journeyId) as { m: number | null }; + let nextOrder = (maxOrderRow?.m ?? -1) + 1; + + for (const tp of tripPhotos) { + db.prepare( + ` + INSERT OR IGNORE INTO journey_photos (journey_id, photo_id, shared, sort_order, created_at) + VALUES (?, ?, ?, ?, ?) + `, + ).run(journeyId, tp.photo_id, tp.shared, nextOrder++, now); + } +} + +// called when a trip place is created +export function onPlaceCreated(tripId: number, placeId: number) { + const links = db.prepare('SELECT journey_id FROM journey_trips WHERE trip_id = ?').all(tripId) as { + journey_id: number; + }[]; + if (!links.length) return; + + const place = db + .prepare( + ` + SELECT p.*, da.day_id, d.date as day_date, da.assignment_time, d.day_number + FROM places p + INNER JOIN day_assignments da ON da.place_id = p.id + INNER JOIN days d ON da.day_id = d.id + WHERE p.id = ? + `, + ) + .get(placeId) as any; + if (!place) return; // not assigned to a day yet — skip + + const now = ts(); + for (const link of links) { + const already = db + .prepare('SELECT 1 FROM journey_entries WHERE journey_id = ? AND source_place_id = ?') + .get(link.journey_id, placeId); + if (already) continue; + + const journey = db.prepare('SELECT user_id FROM journeys WHERE id = ?').get(link.journey_id) as { user_id: number }; + const entryDate = place.day_date; + const maxOrder = db + .prepare('SELECT MAX(sort_order) AS m FROM journey_entries WHERE journey_id = ? AND entry_date = ?') + .get(link.journey_id, entryDate) as { m: number | null }; + const nextOrder = (maxOrder?.m ?? -1) + 1; + + db.prepare( + ` + INSERT INTO journey_entries (journey_id, source_trip_id, source_place_id, author_id, type, title, entry_date, entry_time, location_name, location_lat, location_lng, sort_order, created_at, updated_at) + VALUES (?, ?, ?, ?, 'skeleton', ?, ?, ?, ?, ?, ?, ?, ?, ?) + `, + ).run( + link.journey_id, + tripId, + placeId, + journey.user_id, + place.name, + entryDate, + place.assignment_time || place.place_time || null, + place.address || place.name, + place.lat || null, + place.lng || null, + nextOrder, + now, + now, + ); + } +} + +// called when a trip place is updated +export function onPlaceUpdated(placeId: number) { + const entries = db.prepare('SELECT * FROM journey_entries WHERE source_place_id = ?').all(placeId) as JourneyEntry[]; + if (!entries.length) return; + + const place = db + .prepare( + ` + SELECT p.*, da.day_id, d.date as day_date, da.assignment_time, d.day_number + FROM places p + LEFT JOIN day_assignments da ON da.place_id = p.id + LEFT JOIN days d ON da.day_id = d.id + WHERE p.id = ? + `, + ) + .get(placeId) as any; + if (!place) return; + + const now = ts(); + for (const entry of entries) { + if (entry.type === 'skeleton') { + // update everything on skeletons + db.prepare( + ` + UPDATE journey_entries SET title = ?, entry_date = ?, entry_time = ?, location_name = ?, location_lat = ?, location_lng = ?, updated_at = ? + WHERE id = ? + `, + ).run( + place.name, + place.day_date || entry.entry_date, + place.assignment_time || place.place_time || entry.entry_time, + place.address || place.name, + place.lat || null, + place.lng || null, + now, + entry.id, + ); + } else { + // for filled entries, only update location silently + db.prepare( + ` + UPDATE journey_entries SET location_name = ?, location_lat = ?, location_lng = ?, updated_at = ? + WHERE id = ? + `, + ).run(place.address || place.name, place.lat || null, place.lng || null, now, entry.id); + } + } +} + +// called when a trip place is deleted +export function onPlaceDeleted(placeId: number) { + const entries = db.prepare('SELECT * FROM journey_entries WHERE source_place_id = ?').all(placeId) as JourneyEntry[]; + + for (const entry of entries) { + if (entry.type === 'skeleton') { + // no content: just delete + const hasPhotos = db.prepare('SELECT 1 FROM journey_entry_photos WHERE entry_id = ?').get(entry.id); + if (!hasPhotos && !entry.story) { + db.prepare('DELETE FROM journey_entries WHERE id = ?').run(entry.id); + continue; + } + } + // entry has content: keep it, detach, add note + const note = '\n\n> _Note: the original trip place was removed from the trip plan_'; + const newStory = (entry.story || '') + note; + db.prepare( + 'UPDATE journey_entries SET source_place_id = NULL, source_trip_id = NULL, type = ?, story = ?, updated_at = ? WHERE id = ?', + ).run(entry.type === 'skeleton' ? 'entry' : entry.type, newStory, ts(), entry.id); + } +} + +// ── Entries ────────────────────────────────────────────────────────────── + +export function listEntries(journeyId: number, userId: number) { + if (!canAccessJourney(journeyId, userId)) return null; + + const entries = db + .prepare('SELECT * FROM journey_entries WHERE journey_id = ? ORDER BY entry_date ASC, sort_order ASC, id ASC') + .all(journeyId) as JourneyEntry[]; + + const photos = db + .prepare( + `SELECT ${JP_SELECT} FROM ${JP_JOIN} WHERE jep.entry_id IN (SELECT id FROM journey_entries WHERE journey_id = ?) ORDER BY jep.sort_order ASC`, + ) + .all(journeyId) as JourneyPhoto[]; + + const photosByEntry: Record = {}; + for (const p of photos) { + (photosByEntry[p.entry_id] ||= []).push(p); + } + + return entries.map((e) => ({ + ...e, + tags: e.tags ? JSON.parse(e.tags) : [], + pros_cons: e.pros_cons ? JSON.parse(e.pros_cons) : null, + photos: photosByEntry[e.id] || [], + source_trip_name: e.source_trip_id + ? (db.prepare('SELECT title FROM trips WHERE id = ?').get(e.source_trip_id) as { title: string } | undefined) + ?.title || null + : null, + })); +} + +export function createEntry( + journeyId: number, + userId: number, + data: { + type?: string; + title?: string; + story?: string; + entry_date: string; + entry_time?: string; + location_name?: string; + location_lat?: number; + location_lng?: number; + mood?: string; + weather?: string; + tags?: string[]; + pros_cons?: { pros: string[]; cons: string[] }; + visibility?: string; + sort_order?: number; + }, + sid?: string, +): JourneyEntry | null { + if (!canEdit(journeyId, userId)) return null; + + const now = ts(); + const maxOrder = db + .prepare('SELECT MAX(sort_order) as m FROM journey_entries WHERE journey_id = ? AND entry_date = ?') + .get(journeyId, data.entry_date) as { m: number | null }; + + const prosConsJson = + data.pros_cons && (data.pros_cons.pros.length || data.pros_cons.cons.length) + ? JSON.stringify(data.pros_cons) + : null; + + 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, tags, pros_cons, visibility, sort_order, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `, + ) + .run( + journeyId, + userId, + data.type || 'entry', + data.title || null, + data.story || null, + data.entry_date, + data.entry_time || null, + data.location_name || null, + data.location_lat ?? null, + data.location_lng ?? null, + data.mood || null, + data.weather || null, + data.tags?.length ? JSON.stringify(data.tags) : null, + prosConsJson, + data.visibility || 'private', + (maxOrder?.m ?? -1) + 1, + now, + now, + ); + + const created = db + .prepare('SELECT * FROM journey_entries WHERE id = ?') + .get(Number(res.lastInsertRowid)) as JourneyEntry; + broadcastJourneyEvent(journeyId, 'journey:entry:created', { entry: created }, sid); + return created; +} + +export function updateEntry( + entryId: number, + userId: number, + data: Partial<{ + type: string; + title: string; + story: string; + entry_date: string; + entry_time: string; + location_name: string; + location_lat: number; + location_lng: number; + mood: string; + weather: string; + tags: string[]; + pros_cons: { pros: string[]; cons: string[] }; + visibility: string; + sort_order: number; + }>, + sid?: string, +): JourneyEntry | null { + const entry = db.prepare('SELECT * FROM journey_entries WHERE id = ?').get(entryId) as JourneyEntry | undefined; + if (!entry) return null; + if (!canEdit(entry.journey_id, userId)) return null; + + const fields: string[] = []; + const values: unknown[] = []; + + // Allow-list the columns a client may set: keys come from the request body + // and are interpolated as SQL column names, so restrict them to the known + // entry fields. Keep this in sync with the data type above. + const allowed = new Set([ + 'type', + 'title', + 'story', + 'entry_date', + 'entry_time', + 'location_name', + 'location_lat', + 'location_lng', + 'mood', + 'weather', + 'tags', + 'pros_cons', + 'visibility', + 'sort_order', + ]); + + for (const [key, val] of Object.entries(data)) { + if (val === undefined) continue; + if (!allowed.has(key)) continue; + if (key === 'tags') { + fields.push('tags = ?'); + values.push(Array.isArray(val) ? JSON.stringify(val) : val); + } else if (key === 'pros_cons') { + fields.push('pros_cons = ?'); + values.push(val && typeof val === 'object' ? JSON.stringify(val) : val); + } else { + fields.push(`${key} = ?`); + values.push(val); + } + } + + // if adding story to a skeleton, promote to entry + if (entry.type === 'skeleton' && data.story && data.story.trim()) { + fields.push('type = ?'); + values.push('entry'); + } + + if (fields.length === 0) return entry; + + fields.push('updated_at = ?'); + values.push(ts()); + values.push(entryId); + db.prepare(`UPDATE journey_entries SET ${fields.join(', ')} WHERE id = ?`).run(...values); + + // touch the journey + db.prepare('UPDATE journeys SET updated_at = ? WHERE id = ?').run(ts(), entry.journey_id); + + const updated = db.prepare('SELECT * FROM journey_entries WHERE id = ?').get(entryId) as JourneyEntry; + broadcastJourneyEvent(entry.journey_id, 'journey:entry:updated', { entry: updated }, sid); + return updated; +} + +// Reorder entries (typically within a single day). Caller passes the new +// desired order of ids; each entry's sort_order is set to its index in the +// array. Only entries owned by this journey are accepted. +export function reorderEntries(journeyId: number, userId: number, orderedIds: number[], sid?: string): boolean { + if (!canEdit(journeyId, userId)) return false; + if (!orderedIds.length) return true; + + const placeholders = orderedIds.map(() => '?').join(','); + const rows = db + .prepare(`SELECT id FROM journey_entries WHERE id IN (${placeholders}) AND journey_id = ?`) + .all(...orderedIds, journeyId) as { id: number }[]; + if (rows.length !== orderedIds.length) return false; + + const now = ts(); + const update = db.prepare('UPDATE journey_entries SET sort_order = ?, updated_at = ? WHERE id = ?'); + const tx = db.transaction(() => { + orderedIds.forEach((id, index) => update.run(index, now, id)); + db.prepare('UPDATE journeys SET updated_at = ? WHERE id = ?').run(now, journeyId); + }); + tx(); + + broadcastJourneyEvent(journeyId, 'journey:entries:reordered', { orderedIds }, sid); + return true; +} + +export function deleteEntry(entryId: number, userId: number, sid?: string): boolean { + const entry = db.prepare('SELECT * FROM journey_entries WHERE id = ?').get(entryId) as JourneyEntry | undefined; + if (!entry) return false; + if (!canEdit(entry.journey_id, userId)) return false; + + if (entry.source_trip_id && entry.source_place_id && entry.type !== 'skeleton') { + // Revert filled entry back to skeleton instead of deleting + db.prepare( + ` + UPDATE journey_entries + SET type = 'skeleton', story = NULL, mood = NULL, weather = NULL, pros_cons = NULL, + visibility = 'private', updated_at = ? + WHERE id = ? + `, + ).run(ts(), entryId); + broadcastJourneyEvent(entry.journey_id, 'journey:entry:updated', { entryId }, sid); + } else { + db.prepare('DELETE FROM journey_entries WHERE id = ?').run(entryId); + broadcastJourneyEvent(entry.journey_id, 'journey:entry:deleted', { entryId }, sid); + } + + return true; +} + +// ── Photos ─────────────────────────────────────────────────────────────── + +// Promote a skeleton suggestion to a concrete entry. Called whenever the user +// adds content (photo upload, provider photo, gallery link) — a suggestion +// with photos is no longer just a suggestion. +function promoteSkeletonIfNeeded(entry: JourneyEntry): void { + if (entry.type !== 'skeleton') return; + db.prepare('UPDATE journey_entries SET type = ?, updated_at = ? WHERE id = ?').run('entry', ts(), entry.id); +} + +// Ensure a trek_photo_id is in the journey gallery; return its gallery row id. +function ensureInGallery(journeyId: number, trekPhotoId: number, caption?: string, shared?: number): number { + const now = ts(); + const maxOrderRow = db + .prepare('SELECT MAX(sort_order) as m FROM journey_photos WHERE journey_id = ?') + .get(journeyId) as { m: number | null }; + db.prepare( + ` + INSERT OR IGNORE INTO journey_photos (journey_id, photo_id, caption, shared, sort_order, created_at) + VALUES (?, ?, ?, ?, ?, ?) + `, + ).run(journeyId, trekPhotoId, caption || null, shared ?? 0, (maxOrderRow?.m ?? -1) + 1, now); + const row = db + .prepare('SELECT id FROM journey_photos WHERE journey_id = ? AND photo_id = ?') + .get(journeyId, trekPhotoId) as { id: number }; + return row.id; +} + +// Link a gallery photo to an entry (idempotent). Returns the junction JP_SELECT row. +function linkGalleryPhotoToEntry(galleryId: number, entryId: number): JourneyPhoto | null { + const now = ts(); + const maxOrderRow = db + .prepare('SELECT MAX(sort_order) as m FROM journey_entry_photos WHERE entry_id = ?') + .get(entryId) as { m: number | null }; + db.prepare( + ` + INSERT OR IGNORE INTO journey_entry_photos (entry_id, journey_photo_id, sort_order, created_at) + VALUES (?, ?, ?, ?) + `, + ).run(entryId, galleryId, (maxOrderRow?.m ?? -1) + 1, now); + return db + .prepare(`SELECT ${JP_SELECT} FROM ${JP_JOIN} WHERE jep.entry_id = ? AND jep.journey_photo_id = ?`) + .get(entryId, galleryId) as JourneyPhoto | null; +} + +export function addPhoto( + entryId: number, + userId: number, + filePath: string, + thumbnailPath?: string, + caption?: string, +): JourneyPhoto | null { + const entry = db.prepare('SELECT * FROM journey_entries WHERE id = ?').get(entryId) as JourneyEntry | undefined; + if (!entry) return null; + if (!canEdit(entry.journey_id, userId)) return null; + + const trekPhotoId = getOrCreateLocalTrekPhoto(filePath, thumbnailPath); + const galleryId = db.transaction(() => ensureInGallery(entry.journey_id, trekPhotoId, caption))(); + const result = linkGalleryPhotoToEntry(galleryId, entryId); + promoteSkeletonIfNeeded(entry); + return result; +} + +export function addProviderPhoto( + entryId: number, + userId: number, + provider: string, + assetId: string, + caption?: string, + passphrase?: string, +): JourneyPhoto | null { + const entry = db.prepare('SELECT * FROM journey_entries WHERE id = ?').get(entryId) as JourneyEntry | undefined; + if (!entry) return null; + if (!canEdit(entry.journey_id, userId)) return null; + + const trekPhotoId = getOrCreateTrekPhoto(provider, assetId, userId, passphrase); + + // skip if this photo is already linked to this entry + const alreadyLinked = db + .prepare( + ` + SELECT 1 FROM journey_entry_photos jep + JOIN journey_photos gp ON gp.id = jep.journey_photo_id + WHERE jep.entry_id = ? AND gp.photo_id = ? + `, + ) + .get(entryId, trekPhotoId); + if (alreadyLinked) return null; + + const galleryId = db.transaction(() => ensureInGallery(entry.journey_id, trekPhotoId, caption))(); + const result = linkGalleryPhotoToEntry(galleryId, entryId); + promoteSkeletonIfNeeded(entry); + return result; +} + +// Link a gallery photo (by its journey_photos.id) to an entry — idempotent. +export function linkPhotoToEntry(entryId: number, journeyPhotoId: number, userId: number): JourneyPhoto | null { + const entry = db.prepare('SELECT * FROM journey_entries WHERE id = ?').get(entryId) as JourneyEntry | undefined; + if (!entry) return null; + if (!canEdit(entry.journey_id, userId)) return null; + + // Verify the gallery photo belongs to this journey + const galleryRow = db.prepare('SELECT id, journey_id FROM journey_photos WHERE id = ?').get(journeyPhotoId) as + | { id: number; journey_id: number } + | undefined; + if (!galleryRow || galleryRow.journey_id !== entry.journey_id) return null; + + const result = linkGalleryPhotoToEntry(galleryRow.id, entryId); + promoteSkeletonIfNeeded(entry); + return result; +} + +// Upload photos to the journey gallery only (no entry association). +export function uploadGalleryPhotos( + journeyId: number, + userId: number, + filePaths: { path: string; thumbnail?: string }[], +): JourneyPhoto[] { + if (!canEdit(journeyId, userId)) return []; + const results: any[] = []; + const now = ts(); + const maxOrderRow = db + .prepare('SELECT MAX(sort_order) as m FROM journey_photos WHERE journey_id = ?') + .get(journeyId) as { m: number | null }; + let nextOrder = (maxOrderRow?.m ?? -1) + 1; + + for (const f of filePaths) { + const trekPhotoId = getOrCreateLocalTrekPhoto(f.path, f.thumbnail); + db.prepare( + ` + INSERT OR IGNORE INTO journey_photos (journey_id, photo_id, shared, sort_order, created_at) + VALUES (?, ?, 0, ?, ?) + `, + ).run(journeyId, trekPhotoId, nextOrder++, now); + const row = db + .prepare(`SELECT ${GALLERY_SELECT} FROM ${GALLERY_JOIN} WHERE gp.journey_id = ? AND gp.photo_id = ?`) + .get(journeyId, trekPhotoId); + if (row) results.push(row); + } + return results; +} + +// Add a provider photo to the gallery only (no entry link). +export function addProviderPhotoToGallery( + journeyId: number, + userId: number, + provider: string, + assetId: string, + caption?: string, + passphrase?: string, +): any | null { + if (!canEdit(journeyId, userId)) return null; + const trekPhotoId = getOrCreateTrekPhoto(provider, assetId, userId, passphrase); + const galleryId = db.transaction(() => ensureInGallery(journeyId, trekPhotoId, caption))(); + return db.prepare(`SELECT ${GALLERY_SELECT} FROM ${GALLERY_JOIN} WHERE gp.id = ?`).get(galleryId) ?? null; +} + +// Unlink a photo from a specific entry; gallery row is preserved. +export function unlinkPhotoFromEntry(entryId: number, journeyPhotoId: number, userId: number): boolean { + const entry = db.prepare('SELECT * FROM journey_entries WHERE id = ?').get(entryId) as JourneyEntry | undefined; + if (!entry) return false; + if (!canEdit(entry.journey_id, userId)) return false; + + const result = db + .prepare('DELETE FROM journey_entry_photos WHERE entry_id = ? AND journey_photo_id = ?') + .run(entryId, journeyPhotoId); + return result.changes > 0; +} + +// Hard-delete a gallery photo (removes from all entries and the gallery). +export function deleteGalleryPhoto( + journeyPhotoId: number, + userId: number, +): { photo_id: number; file_path?: string | null } | null { + const row = db.prepare('SELECT * FROM journey_photos WHERE id = ?').get(journeyPhotoId) as + | { id: number; journey_id: number; photo_id: number } + | undefined; + if (!row) return null; + if (!canEdit(row.journey_id, userId)) return null; + + const trekRow = db.prepare('SELECT file_path, provider FROM trek_photos WHERE id = ?').get(row.photo_id) as + | { file_path?: string; provider?: string } + | undefined; + + // cascade on journey_entry_photos.journey_photo_id handles junction cleanup + db.prepare('DELETE FROM journey_photos WHERE id = ?').run(journeyPhotoId); + deleteTrekPhotoIfOrphan(row.photo_id); + + return { photo_id: row.photo_id, file_path: trekRow?.file_path ?? null }; +} + +export function setPhotoProvider(photoId: number, provider: string, assetId: string, ownerId: number) { + // photoId = journey_photos.id (gallery row); look up the trek_photo_id + const jp = db.prepare('SELECT photo_id FROM journey_photos WHERE id = ?').get(photoId) as + | { photo_id: number } + | undefined; + if (!jp) return; + setTrekPhotoProvider(jp.photo_id, provider, assetId, ownerId); + // also denorm on gallery row for fast reads + db.prepare('UPDATE journey_photos SET provider = ?, asset_id = ?, owner_id = ? WHERE id = ?').run( + provider, + assetId, + ownerId, + photoId, + ); +} + +export function updatePhoto( + photoId: number, + userId: number, + data: { caption?: string; sort_order?: number }, +): JourneyPhoto | null { + // photoId = journey_photos.id (gallery row) + const row = db.prepare('SELECT id, journey_id FROM journey_photos WHERE id = ?').get(photoId) as + | { id: number; journey_id: number } + | undefined; + if (!row) return null; + if (!canEdit(row.journey_id, userId)) return null; + + // caption lives on the gallery row; sort_order lives on the junction table + // (JP_SELECT reads jep.sort_order, so updating journey_photos.sort_order + // would not be reflected in the returned row). + if (data.caption !== undefined) { + db.prepare('UPDATE journey_photos SET caption = ? WHERE id = ?').run(data.caption, photoId); + } + if (data.sort_order !== undefined) { + db.prepare('UPDATE journey_entry_photos SET sort_order = ? WHERE journey_photo_id = ?').run( + data.sort_order, + photoId, + ); + } + return db.prepare(`SELECT ${JP_SELECT} FROM ${JP_JOIN} WHERE gp.id = ? LIMIT 1`).get(photoId) as JourneyPhoto | null; +} + +// deletePhoto: hard-delete (backwards compat name used by old route). +export function deletePhoto( + photoId: number, + userId: number, +): { id: number; photo_id: number; file_path?: string | null; journey_id: number } | null { + const row = db.prepare('SELECT id, journey_id, photo_id FROM journey_photos WHERE id = ?').get(photoId) as + | { id: number; journey_id: number; photo_id: number } + | undefined; + if (!row) return null; + if (!canEdit(row.journey_id, userId)) return null; + + const trekRow = db.prepare('SELECT file_path, provider FROM trek_photos WHERE id = ?').get(row.photo_id) as + | { file_path?: string; provider?: string } + | undefined; + + db.prepare('DELETE FROM journey_photos WHERE id = ?').run(photoId); + deleteTrekPhotoIfOrphan(row.photo_id); + + return { id: row.id, photo_id: row.photo_id, file_path: trekRow?.file_path ?? null, journey_id: row.journey_id }; +} + +// ── Contributors ───────────────────────────────────────────────────────── + +export function addContributor( + journeyId: number, + userId: number, + targetUserId: number, + role: 'editor' | 'viewer', +): boolean { + if (!isOwner(journeyId, userId)) return false; + if (targetUserId === userId) return false; + try { + db.prepare( + 'INSERT OR REPLACE INTO journey_contributors (journey_id, user_id, role, added_at) VALUES (?, ?, ?, ?)', + ).run(journeyId, targetUserId, role, ts()); + broadcastJourneyEvent(journeyId, 'journey:contributor:changed', { targetUserId, role }); + return true; + } catch { + return false; + } +} + +export function updateContributorRole( + journeyId: number, + userId: number, + targetUserId: number, + role: 'editor' | 'viewer', +): boolean { + if (!isOwner(journeyId, userId)) return false; + db.prepare('UPDATE journey_contributors SET role = ? WHERE journey_id = ? AND user_id = ?').run( + role, + journeyId, + targetUserId, + ); + broadcastJourneyEvent(journeyId, 'journey:contributor:changed', { targetUserId, role }); + return true; +} + +export function removeContributor(journeyId: number, userId: number, targetUserId: number): boolean { + if (!isOwner(journeyId, userId)) return false; + db.prepare("DELETE FROM journey_contributors WHERE journey_id = ? AND user_id = ? AND role != 'owner'").run( + journeyId, + targetUserId, + ); + return true; +} + +// ── Suggestions ────────────────────────────────────────────────────────── + +export function getSuggestions(userId: number) { + const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]; + return db + .prepare( + ` + SELECT t.id, t.title, t.start_date, t.end_date, t.cover_image, + (SELECT COUNT(*) FROM places p INNER JOIN day_assignments da ON da.place_id = p.id WHERE p.trip_id = t.id) as place_count + FROM trips t + LEFT JOIN trip_members tm ON t.id = tm.trip_id AND tm.user_id = ? + WHERE (t.user_id = ? OR tm.user_id = ?) + AND t.end_date IS NOT NULL + AND t.end_date >= ? + AND t.end_date <= date('now') + AND t.id NOT IN (SELECT trip_id FROM journey_trips) + ORDER BY t.end_date DESC + `, + ) + .all(userId, userId, userId, thirtyDaysAgo); +} + +// ── User trips (for trip picker) ───────────────────────────────────────── + +export function listUserTrips(userId: number) { + return db + .prepare( + ` + SELECT t.id, t.title, t.start_date, t.end_date, t.cover_image, + (SELECT COUNT(*) FROM places p INNER JOIN day_assignments da ON da.place_id = p.id WHERE p.trip_id = t.id) as place_count + FROM trips t + LEFT JOIN trip_members tm ON t.id = tm.trip_id AND tm.user_id = ? + WHERE t.user_id = ? OR tm.user_id = ? + ORDER BY t.start_date DESC + `, + ) + .all(userId, userId, userId); +} diff --git a/server/src/services/journeyShareService.ts b/server/src/services/journeyShareService.ts new file mode 100644 index 0000000000000000000000000000000000000000..d07e5b782302f9cc4b6d9ae317c2bf9a697e6160 --- /dev/null +++ b/server/src/services/journeyShareService.ts @@ -0,0 +1,193 @@ +import { db } from '../db/database'; +import crypto from 'crypto'; +import { isOwner } from './journeyService'; + +interface JourneySharePermissions { + share_timeline?: boolean; + share_gallery?: boolean; + share_map?: boolean; +} + +interface JourneyShareTokenInfo { + token: string; + created_at: string; + share_timeline: boolean; + share_gallery: boolean; + share_map: boolean; +} + +export function createOrUpdateJourneyShareLink( + journeyId: number, + createdBy: number, + permissions: JourneySharePermissions +): { token: string; created: boolean } | null { + // Public sharing is an owner-only action — editors/viewers must not be + // able to publish the journey or change which screens are shared. + if (!isOwner(journeyId, createdBy)) return null; + + const { + share_timeline = true, + share_gallery = true, + share_map = true, + } = permissions; + + const existing = db.prepare('SELECT token FROM journey_share_tokens WHERE journey_id = ?').get(journeyId) as { token: string } | undefined; + if (existing) { + db.prepare('UPDATE journey_share_tokens SET share_timeline = ?, share_gallery = ?, share_map = ? WHERE journey_id = ?') + .run(share_timeline ? 1 : 0, share_gallery ? 1 : 0, share_map ? 1 : 0, journeyId); + return { token: existing.token, created: false }; + } + + const token = crypto.randomBytes(24).toString('base64url'); + db.prepare('INSERT INTO journey_share_tokens (journey_id, token, created_by, share_timeline, share_gallery, share_map) VALUES (?, ?, ?, ?, ?, ?)') + .run(journeyId, token, createdBy, share_timeline ? 1 : 0, share_gallery ? 1 : 0, share_map ? 1 : 0); + return { token, created: true }; +} + +export function getJourneyShareLink(journeyId: number): JourneyShareTokenInfo | null { + const row = db.prepare('SELECT * FROM journey_share_tokens WHERE journey_id = ?').get(journeyId) as any; + if (!row) return null; + return { + token: row.token, + created_at: row.created_at, + share_timeline: !!row.share_timeline, + share_gallery: !!row.share_gallery, + share_map: !!row.share_map, + }; +} + +export function deleteJourneyShareLink(journeyId: number, userId: number): boolean { + if (!isOwner(journeyId, userId)) return false; + db.prepare('DELETE FROM journey_share_tokens WHERE journey_id = ?').run(journeyId); + return true; +} + +export function validateShareTokenForPhoto(token: string, photoId: number): { journeyId: number; ownerId: number } | null { + const row = db.prepare('SELECT journey_id FROM journey_share_tokens WHERE token = ?').get(token) as any; + if (!row) return null; + const photo = db.prepare(` + SELECT gp.photo_id, tkp.owner_id, gp.journey_id + FROM journey_photos gp + JOIN trek_photos tkp ON tkp.id = gp.photo_id + WHERE gp.photo_id = ? AND gp.journey_id = ? + `).get(photoId, row.journey_id) as any; + if (!photo) return null; + const journey = db.prepare('SELECT user_id FROM journeys WHERE id = ?').get(row.journey_id) as any; + return journey ? { journeyId: row.journey_id, ownerId: photo.owner_id || journey.user_id } : null; +} + +export function validateShareTokenForAsset(token: string, assetId: string): { ownerId: number } | null { + const row = db.prepare('SELECT journey_id FROM journey_share_tokens WHERE token = ?').get(token) as any; + if (!row) return null; + const photo = db.prepare(` + SELECT tkp.owner_id FROM journey_photos gp + JOIN trek_photos tkp ON tkp.id = gp.photo_id + WHERE tkp.asset_id = ? AND gp.journey_id = ? + `).get(assetId, row.journey_id) as any; + // Only resolve assets that actually belong to this shared journey. + if (!photo) return null; + return { ownerId: photo.owner_id }; +} + +export function getPublicJourney(token: string) { + const row = db.prepare('SELECT * FROM journey_share_tokens WHERE token = ?').get(token) as any; + if (!row) return null; + + const journey = db.prepare('SELECT * FROM journeys WHERE id = ?').get(row.journey_id) as any; + if (!journey) return null; + + // Entries with photos + const entries = db.prepare(` + SELECT je.* FROM journey_entries je + WHERE je.journey_id = ? AND je.type != 'skeleton' + ORDER BY je.entry_date, je.sort_order + `).all(row.journey_id) as any[]; + + const photos = db.prepare(` + SELECT gp.id, jep.entry_id, gp.photo_id, gp.caption, jep.sort_order, gp.shared, gp.created_at, + tkp.provider, tkp.asset_id, tkp.owner_id, tkp.file_path, tkp.thumbnail_path, tkp.width, tkp.height + FROM journey_entry_photos jep + JOIN journey_photos gp ON gp.id = jep.journey_photo_id + JOIN trek_photos tkp ON tkp.id = gp.photo_id + WHERE gp.journey_id = ? + ORDER BY jep.sort_order + `).all(row.journey_id) as any[]; + + const photosByEntry: Record = {}; + for (const p of photos) { + (photosByEntry[p.entry_id] ||= []).push(p); + } + + const gallery = db.prepare(` + SELECT gp.id, gp.journey_id, gp.photo_id, gp.caption, gp.shared, gp.sort_order, gp.created_at, + tkp.provider, tkp.asset_id, tkp.owner_id, tkp.file_path, tkp.thumbnail_path, tkp.width, tkp.height + FROM journey_photos gp + JOIN trek_photos tkp ON tkp.id = gp.photo_id + WHERE gp.journey_id = ? + ORDER BY gp.sort_order + `).all(row.journey_id) as any[]; + + const enrichedEntries = entries + .map(e => ({ + ...e, + tags: e.tags ? JSON.parse(e.tags) : [], + pros_cons: e.pros_cons ? JSON.parse(e.pros_cons) : null, + photos: photosByEntry[e.id] || [], + })); + + // Stats are derived from the full data so the overview pills stay accurate + // even when a section is hidden. + const stats = { + entries: entries.length, + photos: gallery.length, + places: new Set(entries.filter(e => e.location_name).map(e => e.location_name)).size, + }; + + const shareTimeline = !!row.share_timeline; + const shareGallery = !!row.share_gallery; + const shareMap = !!row.share_map; + + // Honour the share flags server-side so the API only returns the sections the + // owner enabled (the client gates these too, but it must not rely on that). + let publicEntries: Record[] = []; + if (shareTimeline) { + // Include the full entry, but drop GPS unless the map is shared and inline + // photos unless the gallery is shared. + publicEntries = enrichedEntries.map(e => { + const projected: Record = { ...e }; + if (!shareMap) { projected.location_lat = null; projected.location_lng = null; } + if (!shareGallery) projected.photos = []; + return projected; + }); + } else if (shareMap) { + // Map-only share: just enough to plot markers, no story/photos/mood. + publicEntries = enrichedEntries.map(e => ({ + id: e.id, + journey_id: e.journey_id, + type: e.type, + entry_date: e.entry_date, + title: e.title, + location_name: e.location_name, + location_lat: e.location_lat, + location_lng: e.location_lng, + sort_order: e.sort_order, + })); + } + + return { + journey: { + title: journey.title, + subtitle: journey.subtitle, + cover_image: journey.cover_image, + status: journey.status, + }, + entries: publicEntries, + gallery: shareGallery ? gallery : [], + stats, + permissions: { + share_timeline: shareTimeline, + share_gallery: shareGallery, + share_map: shareMap, + }, + }; +} diff --git a/server/src/services/kmlImport.ts b/server/src/services/kmlImport.ts new file mode 100644 index 0000000000000000000000000000000000000000..599cffff130c621b344123623cc44459563906f9 --- /dev/null +++ b/server/src/services/kmlImport.ts @@ -0,0 +1,212 @@ +import { TextDecoder } from 'util'; + +export interface ParsedKmlPlacemark { + name: string | null; + description: string | null; + lat: number | null; + lng: number | null; + folderName: string | null; + routeGeometry: string | null; +} + +export interface KmlPlacemarkNode { + placemark: any; + folderName: string | null; +} + +export interface KmlImportSummary { + totalPlacemarks: number; + createdCount: number; + skippedCount: number; + warnings: string[]; + errors: string[]; +} + +const UTF8_DECODER_FATAL = new TextDecoder('utf-8', { fatal: true }); +const UTF8_DECODER_LOOSE = new TextDecoder('utf-8'); + +const ENTITY_MAP: Record = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + ''': "'", + ' ': ' ', +}; + +function asArray(value: T | T[] | null | undefined): T[] { + if (value == null) return []; + return Array.isArray(value) ? value : [value]; +} + +function asTrimmedString(value: unknown): string | null { + if (value == null) return null; + // Parsed objects (mixed-content XML parsed without stopNodes) must not + // produce "[object Object]" — extract #text if present, else return null. + if (typeof value === 'object') { + const candidate = (value as Record)['#text']; + if (typeof candidate === 'string') return candidate.trim() || null; + return null; + } + const text = String(value).trim(); + return text.length > 0 ? text : null; +} + +function decodeHtmlEntities(value: string): string { + const withNamedEntities = value.replace(/&(amp|lt|gt|quot|#39|nbsp);/g, (m) => ENTITY_MAP[m] || m); + + return withNamedEntities + .replace(/&#(\d+);/g, (_, dec) => { + const code = Number(dec); + return Number.isFinite(code) && code >= 0 && code <= 0x10ffff ? String.fromCodePoint(code) : _; + }) + .replace(/&#x([0-9a-fA-F]+);/g, (_, hex) => { + const code = Number.parseInt(hex, 16); + return Number.isFinite(code) && code >= 0 && code <= 0x10ffff ? String.fromCodePoint(code) : _; + }); +} + +export function decodeUtf8WithWarning(fileBuffer: Buffer): { text: string; warning: string | null } { + try { + return { text: UTF8_DECODER_FATAL.decode(fileBuffer), warning: null }; + } catch { + return { + text: UTF8_DECODER_LOOSE.decode(fileBuffer), + warning: 'The uploaded file is not valid UTF-8. Some characters may be shown incorrectly.', + }; + } +} + +export function sanitizeKmlDescription(value: unknown): string | null { + const raw = asTrimmedString(value); + if (!raw) return null; + + // Unwrap CDATA sections — present when fast-xml-parser returns raw node text + // via stopNodes. Must happen before tag-stripping so the CDATA markers are + // not mis-parsed by the <[^>]+> regex. + const withoutCdata = raw.replace(//g, '$1'); + + const withLineBreaks = withoutCdata.replace(//gi, '\n'); + const stripped = withLineBreaks.replace(/<[^>]+>/g, ''); + const decoded = decodeHtmlEntities(stripped) + .replace(/\r\n/g, '\n') + .replace(/\r/g, '\n') + .replace(/[\t\f\v]+/g, ' ') + .replace(/\n{3,}/g, '\n\n') + .trim(); + + return decoded || null; +} + +export function parseKmlLineStringCoordinates(value: unknown): Array<{ lat: number; lng: number; ele: number | null }> | null { + const coordinates = asTrimmedString(value); + if (!coordinates) return null; + + const points = coordinates + .trim() + .split(/\s+/) + .map(coord => { + const parts = coord.split(','); + const lng = Number.parseFloat(parts[0] ?? ''); + const lat = Number.parseFloat(parts[1] ?? ''); + const eleRaw = parts[2] != null ? Number.parseFloat(parts[2]) : NaN; + if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null; + return { lat, lng, ele: Number.isFinite(eleRaw) ? eleRaw : null }; + }) + .filter((p): p is { lat: number; lng: number; ele: number | null } => p !== null); + + return points.length >= 2 ? points : null; +} + +export function parseKmlPointCoordinates(value: unknown): { lat: number; lng: number } | null { + const coordinates = asTrimmedString(value); + if (!coordinates) return null; + + const firstCoordinate = coordinates.split(/\s+/)[0]; + const [lngRaw, latRaw] = firstCoordinate.split(','); + if (lngRaw == null || latRaw == null) return null; + + const lng = Number.parseFloat(lngRaw); + const lat = Number.parseFloat(latRaw); + + if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null; + return { lat, lng }; +} + +export function createKmlImportSummary(totalPlacemarks: number): KmlImportSummary { + return { + totalPlacemarks, + createdCount: 0, + skippedCount: 0, + warnings: [], + errors: [], + }; +} + +export function buildCategoryNameLookup(categories: { id: number; name: string }[]): Map { + const lookup = new Map(); + for (const category of categories) { + const normalizedName = category.name.trim().toLowerCase(); + if (!normalizedName) continue; + if (!lookup.has(normalizedName)) { + lookup.set(normalizedName, category.id); + } + } + return lookup; +} + +export function resolveCategoryIdForFolder(folderName: string | null, lookup: Map): number | null { + if (!folderName) return null; + const normalizedFolder = folderName.trim().toLowerCase(); + if (!normalizedFolder) return null; + return lookup.get(normalizedFolder) ?? null; +} + +export function extractKmlPlacemarkNodes(kmlRoot: any): KmlPlacemarkNode[] { + const nodes: KmlPlacemarkNode[] = []; + + const visitNode = (node: any, currentFolderName: string | null): void => { + if (!node || typeof node !== 'object') return; + + for (const placemark of asArray(node.Placemark)) { + nodes.push({ placemark, folderName: currentFolderName }); + } + + for (const folder of asArray(node.Folder)) { + // Nested folders inherit/override folder context used for category matching. + const folderName = asTrimmedString(folder?.name) || currentFolderName; + visitNode(folder, folderName); + } + + for (const childDocument of asArray(node.Document)) { + visitNode(childDocument, currentFolderName); + } + }; + + visitNode(kmlRoot, null); + return nodes; +} + +export function parsePlacemarkNode(node: KmlPlacemarkNode): ParsedKmlPlacemark { + const pointCoords = parseKmlPointCoordinates(node.placemark?.Point?.coordinates); + + let routeGeometry: string | null = null; + let pathFirstPt: { lat: number; lng: number } | null = null; + if (!pointCoords) { + const linePts = parseKmlLineStringCoordinates(node.placemark?.LineString?.coordinates); + if (linePts) { + pathFirstPt = { lat: linePts[0].lat, lng: linePts[0].lng }; + const hasAllEle = linePts.every(p => p.ele !== null); + routeGeometry = JSON.stringify(linePts.map(p => hasAllEle ? [p.lat, p.lng, p.ele] : [p.lat, p.lng])); + } + } + + return { + name: asTrimmedString(node.placemark?.name), + description: sanitizeKmlDescription(node.placemark?.description), + lat: pointCoords?.lat ?? pathFirstPt?.lat ?? null, + lng: pointCoords?.lng ?? pathFirstPt?.lng ?? null, + folderName: node.folderName, + routeGeometry, + }; +} diff --git a/server/src/services/mapsService.ts b/server/src/services/mapsService.ts new file mode 100644 index 0000000000000000000000000000000000000000..704f83801ff8e6d1542c0b3b39766587702de4f2 --- /dev/null +++ b/server/src/services/mapsService.ts @@ -0,0 +1,1054 @@ +import { db } from '../db/database'; +import { decrypt_api_key } from './apiKeyCrypto'; +import { safeFetchFollow, SsrfBlockedError } from '../utils/ssrfGuard'; +import { getAppUrl } from './notifications'; + +// ── Google API call counter ─────────────────────────────────────────────────── + +let googleApiCallCount = 0; + +function googleFetch(endpoint: string, label: string, init?: RequestInit): Promise { + googleApiCallCount++; + console.debug(`[Google API] #${googleApiCallCount} ${label} → ${endpoint}`); + const referer = process.env.APP_URL ? getAppUrl() : undefined; + return fetch(endpoint, { + ...init, + headers: { ...(referer ? { Referer: referer } : {}), ...(init?.headers as Record ?? {}) }, + }); +} + +// ── Interfaces ─────────────────────────────────────────────────────────────── + +interface NominatimResult { + osm_type: string; + osm_id: string; + name?: string; + display_name?: string; + lat: string; + lon: string; +} + +interface OverpassElement { + tags?: Record; +} + +interface WikiCommonsPage { + imageinfo?: { url?: string; thumburl?: string; extmetadata?: { Artist?: { value?: string } } }[]; +} + +interface GooglePlaceResult { + id: string; + displayName?: { text: string }; + formattedAddress?: string; + location?: { latitude: number; longitude: number }; + rating?: number; + websiteUri?: string; + nationalPhoneNumber?: string; + types?: string[]; +} + +interface GoogleAutocompleteSuggestion { + placePrediction?: { + placeId: string; + structuredFormat?: { + mainText?: { text: string }; + secondaryText?: { text: string }; + }; + }; +} + +interface GooglePlaceDetails extends GooglePlaceResult { + userRatingCount?: number; + regularOpeningHours?: { weekdayDescriptions?: string[]; openNow?: boolean }; + googleMapsUri?: string; + editorialSummary?: { text: string }; + reviews?: { authorAttribution?: { displayName?: string; photoUri?: string }; rating?: number; text?: { text?: string }; relativePublishTimeDescription?: string }[]; + photos?: { name: string; authorAttributions?: { displayName?: string }[] }[]; +} + +// ── Constants ──────────────────────────────────────────────────────────────── + +const UA = 'TREK Travel Planner (https://github.com/mauriceboe/TREK)'; + +// TREK's internal language codes mostly coincide with valid BCP-47 codes, but a +// couple don't: 'br' is Brazilian Portuguese here (BCP-47 'pt-BR'; bare 'br' is +// Breton) and 'gr' is Greek (BCP-47 'el'). Outbound geo APIs (Google Places, +// Nominatim) expect BCP-47, so normalise before sending — otherwise names and +// opening hours come back in the wrong language. Codes not listed here pass +// through unchanged (they are already valid), as do locale forms the client +// sometimes sends (e.g. 'pt-BR'). +const API_LANG_OVERRIDES: Record = { + br: 'pt-BR', + gr: 'el', + 'el-GR': 'el', +}; +function toApiLang(lang: string | undefined, fallback = 'en'): string { + const code = (lang || '').trim(); + if (!code) return fallback; + return API_LANG_OVERRIDES[code] ?? code; +} + +// ── Photo cache (disk-backed) ──────────────────────────────────────────────── +import * as placePhotoCache from './placePhotoCache'; + +// ── Concurrency limiter for outbound photo fetches ─────────────────────────── +// Caps simultaneous Wikimedia/Google photo requests so a bulk import of hundreds +// of places cannot monopolise the event loop or trigger external API rate limits. +const MAX_CONCURRENT_PHOTO_FETCHES = 5; +let photoFetchActive = 0; +const photoFetchQueue: Array<() => void> = []; + +function acquirePhotoFetchSlot(): Promise { + if (photoFetchActive < MAX_CONCURRENT_PHOTO_FETCHES) { + photoFetchActive++; + return Promise.resolve(); + } + return new Promise(resolve => photoFetchQueue.push(resolve)); +} + +function releasePhotoFetchSlot(): void { + const next = photoFetchQueue.shift(); + if (next) { + next(); + } else { + photoFetchActive--; + } +} + +// ── API key retrieval ──────────────────────────────────────────────────────── + +export function getMapsKey(userId: number): string | null { + const user = db.prepare('SELECT maps_api_key FROM users WHERE id = ?').get(userId) as { maps_api_key: string | null } | undefined; + const user_key = decrypt_api_key(user?.maps_api_key); + if (user_key) return user_key; + const admin = db.prepare("SELECT maps_api_key FROM users WHERE role = 'admin' AND maps_api_key IS NOT NULL AND maps_api_key != '' LIMIT 1").get() as { maps_api_key: string } | undefined; + return decrypt_api_key(admin?.maps_api_key) || null; +} + +// ── Nominatim search ───────────────────────────────────────────────────────── + +export async function searchNominatim(query: string, lang?: string) { + const params = new URLSearchParams({ + q: query, + format: 'json', + addressdetails: '1', + limit: '10', + 'accept-language': toApiLang(lang), + }); + const response = await fetch(`https://nominatim.openstreetmap.org/search?${params}`, { + headers: { 'User-Agent': UA }, + }); + if (!response.ok) { + const text = await response.text().catch(() => ''); + throw new Error(`Nominatim API error: ${response.status} ${response.statusText}${text ? ' - ' + text.substring(0, 200) : ''}`); + } + const data = await response.json() as NominatimResult[]; + return data.map(item => ({ + google_place_id: null, + osm_id: `${item.osm_type}:${item.osm_id}`, + name: item.name || item.display_name?.split(',')[0] || '', + address: item.display_name || '', + lat: parseFloat(item.lat) || null, + lng: parseFloat(item.lon) || null, + rating: null, + website: null, + phone: null, + source: 'openstreetmap', + })); +} + +// ── Nominatim lookup (by OSM ID) ──────────────────────────────────────────── + +export async function lookupNominatim(osmType: string, osmId: string, lang?: string): Promise<{ + name: string; address: string; lat: number | null; lng: number | null; +} | null> { + const typePrefix = osmType.charAt(0).toUpperCase(); // N, W, R + const params = new URLSearchParams({ + osm_ids: `${typePrefix}${osmId}`, + format: 'json', + 'accept-language': toApiLang(lang), + }); + try { + const res = await fetch(`https://nominatim.openstreetmap.org/lookup?${params}`, { + headers: { 'User-Agent': UA }, + }); + if (!res.ok) return null; + const data = await res.json() as NominatimResult[]; + const item = data[0]; + if (!item) return null; + return { + name: item.name || item.display_name?.split(',')[0] || '', + address: item.display_name || '', + lat: parseFloat(item.lat) || null, + lng: parseFloat(item.lon) || null, + }; + } catch { return null; } +} + +// ── Overpass API (OSM details) ─────────────────────────────────────────────── + +export async function fetchOverpassDetails(osmType: string, osmId: string): Promise { + const typeMap: Record = { node: 'node', way: 'way', relation: 'rel' }; + const oType = typeMap[osmType]; + if (!oType) return null; + const query = `[out:json][timeout:5];${oType}(${osmId});out tags;`; + try { + const res = await fetch('https://overpass-api.de/api/interpreter', { + method: 'POST', + headers: { 'User-Agent': UA, 'Content-Type': 'application/x-www-form-urlencoded' }, + body: `data=${encodeURIComponent(query)}`, + }); + if (!res.ok) return null; + const data = await res.json() as { elements?: OverpassElement[] }; + return data.elements?.[0] || null; + } catch { return null; } +} + +// ── Overpass POI search (by category within a viewport bbox) ───────────────── +// Powers the "explore places on the map" pill. OSM-ONLY by design — this never +// calls Google, even when a Google key is configured. + +export interface OverpassPoi { + osm_id: string; // 'node:123' | 'way:123' | 'relation:123' (matches the placeId format elsewhere) + name: string; + lat: number; + lng: number; + category: string; // the requested pill category key, e.g. 'restaurant' + poi_type: string; // the raw OSM tag that matched, e.g. 'amenity=restaurant' + address: string | null; + website: string | null; + phone: string | null; + opening_hours: string | null; + cuisine: string | null; + source: 'openstreetmap'; +} + +// Each pill category → the OSM tag selectors it searches. Keys here are the +// contract with the client's POI_CATEGORIES (same keys, label/icon/colour live +// client-side). +const CATEGORY_OSM_FILTERS: Record = { + restaurant: ['amenity=restaurant', 'amenity=fast_food'], + cafe: ['amenity=cafe'], + bar: ['amenity=bar', 'amenity=pub', 'amenity=nightclub'], + hotel: ['tourism=hotel', 'tourism=hostel', 'tourism=guest_house', 'tourism=apartment', 'tourism=motel'], + sights: ['tourism=attraction', 'tourism=viewpoint', 'historic=monument', 'historic=castle', 'historic=memorial', 'historic=ruins'], + museum: ['tourism=museum', 'tourism=gallery', 'tourism=artwork', 'amenity=theatre'], + nature: ['leisure=park', 'leisure=garden', 'natural=beach', 'natural=peak'], + activity: ['tourism=theme_park', 'tourism=zoo', 'tourism=aquarium', 'leisure=water_park'], + shopping: ['shop=mall', 'shop=department_store', 'amenity=marketplace'], + supermarket: ['shop=supermarket', 'shop=convenience'], +}; + +export const POI_CATEGORY_KEYS = Object.keys(CATEGORY_OSM_FILTERS); + +interface OverpassPoiElement { + type: string; + id: number; + lat?: number; + lon?: number; + center?: { lat: number; lon: number }; + tags?: Record; +} + +interface PoiSearchResult { + pois: OverpassPoi[]; + source: 'openstreetmap'; + truncated: boolean; + // True when the requested viewport was too large and got shrunk to a centred + // window before querying — the results then cover the middle of the view only. + clamped: boolean; +} + +// Public Overpass mirrors, queried in PARALLEL (first valid response wins). +// Reachability and load vary a lot by network/region — the canonical instance is +// frequently overloaded (504s) and some community mirrors are unreachable from +// certain networks. Racing them means whichever mirror is fastest-reachable for +// this user answers, and an overloaded or blocked one never blocks the others. +const OVERPASS_MIRRORS = [ + 'https://overpass-api.de/api/interpreter', + 'https://maps.mail.ru/osm/tools/overpass/api/interpreter', + 'https://overpass.kumi.systems/api/interpreter', + 'https://overpass.private.coffee/api/interpreter', +]; +// Per-mirror cap. Because mirrors race in parallel this is also the worst-case +// total wait before every mirror is given up on and a 502 is returned. +const OVERPASS_TIMEOUT_MS = 12000; +// Largest viewport side we send to Overpass. A country/continent-sized bbox makes +// Overpass scan millions of elements and time out; clamping to a centred window +// keeps the query cheap so the explore pill returns fast at ANY zoom level. +const MAX_BBOX_SPAN_DEG = 0.5; + +// Short-lived cache so panning back over / re-toggling the same area doesn't +// re-hit Overpass. Keyed by category + rounded (post-clamp) bbox. +const POI_CACHE = new Map(); +const POI_CACHE_TTL_MS = 5 * 60 * 1000; +// Cap the number of cached areas so panning across the globe can't grow the map +// without bound (entries are evicted oldest-first once the cap is reached). +const POI_CACHE_MAX = 500; + +// POST the query to all mirrors at once and return the first one that answers with +// valid JSON. Throws {status:502} only if every mirror fails. Racing (rather than +// trying one-by-one) keeps latency at the fastest reachable mirror instead of the +// sum of every dead mirror's timeout. +async function overpassFetch(query: string): Promise { + const body = `data=${encodeURIComponent(query)}`; + const controllers: AbortController[] = []; + + const attempt = async (url: string): Promise => { + const ctrl = new AbortController(); + controllers.push(ctrl); + const timer = setTimeout(() => ctrl.abort(), OVERPASS_TIMEOUT_MS); + try { + const res = await fetch(url, { + method: 'POST', + headers: { 'User-Agent': UA, 'Content-Type': 'application/x-www-form-urlencoded' }, + body, + signal: ctrl.signal, + }); + if (!res.ok) throw new Error(`Overpass ${res.status} @ ${url}`); + const data = await res.json() as { elements?: OverpassPoiElement[]; remark?: string }; + // Overpass signals an internal timeout / runtime error via `remark` while + // still answering HTTP 200 — often fast, with an empty or partial element + // set. Treat that as a failed attempt so a healthy mirror wins the race + // instead of this fast-but-empty answer, and so the all-mirrors-failed path + // still surfaces a real error to the client instead of a silent "no places". + if (data.remark) throw new Error(`Overpass remark @ ${url}: ${data.remark}`); + if (!Array.isArray(data.elements)) throw new Error(`Overpass non-OSM body @ ${url}`); + return data.elements; + } finally { + clearTimeout(timer); + } + }; + + try { + // Promise.any resolves with the first mirror to return valid JSON, and only + // rejects (AggregateError) once every mirror has failed. + return await Promise.any(OVERPASS_MIRRORS.map(attempt)); + } catch { + throw Object.assign(new Error('Overpass request failed'), { status: 502 }); + } finally { + // Cancel the slower/losing requests — we already have (or have given up on) a result. + controllers.forEach(c => { try { c.abort(); } catch { /* noop */ } }); + } +} + +export async function searchOverpassPois( + category: string, + bbox: { south: number; west: number; north: number; east: number }, + limit = 60, +): Promise { + const filters = CATEGORY_OSM_FILTERS[category]; + if (!filters) throw Object.assign(new Error('Unknown POI category'), { status: 400 }); + + // Clamp an oversized viewport to a centred window so the query stays cheap and + // returns fast at any zoom, instead of timing out / 502-ing on a huge area. + let { south, west, north, east } = bbox; + let clamped = false; + if (north - south > MAX_BBOX_SPAN_DEG) { + const c = (north + south) / 2; + south = c - MAX_BBOX_SPAN_DEG / 2; + north = c + MAX_BBOX_SPAN_DEG / 2; + clamped = true; + } + if (east - west > MAX_BBOX_SPAN_DEG) { + const c = (east + west) / 2; + west = c - MAX_BBOX_SPAN_DEG / 2; + east = c + MAX_BBOX_SPAN_DEG / 2; + clamped = true; + } + + // Serve repeat pans/toggles of the same area straight from the cache. + const cacheKey = `${category}|${south.toFixed(2)},${west.toFixed(2)},${north.toFixed(2)},${east.toFixed(2)}|${limit}`; + const cached = POI_CACHE.get(cacheKey); + if (cached && Date.now() - cached.at < POI_CACHE_TTL_MS) return cached.value; + if (cached) POI_CACHE.delete(cacheKey); // expired — drop it before refetching + + // Overpass wants the box as (south,west,north,east) = (minLat,minLng,maxLat,maxLng). + const box = `(${south},${west},${north},${east})`; + const selectors = filters.map(f => { + const [k, v] = f.split('='); + return ` nwr["${k}"="${v}"]${box};`; + }).join('\n'); + // `out center tags ` returns ways/relations with a computed center and caps + // the result count in one round-trip. + const query = `[out:json][timeout:20];\n(\n${selectors}\n);\nout center tags ${limit + 25};`; + + const elements = await overpassFetch(query); + + const pois: OverpassPoi[] = []; + for (const el of elements) { + const tags = el.tags || {}; + const name = tags.name || tags['name:en'] || tags.brand || null; + if (!name) continue; // unnamed POIs aren't useful to add to a plan + const lat = el.lat ?? el.center?.lat; + const lng = el.lon ?? el.center?.lon; + if (lat == null || lng == null) continue; + const matched = filters.find(f => { const [k, v] = f.split('='); return tags[k] === v; }) || filters[0]; + const addr = [tags['addr:street'], tags['addr:housenumber'], tags['addr:postcode'], tags['addr:city']].filter(Boolean).join(' ') || null; + pois.push({ + osm_id: `${el.type}:${el.id}`, + name, + lat, + lng, + category, + poi_type: matched, + address: addr, + website: tags.website || tags['contact:website'] || null, + phone: tags.phone || tags['contact:phone'] || null, + opening_hours: tags.opening_hours || null, + cuisine: tags.cuisine || null, + source: 'openstreetmap', + }); + } + const truncated = pois.length > limit; + const value: PoiSearchResult = { pois: pois.slice(0, limit), source: 'openstreetmap', truncated, clamped }; + // FIFO eviction: a Map preserves insertion order, so the first key is the oldest. + if (POI_CACHE.size >= POI_CACHE_MAX) POI_CACHE.delete(POI_CACHE.keys().next().value as string); + POI_CACHE.set(cacheKey, { at: Date.now(), value }); + return value; +} + +// ── Opening hours parsing ──────────────────────────────────────────────────── + +export function parseOpeningHours(ohString: string): { weekdayDescriptions: string[]; openNow: boolean | null } { + const DAYS = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su']; + const LONG = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']; + const result: string[] = LONG.map(d => `${d}: ?`); + + // Parse segments like "Mo-Fr 09:00-18:00; Sa 10:00-14:00" + for (const segment of ohString.split(';')) { + const trimmed = segment.trim(); + if (!trimmed) continue; + const match = trimmed.match(/^((?:Mo|Tu|We|Th|Fr|Sa|Su)(?:\s*-\s*(?:Mo|Tu|We|Th|Fr|Sa|Su))?(?:\s*,\s*(?:Mo|Tu|We|Th|Fr|Sa|Su)(?:\s*-\s*(?:Mo|Tu|We|Th|Fr|Sa|Su))?)*)\s+(.+)$/i); + if (!match) continue; + const [, daysPart, timePart] = match; + const dayIndices = new Set(); + for (const range of daysPart.split(',')) { + const parts = range.trim().split('-').map(d => DAYS.indexOf(d.trim())); + if (parts.length === 2 && parts[0] >= 0 && parts[1] >= 0) { + for (let i = parts[0]; i !== (parts[1] + 1) % 7; i = (i + 1) % 7) dayIndices.add(i); + dayIndices.add(parts[1]); + } else if (parts[0] >= 0) { + dayIndices.add(parts[0]); + } + } + for (const idx of dayIndices) { + result[idx] = `${LONG[idx]}: ${timePart.trim()}`; + } + } + + // Compute openNow + let openNow: boolean | null = null; + try { + const now = new Date(); + const jsDay = now.getDay(); + const dayIdx = jsDay === 0 ? 6 : jsDay - 1; + const todayLine = result[dayIdx]; + const timeRanges = [...todayLine.matchAll(/(\d{1,2}):(\d{2})\s*-\s*(\d{1,2}):(\d{2})/g)]; + if (timeRanges.length > 0) { + const nowMins = now.getHours() * 60 + now.getMinutes(); + openNow = timeRanges.some(m => { + const start = parseInt(m[1]) * 60 + parseInt(m[2]); + const end = parseInt(m[3]) * 60 + parseInt(m[4]); + return end > start ? nowMins >= start && nowMins < end : nowMins >= start || nowMins < end; + }); + } + } catch { /* best effort */ } + + return { weekdayDescriptions: result, openNow }; +} + +// ── Build standardized OSM details ─────────────────────────────────────────── + +export function buildOsmDetails(tags: Record, osmType: string, osmId: string) { + let opening_hours: string[] | null = null; + let open_now: boolean | null = null; + if (tags.opening_hours) { + const parsed = parseOpeningHours(tags.opening_hours); + const hasData = parsed.weekdayDescriptions.some(line => !line.endsWith('?')); + if (hasData) { + opening_hours = parsed.weekdayDescriptions; + open_now = parsed.openNow; + } + } + return { + website: tags['contact:website'] || tags.website || null, + phone: tags['contact:phone'] || tags.phone || null, + opening_hours, + open_now, + osm_url: `https://www.openstreetmap.org/${osmType}/${osmId}`, + summary: tags.description || null, + source: 'openstreetmap' as const, + }; +} + +// ── Wikimedia Commons photo lookup ─────────────────────────────────────────── + +export async function fetchWikimediaPhoto(lat: number, lng: number, name?: string): Promise<{ photoUrl: string; attribution: string | null } | null> { + // Strategy 1: Search Wikipedia for the place name -> get the article image + if (name) { + try { + const searchParams = new URLSearchParams({ + action: 'query', format: 'json', + titles: name, + prop: 'pageimages', + piprop: 'thumbnail', + pithumbsize: '400', + pilimit: '1', + redirects: '1', + }); + const res = await fetch(`https://en.wikipedia.org/w/api.php?${searchParams}`, { headers: { 'User-Agent': UA } }); + if (res.ok) { + const data = await res.json() as { query?: { pages?: Record } }; + const pages = data.query?.pages; + if (pages) { + for (const page of Object.values(pages)) { + if (page.thumbnail?.source) { + return { photoUrl: page.thumbnail.source, attribution: 'Wikipedia' }; + } + } + } + } + } catch { /* fall through to geosearch */ } + } + + // Strategy 2: Wikimedia Commons geosearch by coordinates + const params = new URLSearchParams({ + action: 'query', format: 'json', + generator: 'geosearch', + ggsprimary: 'all', + ggsnamespace: '6', + ggsradius: '300', + ggscoord: `${lat}|${lng}`, + ggslimit: '5', + prop: 'imageinfo', + iiprop: 'url|extmetadata|mime', + iiurlwidth: '400', + }); + try { + const res = await fetch(`https://commons.wikimedia.org/w/api.php?${params}`, { headers: { 'User-Agent': UA } }); + if (!res.ok) return null; + const data = await res.json() as { query?: { pages?: Record } }; + const pages = data.query?.pages; + if (!pages) return null; + for (const page of Object.values(pages)) { + const info = page.imageinfo?.[0]; + // Only use actual photos (JPEG/PNG), skip SVGs and PDFs + const mime = (info as { mime?: string })?.mime || ''; + if (info?.url && (mime.startsWith('image/jpeg') || mime.startsWith('image/png'))) { + const attribution = info.extmetadata?.Artist?.value?.replace(/<[^>]+>/g, '').trim() || null; + // iiurlwidth=400 makes Commons also return a scaled thumburl. Prefer it — + // info.url is the full-resolution original (multi-megapixel camera exports). + return { photoUrl: info.thumburl ?? info.url, attribution }; + } + } + return null; + } catch { return null; } +} + +// ── Search places (Google or Nominatim fallback) ───────────────────────────── + +export async function searchPlaces(userId: number, query: string, lang?: string, locationBias?: { lat: number; lng: number; radius?: number }): Promise<{ places: Record[]; source: string }> { + const apiKey = getMapsKey(userId); + + if (!apiKey) { + const places = await searchNominatim(query, lang); + return { places, source: 'openstreetmap' }; + } + + const searchBody: Record = { textQuery: query, languageCode: toApiLang(lang) }; + // Bias results toward the caller's area when supplied — without it Google Text + // Search falls back to the API key's billing region, which skews foreign-region queries. + if (locationBias) { + searchBody.locationBias = { + circle: { + center: { latitude: locationBias.lat, longitude: locationBias.lng }, + radius: locationBias.radius ?? 50000, + }, + }; + } + + const response = await googleFetch('https://places.googleapis.com/v1/places:searchText', 'searchText', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Goog-Api-Key': apiKey, + 'X-Goog-FieldMask': 'places.id,places.displayName,places.formattedAddress,places.location,places.rating,places.websiteUri,places.nationalPhoneNumber,places.types', + }, + body: JSON.stringify(searchBody), + }); + + const data = await response.json() as { places?: GooglePlaceResult[]; error?: { message?: string } }; + + if (!response.ok) { + const err = new Error(data.error?.message || 'Google Places API error') as Error & { status: number }; + err.status = response.status; + throw err; + } + + const places = (data.places || []).map((p: GooglePlaceResult) => ({ + google_place_id: p.id, + name: p.displayName?.text || '', + address: p.formattedAddress || '', + lat: p.location?.latitude || null, + lng: p.location?.longitude || null, + rating: p.rating || null, + website: p.websiteUri || null, + phone: p.nationalPhoneNumber || null, + types: p.types || [], + source: 'google', + })); + + return { places, source: 'google' }; +} + +// ── Autocomplete (Google or Nominatim fallback) ───────────────────────────── + +export async function autocompletePlaces( + userId: number, + input: string, + lang?: string, + locationBias?: { low: { lat: number; lng: number }; high: { lat: number; lng: number } }, +): Promise<{ suggestions: { placeId: string; mainText: string; secondaryText: string }[]; source: string }> { + const apiKey = getMapsKey(userId); + + if (!apiKey) { + return autocompleteNominatim(input, lang); + } + + const body: Record = { + input, + languageCode: toApiLang(lang), + }; + if (locationBias) { + body.locationBias = { + rectangle: { + low: { latitude: locationBias.low.lat, longitude: locationBias.low.lng }, + high: { latitude: locationBias.high.lat, longitude: locationBias.high.lng }, + }, + }; + } + + const response = await googleFetch('https://places.googleapis.com/v1/places:autocomplete', 'autocomplete', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Goog-Api-Key': apiKey, + }, + body: JSON.stringify(body), + }); + + const data = await response.json() as { suggestions?: GoogleAutocompleteSuggestion[]; error?: { message?: string } }; + + if (!response.ok) { + const err = new Error(data.error?.message || 'Google Places Autocomplete error') as Error & { status: number }; + err.status = response.status; + throw err; + } + + const suggestions = (data.suggestions || []) + .filter((s) => s.placePrediction) + .slice(0, 5) + .map((s) => ({ + placeId: s.placePrediction!.placeId, + mainText: s.placePrediction!.structuredFormat?.mainText?.text || '', + secondaryText: s.placePrediction!.structuredFormat?.secondaryText?.text || '', + })); + + return { suggestions, source: 'google' }; +} + +async function autocompleteNominatim( + input: string, + lang?: string, +): Promise<{ suggestions: { placeId: string; mainText: string; secondaryText: string }[]; source: string }> { + try { + const places = await searchNominatim(input, lang); + const suggestions = places + .filter((p) => p.osm_id && p.osm_id.includes(':') && p.osm_id.split(':')[1] !== '') + .slice(0, 5) + .map((p) => { + const parts = (p.address || '').split(',').map((s) => s.trim()); + return { + placeId: p.osm_id, + mainText: p.name || parts[0] || '', + secondaryText: parts.slice(1).join(', '), + }; + }); + return { suggestions, source: 'nominatim' }; + } catch (err) { + console.error('Nominatim autocomplete failed:', err); + return { suggestions: [], source: 'nominatim' }; + } +} + +// ── Place details (Google or OSM) ──────────────────────────────────────────── + +export async function getPlaceDetails(userId: number, placeId: string, lang?: string): Promise<{ place: Record }> { + // OSM details: placeId is "node:123456" or "way:123456" etc. + if (placeId.includes(':')) { + const [osmType, osmId] = placeId.split(':'); + const element = await fetchOverpassDetails(osmType, osmId); + const details = buildOsmDetails(element?.tags || {}, osmType, osmId); + + // Fetch Nominatim only when Overpass lacks coordinates or address + const d = details as Record; + const needsNominatim = !d.lat || !d.lng || !d.address; + const nominatim = needsNominatim ? await lookupNominatim(osmType, osmId, lang) : null; + + return { + place: { + ...details, + name: (d.name as string) || nominatim?.name || element?.tags?.name || '', + address: (d.address as string) || nominatim?.address || '', + lat: d.lat ?? nominatim?.lat ?? null, + lng: d.lng ?? nominatim?.lng ?? null, + osm_id: placeId, + }, + }; + } + + // Google details + const langKey = toApiLang(lang, 'de'); + const apiKey = getMapsKey(userId); + if (!apiKey) { + throw Object.assign(new Error('Google Maps API key not configured'), { status: 400 }); + } + + // Check DB cache first (lean mask, expanded=0) — 7-day TTL + const DETAILS_TTL = 7 * 24 * 60 * 60 * 1000; + const cached = db.prepare( + 'SELECT payload_json, fetched_at FROM place_details_cache WHERE place_id = ? AND lang = ? AND expanded = 0' + ).get(placeId, langKey) as { payload_json: string; fetched_at: number } | undefined; + if (cached && Date.now() - cached.fetched_at < DETAILS_TTL) return { place: JSON.parse(cached.payload_json) }; + + const response = await googleFetch(`https://places.googleapis.com/v1/places/${placeId}?languageCode=${langKey}`, `getPlaceDetails(${placeId})`, { + method: 'GET', + headers: { + 'X-Goog-Api-Key': apiKey, + 'X-Goog-FieldMask': 'id,displayName,formattedAddress,location,rating,userRatingCount,websiteUri,nationalPhoneNumber,regularOpeningHours,googleMapsUri', + }, + }); + + const data = await response.json() as GooglePlaceDetails & { error?: { message?: string } }; + + if (!response.ok) { + const err = new Error(data.error?.message || 'Google Places API error') as Error & { status: number }; + err.status = response.status; + throw err; + } + + const place = { + google_place_id: data.id, + name: data.displayName?.text || '', + address: data.formattedAddress || '', + lat: data.location?.latitude || null, + lng: data.location?.longitude || null, + rating: data.rating || null, + rating_count: data.userRatingCount || null, + website: data.websiteUri || null, + phone: data.nationalPhoneNumber || null, + opening_hours: data.regularOpeningHours?.weekdayDescriptions || null, + open_now: data.regularOpeningHours?.openNow ?? null, + google_maps_url: data.googleMapsUri || null, + summary: null, + reviews: [], + source: 'google' as const, + cached_at: Date.now(), + }; + + try { + db.prepare( + 'INSERT OR REPLACE INTO place_details_cache (place_id, lang, expanded, payload_json, fetched_at) VALUES (?, ?, 0, ?, ?)' + ).run(placeId, langKey, JSON.stringify(place), Date.now()); + } catch (dbErr) { + console.error('Failed to cache place details:', dbErr); + } + + return { place }; +} + +export async function getPlaceDetailsExpanded(userId: number, placeId: string, lang?: string, refresh = false): Promise<{ place: Record }> { + const langKey = toApiLang(lang, 'de'); + const apiKey = getMapsKey(userId); + if (!apiKey) throw Object.assign(new Error('Google Maps API key not configured'), { status: 400 }); + + // Check DB cache for expanded result + if (!refresh) { + const cached = db.prepare( + 'SELECT payload_json FROM place_details_cache WHERE place_id = ? AND lang = ? AND expanded = 1' + ).get(placeId, langKey) as { payload_json: string } | undefined; + if (cached) return { place: JSON.parse(cached.payload_json) }; + } + + const response = await googleFetch(`https://places.googleapis.com/v1/places/${placeId}?languageCode=${langKey}`, `getPlaceDetailsExpanded(${placeId})`, { + method: 'GET', + headers: { + 'X-Goog-Api-Key': apiKey, + 'X-Goog-FieldMask': 'id,displayName,formattedAddress,location,rating,userRatingCount,websiteUri,nationalPhoneNumber,regularOpeningHours,googleMapsUri,reviews,editorialSummary', + }, + }); + + const data = await response.json() as GooglePlaceDetails & { error?: { message?: string } }; + + if (!response.ok) { + const err = new Error(data.error?.message || 'Google Places API error') as Error & { status: number }; + err.status = response.status; + throw err; + } + + const place = { + google_place_id: data.id, + name: data.displayName?.text || '', + address: data.formattedAddress || '', + lat: data.location?.latitude || null, + lng: data.location?.longitude || null, + rating: data.rating || null, + rating_count: data.userRatingCount || null, + website: data.websiteUri || null, + phone: data.nationalPhoneNumber || null, + opening_hours: data.regularOpeningHours?.weekdayDescriptions || null, + open_now: data.regularOpeningHours?.openNow ?? null, + google_maps_url: data.googleMapsUri || null, + summary: data.editorialSummary?.text || null, + reviews: (data.reviews || []).slice(0, 5).map((r: NonNullable[number]) => ({ + author: r.authorAttribution?.displayName || null, + rating: r.rating || null, + text: r.text?.text || null, + time: r.relativePublishTimeDescription || null, + photo: r.authorAttribution?.photoUri || null, + })), + source: 'google' as const, + cached_at: Date.now(), + }; + + try { + db.prepare( + 'INSERT OR REPLACE INTO place_details_cache (place_id, lang, expanded, payload_json, fetched_at) VALUES (?, ?, 1, ?, ?)' + ).run(placeId, langKey, JSON.stringify(place), Date.now()); + } catch (dbErr) { + console.error('Failed to cache expanded place details:', dbErr); + } + + return { place }; +} + +// ── Place photo (Google or Wikimedia, disk-cached) ──────────────────────────── + +export async function getPlacePhoto( + userId: number, + placeId: string, + lat: number, + lng: number, + name?: string, +): Promise<{ photoUrl: string; attribution: string | null }> { + // Disk cache hit — serve immediately, no Google call + const diskHit = placePhotoCache.get(placeId); + if (diskHit) return { photoUrl: diskHit.photoUrl, attribution: diskHit.attribution }; + + // Recent error — don't hammer the API + if (placePhotoCache.getErrored(placeId)) { + throw Object.assign(new Error('(Cache) No photo available'), { status: 404 }); + } + + // Deduplicate concurrent requests for the same placeId + const existing = placePhotoCache.getInFlight(placeId); + if (existing) { + const result = await existing; + if (!result) throw Object.assign(new Error('(Cache) No photo available'), { status: 404 }); + return { photoUrl: `/api/maps/place-photo/${encodeURIComponent(placeId)}/bytes`, attribution: result.attribution }; + } + + const fetchPromise = (async (): Promise<{ filePath: string; attribution: string | null } | null> => { + await acquirePhotoFetchSlot(); + try { + const apiKey = getMapsKey(userId); + const isCoordLookup = placeId.startsWith('coords:'); + + // Coordinate-based Wikipedia/Wikimedia lookup. Used for coordinate-only + // (right-click) places and as a fallback when a Google place yields no photo, + // so a place added via search still gets a marker image when Google returns + // nothing. Returns null (without marking an error) so the caller decides. + const fetchWikimediaFallback = async (): Promise<{ filePath: string; attribution: string | null } | null> => { + if (isNaN(lat) || isNaN(lng)) return null; + try { + const wiki = await fetchWikimediaPhoto(lat, lng, name); + if (!wiki) return null; + // Follow redirects manually so each hop (the image URL can 3xx to a CDN + // host) is re-validated against the SSRF guard, not just the first URL. + const imgRes = await safeFetchFollow(wiki.photoUrl, undefined, { bypassInternalIpAllowed: true }); + if (!imgRes.ok) return null; + const bytes = Buffer.from(await imgRes.arrayBuffer()); + const cached = await placePhotoCache.put(placeId, bytes, wiki.attribution); + return { filePath: cached.filePath, attribution: cached.attribution }; + } catch { + return null; + } + }; + + // Google Places photo for a Google place_id. Returns null (without marking an + // error) on any miss — no key, URL-shaped id, request rejected, no photos, or + // a failed media download — so the caller can fall back to Wikimedia. + const fetchGooglePhoto = async (): Promise<{ filePath: string; attribution: string | null } | null> => { + // URL-shaped placeIds aren't Google IDs — legacy DBs may store raw photo URLs in image_url + if (!apiKey || /^https?:\/\//i.test(placeId)) return null; + + // Fetch details to get the photo name + const detailsRes = await googleFetch(`https://places.googleapis.com/v1/places/${placeId}`, `getPlacePhoto/details(${placeId})`, { + headers: { + 'X-Goog-Api-Key': apiKey, + 'X-Goog-FieldMask': 'photos', + }, + }); + const body = await detailsRes.text(); + if (!detailsRes.ok) { + console.error('Google Places photo details error:', detailsRes.status, body.slice(0, 200)); + return null; + } + let details: GooglePlaceDetails & { error?: { message?: string } }; + try { details = body ? JSON.parse(body) : { photos: [] }; } + catch { return null; } + if (!details.photos?.length) return null; + + const photo = details.photos[0]; + const photoName = photo.name; + const attribution = photo.authorAttributions?.[0]?.displayName || null; + + // Fetch actual image bytes + const mediaRes = await googleFetch( + `https://places.googleapis.com/v1/${photoName}/media?maxHeightPx=400`, + `getPlacePhoto/media(${placeId})`, + { headers: { 'X-Goog-Api-Key': apiKey } } + ); + if (!mediaRes.ok) return null; + + const bytes = Buffer.from(await mediaRes.arrayBuffer()); + if (!bytes.length) return null; + + const cached = await placePhotoCache.put(placeId, bytes, attribution); + + // Persist stable proxy URL to database + try { + db.prepare( + 'UPDATE places SET image_url = ?, updated_at = CURRENT_TIMESTAMP WHERE google_place_id = ? AND (image_url IS NULL OR image_url = \'\')' + ).run(cached.photoUrl, placeId); + } catch (dbErr) { + console.error('Failed to persist photo URL to database:', dbErr); + } + + return { filePath: cached.filePath, attribution }; + }; + + // Prefer the Google photo (higher quality); if Google yields nothing, fall + // back to the same coordinate-based Wikipedia/OSM lookup that right-click + // places use. Coordinate-only ids skip Google entirely. + if (!isCoordLookup) { + const googlePhoto = await fetchGooglePhoto(); + if (googlePhoto) return googlePhoto; + } + + const fallback = await fetchWikimediaFallback(); + if (fallback) return fallback; + + placePhotoCache.markError(placeId); + return null; + } finally { + releasePhotoFetchSlot(); + } + })(); + + placePhotoCache.setInFlight(placeId, fetchPromise); + + const result = await fetchPromise; + if (!result) throw Object.assign(new Error('No photo available'), { status: 404 }); + return { photoUrl: `/api/maps/place-photo/${encodeURIComponent(placeId)}/bytes`, attribution: result.attribution }; +} + +// ── Reverse geocoding ──────────────────────────────────────────────────────── + +export async function reverseGeocode(lat: string, lng: string, lang?: string): Promise<{ name: string | null; address: string | null }> { + const params = new URLSearchParams({ + lat, lon: lng, format: 'json', addressdetails: '1', zoom: '18', + 'accept-language': toApiLang(lang), + }); + const response = await fetch(`https://nominatim.openstreetmap.org/reverse?${params}`, { + headers: { 'User-Agent': UA }, + }); + if (!response.ok) return { name: null, address: null }; + const data = await response.json() as { name?: string; display_name?: string; address?: Record }; + const addr = data.address || {}; + const name = data.name || addr.tourism || addr.amenity || addr.shop || addr.building || addr.road || null; + return { name, address: data.display_name || null }; +} + +// ── Resolve Google Maps URL ────────────────────────────────────────────────── + +export async function resolveGoogleMapsUrl(url: string): Promise<{ lat: number; lng: number; name: string | null; address: string | null }> { + let resolvedUrl = url; + + // Follow redirects for short URLs (goo.gl, maps.app.goo.gl) with SSRF protection. + // Redirects are followed manually so every hop is re-checked — a short link + // that 302s to an internal IP is blocked, while a legitimate cross-host + // redirect (goo.gl → maps.google.com) still resolves. + const parsed = new URL(url); + if (['goo.gl', 'maps.app.goo.gl'].includes(parsed.hostname)) { + try { + const redirectRes = await safeFetchFollow( + url, + { signal: AbortSignal.timeout(10000) }, + { bypassInternalIpAllowed: true }, + ); + resolvedUrl = redirectRes.url; + } catch (err) { + if (err instanceof SsrfBlockedError) { + throw Object.assign(new Error('URL blocked by SSRF check'), { status: 403 }); + } + throw err; + } + } + + // Extract coordinates from Google Maps URL patterns: + // /@48.8566,2.3522,15z or /place/.../@48.8566,2.3522 + // ?q=48.8566,2.3522 or ?ll=48.8566,2.3522 + let lat: number | null = null; + let lng: number | null = null; + let placeName: string | null = null; + + // Pattern: /@lat,lng + const atMatch = resolvedUrl.match(/@(-?\d+\.?\d*),(-?\d+\.?\d*)/); + if (atMatch) { lat = parseFloat(atMatch[1]); lng = parseFloat(atMatch[2]); } + + // Pattern: !3dlat!4dlng (Google Maps data params) + if (!lat) { + const dataMatch = resolvedUrl.match(/!3d(-?\d+\.?\d*)!4d(-?\d+\.?\d*)/); + if (dataMatch) { lat = parseFloat(dataMatch[1]); lng = parseFloat(dataMatch[2]); } + } + + // Pattern: ?q=lat,lng or &q=lat,lng + if (!lat) { + const qMatch = resolvedUrl.match(/[?&]q=(-?\d+\.?\d*),(-?\d+\.?\d*)/); + if (qMatch) { lat = parseFloat(qMatch[1]); lng = parseFloat(qMatch[2]); } + } + + // Extract place name from URL path: /place/Place+Name/@... + const placeMatch = resolvedUrl.match(/\/place\/([^/@]+)/); + if (placeMatch) { + placeName = decodeURIComponent(placeMatch[1].replace(/\+/g, ' ')); + } + + if (!lat || !lng || isNaN(lat) || isNaN(lng)) { + throw Object.assign(new Error('Could not extract coordinates from URL'), { status: 400 }); + } + + // Reverse geocode to get address + const nominatimRes = await fetch( + `https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lng}&format=json&addressdetails=1`, + { headers: { 'User-Agent': 'TREK-Travel-Planner/1.0' }, signal: AbortSignal.timeout(8000) } + ); + const nominatim = await nominatimRes.json() as { display_name?: string; name?: string; address?: Record }; + + const name = placeName || nominatim.name || nominatim.address?.tourism || nominatim.address?.building || null; + const address = nominatim.display_name || null; + + return { lat, lng, name, address }; +} diff --git a/server/src/services/memories/helpersService.ts b/server/src/services/memories/helpersService.ts new file mode 100644 index 0000000000000000000000000000000000000000..7720feb1f3c240e5644482ea9f13e8a35cfb6a2f --- /dev/null +++ b/server/src/services/memories/helpersService.ts @@ -0,0 +1,286 @@ +import { pipeline } from 'node:stream/promises'; +import { Readable } from 'node:stream'; +import { Response } from 'express'; +import { canAccessTrip, db } from "../../db/database"; +import { safeFetch, SsrfBlockedError } from '../../utils/ssrfGuard'; +import { decrypt_api_key } from '../apiKeyCrypto'; + +// helpers for handling return types + +type ServiceError = { success: false; error: { message: string; status: number } }; +export type ServiceResult = { success: true; data: T } | ServiceError; + + +export function fail(error: string, status: number): ServiceError { + return { success: false, error: { message: error, status } }; +} + + +export function success(data: T): ServiceResult { + return { success: true, data: data }; +} + + +export function mapDbError(error: Error, fallbackMessage: string): ServiceError { + if (error && /unique|constraint/i.test(error.message)) { + return fail('Resource already exists', 409); + } + return fail(error.message, 500); +} + + +export function handleServiceResult(res: Response, result: ServiceResult): void { + if ('error' in result) { + res.status(result.error.status).json({ error: result.error.message }); + } + else { + res.json(result.data); + } +} + +// ---------------------------------------------- +// types used across memories services +export type Selection = { + provider: string; + asset_ids: string[]; + passphrase?: string; +}; + +export type StatusResult = { + connected: true; + user: { name: string } +} | { + connected: false; + error: string +}; + +export type SyncAlbumResult = { + added: number; + total: number +}; + + +export type AlbumsList = { + albums: Array<{ id: string; albumName: string; assetCount: number; passphrase?: string }> +}; + +export type Asset = { + id: string; + takenAt: string; +}; + +export type AssetsList = { + assets: Asset[], + total: number, + hasMore: boolean +}; + + +export type AssetInfo = { + id: string; + takenAt: string | null; + city: string | null; + country: string | null; + state?: string | null; + camera?: string | null; + lens?: string | null; + focalLength?: string | number | null; + aperture?: string | number | null; + shutter?: string | number | null; + iso?: string | number | null; + lat?: number | null; + lng?: number | null; + orientation?: number | null; + description?: string | null; + width?: number | null; + height?: number | null; + fileSize?: number | null; + fileName?: string | null; +} + + +//for loading routes to settings page, and validating which services user has connected +type PhotoProviderConfig = { + settings_get: string; + settings_put: string; + status_get: string; + test_post: string; +}; + + +export function getPhotoProviderConfig(providerId: string): PhotoProviderConfig { + const prefix = `/integrations/memories/${providerId}`; + return { + settings_get: `${prefix}/settings`, + settings_put: `${prefix}/settings`, + status_get: `${prefix}/status`, + test_post: `${prefix}/test`, + }; +} + +//----------------------------------------------- +//access check helper + +export function canAccessUserPhoto(requestingUserId: number, ownerUserId: number, tripId: string, assetId: string, provider: string): boolean { + if (requestingUserId === ownerUserId) { + return true; + } + + // Journey photos use tripId=0 — check journey_photos + journey_contributors + if (tripId === '0') { + const journeyPhoto = db.prepare(` + SELECT gp.journey_id + FROM journey_photos gp + JOIN trek_photos tkp ON tkp.id = gp.photo_id + WHERE tkp.asset_id = ? + AND tkp.provider = ? + AND tkp.owner_id = ? + LIMIT 1 + `).get(assetId, provider, ownerUserId) as { journey_id: number } | undefined; + if (!journeyPhoto) return false; + + const access = db.prepare(` + SELECT 1 FROM journeys WHERE id = ? AND user_id = ? + UNION ALL + SELECT 1 FROM journey_contributors WHERE journey_id = ? AND user_id = ? + LIMIT 1 + `).get(journeyPhoto.journey_id, requestingUserId, journeyPhoto.journey_id, requestingUserId); + return !!access; + } + + // Regular trip photos — join through trek_photos + const sharedAsset = db.prepare(` + SELECT 1 + FROM trip_photos tp + JOIN trek_photos tkp ON tkp.id = tp.photo_id + WHERE tp.user_id = ? + AND tkp.asset_id = ? + AND tkp.provider = ? + AND tp.trip_id = ? + AND tp.shared = 1 + LIMIT 1 + `).get(ownerUserId, assetId, provider, tripId); + + if (!sharedAsset) { + return false; + } + return !!canAccessTrip(tripId, requestingUserId); +} + + +// ── Unified photo access check (trek_photos based) ────────────────────── + +export function canAccessTrekPhoto(requestingUserId: number, trekPhotoId: number): boolean { + const photo = db.prepare('SELECT * FROM trek_photos WHERE id = ?').get(trekPhotoId) as { id: number; provider: string; owner_id: number | null } | undefined; + if (!photo) return false; + + // Owner always has access + if (photo.owner_id === requestingUserId) return true; + + // Check trip_photos — is this photo shared in a trip the user has access to? + const tripAccess = db.prepare(` + SELECT 1 FROM trip_photos tp + WHERE tp.photo_id = ? + AND tp.shared = 1 + AND EXISTS ( + SELECT 1 FROM trip_members tm WHERE tm.trip_id = tp.trip_id AND tm.user_id = ? + UNION ALL + SELECT 1 FROM trips t WHERE t.id = tp.trip_id AND t.user_id = ? + ) + LIMIT 1 + `).get(trekPhotoId, requestingUserId, requestingUserId); + if (tripAccess) return true; + + // Check journey_photos — is this photo in a journey the user can access? + const journeyAccess = db.prepare(` + SELECT 1 FROM journey_photos gp + WHERE gp.photo_id = ? + AND EXISTS ( + SELECT 1 FROM journeys j WHERE j.id = gp.journey_id AND j.user_id = ? + UNION ALL + SELECT 1 FROM journey_contributors jc WHERE jc.journey_id = gp.journey_id AND jc.user_id = ? + ) + LIMIT 1 + `).get(trekPhotoId, requestingUserId, requestingUserId); + if (journeyAccess) return true; + + // Local photos without owner (uploaded files) — check if user has journey access + if (photo.provider === 'local' && !photo.owner_id) { + return !!journeyAccess; + } + + return false; +} + + +// ---------------------------------------------- +//helpers for album link syncing + +export function getAlbumIdFromLink(tripId: string, linkId: string, userId: number): ServiceResult { + const access = canAccessTrip(tripId, userId); + if (!access) return fail('Trip not found or access denied', 404); + + try { + const row = db.prepare('SELECT album_id FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ?') + .get(linkId, tripId, userId) as { album_id: string } | null; + + return row ? success(row.album_id) : fail('Album link not found', 404); + } catch { + return fail('Failed to retrieve album link', 500); + } +} + +export function getAlbumLinkForSync(tripId: string, linkId: string, userId: number): ServiceResult<{ albumId: string; passphrase?: string }> { + const access = canAccessTrip(tripId, userId); + if (!access) return fail('Trip not found or access denied', 404); + + try { + const row = db.prepare('SELECT album_id, passphrase FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ?') + .get(linkId, tripId, userId) as { album_id: string; passphrase: string | null } | null; + + if (!row) return fail('Album link not found', 404); + + const decrypted = row.passphrase ? decrypt_api_key(row.passphrase) ?? undefined : undefined; + return success({ albumId: row.album_id, passphrase: decrypted || undefined }); + } catch { + return fail('Failed to retrieve album link', 500); + } +} + +export function updateSyncTimeForAlbumLink(linkId: string): void { + db.prepare('UPDATE trip_album_links SET last_synced_at = CURRENT_TIMESTAMP WHERE id = ?').run(linkId); +} + +export async function pipeAsset(url: string, response: Response, headers?: Record, signal?: AbortSignal, defaultCacheControl?: string): Promise { + try { + const resp = await safeFetch(url, { headers, signal: signal as any }); + + response.status(resp.status); + if (resp.headers.get('content-type')) response.set('Content-Type', resp.headers.get('content-type') as string); + if (!resp.ok) { + response.set('Cache-Control', 'no-store, max-age=0'); + } else if (resp.headers.get('cache-control')) { + response.set('Cache-Control', resp.headers.get('cache-control') as string); + } else if (defaultCacheControl) { + response.set('Cache-Control', defaultCacheControl); + } + if (resp.headers.get('content-length')) response.set('Content-Length', resp.headers.get('content-length') as string); + if (resp.headers.get('content-disposition')) response.set('Content-Disposition', resp.headers.get('content-disposition') as string); + + if (!resp.body) { + response.end(); + } else { + await pipeline(Readable.fromWeb(resp.body as any), response); + } + } catch (error) { + if (response.headersSent) { + response.end(); + return; + } + if (error instanceof SsrfBlockedError) { + response.status(400).json({ error: error.message }); + } else { + response.status(500).json({ error: 'Failed to fetch asset' }); + } + } +} \ No newline at end of file diff --git a/server/src/services/memories/immichService.ts b/server/src/services/memories/immichService.ts new file mode 100644 index 0000000000000000000000000000000000000000..863f394bff79acffbdf56527e8ded110b8c2bf20 --- /dev/null +++ b/server/src/services/memories/immichService.ts @@ -0,0 +1,447 @@ +import { Response } from 'express'; +import { db } from '../../db/database'; +import { maybe_encrypt_api_key, decrypt_api_key } from '../apiKeyCrypto'; +import { checkSsrf, safeFetch } from '../../utils/ssrfGuard'; +import { writeAudit } from '../auditLog'; +import { addTripPhotos} from './unifiedService'; +import { getAlbumIdFromLink, updateSyncTimeForAlbumLink, Selection, pipeAsset } from './helpersService'; + +// ── Credentials ──────────────────────────────────────────────────────────── + +export function getImmichCredentials(userId: number) { + const user = db.prepare('SELECT immich_url, immich_api_key FROM users WHERE id = ?').get(userId) as any; + if (!user?.immich_url || !user?.immich_api_key) return null; + const apiKey = decrypt_api_key(user.immich_api_key); + if (!apiKey) return null; + return { immich_url: user.immich_url as string, immich_api_key: apiKey }; +} + +/** Validate that an asset ID is a safe UUID-like string (no path traversal). */ +export function isValidAssetId(id: string): boolean { + return /^[a-zA-Z0-9_-]+$/.test(id) && id.length <= 100; +} + +// ── Connection Settings ──────────────────────────────────────────────────── + +export function getConnectionSettings(userId: number) { + const creds = getImmichCredentials(userId); + const prefs = db.prepare('SELECT immich_auto_upload FROM users WHERE id = ?').get(userId) as { immich_auto_upload?: number } | undefined; + return { + immich_url: creds?.immich_url || '', + connected: !!(creds?.immich_url && creds?.immich_api_key), + auto_upload: !!(prefs?.immich_auto_upload), + }; +} + +export function setImmichAutoUpload(userId: number, enabled: boolean): void { + db.prepare('UPDATE users SET immich_auto_upload = ? WHERE id = ?').run(enabled ? 1 : 0, userId); +} + +export async function saveImmichSettings( + userId: number, + immichUrl: string | undefined, + immichApiKey: string | undefined, + clientIp: string | null +): Promise<{ success: boolean; warning?: string; error?: string }> { + if (immichUrl) { + const ssrf = await checkSsrf(immichUrl.trim()); + if (!ssrf.allowed) { + return { success: false, error: `Invalid Immich URL: ${ssrf.error}` }; + } + db.prepare('UPDATE users SET immich_url = ?, immich_api_key = ? WHERE id = ?').run( + immichUrl.trim(), + maybe_encrypt_api_key(immichApiKey), + userId + ); + if (ssrf.isPrivate) { + writeAudit({ + userId, + action: 'immich.private_ip_configured', + ip: clientIp, + details: { immich_url: immichUrl.trim(), resolved_ip: ssrf.resolvedIp }, + }); + return { + success: true, + warning: `Immich URL resolves to a private IP address (${ssrf.resolvedIp}). Make sure this is intentional.`, + }; + } + } else { + db.prepare('UPDATE users SET immich_url = ?, immich_api_key = ? WHERE id = ?').run( + null, + maybe_encrypt_api_key(immichApiKey), + userId + ); + } + return { success: true }; +} + +// ── Connection Test / Status ─────────────────────────────────────────────── + +export async function testConnection( + immichUrl: string, + immichApiKey: string +): Promise<{ connected: boolean; error?: string; user?: { name?: string; email?: string }; canonicalUrl?: string }> { + const ssrf = await checkSsrf(immichUrl); + if (!ssrf.allowed) return { connected: false, error: ssrf.error ?? 'Invalid Immich URL' }; + try { + const resp = await safeFetch(`${immichUrl}/api/users/me`, { + headers: { 'x-api-key': immichApiKey, 'Accept': 'application/json' }, + signal: AbortSignal.timeout(10000) as any, + }); + if (!resp.ok) return { connected: false, error: `HTTP ${resp.status}` }; + const data = await resp.json() as { name?: string; email?: string }; + + // Detect http → https upgrade only: same host/port, protocol changed to https + let canonicalUrl: string | undefined; + if (resp.url) { + const finalUrl = new URL(resp.url); + const inputUrl = new URL(immichUrl); + if ( + inputUrl.protocol === 'http:' && + finalUrl.protocol === 'https:' && + finalUrl.hostname === inputUrl.hostname && + finalUrl.port === inputUrl.port + ) { + canonicalUrl = finalUrl.origin; + } + } + + return { connected: true, user: { name: data.name, email: data.email }, canonicalUrl }; + } catch (err: unknown) { + return { connected: false, error: err instanceof Error ? err.message : 'Connection failed' }; + } +} + +export async function getConnectionStatus( + userId: number +): Promise<{ connected: boolean; error?: string; user?: { name?: string; email?: string } }> { + const creds = getImmichCredentials(userId); + if (!creds) return { connected: false, error: 'Not configured' }; + try { + const resp = await safeFetch(`${creds.immich_url}/api/users/me`, { + headers: { 'x-api-key': creds.immich_api_key, 'Accept': 'application/json' }, + signal: AbortSignal.timeout(10000) as any, + }); + if (!resp.ok) return { connected: false, error: `HTTP ${resp.status}` }; + const data = await resp.json() as { name?: string; email?: string }; + return { connected: true, user: { name: data.name, email: data.email } }; + } catch (err: unknown) { + return { connected: false, error: err instanceof Error ? err.message : 'Connection failed' }; + } +} + +// ── Browse Timeline / Search ─────────────────────────────────────────────── + +export async function browseTimeline( + userId: number +): Promise<{ buckets?: any; error?: string; status?: number }> { + const creds = getImmichCredentials(userId); + if (!creds) return { error: 'Immich not configured', status: 400 }; + + try { + const resp = await safeFetch(`${creds.immich_url}/api/timeline/buckets`, { + method: 'GET', + headers: { 'x-api-key': creds.immich_api_key, 'Accept': 'application/json' }, + signal: AbortSignal.timeout(15000) as any, + }); + if (!resp.ok) return { error: 'Failed to fetch from Immich', status: resp.status }; + const buckets = await resp.json(); + return { buckets }; + } catch { + return { error: 'Could not reach Immich', status: 502 }; + } +} + +export async function searchPhotos( + userId: number, + from?: string, + to?: string, + page: number = 1, + size: number = 50, +): Promise<{ assets?: any[]; hasMore?: boolean; error?: string; status?: number }> { + const creds = getImmichCredentials(userId); + if (!creds) return { error: 'Immich not configured', status: 400 }; + + try { + const resp = await safeFetch(`${creds.immich_url}/api/search/metadata`, { + method: 'POST', + headers: { 'x-api-key': creds.immich_api_key, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + takenAfter: from ? `${from}T00:00:00.000Z` : undefined, + takenBefore: to ? `${to}T23:59:59.999Z` : undefined, + type: 'IMAGE', + size, + page, + }), + signal: AbortSignal.timeout(15000) as any, + }); + if (!resp.ok) return { error: 'Search failed', status: resp.status }; + const data = await resp.json() as { assets?: { items?: any[] } }; + const items = data.assets?.items || []; + const assets = items.map((a: any) => ({ + id: a.id, + takenAt: a.fileCreatedAt || a.createdAt, + city: a.exifInfo?.city || null, + country: a.exifInfo?.country || null, + })); + return { assets, hasMore: items.length >= size }; + } catch { + return { error: 'Could not reach Immich', status: 502 }; + } +} + + +// ── Asset Info / Proxy ───────────────────────────────────────────────────── + + +export async function getAssetInfo( + userId: number, + assetId: string, + ownerUserId?: number +): Promise<{ data?: any; error?: string; status?: number }> { + const effectiveUserId = ownerUserId ?? userId; + const creds = getImmichCredentials(effectiveUserId); + if (!creds) return { error: 'Not found', status: 404 }; + + try { + const resp = await safeFetch(`${creds.immich_url}/api/assets/${assetId}`, { + headers: { 'x-api-key': creds.immich_api_key, 'Accept': 'application/json' }, + signal: AbortSignal.timeout(10000) as any, + }); + if (!resp.ok) return { error: 'Failed', status: resp.status }; + const asset = await resp.json() as any; + return { + data: { + id: asset.id, + takenAt: asset.fileCreatedAt || asset.createdAt, + width: asset.exifInfo?.exifImageWidth || null, + height: asset.exifInfo?.exifImageHeight || null, + camera: asset.exifInfo?.make && asset.exifInfo?.model ? `${asset.exifInfo.make} ${asset.exifInfo.model}` : null, + lens: asset.exifInfo?.lensModel || null, + focalLength: asset.exifInfo?.focalLength ? `${asset.exifInfo.focalLength}mm` : null, + aperture: asset.exifInfo?.fNumber ? `f/${asset.exifInfo.fNumber}` : null, + shutter: asset.exifInfo?.exposureTime || null, + iso: asset.exifInfo?.iso || null, + city: asset.exifInfo?.city || null, + state: asset.exifInfo?.state || null, + country: asset.exifInfo?.country || null, + lat: asset.exifInfo?.latitude || null, + lng: asset.exifInfo?.longitude || null, + fileSize: asset.exifInfo?.fileSizeInByte || null, + fileName: asset.originalFileName || null, + }, + }; + } catch { + return { error: 'Proxy error', status: 502 }; + } +} + +export async function fetchImmichThumbnailBytes( + userId: number, + assetId: string, + ownerUserId?: number +): Promise<{ bytes: Buffer; contentType: string } | { error: string; status: number }> { + const effectiveUserId = ownerUserId ?? userId; + const creds = getImmichCredentials(effectiveUserId); + if (!creds) return { error: 'Not found', status: 404 }; + + const url = `${creds.immich_url}/api/assets/${assetId}/thumbnail?size=thumbnail`; + try { + const resp = await safeFetch(url, { + headers: { 'x-api-key': creds.immich_api_key }, + signal: AbortSignal.timeout(10000) as any, + }); + if (!resp.ok) return { error: 'Upstream error', status: resp.status }; + const contentType = resp.headers.get('content-type') || 'image/jpeg'; + const bytes = Buffer.from(await resp.arrayBuffer()); + return { bytes, contentType }; + } catch { + return { error: 'Proxy error', status: 502 }; + } +} + +export async function streamImmichAsset( + response: Response, + userId: number, + assetId: string, + kind: 'thumbnail' | 'original', + ownerUserId?: number +): Promise<{ error?: string; status?: number } | void> { + const effectiveUserId = ownerUserId ?? userId; + const creds = getImmichCredentials(effectiveUserId); + if (!creds) return { error: 'Not found', status: 404 }; + + const timeout = kind === 'thumbnail' ? 10000 : 30000; + const url = kind === 'thumbnail' + ? `${creds.immich_url}/api/assets/${assetId}/thumbnail?size=thumbnail` + : `${creds.immich_url}/api/assets/${assetId}/thumbnail?size=fullsize`; + + await pipeAsset(url, response, { 'x-api-key': creds.immich_api_key }, AbortSignal.timeout(timeout), 'public, max-age=86400'); +} + +// ── Albums ────────────────────────────────────────────────────────────────── + +export async function listAlbums( + userId: number +): Promise<{ albums?: any[]; error?: string; status?: number }> { + const creds = getImmichCredentials(userId); + if (!creds) return { error: 'Immich not configured', status: 400 }; + + try { + // Fetch both owned and shared albums + const [ownResp, sharedResp] = await Promise.all([ + safeFetch(`${creds.immich_url}/api/albums`, { + headers: { 'x-api-key': creds.immich_api_key, 'Accept': 'application/json' }, + signal: AbortSignal.timeout(10000) as any, + }), + safeFetch(`${creds.immich_url}/api/albums?shared=true`, { + headers: { 'x-api-key': creds.immich_api_key, 'Accept': 'application/json' }, + signal: AbortSignal.timeout(10000) as any, + }), + ]); + if (!ownResp.ok) return { error: 'Failed to fetch albums', status: ownResp.status }; + const ownAlbums = await ownResp.json() as any[]; + const sharedAlbums = sharedResp.ok ? await sharedResp.json() as any[] : []; + const seenIds = new Set(); + const allAlbums = [...ownAlbums, ...sharedAlbums].filter((a: any) => { + if (seenIds.has(a.id)) return false; + seenIds.add(a.id); + return true; + }); + const albums = allAlbums.map((a: any) => ({ + id: a.id, + albumName: a.albumName, + assetCount: a.assetCount || 0, + startDate: a.startDate, + endDate: a.endDate, + albumThumbnailAssetId: a.albumThumbnailAssetId, + shared: a.shared || a.sharedUsers?.length > 0, + })); + return { albums }; + } catch { + return { error: 'Could not reach Immich', status: 502 }; + } +} + +export async function getAlbumPhotos( + userId: number, + albumId: string, +): Promise<{ assets?: any[]; error?: string; status?: number }> { + const creds = getImmichCredentials(userId); + if (!creds) return { error: 'Immich not configured', status: 400 }; + + try { + const resp = await safeFetch(`${creds.immich_url}/api/albums/${albumId}`, { + headers: { 'x-api-key': creds.immich_api_key, 'Accept': 'application/json' }, + signal: AbortSignal.timeout(15000) as any, + }); + if (!resp.ok) return { error: 'Failed to fetch album', status: resp.status }; + const albumData = await resp.json() as { assets?: any[] }; + const assets = (albumData.assets || []).filter((a: any) => a.type === 'IMAGE').map((a: any) => ({ + id: a.id, + takenAt: a.fileCreatedAt || a.createdAt, + city: a.exifInfo?.city || null, + country: a.exifInfo?.country || null, + })); + return { assets }; + } catch { + return { error: 'Could not reach Immich', status: 502 }; + } +} + +export async function syncAlbumAssets( + tripId: string, + linkId: string, + userId: number, + sid: string, +): Promise<{ success?: boolean; added?: number; total?: number; error?: string; status?: number }> { + const response = getAlbumIdFromLink(tripId, linkId, userId); + if (!response.success) return { error: 'Album link not found', status: 404 }; + + const creds = getImmichCredentials(userId); + if (!creds) return { error: 'Immich not configured', status: 400 }; + + try { + const resp = await safeFetch(`${creds.immich_url}/api/albums/${response.data}`, { + headers: { 'x-api-key': creds.immich_api_key, 'Accept': 'application/json' }, + signal: AbortSignal.timeout(15000) as any, + }); + if (!resp.ok) return { error: 'Failed to fetch album', status: resp.status }; + const albumData = await resp.json() as { assets?: any[] }; + const assets = (albumData.assets || []).filter((a: any) => a.type === 'IMAGE'); + + const selection: Selection = { + provider: 'immich', + asset_ids: assets.map((a: any) => a.id), + }; + + const result = await addTripPhotos(tripId, userId, true, [selection], sid, linkId); + if ('error' in result) return { error: result.error.message, status: result.error.status }; + + updateSyncTimeForAlbumLink(linkId); + + return { success: true, added: result.data.added, total: assets.length }; + } catch { + return { error: 'Could not reach Immich', status: 502 }; + } +} + +// ── Upload to Immich ────────────────────────────────────────────────────── + +export async function uploadToImmich(userId: number, filePath: string, fileName: string): Promise { + const creds = getImmichCredentials(userId); + if (!creds) return null; + + const fs = await import('node:fs'); + const path = await import('node:path'); + + const fullPath = path.join(__dirname, '../../../uploads', filePath); + if (!fs.existsSync(fullPath)) return null; + + try { + const fileBuffer = fs.readFileSync(fullPath); + const boundary = '----ImmichUpload' + Date.now(); + const ext = path.extname(fileName).toLowerCase(); + const mimeTypes: Record = { + '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', + '.gif': 'image/gif', '.webp': 'image/webp', '.heic': 'image/heic', + }; + const contentType = mimeTypes[ext] || 'application/octet-stream'; + const now = new Date().toISOString(); + + const parts: Buffer[] = []; + const addField = (name: string, value: string) => { + parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${name}"\r\n\r\n${value}\r\n`)); + }; + addField('deviceAssetId', `trek-${Date.now()}`); + addField('deviceId', 'TREK'); + addField('fileCreatedAt', now); + addField('fileModifiedAt', now); + + parts.push(Buffer.from( + `--${boundary}\r\nContent-Disposition: form-data; name="assetData"; filename="${fileName}"\r\nContent-Type: ${contentType}\r\n\r\n` + )); + parts.push(fileBuffer); + parts.push(Buffer.from(`\r\n--${boundary}--\r\n`)); + + const body = Buffer.concat(parts); + + const res = await safeFetch(`${creds.immich_url}/api/assets`, { + method: 'POST', + headers: { + 'x-api-key': creds.immich_api_key, + 'Content-Type': `multipart/form-data; boundary=${boundary}`, + 'Content-Length': String(body.length), + }, + body, + }); + + if (res.ok) { + const data = await res.json() as { id?: string }; + return data.id || null; + } + return null; + } catch { + return null; + } +} diff --git a/server/src/services/memories/photoResolverService.ts b/server/src/services/memories/photoResolverService.ts new file mode 100644 index 0000000000000000000000000000000000000000..3d272ca2495d3f1fbf1920be1b5544fb3564b1a3 --- /dev/null +++ b/server/src/services/memories/photoResolverService.ts @@ -0,0 +1,232 @@ +import { Response } from 'express'; +import path from 'path'; +import fs from 'fs'; +import { db } from '../../db/database'; +import type { TrekPhoto } from '../../types'; +import { streamImmichAsset, fetchImmichThumbnailBytes, getAssetInfo as getImmichAssetInfo } from './immichService'; +import { streamSynologyAsset, fetchSynologyThumbnailBytes, getSynologyAssetInfo } from './synologyService'; +import type { ServiceResult, AssetInfo } from './helpersService'; +import { fail, success } from './helpersService'; +import { encrypt_api_key, decrypt_api_key } from '../apiKeyCrypto'; +import * as photoCache from './trekPhotoCache'; +import { ensureLocalThumbnail } from './thumbnailService'; + +// ── Lookup / Register ──────────────────────────────────────────────────── + +export function getOrCreateTrekPhoto( + provider: string, + assetId: string, + ownerId: number, + passphrase?: string, +): number { + const existing = db.prepare( + 'SELECT id FROM trek_photos WHERE provider = ? AND asset_id = ? AND owner_id = ?' + ).get(provider, assetId, ownerId) as { id: number } | undefined; + if (existing) { + if (passphrase) { + db.prepare('UPDATE trek_photos SET passphrase = ? WHERE id = ?') + .run(encrypt_api_key(passphrase), existing.id); + } + return existing.id; + } + + const res = db.prepare( + 'INSERT INTO trek_photos (provider, asset_id, owner_id, passphrase) VALUES (?, ?, ?, ?)' + ).run(provider, assetId, ownerId, passphrase ? encrypt_api_key(passphrase) : null); + return Number(res.lastInsertRowid); +} + +export function getOrCreateLocalTrekPhoto( + filePath: string, + thumbnailPath?: string | null, + width?: number | null, + height?: number | null, +): number { + const existing = db.prepare( + "SELECT id FROM trek_photos WHERE provider = 'local' AND file_path = ?" + ).get(filePath) as { id: number } | undefined; + if (existing) return existing.id; + + const res = db.prepare( + 'INSERT INTO trek_photos (provider, file_path, thumbnail_path, width, height) VALUES (?, ?, ?, ?, ?)' + ).run('local', filePath, thumbnailPath || null, width || null, height || null); + return Number(res.lastInsertRowid); +} + +export function resolveTrekPhoto(photoId: number): TrekPhoto | null { + return db.prepare('SELECT * FROM trek_photos WHERE id = ?').get(photoId) as TrekPhoto | undefined || null; +} + +// ── Streaming ──────────────────────────────────────────────────────────── + +async function streamCachedThumbnail( + res: Response, + photo: TrekPhoto, + fetchBytes: () => Promise<{ bytes: Buffer; contentType: string } | { error: string; status: number }>, + fallback: () => Promise, +): Promise { + const key = photoCache.cacheKey(photo.provider!, photo.asset_id!, 'thumbnail', photo.owner_id!); + + if (photoCache.serveFresh(res, key)) return; + + const existing = photoCache.getInFlight(key); + if (existing) { + const bytes = await existing; + if (bytes && photoCache.serveFresh(res, key)) return; + await fallback(); + return; + } + + const promise = fetchBytes().then(async result => { + if ('error' in result) return null; + await photoCache.put(key, result.bytes, result.contentType); + return result.bytes; + }); + photoCache.setInFlight(key, promise); + + const bytes = await promise; + if (bytes && photoCache.serveFresh(res, key)) return; + await fallback(); +} + +export async function streamPhoto( + res: Response, + userId: number, + photoId: number, + kind: 'thumbnail' | 'original', +): Promise { + const photo = resolveTrekPhoto(photoId); + if (!photo) { + res.status(404).json({ error: 'Photo not found' }); + return; + } + + if (photo.file_path) { + const uploadsRoot = path.join(__dirname, '../../../uploads'); + + if (kind === 'thumbnail') { + let thumbRel = photo.thumbnail_path ?? null; + if (!thumbRel) { + const result = await ensureLocalThumbnail(uploadsRoot, photo.file_path); + if (result) { + thumbRel = result.thumbnailRelPath; + db.prepare( + 'UPDATE trek_photos SET thumbnail_path = ?, width = COALESCE(width, ?), height = COALESCE(height, ?) WHERE id = ?' + ).run(thumbRel, result.width, result.height, photo.id); + } + } + if (thumbRel) { + const thumbAbs = path.join(uploadsRoot, thumbRel); + if (fs.existsSync(thumbAbs)) { + res.set('Cache-Control', 'public, max-age=86400, immutable'); + res.sendFile(thumbAbs); + return; + } + } + // Fall through to original if thumbnail unavailable. + } + + const localPath = path.join(uploadsRoot, photo.file_path); + if (fs.existsSync(localPath)) { + res.set('Cache-Control', 'public, max-age=86400'); + res.sendFile(localPath); + return; + } + } + + switch (photo.provider) { + case 'local': { + res.status(404).json({ error: 'File not found' }); + return; + } + case 'immich': { + if (kind === 'thumbnail') { + await streamCachedThumbnail( + res, photo, + () => fetchImmichThumbnailBytes(userId, photo.asset_id!, photo.owner_id!), + () => streamImmichAsset(res, userId, photo.asset_id!, kind, photo.owner_id!), + ); + return; + } + await streamImmichAsset(res, userId, photo.asset_id!, kind, photo.owner_id!); + return; + } + case 'synologyphotos': { + const passphrase = photo.passphrase ? (decrypt_api_key(photo.passphrase) || undefined) : undefined; + if (kind === 'thumbnail') { + await streamCachedThumbnail( + res, photo, + () => fetchSynologyThumbnailBytes(userId, photo.owner_id!, photo.asset_id!, passphrase), + () => streamSynologyAsset(res, userId, photo.owner_id!, photo.asset_id!, kind, undefined, passphrase), + ); + return; + } + await streamSynologyAsset(res, userId, photo.owner_id!, photo.asset_id!, kind, undefined, passphrase); + return; + } + default: + res.status(400).json({ error: `Unknown provider: ${photo.provider}` }); + } +} + +// ── Asset Info ──────────────────────────────────────────────────────────── + +export async function getPhotoInfo( + userId: number, + photoId: number, +): Promise> { + const photo = resolveTrekPhoto(photoId); + if (!photo) return fail('Photo not found', 404); + + switch (photo.provider) { + case 'local': { + return success({ + id: String(photo.id), + takenAt: photo.created_at, + city: null, + country: null, + width: photo.width, + height: photo.height, + fileName: photo.file_path?.split('/').pop() || null, + } as AssetInfo); + } + case 'immich': { + const result = await getImmichAssetInfo(userId, photo.asset_id!, photo.owner_id!); + if (result.error) return fail(result.error, result.status || 500); + return success(result.data as AssetInfo); + } + case 'synologyphotos': { + const passphrase = photo.passphrase ? (decrypt_api_key(photo.passphrase) || undefined) : undefined; + return getSynologyAssetInfo(userId, photo.asset_id!, photo.owner_id!, passphrase); + } + default: + return fail(`Unknown provider: ${photo.provider}`, 400); + } +} + +// ── Update provider on existing trek_photo (for Immich upload sync) ───── + +export function setTrekPhotoProvider( + trekPhotoId: number, + provider: string, + assetId: string, + ownerId: number, +): void { + db.prepare( + 'UPDATE trek_photos SET provider = ?, asset_id = ?, owner_id = ? WHERE id = ?' + ).run(provider, assetId, ownerId, trekPhotoId); +} + +// ── Orphan cleanup ─────────────────────────────────────────────────────── + +export function deleteTrekPhotoIfOrphan(photoId: number): void { + const stillUsed = db.prepare(` + SELECT 1 FROM trip_photos WHERE photo_id = ? + UNION ALL + SELECT 1 FROM journey_photos WHERE photo_id = ? + LIMIT 1 + `).get(photoId, photoId); + if (stillUsed) return; + db.prepare("DELETE FROM trek_photos WHERE id = ? AND provider != 'local'").run(photoId); +} + diff --git a/server/src/services/memories/synologyService.ts b/server/src/services/memories/synologyService.ts new file mode 100644 index 0000000000000000000000000000000000000000..83b44402de6e4ac73fb4ff3d483c3997bb84305a --- /dev/null +++ b/server/src/services/memories/synologyService.ts @@ -0,0 +1,705 @@ + +import { Response } from 'express'; +import { db } from '../../db/database'; +import { decrypt_api_key, encrypt_api_key, maybe_encrypt_api_key } from '../apiKeyCrypto'; +import { safeFetch, SsrfBlockedError, checkSsrf } from '../../utils/ssrfGuard'; +import { addTripPhotos } from './unifiedService'; +import { + getAlbumLinkForSync, + updateSyncTimeForAlbumLink, + Selection, + ServiceResult, + fail, + success, + handleServiceResult, + pipeAsset, + AlbumsList, + AssetsList, + StatusResult, + SyncAlbumResult, + AssetInfo +} from './helpersService'; +import { send as sendNotification } from '../notificationService'; + +const SYNOLOGY_PROVIDER = 'synologyphotos'; +// Users provide the full base URL including the Photos app path (e.g. https://nas:5001/photo). +// The API endpoint is always at {base_url}/webapi/entry.cgi. +const SYNOLOGY_ENDPOINT_PATH = '/webapi/entry.cgi'; + +const SYNOLOGY_ERROR_MESSAGES: Record = { + 101: 'Missing API, method, or version parameter.', + 102: 'Requested API does not exist.', + 103: 'Requested method does not exist.', + 104: 'Requested API version is not supported.', + 105: 'Insufficient privilege.', + 106: 'Connection timeout.', + 107: 'Multiple logins blocked from this IP.', + 117: 'Manager privilege required.', + 119: 'Session is invalid or expired.', + 400: 'Invalid credentials.', + 401: 'Session expired or account disabled.', + 402: 'No permission to use this account.', + 403: 'Two-factor authentication code required.', + 404: 'Two-factor authentication failed.', + 406: 'Two-factor authentication is enforced for this account.', + 407: 'Maximum login attempts reached.', + 408: 'Password expired.', + 409: 'Remote password expired.', + 410: 'Password must be changed before login.', + 412: 'Guest account cannot log in.', + 413: 'OTP system files are corrupted.', + 414: 'Unable to log in.', + 416: 'Unable to log in.', + 417: 'OTP system is full.', + 498: 'System is upgrading.', + 499: 'System is not ready.', +}; + +interface SynologyUserRecord { + synology_url?: string | null; + synology_username?: string | null; + synology_password?: string | null; + synology_sid?: string | null; + synology_did?: string | null; + synology_skip_ssl?: number | null; +}; + +interface SynologyCredentials { + synology_url: string; + synology_username: string; + synology_password: string; + synology_skip_ssl: boolean; +} + +interface SynologySettings { + synology_url: string; + synology_username: string; + synology_skip_ssl: boolean; + connected: boolean; +} + +interface ApiCallParams { + api: string; + method: string; + version?: number; + [key: string]: unknown; +} + +interface SynologyApiResponse { + success: boolean; + data?: T; + error?: { code: number }; +} + + +interface SynologyPhotoItem { + id?: string | number; + filename?: string; + filesize?: number; + time?: number; + item_count?: number; + name?: string; + additional?: { + thumbnail?: { cache_key?: string }; + address?: { city?: string; country?: string; state?: string }; + resolution?: { width?: number; height?: number }; + exif?: { + camera?: string; + lens?: string; + focal_length?: string | number; + aperture?: string | number; + exposure_time?: string | number; + iso?: string | number; + }; + gps?: { latitude?: number; longitude?: number }; + orientation?: number; + description?: string; + }; +} + + +function _readSynologyUser(userId: number, columns: string[]): ServiceResult { + try { + const row = db.prepare(`SELECT synology_url, synology_username, synology_password, synology_sid, synology_did, synology_skip_ssl FROM users WHERE id = ?`).get(userId) as SynologyUserRecord | undefined; + + if (!row) { + return fail('User not found', 404); + } + + const filtered: SynologyUserRecord = {}; + for (const column of columns) { + filtered[column] = row[column]; + } + + return success(filtered); + } catch { + return fail('Failed to read Synology user data', 500); + } +} + +function _getSynologyCredentials(userId: number): ServiceResult { + const user = _readSynologyUser(userId, ['synology_url', 'synology_username', 'synology_password', 'synology_skip_ssl']); + if (!user.success) return user as ServiceResult; + if (!user?.data.synology_url || !user.data.synology_username || !user.data.synology_password) return fail('Synology not configured', 400); + const password = decrypt_api_key(user.data.synology_password); + if (!password) return fail('Synology credentials corrupted', 500); + return success({ + synology_url: user.data.synology_url, + synology_username: user.data.synology_username, + synology_password: password, + synology_skip_ssl: user.data.synology_skip_ssl !== 0, + }); +} + + +function _buildSynologyEndpoint(url: string, params: string): string { + const normalized = url.replace(/\/$/, '').match(/^https?:\/\//) ? url.replace(/\/$/, '') : `https://${url.replace(/\/$/, '')}`; + return `${normalized}${SYNOLOGY_ENDPOINT_PATH}?${params}`; +} + +function _buildSynologyFormBody(params: ApiCallParams): URLSearchParams { + const body = new URLSearchParams(); + for (const [key, value] of Object.entries(params)) { + if (value === undefined || value === null) continue; + body.append(key, typeof value === 'object' ? JSON.stringify(value) : String(value)); + } + return body; +} + +async function _fetchSynologyJson(url: string, body: URLSearchParams, skipSsl = true): Promise> { + const endpoint = _buildSynologyEndpoint(url, `api=${body.get('api')}`); + try { + const resp = await safeFetch(endpoint, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', + }, + body, + signal: AbortSignal.timeout(30000) as any, + }, { rejectUnauthorized: !skipSsl }); + if (!resp.ok) { + return fail('Synology API request failed with status ' + resp.status, resp.status); + } + const response = await resp.json() as SynologyApiResponse; + if (!response.success) { + const code = response.error.code; + const message = SYNOLOGY_ERROR_MESSAGES[code] ?? 'Synology API request failed (code ' + code + ')'; + // Preserve session error codes (106, 107, 119) for internal retry logic in _requestSynologyApi. + // All other Synology app-level codes are mapped to HTTP 400 — they are not HTTP status codes. + const httpStatus = [106, 107, 119].includes(code) ? code : 400; + return fail(message, httpStatus); + } + return success(response.data); + } catch (error) { + if (error instanceof SsrfBlockedError) { + return fail(error.message, 400); + } + return fail('Failed to connect to Synology API', 500); + } +} + +const SYNOLOGY_DEVICE_NAME = 'trek'; + +async function _loginToSynology( + url: string, + username: string, + password: string, + opts: { otp?: string; deviceId?: string; skipSsl?: boolean } = {}, +): Promise> { + const { otp, deviceId, skipSsl = false } = opts; + const body = new URLSearchParams({ + api: 'SYNO.API.Auth', + method: 'login', + version: '6', + account: username, + passwd: password, + format: 'sid', + client: 'browser', + device_name: SYNOLOGY_DEVICE_NAME, + }); + if (otp && otp.trim()) { + body.append('otp_code', otp.trim()); + body.append('enable_device_token', 'yes'); + } + if (deviceId) { + body.append('device_id', deviceId); + } + + const result = await _fetchSynologyJson<{ sid?: string; did?: string }>(url, body, skipSsl); + if (!result.success) { + return result as ServiceResult<{ sid: string; did?: string }>; + } + if (!result.data.sid) { + return fail('Failed to get session ID from Synology', 500); + } + return success({ sid: result.data.sid, did: result.data.did }); +} + +async function _requestSynologyApi(userId: number, params: ApiCallParams): Promise> { + const creds = _getSynologyCredentials(userId); + if (!creds.success) { + return creds as ServiceResult; + } + + const session = await _getSynologySession(userId); + if (!session.success || !session.data) { + return session as ServiceResult; + } + + const skipSsl = creds.data.synology_skip_ssl; + const body = _buildSynologyFormBody({ ...params, _sid: session.data }); + const result = await _fetchSynologyJson(creds.data.synology_url, body, skipSsl); + // 106 = session timeout, 107 = duplicate login kicked us out, 119 = SID not found/invalid + if ('error' in result && [106, 107, 119].includes(result.error.status)) { + _clearSynologySID(userId); + const retrySession = await _getSynologySession(userId); + if (!retrySession.success || !retrySession.data) { + return retrySession as ServiceResult; + } + return _fetchSynologyJson(creds.data.synology_url, _buildSynologyFormBody({ ...params, _sid: retrySession.data }), skipSsl); + } + return result; +} + +function _normalizeSynologyPhotoInfo(item: SynologyPhotoItem): AssetInfo { + const address = item.additional?.address || {}; + const exif = item.additional?.exif || {}; + const gps = item.additional?.gps || {}; + + return { + id: String(item.additional?.thumbnail?.cache_key || ''), + takenAt: item.time ? new Date(item.time * 1000).toISOString() : null, + city: address.city || null, + country: address.country || null, + state: address.state || null, + camera: exif.camera || null, + lens: exif.lens || null, + focalLength: exif.focal_length || null, + aperture: exif.aperture || null, + shutter: exif.exposure_time || null, + iso: exif.iso || null, + lat: gps.latitude || null, + lng: gps.longitude || null, + orientation: item.additional?.orientation || null, + description: item.additional?.description || null, + width: item.additional?.resolution?.width || null, + height: item.additional?.resolution?.height || null, + fileSize: item.filesize || null, + fileName: item.filename || null, + }; +} + + +function _clearSynologySID(userId: number): void { + db.prepare('UPDATE users SET synology_sid = NULL WHERE id = ?').run(userId); +} + +function _clearSynologySession(userId: number): void { + db.prepare('UPDATE users SET synology_sid = NULL, synology_did = NULL WHERE id = ?').run(userId); +} + +function _splitPackedSynologyId(rawId: string): { id: string; cacheKey: string; assetId: string } | null { + // cache_key format from Synology is "{unit_id}_{timestamp}", e.g. "40808_1633659236". + // The first segment must be a non-empty integer (the unit ID used for API calls). + if (!/^\d+_.+$/.test(rawId)) return null; + const id = rawId.split('_')[0]; + return { id, cacheKey: rawId, assetId: rawId }; +} + +async function _getSynologySession(userId: number): Promise> { + const cached = _readSynologyUser(userId, ['synology_sid', 'synology_did']); + if (cached.success && cached.data?.synology_sid) { + const decryptedSid = decrypt_api_key(cached.data.synology_sid); + if (decryptedSid) return success(decryptedSid); + // Decryption failed (e.g. key rotation) — clear the stale SID and re-login + _clearSynologySID(userId); + } + + const creds = _getSynologyCredentials(userId); + if (!creds.success) { + return creds as ServiceResult; + } + + // Use stored device ID to skip OTP on re-login (trusted device flow) + const storedDid = cached.success && cached.data?.synology_did + ? (decrypt_api_key(cached.data.synology_did) || undefined) + : undefined; + + const resp = await _loginToSynology(creds.data.synology_url, creds.data.synology_username, creds.data.synology_password, { + deviceId: storedDid, + skipSsl: creds.data.synology_skip_ssl, + }); + + if (!resp.success) { + return resp as ServiceResult; + } + + db.prepare('UPDATE users SET synology_sid = ? WHERE id = ?').run(encrypt_api_key(resp.data.sid), userId); + return success(resp.data.sid); +} + +export async function getSynologySettings(userId: number): Promise> { + const creds = _getSynologyCredentials(userId); + if (!creds.success) return creds as ServiceResult; + const session = await _getSynologySession(userId); + return success({ + synology_url: creds.data.synology_url || '', + synology_username: creds.data.synology_username || '', + synology_skip_ssl: creds.data.synology_skip_ssl, + connected: session.success, + }); +} + +export async function updateSynologySettings(userId: number, synologyUrl: string, synologyUsername: string, synologyPassword?: string, synologySkipSsl = false): Promise> { + + const ssrf = await checkSsrf(synologyUrl); + if (!ssrf.allowed) { + return fail(ssrf.error, 400); + } + + const result = _readSynologyUser(userId, ['synology_password']) + if (!result.success) return result as ServiceResult; + const existingEncryptedPassword = result.data?.synology_password || null; + + if (!synologyPassword && !existingEncryptedPassword) { + return fail('No stored password found. Please provide a password to save settings.', 400); + } + + // Only invalidate the session when the account itself changes (different URL or username). + // If the user just tested the connection, testSynologyConnection already stored a fresh + // sid + did — clearing them here would force an unnecessary re-login that may fail (MFA). + const existing = _readSynologyUser(userId, ['synology_url', 'synology_username']); + const urlChanged = existing.success && existing.data.synology_url !== synologyUrl; + const userChanged = existing.success && existing.data.synology_username !== synologyUsername; + const sessionCleared = urlChanged || userChanged; + if (sessionCleared) { + _clearSynologySession(userId); + sendNotification({ + event: 'synology_session_cleared', + actorId: null, + params: {}, + scope: 'user', + targetId: userId, + }); + } + + try { + db.prepare('UPDATE users SET synology_url = ?, synology_username = ?, synology_password = ?, synology_skip_ssl = ? WHERE id = ?').run( + synologyUrl, + synologyUsername, + synologyPassword ? maybe_encrypt_api_key(synologyPassword) : existingEncryptedPassword, + synologySkipSsl ? 1 : 0, + userId, + ); + } catch { + return fail('Failed to update Synology settings', 500); + } + + return success('settings updated'); +} + +export async function getSynologyStatus(userId: number): Promise> { + const sid = await _getSynologySession(userId); + if ('error' in sid) return success({ connected: false, error: sid.error.message }); + if (!sid.data) return success({ connected: false, error: 'Not connected to Synology' }); + try { + const user = db.prepare('SELECT synology_username FROM users WHERE id = ?').get(userId) as { synology_username?: string } | undefined; + return success({ connected: true, user: { name: user?.synology_username || 'unknown user' } }); + } catch (err: unknown) { + return success({ connected: true, user: { name: 'unknown user' } }); + } +} + +export async function testSynologyConnection(userId: number, synologyUrl: string, synologyUsername: string, synologyPassword: string, synologyOtp?: string, synologySkipSsl = false): Promise> { + + const ssrf = await checkSsrf(synologyUrl); + if (!ssrf.allowed) { + return fail(ssrf.error, 400); + } + + const resp = await _loginToSynology(synologyUrl, synologyUsername, synologyPassword, { otp: synologyOtp, skipSsl: synologySkipSsl }); + if ('error' in resp) { + return success({ connected: false, error: resp.error.message }); + } + + // Persist the session so the OTP code is not required again on save. + // The did (device token) allows future re-logins without OTP. + db.prepare('UPDATE users SET synology_sid = ? WHERE id = ?').run(encrypt_api_key(resp.data.sid), userId); + if (resp.data.did) { + db.prepare('UPDATE users SET synology_did = ? WHERE id = ?').run(encrypt_api_key(resp.data.did), userId); + } + + return success({ connected: true, user: { name: synologyUsername } }); +} + +async function _fetchAllSynologyAlbums(userId: number, baseParams: ApiCallParams): Promise> { + const pageSize = 100; + const all: any[] = []; + let offset = 0; + while (true) { + const result = await _requestSynologyApi<{ list: any[] }>(userId, { ...baseParams, offset, limit: pageSize }); + if (!result.success) return result as ServiceResult; + const items = result.data.list || []; + all.push(...items); + if (items.length < pageSize) break; + offset += pageSize; + } + return success(all); +} + +export async function listSynologyAlbums(userId: number): Promise> { + const [personal, shared, sharedWithMe] = await Promise.allSettled([ + _fetchAllSynologyAlbums(userId, { api: 'SYNO.Foto.Browse.Album', method: 'list', version: 4 }), + _fetchAllSynologyAlbums(userId, { api: 'SYNO.Foto.Browse.Album', method: 'list', version: 4, category: 'shared' }), + _fetchAllSynologyAlbums(userId, { api: 'SYNO.Foto.Sharing.Misc', method: 'list_shared_with_me_album', version: 1, additional: ['thumbnail', 'sharing_info'] }), + ]); + + const map = new Map(); + + const addAlbums = (result: PromiseSettledResult>, extractPassphrase: (a: any) => string | undefined) => { + if (result.status === 'rejected') return; + const value = result.value; + if ('error' in value) { + console.warn('[Synology] album list partial failure:', value.error.message); + return; + } + for (const album of value.data ?? []) { + const id = String(album.id); + const passphrase = extractPassphrase(album); + map.set(id, { id, albumName: album.name || '', assetCount: album.item_count || 0, passphrase }); + } + }; + + addAlbums(personal, () => undefined); + addAlbums(shared, (a) => a.passphrase || undefined); + addAlbums(sharedWithMe, (a) => a.passphrase || a.sharing_info?.passphrase || undefined); + + if (map.size === 0 && personal.status === 'fulfilled' && !personal.value.success) { + return personal.value as ServiceResult; + } + + const albums = [...map.values()].sort((a, b) => a.albumName.localeCompare(b.albumName)); + return success({ albums }); +} + + +export async function getSynologyAlbumPhotos(userId: number, albumId: string, passphrase?: string): Promise> { + const allItems: SynologyPhotoItem[] = []; + const pageSize = 50; + let offset = 0; + + while (true) { + const params: ApiCallParams = passphrase + ? { api: 'SYNO.Foto.Browse.Item', method: 'list', version: 1, passphrase, offset, limit: pageSize, additional: ['thumbnail'] } + : { api: 'SYNO.Foto.Browse.Item', method: 'list', version: 1, album_id: Number(albumId), offset, limit: pageSize, additional: ['thumbnail'] }; + const result = await _requestSynologyApi<{ list: SynologyPhotoItem[] }>(userId, params); + if (!result.success) return result as ServiceResult; + const items = result.data.list || []; + allItems.push(...items); + if (items.length < pageSize) break; + offset += pageSize; + } + + const assets = allItems.map(item => ({ + id: String(item.additional?.thumbnail?.cache_key || item.id || ''), + takenAt: item.time ? new Date(item.time * 1000).toISOString() : '', + })).filter(a => a.id); + + return success({ assets, total: assets.length, hasMore: false }); +} + +export async function syncSynologyAlbumLink(userId: number, tripId: string, linkId: string, sid: string): Promise> { + const response = getAlbumLinkForSync(tripId, linkId, userId); + if (!response.success) return response as ServiceResult; + + const { albumId, passphrase } = response.data; + + const allItems: SynologyPhotoItem[] = []; + const pageSize = 50; + let offset = 0; + + while (true) { + const itemParams: ApiCallParams = passphrase + ? { api: 'SYNO.Foto.Browse.Item', method: 'list', version: 1, passphrase, offset, limit: pageSize, additional: ['thumbnail'] } + : { api: 'SYNO.Foto.Browse.Item', method: 'list', version: 1, album_id: Number(albumId), offset, limit: pageSize, additional: ['thumbnail'] }; + + const result = await _requestSynologyApi<{ list: SynologyPhotoItem[] }>(userId, itemParams); + + if (!result.success) return result as ServiceResult; + + const items = result.data.list || []; + allItems.push(...items); + if (items.length < pageSize) break; + offset += pageSize; + } + + const selection: Selection = { + provider: SYNOLOGY_PROVIDER, + asset_ids: allItems.map(item => String(item.additional?.thumbnail?.cache_key || '')).filter(id => id), + passphrase, + }; + + const result = await addTripPhotos(tripId, userId, true, [selection], sid, linkId); + if (!result.success) return result as ServiceResult; + + updateSyncTimeForAlbumLink(linkId); + + return success({ added: result.data.added, total: allItems.length }); +} + +export async function searchSynologyPhotos(userId: number, from?: string, to?: string, offset = 0, limit = 300): Promise> { + const params: ApiCallParams = { + api: 'SYNO.Foto.Search.Search', + method: 'list_item', + version: 1, + offset, + limit, + keyword: '.', + additional: ['thumbnail', 'address'], + }; + + if (from || to) { + if (from) { + params.start_time = Math.floor(new Date(from).getTime() / 1000); + } + if (to) { + params.end_time = Math.floor(new Date(to).getTime() / 1000) + 86400; //adding it as the next day 86400 seconds in day + } + } + + // SYNO.Foto.Search.Search list_item does not return a total count — only data.list. + // hasMore is inferred: if we got a full page, there may be more. + const result = await _requestSynologyApi<{ list: SynologyPhotoItem[] }>(userId, params); + if (!result.success) return result as ServiceResult; + + const allItems = result.data.list || []; + const assets = allItems.map(item => _normalizeSynologyPhotoInfo(item)); + + return success({ + assets, + total: allItems.length, + hasMore: allItems.length === limit, + }); +} + +export async function getSynologyAssetInfo(userId: number, photoId: string, targetUserId: number, passphrase?: string): Promise> { + const parsedId = _splitPackedSynologyId(photoId); + if (!parsedId) return fail('Invalid photo ID format', 400); + const infoParams: ApiCallParams = { + api: 'SYNO.Foto.Browse.Item', + method: 'get', + version: 5, + id: `[${Number(parsedId.id) + 1}]`, //for some reason synology wants id moved by one to get image info + additional: ['resolution', 'exif', 'gps', 'address', 'orientation', 'description'], + }; + if (passphrase) infoParams.passphrase = passphrase; + const result = await _requestSynologyApi<{ list: SynologyPhotoItem[] }>(targetUserId, infoParams); + + if (!result.success) return result as ServiceResult; + + const metadata = result.data.list?.[0]; + if (!metadata) return fail('Photo not found', 404); + + const normalized = _normalizeSynologyPhotoInfo(metadata); + normalized.id = photoId; + return success(normalized); +} + +export async function fetchSynologyThumbnailBytes( + userId: number, + targetUserId: number, + photoId: string, + passphrase?: string, +): Promise<{ bytes: Buffer; contentType: string } | { error: string; status: number }> { + const parsedId = _splitPackedSynologyId(photoId); + if (!parsedId) return { error: 'Invalid photo ID format', status: 400 }; + + const synology_credentials = _getSynologyCredentials(targetUserId); + if (!synology_credentials.success) return { error: 'Credentials error', status: 500 }; + + const sid = await _getSynologySession(targetUserId); + if (!sid.success) return { error: 'Session error', status: 500 }; + if (!sid.data) return { error: 'Session ID missing', status: 500 }; + + const params = new URLSearchParams({ + api: 'SYNO.Foto.Thumbnail', + method: 'get', + version: '2', + mode: 'download', + id: parsedId.id, + type: 'unit', + // Match the uncached streamSynologyAsset default — 'sm' (240px) looked + // pixelated on retina. + size: 'm', + cache_key: parsedId.cacheKey, + _sid: sid.data, + }); + if (passphrase) params.append('passphrase', passphrase); + + const url = _buildSynologyEndpoint(synology_credentials.data.synology_url, params.toString()); + try { + const resp = await safeFetch(url); + if (!resp.ok) return { error: 'Upstream error', status: resp.status }; + const contentType = resp.headers.get('content-type') || 'image/jpeg'; + const bytes = Buffer.from(await resp.arrayBuffer()); + return { bytes, contentType }; + } catch { + return { error: 'Proxy error', status: 502 }; + } +} + +export async function streamSynologyAsset( + response: Response, + userId: number, + targetUserId: number, + photoId: string, + kind: 'thumbnail' | 'original', + size?: string, + passphrase?: string, +): Promise { + const parsedId = _splitPackedSynologyId(photoId); + if (!parsedId) { + handleServiceResult(response, fail('Invalid photo ID format', 400)); + return; + } + + const synology_credentials = _getSynologyCredentials(targetUserId); + if (!synology_credentials.success) { + handleServiceResult(response, synology_credentials); + return; + } + + const sid = await _getSynologySession(targetUserId); + if (!sid.success) { + handleServiceResult(response, sid); + return; + } + if (!sid.data) { + handleServiceResult(response, fail('Failed to retrieve session ID', 500)); + return; + } + + + //size: 'sm' 240px| 'm' 320px| 'xl' 1280px| 'preview' ? + // Use Thumbnail API for both thumbnail and original — avoids serving raw HEIC files + // (original uses xl size to get a full-resolution JPEG-compatible render). + // Thumbnail default is 'm' (~320px) — 'sm' (240px) looked pixelated on + // the journey grid on retina screens. + const resolvedSize = kind === 'original' ? 'xl' : (size || 'm'); + const params = new URLSearchParams({ + api: 'SYNO.Foto.Thumbnail', + method: 'get', + version: '2', + mode: 'download', + id: parsedId.id, + type: 'unit', + size: resolvedSize, + cache_key: parsedId.cacheKey, + _sid: sid.data, + }); + if (passphrase) params.append('passphrase', passphrase); + + const url = _buildSynologyEndpoint(synology_credentials.data.synology_url, params.toString()); + await pipeAsset(url, response, undefined, undefined, 'public, max-age=86400') +} + diff --git a/server/src/services/memories/thumbnailService.ts b/server/src/services/memories/thumbnailService.ts new file mode 100644 index 0000000000000000000000000000000000000000..d328b5797fd13375a98eb079d19d54b2bb1b3fbe --- /dev/null +++ b/server/src/services/memories/thumbnailService.ts @@ -0,0 +1,50 @@ +import { Jimp } from 'jimp' +import path from 'path' +import fs from 'fs/promises' +import crypto from 'crypto' +import { isAddonEnabled } from '../adminService' +import { ADDON_IDS } from '../../addons' + +const THUMB_MAX = 800 +const THUMB_QUALITY = 80 + +export async function ensureLocalThumbnail( + uploadsRoot: string, + originalRelPath: string, +): Promise<{ thumbnailRelPath: string; width: number; height: number } | null> { + if (!isAddonEnabled(ADDON_IDS.JOURNEY)) return null + + const originalAbs = path.join(uploadsRoot, originalRelPath) + try { await fs.access(originalAbs) } catch { return null } + + // Deterministic name so concurrent requests don't race on the same photo. + const hash = crypto.createHash('sha1').update(originalRelPath).digest('hex').slice(0, 16) + const thumbRel = `journey/thumbs/${hash}.jpg` + const thumbAbs = path.join(uploadsRoot, thumbRel) + + try { + const [srcStat, dstStat] = await Promise.all([ + fs.stat(originalAbs), + fs.stat(thumbAbs).catch(() => null), + ]) + if (dstStat && dstStat.mtimeMs >= srcStat.mtimeMs) { + const img = await Jimp.read(thumbAbs) + return { thumbnailRelPath: thumbRel, width: img.bitmap.width, height: img.bitmap.height } + } + + await fs.mkdir(path.dirname(thumbAbs), { recursive: true }) + + // Jimp auto-applies EXIF orientation on read, matching sharp's .rotate() behavior. + const img = await Jimp.read(originalAbs) + const { width: w, height: h } = img.bitmap + if (w > THUMB_MAX || h > THUMB_MAX) { + img.scaleToFit({ w: THUMB_MAX, h: THUMB_MAX }) + } + await img.write(thumbAbs as `${string}.jpg`, { quality: THUMB_QUALITY }) + + return { thumbnailRelPath: thumbRel, width: img.bitmap.width, height: img.bitmap.height } + } catch { + // Unsupported format, corrupt file, etc. — fall back to original in caller. + return null + } +} diff --git a/server/src/services/memories/trekPhotoCache.ts b/server/src/services/memories/trekPhotoCache.ts new file mode 100644 index 0000000000000000000000000000000000000000..4ee45a8087bd534f62b1a4465e0e9bb48450b7ed --- /dev/null +++ b/server/src/services/memories/trekPhotoCache.ts @@ -0,0 +1,91 @@ +import path from 'node:path'; +import fs from 'node:fs'; +import fsPromises from 'node:fs/promises'; +import crypto from 'node:crypto'; +import { Response } from 'express'; +import { db } from '../../db/database'; + +const TREK_PHOTO_DIR = path.join(__dirname, '../../../uploads/photos/trek'); +export const CACHE_TTL = 60 * 60 * 1000; // 1 hour + +const inFlight = new Map>(); + +export function cacheKey(provider: string, assetId: string, kind: string, ownerId: number): string { + return crypto.createHash('sha1').update(`${provider}:${assetId}:${kind}:${ownerId}`).digest('hex'); +} + +function ensureDir(): void { + if (!fs.existsSync(TREK_PHOTO_DIR)) { + fs.mkdirSync(TREK_PHOTO_DIR, { recursive: true }); + } +} + +function cachedFilePath(key: string): string { + return path.join(TREK_PHOTO_DIR, `${key}.bin`); +} + +export function getFresh(key: string): { filePath: string; contentType: string } | null { + const row = db.prepare( + 'SELECT content_type, fetched_at FROM trek_photo_cache_meta WHERE cache_key = ?' + ).get(key) as { content_type: string; fetched_at: number } | undefined; + + if (!row) return null; + + if (Date.now() - row.fetched_at >= CACHE_TTL) { + db.prepare('DELETE FROM trek_photo_cache_meta WHERE cache_key = ?').run(key); + return null; + } + + const fp = cachedFilePath(key); + if (!fs.existsSync(fp)) { + db.prepare('DELETE FROM trek_photo_cache_meta WHERE cache_key = ?').run(key); + return null; + } + + return { filePath: fp, contentType: row.content_type }; +} + +export async function put(key: string, bytes: Buffer, contentType: string): Promise { + ensureDir(); + const fp = cachedFilePath(key); + const tmp = fp + '.tmp'; + + await fsPromises.writeFile(tmp, bytes); + await fsPromises.rename(tmp, fp); + + db.prepare( + 'INSERT OR REPLACE INTO trek_photo_cache_meta (cache_key, content_type, fetched_at) VALUES (?, ?, ?)' + ).run(key, contentType, Date.now()); +} + +export function serveFresh(res: Response, key: string): boolean { + const entry = getFresh(key); + if (!entry) return false; + + res.set('Content-Type', entry.contentType); + res.set('Cache-Control', 'public, max-age=3600'); + res.sendFile(entry.filePath); + return true; +} + +export function getInFlight(key: string): Promise | undefined { + return inFlight.get(key); +} + +export function setInFlight(key: string, promise: Promise): void { + inFlight.set(key, promise); + promise.finally(() => inFlight.delete(key)); +} + +export function sweepExpired(): void { + const cutoff = Date.now() - CACHE_TTL * 2; + const stale = db.prepare( + 'SELECT cache_key FROM trek_photo_cache_meta WHERE fetched_at < ?' + ).all(cutoff) as { cache_key: string }[]; + + for (const row of stale) { + db.prepare('DELETE FROM trek_photo_cache_meta WHERE cache_key = ?').run(row.cache_key); + const fp = cachedFilePath(row.cache_key); + if (fs.existsSync(fp)) fs.unlinkSync(fp); + } +} diff --git a/server/src/services/memories/unifiedService.ts b/server/src/services/memories/unifiedService.ts new file mode 100644 index 0000000000000000000000000000000000000000..01ea556f90b677e0b65e25a1efe70b0d5971576c --- /dev/null +++ b/server/src/services/memories/unifiedService.ts @@ -0,0 +1,315 @@ +import { db, canAccessTrip } from '../../db/database'; +import { send } from '../notificationService'; +import { broadcast } from '../../websocket'; +import { + ServiceResult, + fail, + success, + mapDbError, + Selection, +} from './helpersService'; +import { getOrCreateTrekPhoto, deleteTrekPhotoIfOrphan } from './photoResolverService'; +import { encrypt_api_key } from '../apiKeyCrypto'; + + +function _providers(): Array<{id: string; enabled: boolean}> { + const rows = db.prepare('SELECT id, enabled FROM photo_providers').all() as Array<{id: string; enabled: number}>; + return rows.map(r => ({ id: r.id, enabled: r.enabled === 1 })); +} + +function _validProvider(provider: string): ServiceResult { + const providers = _providers(); + const found = providers.find(p => p.id === provider); + if (!found) { + return fail(`Provider: "${provider}" is not supported`, 400); + } + if (!found.enabled) { + return fail(`Provider: "${provider}" is not enabled, contact server administrator`, 400); + } + return success(provider); +} + + + + +export function listTripPhotos(tripId: string, userId: number): ServiceResult { + const access = canAccessTrip(tripId, userId); + if (!access) { + return fail('Trip not found or access denied', 404); + } + + try { + + const enabledProviders = _providers().filter(p => p.enabled).map(p => p.id); + + if (enabledProviders.length === 0) { + return fail('No photo providers enabled', 400); + } + + const photos = db.prepare(` + SELECT tp.photo_id, tkp.asset_id, tkp.provider, tp.user_id, tp.shared, tp.added_at, + u.username, u.avatar + FROM trip_photos tp + JOIN trek_photos tkp ON tkp.id = tp.photo_id + JOIN users u ON tp.user_id = u.id + WHERE tp.trip_id = ? + AND (tp.user_id = ? OR tp.shared = 1) + AND tkp.provider IN (${enabledProviders.map(() => '?').join(',')}) + ORDER BY tp.added_at ASC + `).all(tripId, userId, ...enabledProviders); + + return success(photos); + } catch (error) { + return mapDbError(error, 'Failed to list trip photos'); + } +} + +export function listTripAlbumLinks(tripId: string, userId: number): ServiceResult { + const access = canAccessTrip(tripId, userId); + if (!access) { + return fail('Trip not found or access denied', 404); + } + + + const enabledProviders = _providers().filter(p => p.enabled).map(p => p.id); + + if (enabledProviders.length === 0) { + return fail('No photo providers enabled', 400); + } + + try { + const links = db.prepare(` + SELECT tal.id, + tal.trip_id, + tal.user_id, + tal.provider, + tal.album_id, + tal.album_name, + tal.sync_enabled, + tal.last_synced_at, + tal.created_at, + u.username + FROM trip_album_links tal + JOIN users u ON tal.user_id = u.id + WHERE tal.trip_id = ? + AND tal.provider IN (${enabledProviders.map(() => '?').join(',')}) + ORDER BY tal.created_at ASC + `).all(tripId, ...enabledProviders); + + return success(links); + } catch (error) { + return mapDbError(error, 'Failed to list trip album links'); + } +} + +//----------------------------------------------- +// managing photos in trip + +function _addTripPhoto(tripId: string, userId: number, provider: string, assetId: string, shared: boolean, albumLinkId?: string, passphrase?: string): ServiceResult { + const providerResult = _validProvider(provider); + if (!providerResult.success) { + return providerResult as ServiceResult; + } + try { + const photoId = getOrCreateTrekPhoto(provider, assetId, userId, passphrase); + const result = db.prepare( + 'INSERT OR IGNORE INTO trip_photos (trip_id, user_id, photo_id, shared, album_link_id) VALUES (?, ?, ?, ?, ?)' + ).run(tripId, userId, photoId, shared ? 1 : 0, albumLinkId || null); + return success(result.changes > 0); + } + catch (error) { + return mapDbError(error, 'Failed to add photo to trip'); + } +} + +export async function addTripPhotos( + tripId: string, + userId: number, + shared: boolean, + selections: Selection[], + sid: string, + albumLinkId?: string, +): Promise> { + const access = canAccessTrip(tripId, userId); + if (!access) { + return fail('Trip not found or access denied', 404); + } + + if (selections.length === 0) { + return fail('No photos selected', 400); + } + + let added = 0; + for (const selection of selections) { + const providerResult = _validProvider(selection.provider); + if (!providerResult.success) { + return providerResult as ServiceResult<{ added: number; shared: boolean }>; + } + for (const raw of selection.asset_ids) { + const assetId = String(raw || '').trim(); + if (!assetId) continue; + const result = _addTripPhoto(tripId, userId, selection.provider, assetId, shared, albumLinkId, selection.passphrase); + if (!result.success) { + return result as ServiceResult<{ added: number; shared: boolean }>; + } + if (result.data) { + added++; + } + } + } + + await _notifySharedTripPhotos(tripId, userId, added); + broadcast(tripId, 'memories:updated', { userId }, sid); + return success({ added, shared }); +} + + +export async function setTripPhotoSharing( + tripId: string, + userId: number, + photoId: number, + shared: boolean, + sid?: string, +): Promise> { + const access = canAccessTrip(tripId, userId); + if (!access) { + return fail('Trip not found or access denied', 404); + } + + try { + db.prepare(` + UPDATE trip_photos + SET shared = ? + WHERE trip_id = ? + AND user_id = ? + AND photo_id = ? + `).run(shared ? 1 : 0, tripId, userId, photoId); + + await _notifySharedTripPhotos(tripId, userId, 1); + broadcast(tripId, 'memories:updated', { userId }, sid); + return success(true); + } catch (error) { + return mapDbError(error, 'Failed to update photo sharing'); + } +} + +export function removeTripPhoto( + tripId: string, + userId: number, + photoId: number, + sid?: string, +): ServiceResult { + const access = canAccessTrip(tripId, userId); + if (!access) { + return fail('Trip not found or access denied', 404); + } + + try { + db.prepare(` + DELETE FROM trip_photos + WHERE trip_id = ? + AND user_id = ? + AND photo_id = ? + `).run(tripId, userId, photoId); + + deleteTrekPhotoIfOrphan(photoId); + broadcast(tripId, 'memories:updated', { userId }, sid); + + return success(true); + } catch (error) { + return mapDbError(error, 'Failed to remove trip photo'); + } +} + +// ---------------------------------------------- +// managing album links in trip + +export function createTripAlbumLink(tripId: string, userId: number, providerRaw: unknown, albumIdRaw: unknown, albumNameRaw: unknown, passphrase?: string): ServiceResult { + const access = canAccessTrip(tripId, userId); + if (!access) { + return fail('Trip not found or access denied', 404); + } + + const provider = String(providerRaw || '').toLowerCase(); + const albumId = String(albumIdRaw || '').trim(); + const albumName = String(albumNameRaw || '').trim(); + + if (!provider) { + return fail('provider is required', 400); + } + if (!albumId) { + return fail('album_id required', 400); + } + + + const providerResult = _validProvider(provider); + if (!providerResult.success) { + return providerResult as ServiceResult; + } + + try { + const encryptedPassphrase = passphrase ? encrypt_api_key(passphrase) : null; + const result = db.prepare( + 'INSERT OR IGNORE INTO trip_album_links (trip_id, user_id, provider, album_id, album_name, passphrase) VALUES (?, ?, ?, ?, ?, ?)' + ).run(tripId, userId, provider, albumId, albumName, encryptedPassphrase); + + if (result.changes === 0) { + return fail('Album already linked', 409); + } + + return success(true); + } catch (error) { + return mapDbError(error, 'Failed to link album'); + } +} + +export function removeAlbumLink(tripId: string, linkId: string, userId: number): ServiceResult { + const access = canAccessTrip(tripId, userId); + if (!access) { + return fail('Trip not found or access denied', 404); + } + + try { + const linkedPhotos = db.prepare('SELECT photo_id FROM trip_photos WHERE trip_id = ? AND album_link_id = ?') + .all(tripId, linkId) as Array<{ photo_id: number }>; + + db.transaction(() => { + db.prepare('DELETE FROM trip_photos WHERE trip_id = ? AND album_link_id = ?') + .run(tripId, linkId); + db.prepare('DELETE FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ?') + .run(linkId, tripId, userId); + })(); + + for (const { photo_id } of linkedPhotos) { + deleteTrekPhotoIfOrphan(photo_id); + } + + return success(true); + } catch (error) { + return mapDbError(error, 'Failed to remove album link'); + } +} + + +//----------------------------------------------- +// notifications helper + +async function _notifySharedTripPhotos( + tripId: string, + actorUserId: number, + added: number, +): Promise> { + if (added <= 0) return success(undefined); + + try { + const actorRow = db.prepare('SELECT username, email FROM users WHERE id = ?').get(actorUserId) as { username: string | null, email: string | null }; + + const tripInfo = db.prepare('SELECT title FROM trips WHERE id = ?').get(tripId) as { title: string } | undefined; + + + send({ event: 'photos_shared', actorId: actorUserId, scope: 'trip', targetId: Number(tripId), params: { trip: tripInfo?.title || 'Untitled', actor: actorRow?.email || 'Unknown', count: String(added), tripId: String(tripId) } }).catch(() => {}); + return success(undefined); + } catch { + return fail('Failed to send notifications', 500); + } +} diff --git a/server/src/services/mfaCrypto.ts b/server/src/services/mfaCrypto.ts new file mode 100644 index 0000000000000000000000000000000000000000..2a64743fffc7974a95e96d071c320338f1446691 --- /dev/null +++ b/server/src/services/mfaCrypto.ts @@ -0,0 +1,25 @@ +import crypto from 'crypto'; +import { ENCRYPTION_KEY } from '../config'; + +function getKey(): Buffer { + return crypto.createHash('sha256').update(`${ENCRYPTION_KEY}:mfa:v1`).digest(); +} + +/** Encrypt TOTP secret for storage in SQLite. */ +export function encryptMfaSecret(plain: string): string { + const iv = crypto.randomBytes(12); + const cipher = crypto.createCipheriv('aes-256-gcm', getKey(), iv); + const enc = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]); + const tag = cipher.getAuthTag(); + return Buffer.concat([iv, tag, enc]).toString('base64'); +} + +export function decryptMfaSecret(blob: string): string { + const buf = Buffer.from(blob, 'base64'); + const iv = buf.subarray(0, 12); + const tag = buf.subarray(12, 28); + const enc = buf.subarray(28); + const decipher = crypto.createDecipheriv('aes-256-gcm', getKey(), iv); + decipher.setAuthTag(tag); + return Buffer.concat([decipher.update(enc), decipher.final()]).toString('utf8'); +} diff --git a/server/src/services/notificationPreferencesService.ts b/server/src/services/notificationPreferencesService.ts new file mode 100644 index 0000000000000000000000000000000000000000..6efe538b61a4622dbaac80bf5bdaf13b8569d28b --- /dev/null +++ b/server/src/services/notificationPreferencesService.ts @@ -0,0 +1,277 @@ +import type Database from 'better-sqlite3'; +import { db } from '../db/database'; +import { decrypt_api_key } from './apiKeyCrypto'; + +// ── Types ────────────────────────────────────────────────────────────────── + +export type NotifChannel = 'email' | 'webhook' | 'inapp' | 'ntfy'; + +export type NotifEventType = + | 'trip_invite' + | 'booking_change' + | 'trip_reminder' + | 'todo_due' + | 'vacay_invite' + | 'photos_shared' + | 'collab_message' + | 'packing_tagged' + | 'version_available' + | 'synology_session_cleared'; + +export interface AvailableChannels { + email: boolean; + webhook: boolean; + inapp: boolean; + ntfy: boolean; +} + +// Which channels are implemented for each event type. +// Only implemented combos show toggles in the user preferences UI. +const IMPLEMENTED_COMBOS: Record = { + trip_invite: ['inapp', 'email', 'webhook', 'ntfy'], + booking_change: ['inapp', 'email', 'webhook', 'ntfy'], + trip_reminder: ['inapp', 'email', 'webhook', 'ntfy'], + todo_due: ['inapp', 'email', 'webhook', 'ntfy'], + vacay_invite: ['inapp', 'email', 'webhook', 'ntfy'], + photos_shared: ['inapp', 'email', 'webhook', 'ntfy'], + collab_message: ['inapp', 'email', 'webhook', 'ntfy'], + packing_tagged: ['inapp', 'email', 'webhook', 'ntfy'], + version_available: ['inapp', 'email', 'webhook', 'ntfy'], + synology_session_cleared: ['inapp'], +}; + +/** Events that target admins only (shown in admin panel, not in user settings). */ +export const ADMIN_SCOPED_EVENTS = new Set(['version_available']); + +// ── Helpers ──────────────────────────────────────────────────────────────── + +function getAppSetting(key: string): string | null { + return (db.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as { value: string } | undefined)?.value || null; +} + +// ── Active channels (admin-configured) ──────────────────────────────────── + +/** + * Returns which channels the admin has enabled (email and/or webhook). + * Reads `notification_channels` (plural) with fallback to `notification_channel` (singular). + * In-app is always considered active at the service level. + */ +export function getActiveChannels(): NotifChannel[] { + const raw = getAppSetting('notification_channels') || getAppSetting('notification_channel') || 'none'; + if (raw === 'none') return []; + return raw.split(',').map(c => c.trim()).filter((c): c is NotifChannel => c === 'email' || c === 'webhook' || c === 'ntfy'); +} + +/** + * Returns which channels are configured (have valid credentials/URLs set). + * In-app is always available. Email/webhook depend on configuration. + */ +export function getAvailableChannels(): AvailableChannels { + const hasSmtp = !!(process.env.SMTP_HOST || getAppSetting('smtp_host')); + const activeChannels = getActiveChannels(); + return { email: hasSmtp, webhook: activeChannels.includes('webhook'), ntfy: activeChannels.includes('ntfy'), inapp: true }; +} + +// ── Per-user preference checks ───────────────────────────────────────────── + +/** + * Returns true if the user has this event+channel enabled. + * Default (no row) = enabled. Only returns false if there's an explicit disabled row. + */ +export function isEnabledForEvent(userId: number, eventType: NotifEventType, channel: NotifChannel): boolean { + const row = db.prepare( + 'SELECT enabled FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?' + ).get(userId, eventType, channel) as { enabled: number } | undefined; + return row === undefined || row.enabled === 1; +} + +// ── Preferences matrix ───────────────────────────────────────────────────── + +export interface PreferencesMatrix { + preferences: Partial>>>; + available_channels: AvailableChannels; + event_types: NotifEventType[]; + implemented_combos: Record; + defaults?: { ntfyServer: string | null }; +} + +/** + * Returns the preferences matrix for a user. + * scope='user' — excludes admin-scoped events (for user settings page) + * scope='admin' — returns only admin-scoped events (for admin notifications tab) + */ +export function getPreferencesMatrix(userId: number, userRole: string, scope: 'user' | 'admin' = 'user'): PreferencesMatrix { + const rows = db.prepare( + 'SELECT event_type, channel, enabled FROM notification_channel_preferences WHERE user_id = ?' + ).all(userId) as Array<{ event_type: string; channel: string; enabled: number }>; + + // Build a lookup from stored rows + const stored: Partial>>> = {}; + for (const row of rows) { + if (!stored[row.event_type]) stored[row.event_type] = {}; + stored[row.event_type]![row.channel] = row.enabled === 1; + } + + // Build the full matrix with defaults (true when no row exists) + const preferences: Partial>>> = {}; + const allEvents = Object.keys(IMPLEMENTED_COMBOS) as NotifEventType[]; + + for (const eventType of allEvents) { + const channels = IMPLEMENTED_COMBOS[eventType]; + preferences[eventType] = {}; + for (const channel of channels) { + // Admin-scoped events use global settings for email/webhook/ntfy + if (scope === 'admin' && ADMIN_SCOPED_EVENTS.has(eventType) && (channel === 'email' || channel === 'webhook' || channel === 'ntfy')) { + preferences[eventType]![channel] = getAdminGlobalPref(eventType, channel); + } else { + preferences[eventType]![channel] = stored[eventType]?.[channel] ?? true; + } + } + } + + // Filter event types by scope + const event_types = scope === 'admin' + ? allEvents.filter(e => ADMIN_SCOPED_EVENTS.has(e)) + : allEvents.filter(e => !ADMIN_SCOPED_EVENTS.has(e)); + + // Available channels depend on scope + let available_channels: AvailableChannels; + if (scope === 'admin') { + const hasSmtp = !!(process.env.SMTP_HOST || getAppSetting('smtp_host')); + const hasAdminWebhook = !!(getAppSetting('admin_webhook_url')); + const hasAdminNtfy = !!(getAppSetting('admin_ntfy_topic')); + available_channels = { email: hasSmtp, webhook: hasAdminWebhook, ntfy: hasAdminNtfy, inapp: true }; + } else { + const activeChannels = getActiveChannels(); + available_channels = { + email: activeChannels.includes('email'), + webhook: activeChannels.includes('webhook'), + ntfy: activeChannels.includes('ntfy'), + inapp: true, + }; + } + + return { + preferences, + available_channels, + event_types, + implemented_combos: IMPLEMENTED_COMBOS, + ...(scope === 'user' && { defaults: { ntfyServer: getAppSetting('admin_ntfy_server') || null } }), + }; +} + +// ── Admin global preferences (stored in app_settings) ───────────────────── + +const ADMIN_GLOBAL_CHANNELS: NotifChannel[] = ['email', 'webhook', 'ntfy']; + +/** + * Returns the global admin preference for an event+channel. + * Stored in app_settings as `admin_notif_pref_{event}_{channel}`. + * Defaults to true (enabled) when no row exists. + */ +export function getAdminGlobalPref(event: NotifEventType, channel: 'email' | 'webhook' | 'ntfy'): boolean { + const val = getAppSetting(`admin_notif_pref_${event}_${channel}`); + return val !== '0'; +} + +function setAdminGlobalPref(event: NotifEventType, channel: 'email' | 'webhook' | 'ntfy', enabled: boolean): void { + db.prepare('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)').run( + `admin_notif_pref_${event}_${channel}`, + enabled ? '1' : '0' + ); +} + +// ── Preferences update ───────────────────────────────────────────────────── + +// ── Shared helper for per-user channel preference upserts ───────────────── + +function applyUserChannelPrefs( + userId: number, + prefs: Partial>>>, + upsert: Database.Statement, + del: Database.Statement +): void { + for (const [eventType, channels] of Object.entries(prefs)) { + if (!channels) continue; + for (const [channel, enabled] of Object.entries(channels)) { + if (enabled) { + // Remove explicit row — default is enabled + del.run(userId, eventType, channel); + } else { + upsert.run(userId, eventType, channel, 0); + } + } + } +} + +/** + * Bulk-update preferences from the matrix UI. + * Inserts disabled rows (enabled=0) and removes rows that are enabled (default). + */ +export function setPreferences( + userId: number, + prefs: Partial>>> +): void { + const upsert = db.prepare( + 'INSERT OR REPLACE INTO notification_channel_preferences (user_id, event_type, channel, enabled) VALUES (?, ?, ?, ?)' + ); + const del = db.prepare( + 'DELETE FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?' + ); + db.transaction(() => applyUserChannelPrefs(userId, prefs, upsert, del))(); +} + +/** + * Bulk-update admin notification preferences. + * email/webhook channels are stored globally in app_settings (not per-user). + * inapp channel remains per-user in notification_channel_preferences. + */ +export function setAdminPreferences( + userId: number, + prefs: Partial>>> +): void { + const upsert = db.prepare( + 'INSERT OR REPLACE INTO notification_channel_preferences (user_id, event_type, channel, enabled) VALUES (?, ?, ?, ?)' + ); + const del = db.prepare( + 'DELETE FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?' + ); + + // Split global (email/webhook) from per-user (inapp) prefs + const globalPrefs: Partial>>> = {}; + const userPrefs: Partial>>> = {}; + + for (const [eventType, channels] of Object.entries(prefs)) { + if (!channels) continue; + for (const [channel, enabled] of Object.entries(channels)) { + if (ADMIN_GLOBAL_CHANNELS.includes(channel as NotifChannel)) { + if (!globalPrefs[eventType]) globalPrefs[eventType] = {}; + globalPrefs[eventType]![channel] = enabled; + } else { + if (!userPrefs[eventType]) userPrefs[eventType] = {}; + userPrefs[eventType]![channel] = enabled; + } + } + } + + // Apply global prefs outside the transaction (they write to app_settings) + for (const [eventType, channels] of Object.entries(globalPrefs)) { + if (!channels) continue; + for (const [channel, enabled] of Object.entries(channels)) { + setAdminGlobalPref(eventType as NotifEventType, channel as 'email' | 'webhook' | 'ntfy', enabled); + } + } + + // Apply per-user (inapp) prefs in a transaction + db.transaction(() => applyUserChannelPrefs(userId, userPrefs, upsert, del))(); +} + +// ── SMTP availability helper (for authService) ───────────────────────────── + +export function isSmtpConfigured(): boolean { + return !!(process.env.SMTP_HOST || getAppSetting('smtp_host')); +} + +export function isWebhookConfigured(): boolean { + return getActiveChannels().includes('webhook'); +} diff --git a/server/src/services/notificationService.ts b/server/src/services/notificationService.ts new file mode 100644 index 0000000000000000000000000000000000000000..67f02f2a5f2a243896e59c8f2c80626950ea830c --- /dev/null +++ b/server/src/services/notificationService.ts @@ -0,0 +1,328 @@ +import { db } from '../db/database'; +import { logDebug, logError } from './auditLog'; +import { + getActiveChannels, + isEnabledForEvent, + getAdminGlobalPref, + isSmtpConfigured, + ADMIN_SCOPED_EVENTS, + type NotifEventType, + type NotifChannel, +} from './notificationPreferencesService'; +import { + getEventText, + sendEmail, + sendWebhook, + sendNtfy, + getUserEmail, + getUserLanguage, + getUserWebhookUrl, + getAdminWebhookUrl, + getUserNtfyConfig, + getAdminNtfyConfig, + resolveNtfyUrl, + getAppUrl, +} from './notifications'; +import { + resolveRecipients, + createNotificationForRecipient, + type NotificationInput, +} from './inAppNotifications'; + +// ── Event config map ─────────────────────────────────────────────────────── + +interface EventNotifConfig { + inAppType: 'simple' | 'navigate'; + titleKey: string; + textKey: string; + navigateTextKey?: string; + navigateTarget: (params: Record) => string | null; +} + +const EVENT_NOTIFICATION_CONFIG: Record = { + // ── Dev-only test events ────────────────────────────────────────────────── + test_simple: { + inAppType: 'simple', + titleKey: 'notif.test.title', + textKey: 'notif.test.simple.text', + navigateTarget: () => null, + }, + test_boolean: { + inAppType: 'simple', // overridden by inApp.type at call site + titleKey: 'notif.test.title', + textKey: 'notif.test.boolean.text', + navigateTarget: () => null, + }, + test_navigate: { + inAppType: 'navigate', + titleKey: 'notif.test.title', + textKey: 'notif.test.navigate.text', + navigateTextKey: 'notif.action.view', + navigateTarget: () => '/dashboard', + }, + // ── Production events ───────────────────────────────────────────────────── + trip_invite: { + inAppType: 'navigate', + titleKey: 'notif.trip_invite.title', + textKey: 'notif.trip_invite.text', + navigateTextKey: 'notif.action.view_trip', + navigateTarget: p => (p.tripId ? `/trips/${p.tripId}` : null), + }, + booking_change: { + inAppType: 'navigate', + titleKey: 'notif.booking_change.title', + textKey: 'notif.booking_change.text', + navigateTextKey: 'notif.action.view_trip', + navigateTarget: p => (p.tripId ? `/trips/${p.tripId}` : null), + }, + trip_reminder: { + inAppType: 'navigate', + titleKey: 'notif.trip_reminder.title', + textKey: 'notif.trip_reminder.text', + navigateTextKey: 'notif.action.view_trip', + navigateTarget: p => (p.tripId ? `/trips/${p.tripId}` : null), + }, + todo_due: { + inAppType: 'navigate', + titleKey: 'notif.todo_due.title', + textKey: 'notif.todo_due.text', + navigateTextKey: 'notif.action.view_trip', + navigateTarget: p => (p.tripId ? `/trips/${p.tripId}` : null), + }, + vacay_invite: { + inAppType: 'navigate', + titleKey: 'notif.vacay_invite.title', + textKey: 'notif.vacay_invite.text', + navigateTextKey: 'notif.action.view_vacay', + navigateTarget: p => (p.planId ? `/vacay/${p.planId}` : null), + }, + photos_shared: { + inAppType: 'navigate', + titleKey: 'notif.photos_shared.title', + textKey: 'notif.photos_shared.text', + navigateTextKey: 'notif.action.view_trip', + navigateTarget: p => (p.tripId ? `/trips/${p.tripId}` : null), + }, + collab_message: { + inAppType: 'navigate', + titleKey: 'notif.collab_message.title', + textKey: 'notif.collab_message.text', + navigateTextKey: 'notif.action.view_collab', + navigateTarget: p => (p.tripId ? `/trips/${p.tripId}` : null), + }, + packing_tagged: { + inAppType: 'navigate', + titleKey: 'notif.packing_tagged.title', + textKey: 'notif.packing_tagged.text', + navigateTextKey: 'notif.action.view_packing', + navigateTarget: p => (p.tripId ? `/trips/${p.tripId}` : null), + }, + version_available: { + inAppType: 'navigate', + titleKey: 'notif.version_available.title', + textKey: 'notif.version_available.text', + navigateTextKey: 'notif.action.view_admin', + navigateTarget: () => '/admin', + }, + synology_session_cleared: { + inAppType: 'simple', + titleKey: 'notifications.synologySessionCleared.title', + textKey: 'notifications.synologySessionCleared.text', + navigateTarget: () => null, + }, +}; + +// ── Fallback config for unknown event types ──────────────────────────────── + +const FALLBACK_EVENT_CONFIG: EventNotifConfig = { + inAppType: 'simple', + titleKey: 'notif.generic.title', + textKey: 'notif.generic.text', + navigateTarget: () => null, +}; + +// ── Unified send() API ───────────────────────────────────────────────────── + +export interface NotificationPayload { + event: NotifEventType; + actorId: number | null; + params: Record; + scope: 'trip' | 'user' | 'admin'; + targetId: number; // tripId for trip scope, userId for user scope, 0 for admin + /** Optional in-app overrides (e.g. boolean type with callbacks) */ + inApp?: { + type?: 'simple' | 'boolean' | 'navigate'; + positiveTextKey?: string; + negativeTextKey?: string; + positiveCallback?: { action: string; payload: Record }; + negativeCallback?: { action: string; payload: Record }; + navigateTarget?: string; // override the auto-generated navigate target + }; +} + +export async function send(payload: NotificationPayload): Promise { + const { event, actorId, params, scope, targetId, inApp } = payload; + + // Resolve recipients based on scope + const recipients = resolveRecipients(scope, targetId, actorId); + if (recipients.length === 0) return; + + const configEntry = EVENT_NOTIFICATION_CONFIG[event]; + if (!configEntry) { + logDebug(`notificationService.send: unknown event type "${event}", using fallback`); + if (process.env.NODE_ENV?.toLowerCase() === 'development' && actorId != null) { + const devSender = (db.prepare('SELECT username, avatar FROM users WHERE id = ?').get(actorId) as { username: string; avatar: string | null } | undefined) ?? null; + createNotificationForRecipient({ + type: 'simple', + scope: 'user', + target: actorId, + sender_id: null, + title_key: 'notif.dev.unknown_event.title', + text_key: 'notif.dev.unknown_event.text', + text_params: { event }, + }, actorId, devSender); + } + } + const config = configEntry ?? FALLBACK_EVENT_CONFIG; + const activeChannels = getActiveChannels(); + const appUrl = getAppUrl(); + + // Build navigate target (used by email/webhook CTA and in-app navigate) + const navigateTarget = inApp?.navigateTarget ?? config.navigateTarget(params); + const fullLink = navigateTarget ? `${appUrl}${navigateTarget}` : undefined; + + // Fetch sender info once for in-app WS payloads + const sender = actorId + ? (db.prepare('SELECT username, avatar FROM users WHERE id = ?').get(actorId) as { username: string; avatar: string | null } | undefined) ?? null + : null; + + logDebug(`notificationService.send event=${event} scope=${scope} targetId=${targetId} recipients=${recipients.length} channels=inapp,${activeChannels.join(',')}`); + + // Dispatch to each recipient in parallel + await Promise.all(recipients.map(async (recipientId) => { + const promises: Promise[] = []; + + // ── In-app ────────────────────────────────────────────────────────── + if (isEnabledForEvent(recipientId, event, 'inapp')) { + const inAppType = inApp?.type ?? config.inAppType; + let notifInput: NotificationInput; + + if (inAppType === 'boolean' && inApp?.positiveCallback && inApp?.negativeCallback) { + notifInput = { + type: 'boolean', + scope, + target: targetId, + sender_id: actorId, + event_type: event, + title_key: config.titleKey, + title_params: params, + text_key: config.textKey, + text_params: params, + positive_text_key: inApp.positiveTextKey ?? 'notif.action.accept', + negative_text_key: inApp.negativeTextKey ?? 'notif.action.decline', + positive_callback: inApp.positiveCallback, + negative_callback: inApp.negativeCallback, + }; + } else if (inAppType === 'navigate' && navigateTarget) { + notifInput = { + type: 'navigate', + scope, + target: targetId, + sender_id: actorId, + event_type: event, + title_key: config.titleKey, + title_params: params, + text_key: config.textKey, + text_params: params, + navigate_text_key: config.navigateTextKey ?? 'notif.action.view', + navigate_target: navigateTarget, + }; + } else { + notifInput = { + type: 'simple', + scope, + target: targetId, + sender_id: actorId, + event_type: event, + title_key: config.titleKey, + title_params: params, + text_key: config.textKey, + text_params: params, + }; + } + + promises.push( + Promise.resolve().then(() => createNotificationForRecipient(notifInput, recipientId, sender ?? null)) + ); + } + + // ── Email ──────────────────────────────────────────────────────────── + // Admin-scoped events: use global pref + SMTP check (bypass notification_channels toggle) + // Regular events: use active channels + per-user pref + const emailEnabled = ADMIN_SCOPED_EVENTS.has(event) + ? isSmtpConfigured() && getAdminGlobalPref(event, 'email') + : activeChannels.includes('email') && isEnabledForEvent(recipientId, event, 'email'); + + if (emailEnabled) { + const email = getUserEmail(recipientId); + if (email) { + const lang = getUserLanguage(recipientId); + const { title, body } = getEventText(lang, event, params); + promises.push(sendEmail(email, title, body, recipientId, navigateTarget ?? undefined)); + } + } + + // ── Webhook (per-user) — skip for admin-scoped events (handled globally below) ── + if (!ADMIN_SCOPED_EVENTS.has(event) && activeChannels.includes('webhook') && isEnabledForEvent(recipientId, event, 'webhook')) { + const webhookUrl = getUserWebhookUrl(recipientId); + if (webhookUrl) { + const lang = getUserLanguage(recipientId); + const { title, body } = getEventText(lang, event, params); + promises.push(sendWebhook(webhookUrl, { event, title, body, tripName: params.trip, link: fullLink })); + } + } + + // ── Ntfy (per-user) — skip for admin-scoped events (handled globally below) ── + if (!ADMIN_SCOPED_EVENTS.has(event) && activeChannels.includes('ntfy') && isEnabledForEvent(recipientId, event, 'ntfy' as NotifChannel)) { + const userNtfyCfg = getUserNtfyConfig(recipientId); + const adminNtfyCfg = getAdminNtfyConfig(); + const ntfyUrl = resolveNtfyUrl(adminNtfyCfg, userNtfyCfg); + if (ntfyUrl) { + const lang = getUserLanguage(recipientId); + const { title, body } = getEventText(lang, event, params); + const token = userNtfyCfg?.token ?? adminNtfyCfg.token; + promises.push(sendNtfy(ntfyUrl, token, { event, title, body, link: fullLink })); + } + } + + const results = await Promise.allSettled(promises); + for (const result of results) { + if (result.status === 'rejected') { + logError(`notificationService.send channel dispatch failed event=${event} recipient=${recipientId}: ${result.reason}`); + } + } + })); + + // ── Admin webhook (scope: admin) — global, respects global pref ────── + if (scope === 'admin' && getAdminGlobalPref(event, 'webhook')) { + const adminWebhookUrl = getAdminWebhookUrl(); + if (adminWebhookUrl) { + const { title, body } = getEventText('en', event, params); + await sendWebhook(adminWebhookUrl, { event, title, body, link: fullLink }).catch((err: unknown) => { + logError(`notificationService.send admin webhook failed event=${event}: ${err instanceof Error ? err.message : err}`); + }); + } + } + + // ── Admin ntfy (scope: admin) — global, respects global pref ───────── + if (scope === 'admin' && getAdminGlobalPref(event, 'ntfy')) { + const adminNtfyCfg = getAdminNtfyConfig(); + const adminNtfyUrl = resolveNtfyUrl(adminNtfyCfg, null); + if (adminNtfyUrl) { + const { title, body } = getEventText('en', event, params); + await sendNtfy(adminNtfyUrl, adminNtfyCfg.token, { event, title, body, link: fullLink }).catch((err: unknown) => { + logError(`notificationService.send admin ntfy failed event=${event}: ${err instanceof Error ? err.message : err}`); + }); + } + } +} diff --git a/server/src/services/notifications.ts b/server/src/services/notifications.ts new file mode 100644 index 0000000000000000000000000000000000000000..c13573dc374b6ce8bb07ef58add8b0fb48c2cd50 --- /dev/null +++ b/server/src/services/notifications.ts @@ -0,0 +1,507 @@ +import nodemailer from 'nodemailer'; +import { db } from '../db/database'; +import { decrypt_api_key } from './apiKeyCrypto'; +import { logInfo, logDebug, logError } from './auditLog'; +import { checkSsrf, createPinnedDispatcher } from '../utils/ssrfGuard'; + +// ── Types ────────────────────────────────────────────────────────────────── + +import type { NotifEventType } from './notificationPreferencesService'; +import { EMAIL_I18N as I18N, EVENT_TEXTS, PASSWORD_RESET_I18N } from '@trek/shared/i18n/externalNotifications'; +import type { EmailStrings, EventText, PasswordResetStrings, NotificationEventKey } from '@trek/shared/i18n/externalNotifications'; + +// Compile-time guard: shared NotificationEventKey and server NotifEventType must stay in sync. +type _EvtFwd = NotifEventType extends NotificationEventKey ? true : never +type _EvtBwd = NotificationEventKey extends NotifEventType ? true : never +const _eventKeyDriftGuard: [_EvtFwd, _EvtBwd] = [true, true] + +interface SmtpConfig { + host: string; + port: number; + user: string; + pass: string; + from: string; + secure: boolean; +} + +// ── HTML escaping ────────────────────────────────────────────────────────── + +function escapeHtml(str: string): string { + return str + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +// ── Settings helpers ─────────────────────────────────────────────────────── + +function getAppSetting(key: string): string | null { + return (db.prepare("SELECT value FROM app_settings WHERE key = ?").get(key) as { value: string } | undefined)?.value || null; +} + +function getSmtpConfig(): SmtpConfig | null { + const host = process.env.SMTP_HOST || getAppSetting('smtp_host'); + const port = process.env.SMTP_PORT || getAppSetting('smtp_port'); + const user = process.env.SMTP_USER || getAppSetting('smtp_user'); + const pass = process.env.SMTP_PASS || decrypt_api_key(getAppSetting('smtp_pass')) || ''; + const from = process.env.SMTP_FROM || getAppSetting('smtp_from'); + if (!host || !port || !from) return null; + return { host, port: parseInt(port, 10), user: user || '', pass: pass || '', from, secure: parseInt(port, 10) === 465 }; +} + +// Exported for use by notificationService +export function getAppUrl(): string { + if (process.env.APP_URL) { + try { + const _ = new URL(process.env.APP_URL); + return process.env.APP_URL.replace(/\/+$/, ''); + } catch (_ignored) { + } + } + const origins = process.env.ALLOWED_ORIGINS; + if (origins) { + const first = origins.split(',')[0]?.trim(); + if (first) { + try { + const _ = new URL(first); + return first.replace(/\/+$/, ''); + } catch (_ignored) { + } + } + } + const port = Number(process.env.PORT) || 3001; + return `http://localhost:${port}`; +} + +/** Returns a URL guaranteed to satisfy the MCP SDK's issuer requirements (HTTPS or localhost). + * Falls back to http://localhost:{PORT} when APP_URL/ALLOWED_ORIGINS use a non-HTTPS, non-localhost scheme + * that would cause checkIssuerUrl to throw "Issuer URL must be HTTPS". */ +export function getMcpSafeUrl(): string { + const candidate = getAppUrl(); + try { + const u = new URL(candidate); + if (u.protocol === 'https:' || u.hostname === 'localhost' || u.hostname === '127.0.0.1') { + return candidate; + } + } catch { + // candidate was somehow invalid — fall through to localhost + } + const port = Number(process.env.PORT) || 3001; + return `http://localhost:${port}`; +} + +export function getUserEmail(userId: number): string | null { + return (db.prepare('SELECT email FROM users WHERE id = ?').get(userId) as { email: string } | undefined)?.email || null; +} + +export function getUserLanguage(userId: number): string { + return (db.prepare("SELECT value FROM settings WHERE user_id = ? AND key = 'language'").get(userId) as { value: string } | undefined)?.value || 'en'; +} + +export function getUserWebhookUrl(userId: number): string | null { + const value = (db.prepare("SELECT value FROM settings WHERE user_id = ? AND key = 'webhook_url'").get(userId) as { value: string } | undefined)?.value || null; + return value ? decrypt_api_key(value) : null; +} + +export function getAdminWebhookUrl(): string | null { + const value = getAppSetting('admin_webhook_url') || null; + return value ? decrypt_api_key(value) : null; +} + +// ── Email i18n strings — imported from @trek/shared/i18n/externalNotifications ── + +// EVENT_TEXTS imported from @trek/shared/i18n/externalNotifications + +// Get localized event text +export function getEventText(lang: string, event: NotifEventType, params: Record): EventText { + const texts = EVENT_TEXTS[lang] || EVENT_TEXTS.en; + const fn = texts[event] ?? EVENT_TEXTS.en[event]; + if (!fn) return { title: event, body: '' }; + return fn(params); +} + +// ── Email HTML builder ───────────────────────────────────────────────────── + +export function buildEmailHtml(subject: string, body: string, lang: string, navigateTarget?: string, rawBody = false): string { + const s = I18N[lang] || I18N.en; + const appUrl = getAppUrl(); + const ctaHref = escapeHtml(navigateTarget ? `${appUrl}${navigateTarget}` : (appUrl || '')); + const safeSubject = escapeHtml(subject); + const safeBody = rawBody ? body : escapeHtml(body); + + return ` + + + + + +
+ + + + + + + ${appUrl ? `` : ''} + + +
+ TREK +
TREK
+
Travel Resource & Exploration Kit
+
+

${safeSubject}

+
+

${safeBody}

+
+ ${s.openTrek} +
+

${s.footer}
${s.manage}

+

${s.madeWith} ♥ by Maurice · GitHub

+
+
+ +`; +} + +// ── Send functions ───────────────────────────────────────────────────────── + +// ── Password reset email ─────────────────────────────────────────────────── + +// PASSWORD_RESET_I18N imported from @trek/shared/i18n/externalNotifications + +function buildPasswordResetHtml(subject: string, strings: PasswordResetStrings, recipient: string, resetUrl: string, lang: string): string { + const safeGreeting = escapeHtml(`${strings.greeting}, ${recipient}`); + const safeBody = escapeHtml(strings.body); + const safeExpiry = escapeHtml(strings.expiry); + const safeIgnore = escapeHtml(strings.ignore); + const safeCta = escapeHtml(strings.ctaIntro); + const block = ` +

${safeGreeting},

+

${safeBody}

+

+ ${safeCta} +

+

${safeExpiry}

+

${safeIgnore}

+ `; + return buildEmailHtml(subject, block, lang, undefined, true); +} + +/** + * Delivers a password-reset link. When SMTP is configured the user + * receives an email. When it isn't, the link is logged to stdout in a + * clearly-fenced block so the self-hosting admin can hand it off by + * other means. In both cases the caller always gets a boolean that + * indicates only whether the caller should treat delivery as + * best-effort done — the API response to the user must NOT leak it. + */ +export async function sendPasswordResetEmail( + to: string, + resetUrl: string, + userId: number | null, +): Promise<{ delivered: 'email' | 'log' | 'failed' }> { + const lang = userId ? getUserLanguage(userId) : 'en'; + const strings = PASSWORD_RESET_I18N[lang] || PASSWORD_RESET_I18N.en; + const smtpCfg = getSmtpConfig(); + + if (!smtpCfg) { + // No SMTP configured — log the link in a visually distinct block so + // the admin can relay it. Never log the associated user id/email + // content at a lower level, only what's needed. + // eslint-disable-next-line no-console + console.log( + `\n===== PASSWORD RESET LINK =====\n` + + `to: ${to}\n` + + `url: ${resetUrl}\n` + + `expires: 60 minutes\n` + + `(SMTP is not configured — deliver this link to the user manually.)\n` + + `================================\n`, + ); + logInfo(`Password reset link issued (no SMTP) for=${to}`); + return { delivered: 'log' }; + } + + try { + const skipTls = process.env.SMTP_SKIP_TLS_VERIFY === 'true' || getAppSetting('smtp_skip_tls_verify') === 'true'; + const transporter = nodemailer.createTransport({ + host: smtpCfg.host, + port: smtpCfg.port, + secure: smtpCfg.secure, + auth: smtpCfg.user ? { user: smtpCfg.user, pass: smtpCfg.pass } : undefined, + ...(skipTls ? { tls: { rejectUnauthorized: false } } : {}), + }); + await transporter.sendMail({ + from: smtpCfg.from, + to, + subject: `TREK — ${strings.subject}`, + text: `${strings.greeting}, ${to}\n\n${strings.body}\n\n${strings.ctaIntro}: ${resetUrl}\n\n${strings.expiry}\n${strings.ignore}`, + html: buildPasswordResetHtml(strings.subject, strings, to, resetUrl, lang), + }); + logInfo(`Password reset email sent to=${to}`); + return { delivered: 'email' }; + } catch (err) { + logError(`Password reset email failed to=${to}: ${err instanceof Error ? err.message : err}`); + return { delivered: 'failed' }; + } +} + +export async function sendEmail(to: string, subject: string, body: string, userId?: number, navigateTarget?: string): Promise { + const config = getSmtpConfig(); + if (!config) return false; + + const lang = userId ? getUserLanguage(userId) : 'en'; + + try { + const skipTls = process.env.SMTP_SKIP_TLS_VERIFY === 'true' || getAppSetting('smtp_skip_tls_verify') === 'true'; + const transporter = nodemailer.createTransport({ + host: config.host, + port: config.port, + secure: config.secure, + auth: config.user ? { user: config.user, pass: config.pass } : undefined, + ...(skipTls ? { tls: { rejectUnauthorized: false } } : {}), + }); + + await transporter.sendMail({ + from: config.from, + to, + subject: `TREK — ${subject}`, + text: body, + html: buildEmailHtml(subject, body, lang, navigateTarget), + }); + logInfo(`Email sent to=${to} subject="${subject}"`); + logDebug(`Email smtp=${config.host}:${config.port} from=${config.from} to=${to}`); + return true; + } catch (err) { + logError(`Email send failed to=${to}: ${err instanceof Error ? err.message : err}`); + return false; + } +} + +export function buildWebhookBody(url: string, payload: { event: string; title: string; body: string; tripName?: string; link?: string }): string { + const isDiscord = /discord(?:app)?\.com\/api\/webhooks\//.test(url); + const isSlack = /hooks\.slack\.com\//.test(url); + + if (isDiscord) { + return JSON.stringify({ + embeds: [{ + title: `📍 ${payload.title}`, + description: payload.body, + url: payload.link, + color: 0x3b82f6, + footer: { text: payload.tripName ? `Trip: ${payload.tripName}` : 'TREK' }, + timestamp: new Date().toISOString(), + }], + }); + } + + if (isSlack) { + const trip = payload.tripName ? ` • _${payload.tripName}_` : ''; + const link = payload.link ? `\n<${payload.link}|Open in TREK>` : ''; + return JSON.stringify({ + text: `*${payload.title}*\n${payload.body}${trip}${link}`, + }); + } + + return JSON.stringify({ ...payload, timestamp: new Date().toISOString(), source: 'TREK' }); +} + +export async function sendWebhook(url: string, payload: { event: string; title: string; body: string; tripName?: string; link?: string }): Promise { + if (!url) return false; + + const ssrf = await checkSsrf(url); + if (!ssrf.allowed) { + logError(`Webhook blocked by SSRF guard event=${payload.event} url=${url} reason=${ssrf.error}`); + return false; + } + + try { + const res = await fetch(url, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: buildWebhookBody(url, payload), + signal: AbortSignal.timeout(10000), + dispatcher: createPinnedDispatcher(ssrf.resolvedIp!), + } as any); + + if (!res.ok) { + const errBody = await res.text().catch(() => ''); + logError(`Webhook HTTP ${res.status}: ${errBody}`); + return false; + } + + logInfo(`Webhook sent event=${payload.event} trip=${payload.tripName || '-'}`); + logDebug(`Webhook url=${url} payload=${buildWebhookBody(url, payload).substring(0, 500)}`); + return true; + } catch (err) { + logError(`Webhook failed event=${payload.event}: ${err instanceof Error ? err.message : err}`); + return false; + } +} + +export async function testSmtp(to: string): Promise<{ success: boolean; error?: string }> { + if (!getSmtpConfig()) return { success: false, error: 'SMTP not configured' }; + try { + const config = getSmtpConfig()!; + const skipTls = process.env.SMTP_SKIP_TLS_VERIFY === 'true' || getAppSetting('smtp_skip_tls_verify') === 'true'; + const transporter = nodemailer.createTransport({ + host: config.host, + port: config.port, + secure: config.secure, + auth: config.user ? { user: config.user, pass: config.pass } : undefined, + ...(skipTls ? { tls: { rejectUnauthorized: false } } : {}), + }); + await transporter.sendMail({ + from: config.from, + to, + subject: 'TREK — Test Notification', + text: 'This is a test email from TREK. If you received this, your SMTP configuration is working correctly.', + }); + return { success: true }; + } catch (err) { + return { success: false, error: err instanceof Error ? err.message : 'Unknown error' }; + } +} + +export async function testWebhook(url: string): Promise<{ success: boolean; error?: string }> { + try { + const sent = await sendWebhook(url, { event: 'test', title: 'Test Notification', body: 'This is a test webhook from TREK. If you received this, your webhook configuration is working correctly.' }); + return sent ? { success: true } : { success: false, error: 'Failed to send webhook' }; + } catch (err) { + return { success: false, error: err instanceof Error ? err.message : 'Unknown error' }; + } +} + +// ── Ntfy ────────────────────────────────────────────────────────────────── + +export interface NtfyConfig { + server: string | null; + topic: string | null; + token: string | null; +} + +/** Priority and tags mapped to each notification event type. */ +const NTFY_EVENT_META: Partial> = { + trip_invite: { priority: 4, tags: ['loudspeaker'] }, + booking_change: { priority: 3, tags: ['calendar'] }, + trip_reminder: { priority: 4, tags: ['bell', 'alarm_clock'] }, + vacay_invite: { priority: 4, tags: ['palm_tree'] }, + photos_shared: { priority: 3, tags: ['camera'] }, + collab_message: { priority: 3, tags: ['speech_balloon'] }, + packing_tagged: { priority: 3, tags: ['luggage'] }, + version_available: { priority: 4, tags: ['package'] }, + synology_session_cleared: { priority: 3, tags: ['warning'] }, +}; +const NTFY_DEFAULT_META = { priority: 3 as const, tags: [] as string[] }; + +export function getUserNtfyConfig(userId: number): NtfyConfig | null { + const rows = db.prepare( + "SELECT key, value FROM settings WHERE user_id = ? AND key IN ('ntfy_topic', 'ntfy_server', 'ntfy_token')" + ).all(userId) as { key: string; value: string }[]; + if (rows.length === 0) return null; + const map: Record = {}; + for (const r of rows) map[r.key] = r.value; + return { + topic: map['ntfy_topic'] || null, + server: map['ntfy_server'] || null, + token: map['ntfy_token'] ? decrypt_api_key(map['ntfy_token']) : null, + }; +} + +export function getAdminNtfyConfig(): NtfyConfig { + const topic = getAppSetting('admin_ntfy_topic') || null; + const server = getAppSetting('admin_ntfy_server') || null; + const rawToken = getAppSetting('admin_ntfy_token') || null; + return { + topic, + server, + token: rawToken ? decrypt_api_key(rawToken) : null, + }; +} + +/** + * Resolve the ntfy POST URL from admin base config + user override. + * Returns null if topic cannot be determined. + */ +export function resolveNtfyUrl(adminCfg: NtfyConfig, userCfg: NtfyConfig | null): string | null { + const topic = userCfg?.topic || adminCfg.topic; + if (!topic) return null; + const base = (userCfg?.server || adminCfg.server || 'https://ntfy.sh').replace(/\/+$/, ''); + return `${base}/${encodeURIComponent(topic)}`; +} + +function encodeHeaderValue(value: string): string { + for (let i = 0; i < value.length; i++) { + if (value.charCodeAt(i) > 0xFF) { + return `=?UTF-8?B?${Buffer.from(value, 'utf8').toString('base64')}?=`; + } + } + return value; +} + +export async function sendNtfy( + url: string, + token: string | null, + payload: { event: string; title: string; body: string; link?: string }, +): Promise { + if (!url) return false; + + const ssrf = await checkSsrf(url); + if (!ssrf.allowed) { + logError(`Ntfy blocked by SSRF guard event=${payload.event} url=${url} reason=${ssrf.error}`); + return false; + } + + const meta = NTFY_EVENT_META[payload.event as NotifEventType] ?? NTFY_DEFAULT_META; + + // ntfy header-based API: POST to topic URL, body = plain text message, metadata in headers + const headers: Record = { + 'Title': encodeHeaderValue(payload.title), + 'Priority': String(meta.priority), + }; + if (meta.tags.length > 0) headers['Tags'] = meta.tags.join(','); + if (payload.link) headers['Click'] = encodeHeaderValue(payload.link); + if (token) headers['Authorization'] = `Bearer ${token}`; + + try { + const res = await fetch(url, { + method: 'POST', + headers, + body: payload.body, + signal: AbortSignal.timeout(10000), + dispatcher: createPinnedDispatcher(ssrf.resolvedIp!), + } as any); + + if (!res.ok) { + const errBody = await res.text().catch(() => ''); + logError(`Ntfy HTTP ${res.status}: ${errBody}`); + return false; + } + + logInfo(`Ntfy sent event=${payload.event}`); + logDebug(`Ntfy url=${url} priority=${meta.priority} tags=${meta.tags.join(',')}`); + return true; + } catch (err) { + logError(`Ntfy failed event=${payload.event}: ${err instanceof Error ? err.message : err}`); + return false; + } +} + +export async function testNtfy(cfg: { topic: string; server?: string | null; token?: string | null }): Promise<{ success: boolean; error?: string }> { + const adminCfg = getAdminNtfyConfig(); + const url = resolveNtfyUrl(adminCfg, { topic: cfg.topic, server: cfg.server ?? null, token: cfg.token ?? null }); + if (!url) return { success: false, error: 'Could not resolve ntfy URL — missing topic' }; + try { + const sent = await sendNtfy(url, cfg.token ?? null, { + event: 'test', + title: 'Test Notification', + body: 'This is a test notification from TREK. If you received this, your ntfy configuration is working correctly.', + }); + return sent ? { success: true } : { success: false, error: 'Failed to send ntfy notification' }; + } catch (err) { + return { success: false, error: err instanceof Error ? err.message : 'Unknown error' }; + } +} + diff --git a/server/src/services/oauthService.ts b/server/src/services/oauthService.ts new file mode 100644 index 0000000000000000000000000000000000000000..45de3b0e12ffe17faba76c026447565e3244312a --- /dev/null +++ b/server/src/services/oauthService.ts @@ -0,0 +1,693 @@ +import crypto, { randomBytes, createHash, randomUUID } from 'crypto'; +import { db } from '../db/database'; +import { isAddonEnabled } from './adminService'; +import { validateScopes } from '../mcp/scopes'; +import { ADDON_IDS } from '../addons'; +import { User } from '../types'; +import { writeAudit, logWarn } from './auditLog'; +import { revokeUserSessionsForClient } from '../mcp/sessionManager'; +import { getMcpSafeUrl } from './notifications'; + +// --------------------------------------------------------------------------- +// Constants +// --------------------------------------------------------------------------- + +const ACCESS_TOKEN_TTL_S = 60 * 60; // 1 hour +const REFRESH_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 days rolling +const AUTH_CODE_TTL_MS = 2 * 60 * 1000; // 2 minutes + +// PKCE format (RFC 7636) +const CODE_CHALLENGE_RE = /^[A-Za-z0-9_-]{43}$/; +const CODE_VERIFIER_RE = /^[A-Za-z0-9\-._~]{43,128}$/; + +// --------------------------------------------------------------------------- +// In-memory auth code store (short-lived, no need for DB persistence) +// --------------------------------------------------------------------------- + +interface PendingCode { + clientId: string; + userId: number; + redirectUri: string; + scopes: string[]; + resource: string | null; + codeChallenge: string; + codeChallengeMethod: 'S256'; + expiresAt: number; +} + +const MAX_PENDING_CODES = 500; +const pendingCodes = new Map(); + +setInterval(() => { + const now = Date.now(); + for (const [key, entry] of pendingCodes) { + if (now > entry.expiresAt) pendingCodes.delete(key); + } +}, 60_000).unref(); + +// --------------------------------------------------------------------------- +// DB row types +// --------------------------------------------------------------------------- + +interface OAuthClientRow { + id: string; + user_id: number; + name: string; + client_id: string; + client_secret_hash: string; + redirect_uris: string; // JSON array + allowed_scopes: string; // JSON array + created_at: string; + is_public: number; // 0 | 1 (SQLite boolean) + created_via: string; // 'settings_ui' | 'browser-registration' + allows_client_credentials: number; // 0 | 1 +} + +interface OAuthTokenRow { + id: number; + client_id: string; + user_id: number; + access_token_hash: string; + refresh_token_hash: string; + scopes: string; // JSON array + audience: string | null; + access_token_expires_at: string; + refresh_token_expires_at: string; + revoked_at: string | null; + parent_token_id: number | null; +} + +// --------------------------------------------------------------------------- +// Token helpers +// --------------------------------------------------------------------------- + +function hashToken(raw: string): string { + return createHash('sha256').update(raw).digest('hex'); +} + +/** Constant-time comparison of two hex-encoded SHA-256 hashes. */ +function timingSafeEqualHex(a: string, b: string): boolean { + if (a.length !== b.length) return false; + try { + return crypto.timingSafeEqual(Buffer.from(a, 'hex'), Buffer.from(b, 'hex')); + } catch { return false; } +} + +function generateAccessToken(): string { + return 'trekoa_' + randomBytes(32).toString('hex'); +} + +function generateRefreshToken(): string { + return 'trekrf_' + randomBytes(32).toString('hex'); +} + +// --------------------------------------------------------------------------- +// Client management (self-service, gated by MCP addon) +// --------------------------------------------------------------------------- + +export function listOAuthClients(userId: number): Record[] { + const rows = db.prepare( + 'SELECT id, user_id, name, client_id, redirect_uris, allowed_scopes, created_at, is_public, created_via, allows_client_credentials FROM oauth_clients WHERE user_id = ? ORDER BY created_at DESC' + ).all(userId) as OAuthClientRow[]; + return rows.map(r => ({ + ...r, + is_public: Boolean(r.is_public), + allows_client_credentials: Boolean(r.allows_client_credentials), + redirect_uris: JSON.parse(r.redirect_uris), + allowed_scopes: JSON.parse(r.allowed_scopes), + })); +} + +export function createOAuthClient( + userId: number | null, + name: string, + redirectUris: string[], + allowedScopes: string[], + ip?: string | null, + options?: { isPublic?: boolean; createdVia?: string; allowsClientCredentials?: boolean }, +): { error?: string; status?: number; client?: Record } { + if (!name?.trim()) return { error: 'Name is required', status: 400 }; + if (name.trim().length > 100) return { error: 'Name must be 100 characters or less', status: 400 }; + const isMachineClient = Boolean(options?.allowsClientCredentials); + if (!isMachineClient && (!redirectUris || redirectUris.length === 0)) return { error: 'At least one redirect URI is required', status: 400 }; + if (redirectUris.length > 10) return { error: 'Maximum 10 redirect URIs per client', status: 400 }; + + for (const uri of redirectUris) { + let parsed: URL; + try { + parsed = new URL(uri); + } catch { + return { error: `Invalid redirect URI: ${uri}`, status: 400 }; + } + if (parsed.protocol !== 'https:' && parsed.hostname !== 'localhost' && parsed.hostname !== '127.0.0.1') { + return { error: `Redirect URI must use HTTPS (localhost exempt): ${uri}`, status: 400 }; + } + } + + if (!allowedScopes || allowedScopes.length === 0) return { error: 'At least one scope is required', status: 400 }; + const { valid, invalid } = validateScopes(allowedScopes); + if (!valid) return { error: `Invalid scopes: ${invalid.join(', ')}`, status: 400 }; + + if (userId !== null) { + const count = (db.prepare('SELECT COUNT(*) as count FROM oauth_clients WHERE user_id = ?').get(userId) as { count: number }).count; + if (count >= 10) return { error: 'Maximum of 10 OAuth clients per user', status: 400 }; + } else { + // Anonymous DCR clients: enforce a global cap to prevent unbounded registration abuse + const count = (db.prepare('SELECT COUNT(*) as count FROM oauth_clients WHERE user_id IS NULL').get() as { count: number }).count; + if (count >= 500) return { error: 'server_error', status: 503 }; + } + + // Machine clients (client_credentials) must always be confidential — ignore isPublic for them. + const isPublic = isMachineClient ? false : (options?.isPublic ?? false); + const createdVia = options?.createdVia ?? 'settings_ui'; + const id = randomUUID(); + const clientId = randomUUID(); + // Public clients have no usable secret; store an opaque random value to satisfy NOT NULL. + const rawSecret = isPublic ? null : 'trekcs_' + randomBytes(24).toString('hex'); + const secretHash = rawSecret ? hashToken(rawSecret) : randomBytes(32).toString('hex'); + + db.prepare( + 'INSERT INTO oauth_clients (id, user_id, name, client_id, client_secret_hash, redirect_uris, allowed_scopes, is_public, created_via, allows_client_credentials) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' + ).run(id, userId, name.trim(), clientId, secretHash, JSON.stringify(redirectUris), JSON.stringify(allowedScopes), isPublic ? 1 : 0, createdVia, isMachineClient ? 1 : 0); + + const row = db.prepare( + 'SELECT id, user_id, name, client_id, redirect_uris, allowed_scopes, created_at, is_public, created_via, allows_client_credentials FROM oauth_clients WHERE id = ?' + ).get(id) as OAuthClientRow; + + writeAudit({ userId, action: 'oauth.client.create', details: { client_id: clientId, name: name.trim(), is_public: isPublic, allows_client_credentials: isMachineClient }, ip }); + + return { + client: { + id: row.id, + user_id: row.user_id, + name: row.name, + client_id: row.client_id, + redirect_uris: JSON.parse(row.redirect_uris), + allowed_scopes: JSON.parse(row.allowed_scopes), + created_at: row.created_at, + is_public: Boolean(row.is_public), + allows_client_credentials: Boolean(row.allows_client_credentials), + created_via: row.created_via, + // client_secret only present for confidential clients — shown once, not stored in plain text + ...(rawSecret ? { client_secret: rawSecret } : {}), + }, + }; +} + +export function rotateOAuthClientSecret( + userId: number, + clientRowId: string, + ip?: string | null, +): { error?: string; status?: number; client_secret?: string } { + const row = db.prepare('SELECT id, client_id, is_public FROM oauth_clients WHERE id = ? AND user_id = ?').get(clientRowId, userId) as OAuthClientRow | undefined; + if (!row) return { error: 'Client not found', status: 404 }; + if (row.is_public) return { error: 'Public clients do not use a client secret', status: 400 }; + + const rawSecret = 'trekcs_' + randomBytes(24).toString('hex'); + const secretHash = hashToken(rawSecret); + + db.prepare('UPDATE oauth_clients SET client_secret_hash = ? WHERE id = ?').run(secretHash, clientRowId); + + // Revoke all existing tokens for this client so old sessions are invalidated + db.prepare("UPDATE oauth_tokens SET revoked_at = datetime('now') WHERE client_id = ? AND revoked_at IS NULL").run(row.client_id); + + // Terminate active MCP sessions for this (user, client) pair + + revokeUserSessionsForClient(userId, row.client_id); + + writeAudit({ userId, action: 'oauth.client.rotate_secret', details: { client_id: row.client_id }, ip }); + + return { client_secret: rawSecret }; +} + +export function deleteOAuthClient( + userId: number, + clientRowId: string, + ip?: string | null, +): { error?: string; status?: number; success?: boolean } { + const row = db.prepare('SELECT id, client_id FROM oauth_clients WHERE id = ? AND user_id = ?').get(clientRowId, userId) as OAuthClientRow | undefined; + if (!row) return { error: 'Client not found', status: 404 }; + db.prepare('DELETE FROM oauth_clients WHERE id = ?').run(clientRowId); + writeAudit({ userId, action: 'oauth.client.delete', details: { client_id: row.client_id }, ip }); + return { success: true }; +} + +// --------------------------------------------------------------------------- +// Auth code (in-memory, 2-minute TTL) +// --------------------------------------------------------------------------- + +export function createAuthCode(params: { + clientId: string; + userId: number; + redirectUri: string; + scopes: string[]; + resource: string | null; + codeChallenge: string; + codeChallengeMethod: 'S256'; +}): string | null { + if (pendingCodes.size >= MAX_PENDING_CODES) return null; + const rawCode = randomBytes(32).toString('hex'); + pendingCodes.set(rawCode, { ...params, expiresAt: Date.now() + AUTH_CODE_TTL_MS }); + return rawCode; +} + +export function consumeAuthCode(code: string): PendingCode | null { + const entry = pendingCodes.get(code); + if (!entry) return null; + pendingCodes.delete(code); + if (Date.now() > entry.expiresAt) return null; + return entry; +} + +// --------------------------------------------------------------------------- +// Consent management +// --------------------------------------------------------------------------- + +export function getConsent(clientId: string, userId: number): string[] | null { + const row = db.prepare( + 'SELECT scopes FROM oauth_consents WHERE client_id = ? AND user_id = ?' + ).get(clientId, userId) as { scopes: string } | undefined; + return row ? JSON.parse(row.scopes) : null; +} + +export function saveConsent(clientId: string, userId: number, scopes: string[], ip?: string | null): void { + // Union existing consent with newly approved scopes (M5: never narrow stored consent) + const existing = getConsent(clientId, userId) ?? []; + const merged = Array.from(new Set([...existing, ...scopes])); + db.prepare( + 'INSERT OR REPLACE INTO oauth_consents (client_id, user_id, scopes, updated_at) VALUES (?, ?, ?, CURRENT_TIMESTAMP)' + ).run(clientId, userId, JSON.stringify(merged)); + writeAudit({ userId, action: 'oauth.consent.grant', details: { client_id: clientId, scopes: merged }, ip }); +} + +export function isConsentSufficient(existingScopes: string[], requestedScopes: string[]): boolean { + return requestedScopes.every(s => existingScopes.includes(s)); +} + +// --------------------------------------------------------------------------- +// Token issuance +// --------------------------------------------------------------------------- + +export function issueTokens( + clientId: string, + userId: number, + scopes: string[], + parentTokenId: number | null = null, + audience: string | null = null, +): { + access_token: string; + refresh_token: string; + token_type: 'Bearer'; + expires_in: number; + scope: string; +} { + const rawAccess = generateAccessToken(); + const rawRefresh = generateRefreshToken(); + const accessHash = hashToken(rawAccess); + const refreshHash = hashToken(rawRefresh); + + const now = new Date(); + const accessExpiry = new Date(now.getTime() + ACCESS_TOKEN_TTL_S * 1000); + const refreshExpiry = new Date(now.getTime() + REFRESH_TOKEN_TTL_MS); + + db.prepare(` + INSERT INTO oauth_tokens + (client_id, user_id, access_token_hash, refresh_token_hash, scopes, audience, access_token_expires_at, refresh_token_expires_at, parent_token_id) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + `).run(clientId, userId, accessHash, refreshHash, JSON.stringify(scopes), audience, accessExpiry.toISOString(), refreshExpiry.toISOString(), parentTokenId); + + return { + access_token: rawAccess, + refresh_token: rawRefresh, + token_type: 'Bearer', + expires_in: ACCESS_TOKEN_TTL_S, + scope: scopes.join(' '), + }; +} + +// Issues an access token only — no refresh token (RFC 6749 §4.4.3). +// Used exclusively for the client_credentials grant. A random opaque hash is +// stored in refresh_token_hash to satisfy the NOT NULL/UNIQUE constraint; it +// can never be presented as a valid refresh token (same precedent as public +// client secret hashes stored in client_secret_hash). +export function issueClientCredentialsToken( + clientId: string, + userId: number, + scopes: string[], + audience: string, +): { + access_token: string; + token_type: 'Bearer'; + expires_in: number; + scope: string; +} { + const rawAccess = generateAccessToken(); + const accessHash = hashToken(rawAccess); + const placeholderHash = randomBytes(32).toString('hex'); + + const now = new Date(); + const accessExpiry = new Date(now.getTime() + ACCESS_TOKEN_TTL_S * 1000); + + db.prepare(` + INSERT INTO oauth_tokens + (client_id, user_id, access_token_hash, refresh_token_hash, scopes, audience, access_token_expires_at, refresh_token_expires_at, parent_token_id) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + `).run(clientId, userId, accessHash, placeholderHash, JSON.stringify(scopes), audience, accessExpiry.toISOString(), now.toISOString(), null); + + return { + access_token: rawAccess, + token_type: 'Bearer', + expires_in: ACCESS_TOKEN_TTL_S, + scope: scopes.join(' '), + }; +} + +// --------------------------------------------------------------------------- +// Token verification (used by MCP handler on every request) +// --------------------------------------------------------------------------- + +export interface OAuthTokenInfo { + user: User; + scopes: string[]; + clientId: string; + audience: string | null; +} + +export function getUserByAccessToken(rawToken: string): OAuthTokenInfo | null { + const hash = hashToken(rawToken); + const row = db.prepare(` + SELECT ot.scopes, ot.audience, ot.revoked_at, ot.access_token_expires_at, + ot.user_id, ot.client_id, u.username, u.email, u.role + FROM oauth_tokens ot + JOIN users u ON ot.user_id = u.id + WHERE ot.access_token_hash = ? + `).get(hash) as (OAuthTokenRow & { username: string; email: string; role: string }) | undefined; + + if (!row) return null; + if (row.revoked_at) return null; + if (new Date(row.access_token_expires_at) < new Date()) return null; + + return { + user: { id: row.user_id, username: row.username, email: row.email, role: row.role as 'admin' | 'user' }, + scopes: JSON.parse(row.scopes), + clientId: row.client_id, + audience: row.audience ?? null, + }; +} + +// --------------------------------------------------------------------------- +// Token refresh (rotation + replay detection) +// --------------------------------------------------------------------------- + +/** Walk parent_token_id upward to find the root token id of this rotation chain. */ +function findChainRoot(tokenId: number): number { + let current = tokenId; + for (let i = 0; i < 100; i++) { + const row = db.prepare('SELECT id, parent_token_id FROM oauth_tokens WHERE id = ?').get(current) as { id: number; parent_token_id: number | null } | undefined; + if (!row || row.parent_token_id === null) return current; + current = row.parent_token_id; + } + return current; +} + +/** Revoke all tokens in the rotation chain rooted at rootId. Returns affected ids. */ +function revokeChain(rootId: number): number[] { + const rows = db.prepare(` + WITH RECURSIVE chain(id) AS ( + SELECT id FROM oauth_tokens WHERE id = ? + UNION ALL + SELECT t.id FROM oauth_tokens t JOIN chain c ON t.parent_token_id = c.id + ) + SELECT id FROM chain + `).all(rootId) as { id: number }[]; + const ids = rows.map(r => r.id); + if (ids.length > 0) { + db.prepare( + `UPDATE oauth_tokens SET revoked_at = CURRENT_TIMESTAMP WHERE id IN (${ids.map(() => '?').join(',')}) AND revoked_at IS NULL` + ).run(...ids); + } + return ids; +} + +export function refreshTokens( + rawRefreshToken: string, + clientId: string, + clientSecret: string | undefined, + ip?: string | null, +): { error?: string; status?: number; tokens?: ReturnType } { + const client = db.prepare('SELECT client_id, client_secret_hash, is_public FROM oauth_clients WHERE client_id = ?').get(clientId) as OAuthClientRow | undefined; + if (!client) return { error: 'invalid_client', status: 401 }; + if (!client.is_public) { + if (!clientSecret || !timingSafeEqualHex(hashToken(clientSecret), client.client_secret_hash)) { + return { error: 'invalid_client', status: 401 }; + } + } + + const hash = hashToken(rawRefreshToken); + const row = db.prepare(` + SELECT id, client_id, user_id, scopes, audience, refresh_token_expires_at, revoked_at, parent_token_id + FROM oauth_tokens WHERE refresh_token_hash = ? + `).get(hash) as OAuthTokenRow | undefined; + + if (!row) return { error: 'invalid_grant', status: 400 }; + if (row.client_id !== clientId) return { error: 'invalid_grant', status: 400 }; + + // ---- Replay detection (C3) ---- + if (row.revoked_at) { + // A revoked refresh token was replayed — assume token theft. Cascade-revoke the chain. + const rootId = findChainRoot(row.id); + revokeChain(rootId); + + + revokeUserSessionsForClient(row.user_id, clientId); + + writeAudit({ + userId: row.user_id, + action: 'oauth.token.replay_detected', + details: { client_id: clientId }, + ip, + }); + logWarn(`[OAuth] Refresh token replay detected for user=${row.user_id} client=${clientId} ip=${ip ?? '-'}`); + + return { error: 'invalid_grant', status: 400 }; + } + + if (new Date(row.refresh_token_expires_at) < new Date()) return { error: 'invalid_grant', status: 400 }; + + // Revoke old pair immediately (rotation) and issue new pair linked to old row + db.prepare('UPDATE oauth_tokens SET revoked_at = CURRENT_TIMESTAMP WHERE id = ?').run(row.id); + + // Terminate active MCP sessions for the old token's client so client must re-authenticate + + revokeUserSessionsForClient(row.user_id, clientId); + + const tokens = issueTokens(clientId, row.user_id, JSON.parse(row.scopes), row.id, row.audience ?? null); + writeAudit({ userId: row.user_id, action: 'oauth.token.refresh', details: { client_id: clientId }, ip }); + + return { tokens }; +} + +// --------------------------------------------------------------------------- +// Token revocation +// --------------------------------------------------------------------------- + +export function revokeToken(rawToken: string, clientId: string, userId?: number, ip?: string | null): void { + const hash = hashToken(rawToken); + + // Get the user_id for the token so we can revoke its MCP sessions + const row = db.prepare( + 'SELECT user_id FROM oauth_tokens WHERE (access_token_hash = ? OR refresh_token_hash = ?) AND client_id = ?' + ).get(hash, hash, clientId) as { user_id: number } | undefined; + + db.prepare(` + UPDATE oauth_tokens + SET revoked_at = CURRENT_TIMESTAMP + WHERE (access_token_hash = ? OR refresh_token_hash = ?) AND client_id = ? + `).run(hash, hash, clientId); + + const affectedUserId = row?.user_id ?? userId; + if (affectedUserId) { + + revokeUserSessionsForClient(affectedUserId, clientId); + writeAudit({ userId: affectedUserId, action: 'oauth.token.revoke', details: { client_id: clientId, method: 'token' }, ip }); + } +} + +// --------------------------------------------------------------------------- +// Active session listing (for user settings page) +// --------------------------------------------------------------------------- + +export function listOAuthSessions(userId: number): Record[] { + const rows = db.prepare(` + SELECT ot.id, ot.client_id, oc.name AS client_name, ot.scopes, + ot.access_token_expires_at, ot.refresh_token_expires_at, ot.created_at + FROM oauth_tokens ot + JOIN oauth_clients oc ON ot.client_id = oc.client_id + WHERE ot.user_id = ? + AND ot.revoked_at IS NULL + AND ot.refresh_token_expires_at > CURRENT_TIMESTAMP + ORDER BY ot.created_at DESC + `).all(userId) as Record[]; + return rows.map(r => ({ ...r, scopes: JSON.parse(r.scopes as string) })); +} + +export function revokeSession( + userId: number, + sessionId: number, + ip?: string | null, +): { error?: string; status?: number; success?: boolean } { + const row = db.prepare('SELECT id, client_id FROM oauth_tokens WHERE id = ? AND user_id = ?').get(sessionId, userId) as { id: number; client_id: string } | undefined; + if (!row) return { error: 'Session not found', status: 404 }; + + db.prepare('UPDATE oauth_tokens SET revoked_at = CURRENT_TIMESTAMP WHERE id = ?').run(sessionId); + + + revokeUserSessionsForClient(userId, row.client_id); + + writeAudit({ userId, action: 'oauth.token.revoke', details: { client_id: row.client_id, method: 'session' }, ip }); + + return { success: true }; +} + +// --------------------------------------------------------------------------- +// Authorize request validation (option A: called by SPA via GET /api/oauth/authorize/validate) +// --------------------------------------------------------------------------- + +export interface AuthorizeParams { + response_type: string; + client_id: string; + redirect_uri: string; + scope: string; + state?: string; + code_challenge: string; + code_challenge_method: string; + resource?: string; +} + +export interface ValidateAuthorizeResult { + valid: boolean; + error?: string; + error_description?: string; + client?: { name: string; allowed_scopes: string[] }; + scopes?: string[]; + resource?: string | null; + /** true when user is logged in but consent UI must be shown */ + consentRequired?: boolean; + /** true when the request is valid but user is not authenticated */ + loginRequired?: boolean; + /** true when the client was registered via machine DCR — user may adjust scopes on the consent screen */ + scopeSelectable?: boolean; +} + +export function validateAuthorizeRequest( + params: AuthorizeParams, + userId: number | null, +): ValidateAuthorizeResult { + if (!isAddonEnabled(ADDON_IDS.MCP)) { + return { valid: false, error: 'mcp_disabled', error_description: 'MCP is not enabled on this server' }; + } + + if (params.response_type !== 'code') { + return { valid: false, error: 'unsupported_response_type', error_description: 'Only response_type=code is supported' }; + } + + if (!params.code_challenge || params.code_challenge_method !== 'S256') { + return { valid: false, error: 'invalid_request', error_description: 'PKCE with code_challenge_method=S256 is required (OAuth 2.1)' }; + } + + // H1: Enforce code_challenge format (RFC 7636 §4.2) + if (!CODE_CHALLENGE_RE.test(params.code_challenge)) { + return { valid: false, error: 'invalid_request', error_description: 'code_challenge must be 43 base64url characters (S256)' }; + } + + if (!params.client_id) { + return { valid: false, error: 'invalid_request', error_description: 'client_id is required' }; + } + + const client = db.prepare('SELECT * FROM oauth_clients WHERE client_id = ?').get(params.client_id) as OAuthClientRow | undefined; + if (!client) { + return { valid: false, error: 'invalid_client', error_description: 'Unknown client_id' }; + } + + const allowedUris: string[] = JSON.parse(client.redirect_uris); + if (!params.redirect_uri || !allowedUris.includes(params.redirect_uri)) { + return { valid: false, error: 'invalid_redirect_uri', error_description: 'redirect_uri does not match any registered URI' }; + } + + // RFC 8707 resource indicator: if provided, must identify the TREK + // MCP endpoint exactly. If the client didn't supply `resource`, we + // bind the token to the MCP endpoint by default — previously this + // left `audience = null`, and the audience-bind check on MCP requests + // then treated a null audience as "valid for any resource". + const mcpResource = `${getMcpSafeUrl().replace(/\/+$/, '')}/mcp`; + const resource = params.resource + ? params.resource.replace(/\/+$/, '') + : mcpResource; + if (resource !== mcpResource) { + return { valid: false, error: 'invalid_target', error_description: 'Requested resource must be the TREK MCP endpoint' }; + } + + const requestedScopes = (params.scope || '').split(' ').filter(Boolean); + if (requestedScopes.length === 0) { + return { valid: false, error: 'invalid_scope', error_description: 'At least one scope is required' }; + } + + const allowedScopes: string[] = JSON.parse(client.allowed_scopes); + // Narrow to the intersection: drop scopes the client isn't permitted for rather + // than rejecting the whole request (per OAuth 2.0 §3.3 scope narrowing). + const grantedScopes = requestedScopes.filter(s => allowedScopes.includes(s)); + if (grantedScopes.length === 0) { + return { valid: false, error: 'invalid_scope', error_description: 'None of the requested scopes are permitted for this client' }; + } + + if (userId === null) { + // H3: return only the minimum required fields — do NOT expose scopes, client.name, or + // allowed_scopes to unauthenticated callers to prevent client enumeration. + return { valid: true, loginRequired: true }; + } + + const existingConsent = getConsent(params.client_id, userId); + const consentRequired = !existingConsent || !isConsentSufficient(existingConsent, grantedScopes); + + return { + valid: true, + client: { name: client.name, allowed_scopes: allowedScopes }, + scopes: grantedScopes, + resource: resource ?? mcpResource, + consentRequired, + scopeSelectable: client.created_via === 'dcr', + }; +} + +// --------------------------------------------------------------------------- +// PKCE verification +// --------------------------------------------------------------------------- + +export function verifyPKCE(codeVerifier: string, codeChallenge: string): boolean { + // H1: validate code_verifier format before hashing + if (!CODE_VERIFIER_RE.test(codeVerifier)) return false; + + const expected = crypto.createHash('sha256').update(codeVerifier).digest('base64url'); + // Constant-time compare (both are base64url strings of equal length for S256) + if (expected.length !== codeChallenge.length) return false; + try { + return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(codeChallenge)); + } catch { return false; } +} + +// --------------------------------------------------------------------------- +// Client authentication (for token endpoint) +// --------------------------------------------------------------------------- + +export function authenticateClient(clientId: string, clientSecret: string | undefined): OAuthClientRow | null { + const client = db.prepare('SELECT * FROM oauth_clients WHERE client_id = ?').get(clientId) as OAuthClientRow | undefined; + if (!client) return null; + if (client.is_public) { + // Public clients are identified by client_id alone — PKCE provides the security guarantee. + return client; + } + // H4: constant-time comparison to prevent timing side-channel + if (!clientSecret) return null; + if (!timingSafeEqualHex(hashToken(clientSecret), client.client_secret_hash)) return null; + return client; +} diff --git a/server/src/services/oidcService.ts b/server/src/services/oidcService.ts new file mode 100644 index 0000000000000000000000000000000000000000..ebf140fa146861615e0473e1c296913681f7ed23 --- /dev/null +++ b/server/src/services/oidcService.ts @@ -0,0 +1,461 @@ +import crypto from 'crypto'; +import jwt from 'jsonwebtoken'; +import { db } from '../db/database'; +import { JWT_SECRET, SESSION_DURATION_SECONDS } from '../config'; +import { User } from '../types'; +import { decrypt_api_key } from './apiKeyCrypto'; +import { resolveAuthToggles } from './authService'; + +// --------------------------------------------------------------------------- +// Types +// --------------------------------------------------------------------------- + +export interface OidcDiscoveryDoc { + authorization_endpoint: string; + token_endpoint: string; + userinfo_endpoint: string; + jwks_uri?: string; + issuer?: string; + _issuer?: string; +} + +export interface OidcTokenResponse { + access_token?: string; + id_token?: string; + token_type?: string; +} + +export interface OidcUserInfo { + sub: string; + email?: string; + // Standard OIDC claim. Some IdPs send it as the string "true"/"false". + email_verified?: boolean | string; + name?: string; + preferred_username?: string; + groups?: string[]; + roles?: string[]; + [key: string]: unknown; +} + +export interface OidcConfig { + issuer: string; + clientId: string; + clientSecret: string; + displayName: string; + discoveryUrl: string | null; +} + +// --------------------------------------------------------------------------- +// Constants / TTLs +// --------------------------------------------------------------------------- + +const AUTH_CODE_TTL = 60000; // 1 minute +const AUTH_CODE_CLEANUP = 30000; // 30 seconds +const STATE_TTL = 5 * 60 * 1000; // 5 minutes +const STATE_CLEANUP = 60 * 1000; // 1 minute +const DISCOVERY_TTL = 60 * 60 * 1000; // 1 hour + +// --------------------------------------------------------------------------- +// State management – pending OIDC states +// --------------------------------------------------------------------------- + +const pendingStates = new Map(); + +setInterval(() => { + const now = Date.now(); + for (const [state, data] of pendingStates) { + if (now - data.createdAt > STATE_TTL) pendingStates.delete(state); + } +}, STATE_CLEANUP); + +function base64url(buf: Buffer): string { + return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +} + +// Creates the login state and a matching PKCE pair. The verifier stays server +// side (in pendingStates); the S256 challenge goes to the provider so PKCE- +// required setups (e.g. Pocket ID with PKCE = required) work. +export function createState(redirectUri: string, inviteToken?: string): { state: string; codeChallenge: string } { + const state = crypto.randomBytes(32).toString('hex'); + const codeVerifier = base64url(crypto.randomBytes(32)); + const codeChallenge = base64url(crypto.createHash('sha256').update(codeVerifier).digest()); + pendingStates.set(state, { createdAt: Date.now(), redirectUri, inviteToken, codeVerifier }); + return { state, codeChallenge }; +} + +export function consumeState(state: string) { + const pending = pendingStates.get(state); + if (!pending) return null; + pendingStates.delete(state); + return pending; +} + +// --------------------------------------------------------------------------- +// Auth code management – short-lived codes exchanged for JWT +// --------------------------------------------------------------------------- + +const authCodes = new Map(); + +setInterval(() => { + const now = Date.now(); + for (const [code, entry] of authCodes) { + if (now - entry.created > AUTH_CODE_TTL) authCodes.delete(code); + } +}, AUTH_CODE_CLEANUP); + +export function createAuthCode(token: string): string { + const { v4: uuidv4 } = require('uuid'); + const authCode: string = uuidv4(); + authCodes.set(authCode, { token, created: Date.now() }); + return authCode; +} + +export function consumeAuthCode(code: string): { token: string } | { error: string } { + const entry = authCodes.get(code); + if (!entry) return { error: 'Invalid or expired code' }; + authCodes.delete(code); + if (Date.now() - entry.created > AUTH_CODE_TTL) return { error: 'Code expired' }; + return { token: entry.token }; +} + +// --------------------------------------------------------------------------- +// OIDC configuration (env + DB) +// --------------------------------------------------------------------------- + +export function getOidcConfig(): OidcConfig | null { + const get = (key: string) => + (db.prepare("SELECT value FROM app_settings WHERE key = ?").get(key) as { value: string } | undefined)?.value || null; + + const issuer = process.env.OIDC_ISSUER || get('oidc_issuer'); + const clientId = process.env.OIDC_CLIENT_ID || get('oidc_client_id'); + const clientSecret = process.env.OIDC_CLIENT_SECRET || decrypt_api_key(get('oidc_client_secret')); + const displayName = process.env.OIDC_DISPLAY_NAME || get('oidc_display_name') || 'SSO'; + const discoveryUrl = process.env.OIDC_DISCOVERY_URL || get('oidc_discovery_url') || null; + + if (!issuer || !clientId || !clientSecret) return null; + return { issuer: issuer.replace(/\/+$/, ''), clientId, clientSecret, displayName, discoveryUrl }; +} + +// --------------------------------------------------------------------------- +// Discovery document (cached, 1 h TTL) +// --------------------------------------------------------------------------- + +let discoveryCache: OidcDiscoveryDoc | null = null; +let discoveryCacheTime = 0; + +export async function discover(issuer: string, discoveryUrl?: string | null): Promise { + const url = discoveryUrl || `${issuer}/.well-known/openid-configuration`; + if (discoveryCache && Date.now() - discoveryCacheTime < DISCOVERY_TTL && discoveryCache._issuer === url) { + return discoveryCache; + } + const res = await fetch(url); + if (!res.ok) throw new Error('Failed to fetch OIDC discovery document'); + const doc = (await res.json()) as OidcDiscoveryDoc; + // Validate that the discovery doc's issuer matches the operator-configured one. + // When no custom discoveryUrl is set, a mismatch signals a MITM or misconfiguration + // and we reject. When the operator explicitly overrides the discovery URL (e.g. + // Authentik realm paths), the discovery doc's issuer is the canonical value — + // trust it and warn rather than blocking login. + const docIssuer = doc.issuer?.replace(/\/+$/, '') ?? ''; + if (docIssuer && docIssuer !== issuer) { + if (discoveryUrl) { + console.warn( + `[OIDC] Discovery doc issuer "${doc.issuer}" differs from configured OIDC_ISSUER "${issuer}". ` + + `Using discovery doc issuer for id_token verification (custom OIDC_DISCOVERY_URL is set).`, + ); + } else { + throw new Error(`OIDC discovery issuer mismatch: expected "${issuer}", got "${doc.issuer}"`); + } + } + doc._issuer = url; + discoveryCache = doc; + discoveryCacheTime = Date.now(); + return doc; +} + +// --------------------------------------------------------------------------- +// Role resolution via OIDC claims +// --------------------------------------------------------------------------- + +export function resolveOidcRole(userInfo: OidcUserInfo, isFirstUser: boolean): 'admin' | 'user' { + if (isFirstUser) return 'admin'; + const adminValue = process.env.OIDC_ADMIN_VALUE; + if (!adminValue) return 'user'; + const claimKey = process.env.OIDC_ADMIN_CLAIM || 'groups'; + const claimData = userInfo[claimKey]; + if (Array.isArray(claimData)) { + return claimData.some((v) => String(v) === adminValue) ? 'admin' : 'user'; + } + if (typeof claimData === 'string') { + return claimData === adminValue ? 'admin' : 'user'; + } + return 'user'; +} + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +export function frontendUrl(path: string): string { + const base = process.env.NODE_ENV === 'production' ? '' : 'http://localhost:5173'; + return base + path; +} + +export function generateToken(user: { id: number }): string { + // Embed the current password_version so an OIDC-issued session is invalidated + // by a password change/reset exactly like a password-login session (the auth + // middleware compares this `pv` against users.password_version). + const pv = (db.prepare('SELECT password_version FROM users WHERE id = ?').get(user.id) as { password_version?: number } | undefined)?.password_version ?? 0; + return jwt.sign({ id: user.id, pv }, JWT_SECRET, { expiresIn: SESSION_DURATION_SECONDS, algorithm: 'HS256' }); +} + +// --------------------------------------------------------------------------- +// Token exchange with OIDC provider +// --------------------------------------------------------------------------- + +export async function exchangeCodeForToken( + doc: OidcDiscoveryDoc, + code: string, + redirectUri: string, + clientId: string, + clientSecret: string, + codeVerifier?: string, +): Promise { + const body = new URLSearchParams({ + grant_type: 'authorization_code', + code, + redirect_uri: redirectUri, + client_id: clientId, + client_secret: clientSecret, + }); + if (codeVerifier) body.set('code_verifier', codeVerifier); + const tokenRes = await fetch(doc.token_endpoint, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body, + }); + const tokenData = (await tokenRes.json()) as OidcTokenResponse; + return { ...tokenData, _ok: tokenRes.ok, _status: tokenRes.status }; +} + +// --------------------------------------------------------------------------- +// Fetch userinfo from OIDC provider +// --------------------------------------------------------------------------- + +export async function getUserInfo(userinfoEndpoint: string, accessToken: string): Promise { + const res = await fetch(userinfoEndpoint, { + headers: { Authorization: `Bearer ${accessToken}` }, + }); + return (await res.json()) as OidcUserInfo; +} + +// --------------------------------------------------------------------------- +// id_token verification (signature + iss + aud + exp) +// --------------------------------------------------------------------------- + +// 5 minute JWKS cache — short enough to pick up key rotation within a +// reasonable window, long enough that normal login flow doesn't fetch +// JWKS on every callback. +const JWKS_TTL_MS = 5 * 60 * 1000; +type JwksEntry = { keys: Array>; fetchedAt: number }; +const jwksCache = new Map(); + +async function fetchJwks(jwksUri: string): Promise>> { + const cached = jwksCache.get(jwksUri); + if (cached && Date.now() - cached.fetchedAt < JWKS_TTL_MS) return cached.keys; + const res = await fetch(jwksUri); + if (!res.ok) throw new Error(`JWKS fetch failed: HTTP ${res.status}`); + const json = (await res.json()) as { keys?: Array> }; + const keys = json.keys ?? []; + jwksCache.set(jwksUri, { keys, fetchedAt: Date.now() }); + return keys; +} + +function base64UrlDecode(input: string): Buffer { + const padded = input.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (input.length % 4)) % 4); + return Buffer.from(padded, 'base64'); +} + +/** + * Verify an OIDC id_token end-to-end: signature against the provider's + * JWKS, issuer match, audience match, and exp/nbf. Does NOT verify a + * nonce — the server doesn't currently send one in the auth request; + * when that's added, pass the expected nonce here and check `claims.nonce`. + * + * Returning the claims lets callers cross-check `sub` / `email` against + * the userinfo response. A mismatch would mean the provider's userinfo + * endpoint is speaking for a different subject than the id_token — a + * classic IdP-side compromise signal worth refusing login over. + */ +export async function verifyIdToken( + idToken: string, + doc: OidcDiscoveryDoc, + clientId: string, + expectedIssuer: string, +): Promise<{ ok: true; claims: Record } | { ok: false; error: string }> { + if (!doc.jwks_uri) return { ok: false, error: 'no_jwks_uri' }; + const parts = idToken.split('.'); + if (parts.length !== 3) return { ok: false, error: 'malformed_token' }; + + let header: { kid?: string; alg?: string }; + try { header = JSON.parse(base64UrlDecode(parts[0]!).toString('utf8')); } + catch { return { ok: false, error: 'bad_header' }; } + + const alg = header.alg; + if (!alg || !/^(RS256|RS384|RS512|ES256|ES384|ES512|PS256|PS384|PS512)$/.test(alg)) { + return { ok: false, error: 'unsupported_alg' }; + } + + let keys: Array>; + try { keys = await fetchJwks(doc.jwks_uri); } + catch (e) { return { ok: false, error: 'jwks_fetch_failed' }; } + + // When the token carries a `kid`, refuse to fall back to any other + // key in the JWKS — a mismatch means the token was signed with a key + // the provider no longer publishes, and we should reject rather than + // mask the failure by trying another key. + const jwk = header.kid + ? keys.find((k) => k['kid'] === header.kid) + : keys[0]; + if (!jwk) return { ok: false, error: 'no_matching_key' }; + + let publicKey; + try { + // Node 16+ understands JWK directly; no PEM conversion library needed. + // Node's crypto accepts a JWK object directly as `{ key, format: 'jwk' }`. + // The type signature isn't strict on our TS config so we cast through any. + publicKey = crypto.createPublicKey({ key: jwk as any, format: 'jwk' }); + } catch { + return { ok: false, error: 'key_import_failed' }; + } + + let claims: Record; + try { + const verified = jwt.verify(idToken, publicKey, { + algorithms: [alg as jwt.Algorithm], + audience: clientId, + }); + claims = typeof verified === 'string' ? {} : (verified as Record); + } catch (err) { + const msg = err instanceof Error ? err.message : 'verify_failed'; + return { ok: false, error: `signature_or_claim_mismatch: ${msg}` }; + } + + // Normalize trailing slash before issuer comparison — some IdPs (e.g. Authentik) + // include a trailing slash in the id_token iss claim. + const tokenIssuer = typeof claims['iss'] === 'string' ? claims['iss'].replace(/\/+$/, '') : ''; + if (tokenIssuer !== expectedIssuer) { + return { ok: false, error: `signature_or_claim_mismatch: jwt issuer invalid. expected: ${expectedIssuer}` }; + } + + return { ok: true, claims }; +} + +// --------------------------------------------------------------------------- +// Find or create user by OIDC sub / email +// --------------------------------------------------------------------------- + +export function findOrCreateUser( + userInfo: OidcUserInfo, + config: OidcConfig, + inviteToken?: string, +): { user: User } | { error: string } { + const email = userInfo.email!.trim().toLowerCase(); + const name = userInfo.name || userInfo.preferred_username || email.split('@')[0]; + const sub = userInfo.sub; + + // Try to find existing user by sub, then by email + let user = db.prepare('SELECT * FROM users WHERE oidc_sub = ? AND oidc_issuer = ?').get(sub, config.issuer) as User | undefined; + if (!user) { + user = db.prepare('SELECT * FROM users WHERE LOWER(email) = ?').get(email) as User | undefined; + } + + if (user) { + // Reaching here without an oidc_sub means we matched an existing local + // account by email. Only auto-link the OIDC identity when the IdP asserts + // the email is verified; an unverified email must not auto-link. + if (!user.oidc_sub) { + const emailVerified = userInfo.email_verified === true || userInfo.email_verified === 'true'; + if (!emailVerified) { + return { error: 'email_not_verified' }; + } + db.prepare('UPDATE users SET oidc_sub = ?, oidc_issuer = ? WHERE id = ?').run(sub, config.issuer, user.id); + } + // Update role based on OIDC claims on every login (if claim mapping is configured) + if (process.env.OIDC_ADMIN_VALUE) { + const newRole = resolveOidcRole(userInfo, false); + if (user.role !== newRole) { + db.prepare('UPDATE users SET role = ? WHERE id = ?').run(newRole, user.id); + user = { ...user, role: newRole } as User; + } + } + return { user }; + } + + // --- New user registration --- + const userCount = (db.prepare('SELECT COUNT(*) as count FROM users').get() as { count: number }).count; + const isFirstUser = userCount === 0; + + let validInvite: any = null; + if (inviteToken) { + validInvite = db.prepare('SELECT * FROM invite_tokens WHERE token = ?').get(inviteToken); + if (validInvite) { + if (validInvite.max_uses > 0 && validInvite.used_count >= validInvite.max_uses) validInvite = null; + if (validInvite?.expires_at && new Date(validInvite.expires_at) < new Date()) validInvite = null; + } + } + + if (!isFirstUser && !validInvite) { + const { oidc_registration } = resolveAuthToggles(); + if (!oidc_registration) { + return { error: 'registration_disabled' }; + } + } + + const role = resolveOidcRole(userInfo, isFirstUser); + const randomPass = crypto.randomBytes(32).toString('hex'); + const bcrypt = require('bcryptjs'); + const hash = bcrypt.hashSync(randomPass, 10); + + // Username: sanitize and avoid collisions + let username = name.replace(/[^a-zA-Z0-9_-]/g, '').substring(0, 30) || 'user'; + const existing = db.prepare('SELECT id FROM users WHERE LOWER(username) = LOWER(?)').get(username); + if (existing) username = `${username}_${Date.now() % 10000}`; + + // Atomic registration: if an invite was presented, the increment IS + // the capacity check — UPDATE matches zero rows the moment another + // concurrent callback wins the last slot, and the transaction aborts + // the user INSERT. Without this, two parallel OIDC callbacks could + // both pass the earlier SELECT-based check and each create a user. + const inviteRaceError = new Error('invite_exhausted'); + try { + const createUser = db.transaction(() => { + if (validInvite) { + const updated = db.prepare( + 'UPDATE invite_tokens SET used_count = used_count + 1 WHERE id = ? AND (max_uses = 0 OR used_count < max_uses)', + ).run(validInvite.id); + if (updated.changes === 0) throw inviteRaceError; + } + return db.prepare( + 'INSERT INTO users (username, email, password_hash, role, oidc_sub, oidc_issuer, first_seen_version, login_count) VALUES (?, ?, ?, ?, ?, ?, ?, 0)', + ).run(username, email, hash, role, sub, config.issuer, process.env.APP_VERSION || '0.0.0'); + }); + const result = createUser() as { lastInsertRowid: number | bigint }; + user = { id: Number(result.lastInsertRowid), username, email, role } as User; + return { user }; + } catch (err) { + if (err === inviteRaceError) { + console.warn(`[OIDC] Invite token ${inviteToken?.slice(0, 8)}... exhausted — concurrent callback won the last slot`); + return { error: 'registration_disabled' }; + } + throw err; + } +} + +// --------------------------------------------------------------------------- +// Update last_login timestamp +// --------------------------------------------------------------------------- + +export function touchLastLogin(userId: number): void { + db.prepare('UPDATE users SET last_login = CURRENT_TIMESTAMP, login_count = login_count + 1 WHERE id = ?').run(userId); +} diff --git a/server/src/services/packingService.ts b/server/src/services/packingService.ts new file mode 100644 index 0000000000000000000000000000000000000000..de487b3eb2819baf7f6bdbeea2312e0eaf7bd136 --- /dev/null +++ b/server/src/services/packingService.ts @@ -0,0 +1,317 @@ +import { db } from '../db/database'; +import { avatarUrl } from './authService'; + +const BAG_COLORS = ['#6366f1', '#ec4899', '#f97316', '#10b981', '#06b6d4', '#8b5cf6', '#ef4444', '#f59e0b', '#3b82f6', '#84cc16', '#d946ef', '#14b8a6', '#f43f5e', '#a855f7', '#eab308', '#64748b']; + +export { verifyTripAccess } from './tripAccess'; + +// ── Items ────────────────────────────────────────────────────────────────── + +export function listItems(tripId: string | number) { + return db.prepare( + 'SELECT * FROM packing_items WHERE trip_id = ? ORDER BY sort_order ASC, created_at ASC' + ).all(tripId); +} + +export function createItem(tripId: string | number, data: { name: string; category?: string; checked?: boolean; quantity?: number }) { + const maxOrder = db.prepare('SELECT MAX(sort_order) as max FROM packing_items WHERE trip_id = ?').get(tripId) as { max: number | null }; + const sortOrder = (maxOrder.max !== null ? maxOrder.max : -1) + 1; + const qty = Math.max(1, Math.min(999, Number(data.quantity) || 1)); + + const result = db.prepare( + 'INSERT INTO packing_items (trip_id, name, checked, category, sort_order, quantity) VALUES (?, ?, ?, ?, ?, ?)' + ).run(tripId, data.name, data.checked ? 1 : 0, data.category || 'Allgemein', sortOrder, qty); + + return db.prepare('SELECT * FROM packing_items WHERE id = ?').get(result.lastInsertRowid); +} + +export function updateItem( + tripId: string | number, + id: string | number, + data: { name?: string; checked?: number; category?: string; weight_grams?: number | null; bag_id?: number | null; quantity?: number }, + bodyKeys: string[] +) { + const item = db.prepare('SELECT * FROM packing_items WHERE id = ? AND trip_id = ?').get(id, tripId); + if (!item) return null; + + db.prepare(` + UPDATE packing_items SET + name = COALESCE(?, name), + checked = CASE WHEN ? IS NOT NULL THEN ? ELSE checked END, + category = COALESCE(?, category), + weight_grams = CASE WHEN ? THEN ? ELSE weight_grams END, + bag_id = CASE WHEN ? THEN ? ELSE bag_id END, + quantity = CASE WHEN ? THEN ? ELSE quantity END + WHERE id = ? + `).run( + data.name || null, + data.checked !== undefined ? 1 : null, + data.checked ? 1 : 0, + data.category || null, + bodyKeys.includes('weight_grams') ? 1 : 0, + data.weight_grams ?? null, + bodyKeys.includes('bag_id') ? 1 : 0, + data.bag_id ?? null, + bodyKeys.includes('quantity') ? 1 : 0, + data.quantity ? Math.max(1, Math.min(999, Number(data.quantity))) : 1, + id + ); + + return db.prepare('SELECT * FROM packing_items WHERE id = ?').get(id); +} + +export function deleteItem(tripId: string | number, id: string | number) { + const item = db.prepare('SELECT id FROM packing_items WHERE id = ? AND trip_id = ?').get(id, tripId); + if (!item) return false; + + db.prepare('DELETE FROM packing_items WHERE id = ?').run(id); + return true; +} + +// ── Bulk Import ──────────────────────────────────────────────────────────── + +interface ImportItem { + name?: string; + checked?: boolean; + category?: string; + weight_grams?: string | number; + bag?: string; + quantity?: number; +} + +export function bulkImport(tripId: string | number, items: ImportItem[]) { + const maxOrder = db.prepare('SELECT MAX(sort_order) as max FROM packing_items WHERE trip_id = ?').get(tripId) as { max: number | null }; + let sortOrder = (maxOrder.max !== null ? maxOrder.max : -1) + 1; + + const stmt = db.prepare('INSERT INTO packing_items (trip_id, name, checked, category, weight_grams, bag_id, sort_order, quantity) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'); + const created: any[] = []; + + const insertAll = db.transaction(() => { + for (const item of items) { + if (!item.name?.trim()) continue; + const checked = item.checked ? 1 : 0; + const weight = item.weight_grams ? parseInt(String(item.weight_grams)) || null : null; + + // Resolve bag by name if provided + let bagId = null; + if (item.bag?.trim()) { + const bagName = item.bag.trim(); + const existing = db.prepare('SELECT id FROM packing_bags WHERE trip_id = ? AND name = ?').get(tripId, bagName) as { id: number } | undefined; + if (existing) { + bagId = existing.id; + } else { + const bagCount = (db.prepare('SELECT COUNT(*) as c FROM packing_bags WHERE trip_id = ?').get(tripId) as { c: number }).c; + const newBag = db.prepare('INSERT INTO packing_bags (trip_id, name, color) VALUES (?, ?, ?)').run(tripId, bagName, BAG_COLORS[bagCount % BAG_COLORS.length]); + bagId = newBag.lastInsertRowid; + } + } + + const qty = Math.max(1, Math.min(999, Number(item.quantity) || 1)); + const result = stmt.run(tripId, item.name.trim(), checked, item.category?.trim() || 'Other', weight, bagId, sortOrder++, qty); + created.push(db.prepare('SELECT * FROM packing_items WHERE id = ?').get(result.lastInsertRowid)); + } + }); + + insertAll(); + return created; +} + +// ── Bags ─────────────────────────────────────────────────────────────────── + +export function listBags(tripId: string | number) { + const bags = db.prepare('SELECT * FROM packing_bags WHERE trip_id = ? ORDER BY sort_order, id').all(tripId) as any[]; + const members = db.prepare(` + SELECT bm.bag_id, bm.user_id, u.username, u.avatar + FROM packing_bag_members bm + JOIN users u ON bm.user_id = u.id + JOIN packing_bags b ON bm.bag_id = b.id + WHERE b.trip_id = ? + `).all(tripId) as { bag_id: number; user_id: number; username: string; avatar: string | null }[]; + const membersByBag = new Map(); + for (const m of members) { + if (!membersByBag.has(m.bag_id)) membersByBag.set(m.bag_id, []); + membersByBag.get(m.bag_id)!.push(m); + } + return bags.map(b => ({ + ...b, + members: (membersByBag.get(b.id) || []).map(m => ({ ...m, avatar: avatarUrl(m) })), + })); +} + +export function setBagMembers(tripId: string | number, bagId: string | number, userIds: number[]) { + const bag = db.prepare('SELECT * FROM packing_bags WHERE id = ? AND trip_id = ?').get(bagId, tripId); + if (!bag) return null; + db.prepare('DELETE FROM packing_bag_members WHERE bag_id = ?').run(bagId); + const ins = db.prepare('INSERT OR IGNORE INTO packing_bag_members (bag_id, user_id) VALUES (?, ?)'); + for (const uid of userIds) ins.run(bagId, uid); + const rows = db.prepare(` + SELECT bm.user_id, u.username, u.avatar + FROM packing_bag_members bm JOIN users u ON bm.user_id = u.id + WHERE bm.bag_id = ? + `).all(bagId) as { user_id: number; username: string; avatar: string | null }[]; + return rows.map(m => ({ ...m, avatar: avatarUrl(m) })); +} + +export function createBag(tripId: string | number, data: { name: string; color?: string }) { + const maxOrder = db.prepare('SELECT MAX(sort_order) as max FROM packing_bags WHERE trip_id = ?').get(tripId) as { max: number | null }; + const result = db.prepare('INSERT INTO packing_bags (trip_id, name, color, sort_order) VALUES (?, ?, ?, ?)').run( + tripId, data.name.trim(), data.color || '#6366f1', (maxOrder.max ?? -1) + 1 + ); + return db.prepare('SELECT * FROM packing_bags WHERE id = ?').get(result.lastInsertRowid); +} + +export function updateBag( + tripId: string | number, + bagId: string | number, + data: { name?: string; color?: string; weight_limit_grams?: number | null; user_id?: number | null }, + bodyKeys?: string[] +) { + const bag = db.prepare('SELECT * FROM packing_bags WHERE id = ? AND trip_id = ?').get(bagId, tripId); + if (!bag) return null; + + db.prepare(`UPDATE packing_bags SET + name = COALESCE(?, name), + color = COALESCE(?, color), + weight_limit_grams = ?, + user_id = CASE WHEN ? THEN ? ELSE user_id END + WHERE id = ?`).run( + data.name?.trim() || null, + data.color || null, + data.weight_limit_grams ?? (bag as any).weight_limit_grams ?? null, + bodyKeys?.includes('user_id') ? 1 : 0, + data.user_id ?? null, + bagId + ); + return db.prepare('SELECT b.*, u.username as assigned_username FROM packing_bags b LEFT JOIN users u ON b.user_id = u.id WHERE b.id = ?').get(bagId); +} + +export function deleteBag(tripId: string | number, bagId: string | number) { + const bag = db.prepare('SELECT * FROM packing_bags WHERE id = ? AND trip_id = ?').get(bagId, tripId); + if (!bag) return false; + + db.prepare('DELETE FROM packing_bags WHERE id = ?').run(bagId); + return true; +} + +// ── List Templates ───────────────────────────────────────────────────────── + +/** + * Read-only template list for trip members (name + item count), so non-admins + * can pick a template to apply. Management (create/edit/delete) stays admin-only + * under /api/admin/packing-templates. + */ +export function listTemplates() { + return db.prepare(` + SELECT pt.id, pt.name, + (SELECT COUNT(*) FROM packing_template_items ti JOIN packing_template_categories tc ON ti.category_id = tc.id WHERE tc.template_id = pt.id) as item_count + FROM packing_templates pt + ORDER BY pt.created_at DESC + `).all() as { id: number; name: string; item_count: number }[]; +} + +// ── Apply Template ───────────────────────────────────────────────────────── + +export function applyTemplate(tripId: string | number, templateId: string | number) { + const templateItems = db.prepare(` + SELECT ti.name, tc.name as category + FROM packing_template_items ti + JOIN packing_template_categories tc ON ti.category_id = tc.id + WHERE tc.template_id = ? + ORDER BY tc.sort_order, ti.sort_order + `).all(templateId) as { name: string; category: string }[]; + + if (templateItems.length === 0) return null; + + const maxOrder = db.prepare('SELECT MAX(sort_order) as max FROM packing_items WHERE trip_id = ?').get(tripId) as { max: number | null }; + let sortOrder = (maxOrder.max !== null ? maxOrder.max : -1) + 1; + + const insert = db.prepare('INSERT INTO packing_items (trip_id, name, checked, category, sort_order) VALUES (?, ?, 0, ?, ?)'); + const added: any[] = []; + for (const ti of templateItems) { + const result = insert.run(tripId, ti.name, ti.category, sortOrder++); + const item = db.prepare('SELECT * FROM packing_items WHERE id = ?').get(result.lastInsertRowid); + added.push(item); + } + + return added; +} + +// ── Save as Template ────────────────────────────────────────────────────── + +export function saveAsTemplate(tripId: string | number, userId: number, templateName: string) { + const items = db.prepare( + 'SELECT name, category FROM packing_items WHERE trip_id = ? ORDER BY sort_order ASC' + ).all(tripId) as { name: string; category: string }[]; + + if (items.length === 0) return null; + + const result = db.prepare('INSERT INTO packing_templates (name, created_by) VALUES (?, ?)').run(templateName, userId); + const templateId = result.lastInsertRowid; + + const categories = [...new Set(items.map(i => i.category || 'Other'))]; + const catIdMap = new Map(); + + for (let i = 0; i < categories.length; i++) { + const catResult = db.prepare('INSERT INTO packing_template_categories (template_id, name, sort_order) VALUES (?, ?, ?)').run(templateId, categories[i], i); + catIdMap.set(categories[i], catResult.lastInsertRowid); + } + + const itemsByCategory = new Map(); + for (const item of items) { + const catId = catIdMap.get(item.category || 'Other')!; + const order = itemsByCategory.get(item.category || 'Other') || 0; + db.prepare('INSERT INTO packing_template_items (category_id, name, sort_order) VALUES (?, ?, ?)').run(catId, item.name, order); + itemsByCategory.set(item.category || 'Other', order + 1); + } + + return { id: Number(templateId), name: templateName, categoryCount: categories.length, itemCount: items.length }; +} + +// ── Category Assignees ───────────────────────────────────────────────────── + +export function getCategoryAssignees(tripId: string | number) { + const rows = db.prepare(` + SELECT pca.category_name, pca.user_id, u.username, u.avatar + FROM packing_category_assignees pca + JOIN users u ON pca.user_id = u.id + WHERE pca.trip_id = ? + `).all(tripId); + + // Group by category + const assignees: Record = {}; + for (const row of rows as any[]) { + if (!assignees[row.category_name]) assignees[row.category_name] = []; + assignees[row.category_name].push({ user_id: row.user_id, username: row.username, avatar: avatarUrl(row) }); + } + + return assignees; +} + +export function updateCategoryAssignees(tripId: string | number, categoryName: string, userIds: number[] | undefined) { + db.prepare('DELETE FROM packing_category_assignees WHERE trip_id = ? AND category_name = ?').run(tripId, categoryName); + + if (Array.isArray(userIds) && userIds.length > 0) { + const insert = db.prepare('INSERT OR IGNORE INTO packing_category_assignees (trip_id, category_name, user_id) VALUES (?, ?, ?)'); + for (const uid of userIds) insert.run(tripId, categoryName, uid); + } + + const updated = db.prepare(` + SELECT pca.user_id, u.username, u.avatar + FROM packing_category_assignees pca + JOIN users u ON pca.user_id = u.id + WHERE pca.trip_id = ? AND pca.category_name = ? + `).all(tripId, categoryName) as { user_id: number; username: string; avatar: string | null }[]; + return updated.map(m => ({ ...m, avatar: avatarUrl(m) })); +} + +// ── Reorder ──────────────────────────────────────────────────────────────── + +export function reorderItems(tripId: string | number, orderedIds: number[]) { + const update = db.prepare('UPDATE packing_items SET sort_order = ? WHERE id = ? AND trip_id = ?'); + const updateMany = db.transaction((ids: number[]) => { + ids.forEach((id, index) => { + update.run(index, id, tripId); + }); + }); + updateMany(orderedIds); +} diff --git a/server/src/services/passkeyService.ts b/server/src/services/passkeyService.ts new file mode 100644 index 0000000000000000000000000000000000000000..7c8c2548705cca7646f152ad5415e5ce6f3636e0 --- /dev/null +++ b/server/src/services/passkeyService.ts @@ -0,0 +1,364 @@ +import bcrypt from 'bcryptjs'; +import { + generateRegistrationOptions, + verifyRegistrationResponse, + generateAuthenticationOptions, + verifyAuthenticationResponse, + type AuthenticatorTransportFuture, +} from '@simplewebauthn/server'; +import { db } from '../db/database'; +import { resolveWebauthnConfig } from './webauthnConfig'; +import { generateToken, stripUserForClient, avatarUrl } from './authService'; +import type { User } from '../types'; + +// --------------------------------------------------------------------------- +// Constants +// --------------------------------------------------------------------------- + +// Short single-use challenge lifetime — a ceremony is a few seconds of user +// interaction. Kept tight so a stray row can't be replayed and the table can't +// accumulate. Mirrors the spirit of the OIDC state TTL. +const CHALLENGE_TTL_MS = 5 * 60 * 1000; + +// Pinned COSE algorithms: EdDSA (-8), ES256 (-7), RS256 (-257). We never want a +// future library default to silently widen what we accept. +const SUPPORTED_ALGORITHM_IDS = [-8, -7, -257]; + +const NOT_CONFIGURED = { error: 'Passkey login is not configured for this server.', status: 400 } as const; +// One generic message for every authentication failure so the endpoint can't be +// used to tell "no such credential" apart from "bad signature" (CWE-203). +const AUTH_FAILED = { error: 'Authentication failed', status: 401 } as const; + +interface CredentialRow { + id: number; + user_id: number; + credential_id: string; + public_key: Buffer; + counter: number; + transports: string | null; + device_type: string | null; + backed_up: number; + name: string | null; + aaguid: string | null; + created_at: string; + last_used_at: string | null; +} + +// --------------------------------------------------------------------------- +// Challenge store (DB-backed, single-use, TTL'd) +// --------------------------------------------------------------------------- + +function purgeExpiredChallenges(now: number): void { + db.prepare('DELETE FROM webauthn_challenges WHERE expires_at < ?').run(now); +} + +function storeChallenge(challenge: string, userId: number | null, type: 'registration' | 'authentication', now: number): void { + db.prepare('INSERT INTO webauthn_challenges (challenge, user_id, type, expires_at) VALUES (?, ?, ?, ?)') + .run(challenge, userId, type, now + CHALLENGE_TTL_MS); +} + +/** + * Atomically claim a challenge by its EXACT bytes + type. This is a single + * DELETE ... RETURNING statement that runs BEFORE any async verification, so a + * concurrent double-submit of the same assertion can never spend one challenge + * twice (the replay window a SELECT→await→DELETE ordering would open). + */ +function claimChallenge(challenge: string, type: 'registration' | 'authentication', now: number): { user_id: number | null } | null { + const row = db.prepare( + 'DELETE FROM webauthn_challenges WHERE challenge = ? AND type = ? AND expires_at > ? RETURNING user_id', + ).get(challenge, type, now) as { user_id: number | null } | undefined; + return row ?? null; +} + +/** Decode the challenge the authenticator echoed back inside clientDataJSON. */ +function challengeFromResponse(resp: unknown): string | null { + try { + const cdj = (resp as { response?: { clientDataJSON?: unknown } })?.response?.clientDataJSON; + if (typeof cdj !== 'string') return null; + const parsed = JSON.parse(Buffer.from(cdj, 'base64url').toString('utf8')) as { challenge?: unknown }; + return typeof parsed.challenge === 'string' ? parsed.challenge : null; + } catch { + return null; + } +} + +function parseTransports(raw: string | null): AuthenticatorTransportFuture[] | undefined { + if (!raw) return undefined; + try { + const parsed = JSON.parse(raw); + return Array.isArray(parsed) ? (parsed as AuthenticatorTransportFuture[]) : undefined; + } catch { + return undefined; + } +} + +function sanitizeName(raw: unknown): string | null { + if (typeof raw !== 'string') return null; + const trimmed = raw.trim().slice(0, 60); + return trimmed || null; +} + +function defaultCredentialName(deviceType: string | undefined): string { + return deviceType === 'multiDevice' ? 'Passkey (synced)' : 'Passkey'; +} + +// --------------------------------------------------------------------------- +// Registration (authenticated — from Settings, password re-auth required) +// --------------------------------------------------------------------------- + +export async function passkeyRegisterOptions( + userId: number, + password: string | undefined, +): Promise<{ error?: string; status?: number; options?: Awaited> }> { + const cfg = resolveWebauthnConfig(); + if (!cfg) return { ...NOT_CONFIGURED }; + + const user = db.prepare('SELECT * FROM users WHERE id = ?').get(userId) as User | undefined; + if (!user) return { error: 'User not found', status: 404 }; + + // Re-authentication: a hijacked session must not be able to silently plant an + // attacker-controlled passkey. Require the current password (parity with the + // change-password / disable-MFA step-up). + if (!password || !user.password_hash || !bcrypt.compareSync(password, user.password_hash)) { + return { error: 'Incorrect password', status: 401 }; + } + + const existing = db.prepare('SELECT credential_id, transports FROM webauthn_credentials WHERE user_id = ?') + .all(userId) as { credential_id: string; transports: string | null }[]; + + const now = Date.now(); + purgeExpiredChallenges(now); + + const options = await generateRegistrationOptions({ + rpName: cfg.rpName, + rpID: cfg.rpID, + userName: user.email, + userDisplayName: user.username, + userID: new TextEncoder().encode(String(user.id)), + attestationType: 'none', + // Stop the same authenticator from enrolling twice on this account. + excludeCredentials: existing.map((c) => ({ id: c.credential_id, transports: parseTransports(c.transports) })), + authenticatorSelection: { residentKey: 'preferred', userVerification: 'required' }, + supportedAlgorithmIDs: SUPPORTED_ALGORITHM_IDS, + }); + + storeChallenge(options.challenge, userId, 'registration', now); + return { options }; +} + +export async function passkeyRegisterVerify( + userId: number, + body: { attestationResponse?: unknown; name?: unknown }, +): Promise<{ error?: string; status?: number; success?: boolean; credential?: unknown }> { + const cfg = resolveWebauthnConfig(); + if (!cfg) return { ...NOT_CONFIGURED }; + + const resp = body?.attestationResponse; + if (!resp) return { error: 'Invalid registration response', status: 400 }; + + const challenge = challengeFromResponse(resp); + if (!challenge) return { error: 'Invalid registration response', status: 400 }; + + const now = Date.now(); + const claimed = claimChallenge(challenge, 'registration', now); + if (!claimed || claimed.user_id !== userId) { + return { error: 'Registration challenge expired. Please try again.', status: 400 }; + } + + let verification; + try { + verification = await verifyRegistrationResponse({ + response: resp as Parameters[0]['response'], + expectedChallenge: challenge, + expectedOrigin: cfg.origins, + expectedRPID: cfg.rpID, + requireUserVerification: true, + }); + } catch { + return { error: 'Could not register this passkey.', status: 400 }; + } + + if (!verification.verified || !verification.registrationInfo) { + return { error: 'Could not register this passkey.', status: 400 }; + } + + // Persist ONLY the values the verifier vouches for — never anything parsed + // from the raw client payload. + const { credential, credentialDeviceType, credentialBackedUp, aaguid } = verification.registrationInfo; + + if (db.prepare('SELECT id FROM webauthn_credentials WHERE credential_id = ?').get(credential.id)) { + return { error: 'This passkey is already registered.', status: 409 }; + } + + const name = sanitizeName(body?.name) || defaultCredentialName(credentialDeviceType); + try { + db.prepare( + `INSERT INTO webauthn_credentials + (user_id, credential_id, public_key, counter, transports, device_type, backed_up, name, aaguid, last_used_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)`, + ).run( + userId, + credential.id, + Buffer.from(credential.publicKey), + credential.counter ?? 0, + credential.transports ? JSON.stringify(credential.transports) : null, + credentialDeviceType ?? null, + credentialBackedUp ? 1 : 0, + name, + aaguid ?? null, + ); + } catch { + return { error: 'Could not register this passkey.', status: 400 }; + } + + const created = db.prepare( + 'SELECT id, name, device_type, backed_up, created_at, last_used_at FROM webauthn_credentials WHERE credential_id = ?', + ).get(credential.id) as { backed_up: number } & Record; + return { success: true, credential: { ...created, backed_up: created.backed_up === 1 } }; +} + +// --------------------------------------------------------------------------- +// Authentication (public — primary, discoverable-credential login) +// --------------------------------------------------------------------------- + +export async function passkeyLoginOptions(): Promise<{ + error?: string; + status?: number; + options?: Awaited>; +}> { + const cfg = resolveWebauthnConfig(); + if (!cfg) return { ...NOT_CONFIGURED }; + + const now = Date.now(); + purgeExpiredChallenges(now); + + const options = await generateAuthenticationOptions({ + rpID: cfg.rpID, + userVerification: 'required', + // Empty allowCredentials → discoverable flow. The server never echoes which + // accounts have passkeys, so the endpoint can't be used to enumerate users. + }); + + storeChallenge(options.challenge, null, 'authentication', now); + return { options }; +} + +export async function passkeyLoginVerify(body: { assertionResponse?: unknown }): Promise<{ + error?: string; + status?: number; + token?: string; + user?: Record; + auditUserId?: number | null; + auditAction?: string; +}> { + const cfg = resolveWebauthnConfig(); + if (!cfg) return { ...NOT_CONFIGURED }; + + const resp = body?.assertionResponse; + if (!resp) return { ...AUTH_FAILED }; + + const challenge = challengeFromResponse(resp); + if (!challenge) return { ...AUTH_FAILED }; + + // Claim the challenge (single-use) BEFORE looking anything up or verifying. + const now = Date.now(); + if (!claimChallenge(challenge, 'authentication', now)) return { ...AUTH_FAILED }; + + const credId = (resp as { id?: unknown; rawId?: unknown }).id ?? (resp as { rawId?: unknown }).rawId; + if (typeof credId !== 'string') return { ...AUTH_FAILED }; + + const cred = db.prepare('SELECT * FROM webauthn_credentials WHERE credential_id = ?').get(credId) as CredentialRow | undefined; + if (!cred) return { ...AUTH_FAILED }; + + let verification; + try { + verification = await verifyAuthenticationResponse({ + response: resp as Parameters[0]['response'], + expectedChallenge: challenge, + expectedOrigin: cfg.origins, + expectedRPID: cfg.rpID, + requireUserVerification: true, + credential: { + id: cred.credential_id, + publicKey: new Uint8Array(cred.public_key), + counter: cred.counter, + transports: parseTransports(cred.transports), + }, + }); + } catch { + return { ...AUTH_FAILED }; + } + + if (!verification.verified) return { ...AUTH_FAILED }; + + const { newCounter } = verification.authenticationInfo; + // Clone detection only makes sense for authenticators that actually increment. + // Synced passkeys legitimately report a counter that stays 0 — never treat + // that as a clone. A regression from a previously NON-ZERO counter rejects + // THIS assertion (and is audited) but does not disable the credential. + if (cred.counter > 0 && newCounter <= cred.counter) { + return { ...AUTH_FAILED, auditUserId: cred.user_id, auditAction: 'user.passkey_clone_suspected' }; + } + + const user = db.prepare('SELECT * FROM users WHERE id = ?').get(cred.user_id) as User | undefined; + if (!user) return { ...AUTH_FAILED }; + + // Persist the new counter + last-used and bump login bookkeeping atomically. + db.transaction(() => { + db.prepare('UPDATE webauthn_credentials SET counter = ?, last_used_at = CURRENT_TIMESTAMP WHERE id = ?').run(newCounter, cred.id); + db.prepare('UPDATE users SET last_login = CURRENT_TIMESTAMP, login_count = login_count + 1 WHERE id = ?').run(user.id); + })(); + + // A user-verified passkey is phishing-resistant and inherently two-factor + // (device possession + biometric/PIN), so it mints the real session directly + // — the SAME path as password and OIDC login (no new token shape). + const token = generateToken(user); + const userSafe = stripUserForClient(user) as Record; + return { token, user: { ...userSafe, avatar_url: avatarUrl(user) }, auditUserId: Number(user.id) }; +} + +// --------------------------------------------------------------------------- +// Management (authenticated, owner-scoped) +// --------------------------------------------------------------------------- + +export function listPasskeys(userId: number): Array> { + const rows = db.prepare( + 'SELECT id, name, device_type, backed_up, created_at, last_used_at FROM webauthn_credentials WHERE user_id = ? ORDER BY created_at DESC', + ).all(userId) as Array<{ backed_up: number } & Record>; + return rows.map((r) => ({ ...r, backed_up: r.backed_up === 1 })); +} + +export function renamePasskey(userId: number, id: string, name: unknown): { error?: string; status?: number; success?: boolean } { + const cleanName = sanitizeName(name); + if (!cleanName) return { error: 'Name is required', status: 400 }; + // Ownership enforced in SQL (404 on miss, never a 403 that leaks existence). + const result = db.prepare('UPDATE webauthn_credentials SET name = ? WHERE id = ? AND user_id = ?').run(cleanName, Number(id), userId); + if (result.changes === 0) return { error: 'Passkey not found', status: 404 }; + return { success: true }; +} + +export function deletePasskey( + userId: number, + id: string, + password: string | undefined, +): { error?: string; status?: number; success?: boolean } { + // Re-auth before removing a credential (a hijacked session must not be able to + // strip the victim's passkeys). Deleting is always allowed because every + // account keeps a usable password as recovery fallback — losing all passkeys + // can never lock anyone out. + const user = db.prepare('SELECT password_hash FROM users WHERE id = ?').get(userId) as { password_hash: string } | undefined; + if (!user || !user.password_hash || !password || !bcrypt.compareSync(password, user.password_hash)) { + return { error: 'Incorrect password', status: 401 }; + } + const result = db.prepare('DELETE FROM webauthn_credentials WHERE id = ? AND user_id = ?').run(Number(id), userId); + if (result.changes === 0) return { error: 'Passkey not found', status: 404 }; + return { success: true }; +} + +/** Admin: clear all of a user's passkeys (e.g. on suspected compromise). */ +export function adminResetPasskeys(targetUserId: number): { error?: string; status?: number; success?: boolean; deleted?: number; email?: string } { + const target = db.prepare('SELECT id, email FROM users WHERE id = ?').get(targetUserId) as { id: number; email: string } | undefined; + if (!target) return { error: 'User not found', status: 404 }; + const result = db.prepare('DELETE FROM webauthn_credentials WHERE user_id = ?').run(targetUserId); + return { success: true, deleted: result.changes, email: target.email }; +} diff --git a/server/src/services/passwordPolicy.ts b/server/src/services/passwordPolicy.ts new file mode 100644 index 0000000000000000000000000000000000000000..9b20143e37af3498d82a033ae6e8eb5bfeaccace --- /dev/null +++ b/server/src/services/passwordPolicy.ts @@ -0,0 +1,28 @@ +const COMMON_PASSWORDS = new Set([ + 'password', '12345678', '123456789', '1234567890', 'password1', + 'qwerty123', 'iloveyou', 'admin123', 'letmein12', 'welcome1', + 'monkey123', 'dragon12', 'master12', 'qwerty12', 'abc12345', + 'trustno1', 'baseball', 'football', 'shadow12', 'michael1', + 'jennifer', 'superman', 'abcdefgh', 'abcd1234', 'password123', + 'admin1234', 'changeme', 'welcome123', 'passw0rd', 'p@ssword', +]); + +export function validatePassword(password: string): { ok: boolean; reason?: string } { + if (password.length < 8) return { ok: false, reason: 'Password must be at least 8 characters' }; + + if (/^(.)\1+$/.test(password)) { + return { ok: false, reason: 'Password is too repetitive' }; + } + + if (COMMON_PASSWORDS.has(password.toLowerCase())) { + return { ok: false, reason: 'Password is too common. Please choose a unique password.' }; + } + + const requirementsMessage = 'Password must contain at least one uppercase letter, one lowercase letter, one number, and one special character'; + if (!/[A-Z]/.test(password)) return { ok: false, reason: requirementsMessage }; + if (!/[a-z]/.test(password)) return { ok: false, reason: requirementsMessage }; + if (!/[0-9]/.test(password)) return { ok: false, reason: requirementsMessage }; + if (!/[^A-Za-z0-9]/.test(password)) return { ok: false, reason: requirementsMessage }; + + return { ok: true }; +} diff --git a/server/src/services/permissions.ts b/server/src/services/permissions.ts new file mode 100644 index 0000000000000000000000000000000000000000..2a0fdddd8c477cd9282233430ffa5dc57b466700 --- /dev/null +++ b/server/src/services/permissions.ts @@ -0,0 +1,149 @@ +import { db } from '../db/database'; + +/** + * Permission levels (hierarchical, higher includes lower): + * admin > trip_owner > trip_member > everybody + * + * "everybody" means any authenticated user with trip access. + * For trip_create, "everybody" means any authenticated user (no trip context). + */ +export type PermissionLevel = 'admin' | 'trip_owner' | 'trip_member' | 'everybody'; + +export interface PermissionAction { + key: string; + defaultLevel: PermissionLevel; + allowedLevels: PermissionLevel[]; +} + +// All configurable actions with their defaults matching upstream behavior +export const PERMISSION_ACTIONS: PermissionAction[] = [ + // Trip management + { key: 'trip_create', defaultLevel: 'everybody', allowedLevels: ['admin', 'everybody'] }, + { key: 'trip_edit', defaultLevel: 'trip_owner', allowedLevels: ['trip_owner', 'trip_member'] }, + { key: 'trip_delete', defaultLevel: 'trip_owner', allowedLevels: ['admin', 'trip_owner'] }, + { key: 'trip_archive', defaultLevel: 'trip_owner', allowedLevels: ['trip_owner', 'trip_member'] }, + { key: 'trip_cover_upload', defaultLevel: 'trip_owner', allowedLevels: ['trip_owner', 'trip_member'] }, + + // Member management + { key: 'member_manage', defaultLevel: 'trip_owner', allowedLevels: ['admin', 'trip_owner', 'trip_member'] }, + + // Files + { key: 'file_upload', defaultLevel: 'trip_member', allowedLevels: ['admin', 'trip_owner', 'trip_member'] }, + { key: 'file_edit', defaultLevel: 'trip_member', allowedLevels: ['trip_owner', 'trip_member'] }, + { key: 'file_delete', defaultLevel: 'trip_member', allowedLevels: ['trip_owner', 'trip_member'] }, + + // Places + { key: 'place_edit', defaultLevel: 'trip_member', allowedLevels: ['trip_owner', 'trip_member'] }, + + // Budget + { key: 'budget_edit', defaultLevel: 'trip_member', allowedLevels: ['trip_owner', 'trip_member'] }, + + // Packing + { key: 'packing_edit', defaultLevel: 'trip_member', allowedLevels: ['trip_owner', 'trip_member'] }, + + // Reservations + { key: 'reservation_edit', defaultLevel: 'trip_member', allowedLevels: ['trip_owner', 'trip_member'] }, + + // Day notes & schedule + { key: 'day_edit', defaultLevel: 'trip_member', allowedLevels: ['trip_owner', 'trip_member'] }, + + // Collaboration (notes, polls, messages) + { key: 'collab_edit', defaultLevel: 'trip_member', allowedLevels: ['trip_owner', 'trip_member'] }, + + // Share link management + { key: 'share_manage', defaultLevel: 'trip_owner', allowedLevels: ['trip_owner', 'trip_member'] }, +]; + +const ACTIONS_MAP = new Map(PERMISSION_ACTIONS.map(a => [a.key, a])); + +// In-memory cache, invalidated on save +let cache: Map | null = null; + +function loadPermissions(): Map { + if (cache) return cache; + cache = new Map(); + try { + const rows = db.prepare("SELECT key, value FROM app_settings WHERE key LIKE 'perm_%'").all() as { key: string; value: string }[]; + for (const row of rows) { + const actionKey = row.key.replace('perm_', ''); + if (ACTIONS_MAP.has(actionKey)) { + cache.set(actionKey, row.value as PermissionLevel); + } + } + } catch { /* table might not exist yet during init */ } + return cache; +} + +export function invalidatePermissionsCache(): void { + cache = null; +} + +export function getPermissionLevel(actionKey: string): PermissionLevel { + const perms = loadPermissions(); + const stored = perms.get(actionKey); + if (stored) return stored; + const action = ACTIONS_MAP.get(actionKey); + return action?.defaultLevel ?? 'trip_owner'; +} + +export function getAllPermissions(): Record { + const perms = loadPermissions(); + const result: Record = {}; + for (const action of PERMISSION_ACTIONS) { + result[action.key] = perms.get(action.key) ?? action.defaultLevel; + } + return result; +} + +export function savePermissions(settings: Record): { skipped: string[] } { + const skipped: string[] = []; + const upsert = db.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)"); + const txn = db.transaction(() => { + for (const [actionKey, level] of Object.entries(settings)) { + const action = ACTIONS_MAP.get(actionKey); + if (!action || !action.allowedLevels.includes(level as PermissionLevel)) { + skipped.push(actionKey); + continue; + } + upsert.run(`perm_${actionKey}`, level); + } + }); + txn(); + invalidatePermissionsCache(); + return { skipped }; +} + +/** + * Check if a user passes the permission check for a given action. + * + * @param actionKey - The permission action key + * @param userRole - 'admin' | 'user' + * @param tripUserId - The trip owner's user ID (null for non-trip actions like trip_create) + * @param userId - The requesting user's ID + * @param isMember - Whether the user is a trip member (not owner) + */ +export function checkPermission( + actionKey: string, + userRole: string, + tripUserId: number | null, + userId: number, + isMember: boolean +): boolean { + // Admins always pass + if (userRole === 'admin') return true; + + const required = getPermissionLevel(actionKey); + + switch (required) { + case 'admin': + return false; // already checked above + case 'trip_owner': + return tripUserId !== null && tripUserId === userId; + case 'trip_member': + return (tripUserId !== null && tripUserId === userId) || isMember; + case 'everybody': + return true; + default: + return false; + } +} diff --git a/server/src/services/placeEnrichment.ts b/server/src/services/placeEnrichment.ts new file mode 100644 index 0000000000000000000000000000000000000000..fa4be26f1a723332d4aa665453e8ccfa7a5733c8 --- /dev/null +++ b/server/src/services/placeEnrichment.ts @@ -0,0 +1,164 @@ +import { db, getPlaceWithTags } from '../db/database'; +import { broadcast } from '../websocket'; +import { getMapsKey, searchPlaces, getPlacePhoto } from './mapsService'; + +/** + * Background enrichment for list-imported places (#886). + * + * Google/Naver list imports only carry name + coordinates, so the imported + * places open as bare pins (the Maps tab jumps to coordinates, no photo, no + * open/closed). When the importer opts in and a Google Maps key is configured, + * we re-resolve each place by name — biased to and validated against the + * imported coordinates — to a real Google place, then fill in the empty fields + * and persist the resolved `google_place_id` (which is what powers on-demand + * opening hours / the proper Maps link going forward). + * + * This runs detached from the import request (fire-and-forget) so a long list + * never blocks the response, and pushes each enriched row over the websocket so + * the sidebar fills in progressively. It only ever fills EMPTY columns, so it + * can never clobber data the import already captured (e.g. a Naver address). + */ + +/** A place the import produced — only the fields enrichment reads/writes. */ +export interface EnrichablePlace { + id: number; + name: string; + lat: number; + lng: number; + google_place_id?: string | null; + address?: string | null; + website?: string | null; + phone?: string | null; + image_url?: string | null; +} + +/** How close a search hit must be to the imported coordinates to be trusted. */ +const MATCH_RADIUS_METERS = 250; +/** Bias the text search to roughly the imported area. */ +const SEARCH_BIAS_RADIUS_METERS = 2000; +/** Concurrent enrichment lookups — small, to stay friendly to the Maps quota. */ +const ENRICH_CONCURRENCY = 3; + +function haversineMeters(a: { lat: number; lng: number }, b: { lat: number; lng: number }): number { + const R = 6371000; + const toRad = (d: number) => (d * Math.PI) / 180; + const dLat = toRad(b.lat - a.lat); + const dLng = toRad(b.lng - a.lng); + const lat1 = toRad(a.lat); + const lat2 = toRad(b.lat); + const h = Math.sin(dLat / 2) ** 2 + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLng / 2) ** 2; + return 2 * R * Math.asin(Math.sqrt(h)); +} + +/** + * Pick the search result that is the same place as the import: it must be a + * Google result (have a google_place_id) with coordinates within + * MATCH_RADIUS_METERS of the imported point. Returns the closest such hit, or + * null when nothing is close enough — in which case the place is left as + * imported rather than risking a wrong-place overwrite (common-name / romanized + * lists). Exported for unit testing. + */ +export function pickEnrichmentMatch( + candidates: Record[], + target: { lat: number; lng: number }, + maxMeters: number = MATCH_RADIUS_METERS, +): Record | null { + let best: { c: Record; dist: number } | null = null; + for (const c of candidates || []) { + const gpid = c.google_place_id; + const lat = c.lat; + const lng = c.lng; + if (typeof gpid !== 'string' || !gpid) continue; + if (typeof lat !== 'number' || typeof lng !== 'number') continue; + const dist = haversineMeters(target, { lat, lng }); + if (dist > maxMeters) continue; + if (!best || dist < best.dist) best = { c, dist }; + } + return best?.c ?? null; +} + +async function mapWithConcurrency(items: T[], limit: number, fn: (item: T) => Promise): Promise { + let cursor = 0; + const workers = Array.from({ length: Math.min(limit, items.length) }, async () => { + while (cursor < items.length) { + const item = items[cursor++]; + await fn(item); + } + }); + await Promise.all(workers); +} + +const str = (v: unknown): string | null => (typeof v === 'string' && v.trim() ? v.trim() : null); + +async function enrichOne(tripId: string, userId: number, place: EnrichablePlace, lang?: string): Promise { + // Already linked (shouldn't happen for list imports) — nothing to resolve. + if (place.google_place_id) return; + if (typeof place.lat !== 'number' || typeof place.lng !== 'number') return; + + const { places: results } = await searchPlaces(userId, place.name, lang, { + lat: place.lat, + lng: place.lng, + radius: SEARCH_BIAS_RADIUS_METERS, + }); + const match = pickEnrichmentMatch(results, { lat: place.lat, lng: place.lng }); + if (!match) return; + + const gpid = str(match.google_place_id); + if (!gpid) return; + + // COALESCE so enrichment only fills empty columns — never overwrites data the + // import already captured (e.g. Naver's address) or anything the user edited. + db.prepare( + `UPDATE places + SET google_place_id = COALESCE(google_place_id, ?), + address = COALESCE(address, ?), + website = COALESCE(website, ?), + phone = COALESCE(phone, ?), + updated_at = CURRENT_TIMESTAMP + WHERE id = ? AND trip_id = ?`, + ).run(gpid, str(match.address), str(match.website), str(match.phone), place.id, tripId); + + // Photo is best-effort: Google often has none, and getPlacePhoto throws 404 in + // that case — a missing photo must never abort the rest of the enrichment. + try { + const photo = await getPlacePhoto(userId, gpid, place.lat, place.lng, place.name); + if (photo?.photoUrl) { + db.prepare( + 'UPDATE places SET image_url = COALESCE(image_url, ?), updated_at = CURRENT_TIMESTAMP WHERE id = ? AND trip_id = ?', + ).run(photo.photoUrl, place.id, tripId); + } + } catch { + /* no photo — leave image_url as-is */ + } + + // Push the enriched row to every connected client (no socket exclusion: the + // importer's own client should also receive the late update). + const updated = getPlaceWithTags(place.id); + if (updated) broadcast(tripId, 'place:updated', { place: updated }, undefined); +} + +/** + * Enrich a batch of just-imported places in the background. Never throws — + * any per-place failure is swallowed so one bad lookup can't take down the + * detached task or the process. No-ops when no Google Maps key is configured. + */ +export async function enrichImportedPlaces( + tripId: string, + userId: number, + places: EnrichablePlace[], + lang?: string, +): Promise { + try { + if (!places.length) return; + if (!getMapsKey(userId)) return; + await mapWithConcurrency(places, ENRICH_CONCURRENCY, async (place) => { + try { + await enrichOne(tripId, userId, place, lang); + } catch (err) { + console.error(`[Places] enrichment failed for place ${place.id}:`, err instanceof Error ? err.message : err); + } + }); + } catch (err) { + console.error('[Places] import enrichment pass failed:', err instanceof Error ? err.message : err); + } +} diff --git a/server/src/services/placePhotoCache.ts b/server/src/services/placePhotoCache.ts new file mode 100644 index 0000000000000000000000000000000000000000..216b1aeae75872d6454868756a7e08ac98fee213 --- /dev/null +++ b/server/src/services/placePhotoCache.ts @@ -0,0 +1,209 @@ +import { db } from '../db/database'; + +import { Jimp, JimpMime } from 'jimp'; +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import fsPromises from 'node:fs/promises'; +import path from 'node:path'; + +// Overridable for tests (mirrors the TREK_DB_FILE seam) so the suite never touches +// the real uploads tree. +const GOOGLE_PHOTO_DIR = process.env.TREK_PLACE_PHOTO_DIR || path.join(__dirname, '../../uploads/photos/google'); +const ERROR_TTL = 5 * 60 * 1000; + +// Marker photos are displayed tiny — cap stored images so an oversized source +// (e.g. a Wikimedia Commons full-res original) can't bloat the cache. Matches +// THUMB_MAX/THUMB_QUALITY in memories/thumbnailService.ts. +const MAX_DIM = 800; +const JPEG_QUALITY = 80; + +// In-flight dedup — prevents stampedes when multiple requests hit the same uncached placeId simultaneously +const inFlight = new Map>(); + +// In-memory set of placeIds whose file is confirmed on disk this session. +// Avoids a synchronous fs.existsSync() call on every cache hit after the first verification. +const knownOnDisk = new Set(); + +// Ensure upload dir exists once at startup — avoids sync FS calls inside put() on every write. +try { + fs.mkdirSync(GOOGLE_PHOTO_DIR, { recursive: true }); +} catch { + /* already exists */ +} + +function filePath(placeId: string): string { + // Hash to avoid filename collisions — coords:lat:lng pseudo-IDs contain characters that + // collapse identically under sanitization (e.g. ':' and '.' both → '_') + const hash = crypto.createHash('sha1').update(placeId).digest('hex'); + return path.join(GOOGLE_PHOTO_DIR, `${hash}.jpg`); +} + +function proxyUrl(placeId: string): string { + return `/api/maps/place-photo/${encodeURIComponent(placeId)}/bytes`; +} + +interface CachedPhoto { + photoUrl: string; + filePath: string; + attribution: string | null; +} + +export function get(placeId: string): CachedPhoto | null { + const row = db + .prepare('SELECT attribution FROM google_place_photo_meta WHERE place_id = ? AND error_at IS NULL') + .get(placeId) as { attribution: string | null } | undefined; + + if (!row) return null; + + const fp = filePath(placeId); + + if (!knownOnDisk.has(placeId)) { + // First time this placeId is checked this session — verify the file exists on disk. + // (Guards against volume wipes or manual deletion between server restarts.) + if (!fs.existsSync(fp)) { + db.prepare('DELETE FROM google_place_photo_meta WHERE place_id = ?').run(placeId); + return null; + } + knownOnDisk.add(placeId); + } + + return { photoUrl: proxyUrl(placeId), filePath: fp, attribution: row.attribution }; +} + +export function getErrored(placeId: string): boolean { + const row = db + .prepare('SELECT error_at FROM google_place_photo_meta WHERE place_id = ? AND error_at IS NOT NULL') + .get(placeId) as { error_at: number } | undefined; + + if (!row) return false; + return Date.now() - row.error_at < ERROR_TTL; +} + +export function markError(placeId: string): void { + knownOnDisk.delete(placeId); + db.prepare( + 'INSERT OR REPLACE INTO google_place_photo_meta (place_id, attribution, fetched_at, error_at) VALUES (?, NULL, ?, ?)', + ).run(placeId, Date.now(), Date.now()); +} + +// Downscale oversized images to MAX_DIM before caching, re-encoding to JPEG. +// Defense-in-depth: keeps the cache small regardless of what the fetch path hands +// us. Jimp auto-applies EXIF orientation on read. Falls back to the original bytes +// on any failure (corrupt/unsupported format) so behaviour is never worse than before. +async function downscale(bytes: Buffer): Promise { + try { + const img = await Jimp.read(bytes); + if (img.bitmap.width <= MAX_DIM && img.bitmap.height <= MAX_DIM) return bytes; + img.scaleToFit({ w: MAX_DIM, h: MAX_DIM }); + return await img.getBuffer(JimpMime.jpeg, { quality: JPEG_QUALITY }); + } catch { + return bytes; + } +} + +export async function put(placeId: string, bytes: Buffer, attribution: string | null): Promise { + const fp = filePath(placeId); + const tmp = fp + '.tmp'; + + const resized = await downscale(bytes); + await fsPromises.writeFile(tmp, resized); + await fsPromises.rename(tmp, fp); + + knownOnDisk.add(placeId); + + db.prepare( + 'INSERT OR REPLACE INTO google_place_photo_meta (place_id, attribution, fetched_at, error_at) VALUES (?, ?, ?, NULL)', + ).run(placeId, attribution, Date.now()); + + return { photoUrl: proxyUrl(placeId), filePath: fp, attribution }; +} + +export function getInFlight( + placeId: string, +): Promise<{ filePath: string; attribution: string | null } | null> | undefined { + return inFlight.get(placeId); +} + +export function setInFlight( + placeId: string, + promise: Promise<{ filePath: string; attribution: string | null } | null>, +): void { + inFlight.set(placeId, promise); + promise + .finally(() => inFlight.delete(placeId)) + .catch(() => { + /* awaiter logs; this .catch only prevents unhandledRejection */ + }); +} + +export function serveFilePath(placeId: string): string | null { + if (knownOnDisk.has(placeId)) return filePath(placeId); + const fp = filePath(placeId); + if (!fs.existsSync(fp)) return null; + knownOnDisk.add(placeId); + return fp; +} + +// A cache entry is "referenced" while any place still points at it — either by the +// Google place_id (the dedup key) or by the stable proxy URL stored in image_url +// (covers coords: pseudo-ids, which never have a google_place_id). +function isReferenced(placeId: string): boolean { + const row = db + .prepare('SELECT 1 FROM places WHERE google_place_id = ? OR image_url = ? LIMIT 1') + .get(placeId, proxyUrl(placeId)); + return !!row; +} + +function deleteEntry(placeId: string): void { + try { + fs.unlinkSync(filePath(placeId)); + } catch { + /* already gone */ + } + db.prepare('DELETE FROM google_place_photo_meta WHERE place_id = ?').run(placeId); + knownOnDisk.delete(placeId); +} + +// Drop a cache entry if no place references it anymore. Called after a place delete +// for prompt reclamation; the nightly sweep is the catch-all for every other path. +export function removeIfUnreferenced(placeId: string): void { + if (isReferenced(placeId)) return; + deleteEntry(placeId); +} + +// Reclaim orphaned cache files + meta rows. Runs on startup and nightly (scheduler). +// Two passes: (1) meta rows no place references; (2) stray .jpg files with no meta row. +export function sweepOrphans(): number { + let removed = 0; + + const rows = db.prepare('SELECT place_id FROM google_place_photo_meta').all() as { place_id: string }[]; + const keepFiles = new Set(); + for (const { place_id } of rows) { + if (isReferenced(place_id)) { + keepFiles.add(`${crypto.createHash('sha1').update(place_id).digest('hex')}.jpg`); + } else { + deleteEntry(place_id); + removed++; + } + } + + // Pass 2: files on disk that no surviving meta row maps to (e.g. left over from a + // crash between writeFile and the DB upsert, or a meta row deleted out-of-band). + let entries: string[]; + try { + entries = fs.readdirSync(GOOGLE_PHOTO_DIR); + } catch { + entries = []; + } + for (const entry of entries) { + if (!entry.endsWith('.jpg') || keepFiles.has(entry)) continue; + try { + fs.unlinkSync(path.join(GOOGLE_PHOTO_DIR, entry)); + removed++; + } catch { + /* race */ + } + } + + return removed; +} diff --git a/server/src/services/placeService.ts b/server/src/services/placeService.ts new file mode 100644 index 0000000000000000000000000000000000000000..d40c08b686ad9dcc4243d913354eddb4ce4a593c --- /dev/null +++ b/server/src/services/placeService.ts @@ -0,0 +1,904 @@ +import { XMLParser, XMLValidator } from 'fast-xml-parser'; +import unzipper from 'unzipper'; +import { db, getPlaceWithTags } from '../db/database'; +import { loadTagsByPlaceIds } from './queryHelpers'; +import { checkSsrf, safeFetchFollow, SsrfBlockedError } from '../utils/ssrfGuard'; +import { Place } from '../types'; +import { + buildCategoryNameLookup, + createKmlImportSummary, + decodeUtf8WithWarning, + extractKmlPlacemarkNodes, + parsePlacemarkNode, + resolveCategoryIdForFolder, + type KmlImportSummary, +} from './kmlImport'; +import { enrichImportedPlaces, type EnrichablePlace } from './placeEnrichment'; +import * as placePhotoCache from './placePhotoCache'; + +// Reclaim a deleted place's cached marker photo if nothing else references it. +// The cache key is the Google place_id, or — for coordinate-only places — the +// pseudo-id embedded in the stored proxy URL (/api/maps/place-photo/{id}/bytes). +function reclaimPhotoCache(googlePlaceId: string | null, imageUrl: string | null): void { + const candidates = new Set(); + if (googlePlaceId) candidates.add(googlePlaceId); + const m = imageUrl?.match(/^\/api\/maps\/place-photo\/(.+)\/bytes$/); + if (m) { try { candidates.add(decodeURIComponent(m[1])); } catch { /* malformed url */ } } + for (const id of candidates) { + try { placePhotoCache.removeIfUnreferenced(id); } catch { /* best-effort */ } + } +} + +/** Opt-in Places-API enrichment for list imports (#886). */ +export interface ListImportOptions { + enrich?: boolean; + userId?: number; + lang?: string; +} + +interface PlaceWithCategory extends Place { + category_name: string | null; + category_color: string | null; + category_icon: string | null; +} + +interface UnsplashSearchResponse { + results?: { id: string; urls?: { regular?: string; thumb?: string }; description?: string; alt_description?: string; user?: { name?: string }; links?: { html?: string } }[]; + errors?: string[]; +} + +export interface PlaceImportResult { + places: any[]; + count: number; + summary: KmlImportSummary; +} + +// --------------------------------------------------------------------------- +// List places +// --------------------------------------------------------------------------- + +export function listPlaces( + tripId: string, + filters: { search?: string; category?: string; tag?: string; assignment?: 'all' | 'unassigned' | 'assigned' }, +) { + let query = ` + SELECT DISTINCT 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.trip_id = ? + `; + const params: (string | number)[] = [tripId]; + + if (filters.search) { + query += ' AND (p.name LIKE ? OR p.address LIKE ? OR p.description LIKE ?)'; + const searchParam = `%${filters.search}%`; + params.push(searchParam, searchParam, searchParam); + } + + if (filters.category) { + query += ' AND p.category_id = ?'; + params.push(filters.category); + } + + if (filters.tag) { + query += ' AND p.id IN (SELECT place_id FROM place_tags WHERE tag_id = ?)'; + params.push(filters.tag); + } + + if (filters.assignment === 'unassigned') { + query += ` AND p.id NOT IN (SELECT da.place_id FROM day_assignments da JOIN days d ON da.day_id = d.id WHERE d.trip_id = ?)`; + params.push(tripId); + } else if (filters.assignment === 'assigned') { + query += ` AND p.id IN (SELECT da.place_id FROM day_assignments da JOIN days d ON da.day_id = d.id WHERE d.trip_id = ?)`; + params.push(tripId); + } + + query += ' ORDER BY p.created_at DESC'; + + const places = db.prepare(query).all(...params) as PlaceWithCategory[]; + + const placeIds = places.map(p => p.id); + const tagsByPlaceId = loadTagsByPlaceIds(placeIds); + + return places.map(p => ({ + ...p, + category: p.category_id ? { + id: p.category_id, + name: p.category_name, + color: p.category_color, + icon: p.category_icon, + } : null, + tags: tagsByPlaceId[p.id] || [], + })); +} + +// --------------------------------------------------------------------------- +// Create place +// --------------------------------------------------------------------------- + +export function createPlace( + tripId: string, + body: { + name: string; description?: string; lat?: number; lng?: number; address?: string; + category_id?: number; price?: number; currency?: string; + place_time?: string; end_time?: string; + duration_minutes?: number; notes?: string; image_url?: string; + google_place_id?: string; osm_id?: string; website?: string; phone?: string; + transport_mode?: string; tags?: number[]; + }, +) { + const { + name, description, lat, lng, address, category_id, price, currency, + place_time, end_time, + duration_minutes, notes, image_url, google_place_id, osm_id, website, phone, + transport_mode, tags = [], + } = body; + + const result = db.prepare(` + INSERT INTO places (trip_id, name, description, lat, lng, address, category_id, price, currency, + place_time, end_time, + duration_minutes, notes, image_url, google_place_id, osm_id, website, phone, transport_mode) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `).run( + tripId, name, description || null, lat || null, lng || null, address || null, + category_id || null, price || null, currency || null, + place_time || null, end_time || null, duration_minutes || 60, notes || null, image_url || null, + google_place_id || null, osm_id || null, website || null, phone || null, transport_mode || 'walking', + ); + + const placeId = result.lastInsertRowid; + + if (tags && tags.length > 0) { + const insertTag = db.prepare('INSERT OR IGNORE INTO place_tags (place_id, tag_id) VALUES (?, ?)'); + for (const tagId of tags) { + insertTag.run(placeId, tagId); + } + } + + return getPlaceWithTags(Number(placeId)); +} + +// --------------------------------------------------------------------------- +// Get single place +// --------------------------------------------------------------------------- + +export function getPlace(tripId: string, placeId: string) { + const placeCheck = db.prepare('SELECT id FROM places WHERE id = ? AND trip_id = ?').get(placeId, tripId); + if (!placeCheck) return null; + return getPlaceWithTags(placeId); +} + +// --------------------------------------------------------------------------- +// Update place +// --------------------------------------------------------------------------- + +export function updatePlace( + tripId: string, + placeId: string, + body: { + name?: string; description?: string; lat?: number; lng?: number; address?: string; + category_id?: number; price?: number; currency?: string; + place_time?: string; end_time?: string; + duration_minutes?: number; notes?: string; image_url?: string; + google_place_id?: string; osm_id?: string; website?: string; phone?: string; + transport_mode?: string; tags?: number[]; + }, +) { + const existingPlace = db.prepare('SELECT * FROM places WHERE id = ? AND trip_id = ?').get(placeId, tripId) as Place | undefined; + if (!existingPlace) return null; + + const { + name, description, lat, lng, address, category_id, price, currency, + place_time, end_time, + duration_minutes, notes, image_url, google_place_id, osm_id, website, phone, + transport_mode, tags, + } = body; + + db.prepare(` + UPDATE places SET + name = COALESCE(?, name), + description = ?, + lat = ?, + lng = ?, + address = ?, + category_id = ?, + price = ?, + currency = COALESCE(?, currency), + place_time = ?, + end_time = ?, + duration_minutes = COALESCE(?, duration_minutes), + notes = ?, + image_url = ?, + google_place_id = ?, + osm_id = ?, + website = ?, + phone = ?, + transport_mode = COALESCE(?, transport_mode), + updated_at = CURRENT_TIMESTAMP + WHERE id = ? + `).run( + name || null, + description !== undefined ? description : existingPlace.description, + lat !== undefined ? lat : existingPlace.lat, + lng !== undefined ? lng : existingPlace.lng, + address !== undefined ? address : existingPlace.address, + category_id !== undefined ? category_id : existingPlace.category_id, + price !== undefined ? price : existingPlace.price, + currency || null, + place_time !== undefined ? place_time : existingPlace.place_time, + end_time !== undefined ? end_time : existingPlace.end_time, + duration_minutes || null, + notes !== undefined ? notes : existingPlace.notes, + image_url !== undefined ? image_url : existingPlace.image_url, + google_place_id !== undefined ? google_place_id : existingPlace.google_place_id, + osm_id !== undefined ? osm_id : existingPlace.osm_id, + website !== undefined ? website : existingPlace.website, + phone !== undefined ? phone : existingPlace.phone, + transport_mode || null, + placeId, + ); + + if (tags !== undefined) { + db.prepare('DELETE FROM place_tags WHERE place_id = ?').run(placeId); + if (tags.length > 0) { + const insertTag = db.prepare('INSERT OR IGNORE INTO place_tags (place_id, tag_id) VALUES (?, ?)'); + for (const tagId of tags) { + insertTag.run(placeId, tagId); + } + } + } + + return getPlaceWithTags(placeId); +} + +// --------------------------------------------------------------------------- +// Delete place +// --------------------------------------------------------------------------- + +export function deletePlace(tripId: string, placeId: string): boolean { + const place = db.prepare( + 'SELECT google_place_id, image_url FROM places WHERE id = ? AND trip_id = ?' + ).get(placeId, tripId) as { google_place_id: string | null; image_url: string | null } | undefined; + if (!place) return false; + db.prepare('DELETE FROM places WHERE id = ?').run(placeId); + reclaimPhotoCache(place.google_place_id, place.image_url); + return true; +} + +export function deletePlacesMany(tripId: string, ids: number[]): number[] { + if (ids.length === 0) return []; + const selectStmt = db.prepare('SELECT google_place_id, image_url FROM places WHERE id = ? AND trip_id = ?'); + const deleteStmt = db.prepare('DELETE FROM places WHERE id = ?'); + const deleted: number[] = []; + const reclaimable: { google_place_id: string | null; image_url: string | null }[] = []; + const run = db.transaction((list: number[]) => { + for (const id of list) { + const row = selectStmt.get(id, tripId) as { google_place_id: string | null; image_url: string | null } | undefined; + if (!row) continue; + deleteStmt.run(id); + deleted.push(id); + reclaimable.push(row); + } + }); + run(ids); + // Reclaim after the transaction commits so isReferenced() sees the final place set. + for (const row of reclaimable) reclaimPhotoCache(row.google_place_id, row.image_url); + return deleted; +} + +// --------------------------------------------------------------------------- +// Import GPX +// --------------------------------------------------------------------------- + +const gpxParser = new XMLParser({ + ignoreAttributes: false, + attributeNamePrefix: '@_', + isArray: (name) => ['wpt', 'trkpt', 'rtept', 'trk', 'trkseg', 'rte'].includes(name), +}); + +const kmlParser = new XMLParser({ + ignoreAttributes: false, + attributeNamePrefix: '@_', + removeNSPrefix: true, + isArray: (name) => ['Placemark', 'Folder', 'Document'].includes(name), + // Treat as raw text so mixed-content HTML (e.g.
, ) + // is returned as a string instead of a parsed object. + stopNodes: ['*.description'], +}); + +export const KMZ_DECOMPRESSED_SIZE_LIMIT = 50 * 1024 * 1024; // 50 MB + +// --------------------------------------------------------------------------- +// Import deduplication helpers +// --------------------------------------------------------------------------- + +const COORD_DEDUP_TOLERANCE = 0.0001; // ≈ 11 m + +interface DedupSet { + names: Set; + coords: Array<{ lat: number; lng: number }>; +} + +/** Build a lookup of names/coords for places already in a trip. */ +function buildDedupSet(tripId: string): DedupSet { + const rows = db.prepare('SELECT name, lat, lng FROM places WHERE trip_id = ?').all(tripId) as Array<{ + name: string | null; + lat: number | null; + lng: number | null; + }>; + const names = new Set(); + const coords: Array<{ lat: number; lng: number }> = []; + for (const row of rows) { + if (row.name) { + names.add(row.name.trim().toLowerCase()); + } else if (row.lat != null && row.lng != null) { + coords.push({ lat: row.lat, lng: row.lng }); + } + } + return { names, coords }; +} + +/** + * Returns true if a candidate place is already represented in the dedup set. + * Named places match by case-insensitive name; unnamed places fall back to + * coordinate proximity. + */ +function isPlaceDuplicate( + candidate: { name: string | null | undefined; lat: number | null; lng: number | null }, + dedup: DedupSet, +): boolean { + const normalizedName = candidate.name?.trim().toLowerCase(); + if (normalizedName) return dedup.names.has(normalizedName); + if (candidate.lat != null && candidate.lng != null) { + return dedup.coords.some( + (c) => + Math.abs(c.lat - candidate.lat!) <= COORD_DEDUP_TOLERANCE && + Math.abs(c.lng - candidate.lng!) <= COORD_DEDUP_TOLERANCE, + ); + } + return false; +} + +/** Record a newly inserted place so subsequent candidates in the same batch are checked against it. */ +function trackInsertedInDedupSet( + place: { name: string | null | undefined; lat: number | null; lng: number | null }, + dedup: DedupSet, +): void { + const normalizedName = place.name?.trim().toLowerCase(); + if (normalizedName) { + dedup.names.add(normalizedName); + } else if (place.lat != null && place.lng != null) { + dedup.coords.push({ lat: place.lat, lng: place.lng }); + } +} + +export interface GpxImportOptions { + importWaypoints?: boolean; + importRoutes?: boolean; + importTracks?: boolean; + /** Source filename used to name unnamed routes/tracks (keeps multiple imports distinct). */ + defaultName?: string; +} + +export interface KmlImportOptions { + importPoints?: boolean; + importPaths?: boolean; +} + +export function importGpx(tripId: string, fileBuffer: Buffer, opts: GpxImportOptions = {}) { + const { importWaypoints = true, importRoutes = true, importTracks = true, defaultName } = opts; + + const parsed = gpxParser.parse(fileBuffer.toString('utf-8')); + const gpx = parsed?.gpx; + if (!gpx) return null; + + const str = (v: unknown) => (v != null ? String(v).trim() : null); + const num = (v: unknown) => { const n = parseFloat(String(v)); return isNaN(n) ? null : n; }; + + // Routes and tracks rarely carry their own . Without one they all fall back to the + // same generic label, so name-based dedup drops every import after the first. Derive a + // base from the source filename (the requested behaviour) and suffix an index so multiple + // geometries from one file stay distinct. + const rawName = str(defaultName); + const baseName = rawName ? rawName.replace(/\.[^.]+$/, '').trim() || rawName : null; + let geoSeq = 0; + const geoName = (explicit: string | null, fallback: string): string => { + if (explicit) return explicit; + geoSeq++; + const base = baseName || fallback; + return geoSeq === 1 ? base : `${base} ${geoSeq}`; + }; + + type WaypointEntry = { name: string; lat: number; lng: number; description: string | null; routeGeometry?: string }; + const waypoints: WaypointEntry[] = []; + + // 1) Parse elements (named waypoints / POIs) + if (importWaypoints) { + for (const wpt of gpx.wpt ?? []) { + const lat = num(wpt['@_lat']); + const lng = num(wpt['@_lon']); + if (lat === null || lng === null) continue; + waypoints.push({ lat, lng, name: str(wpt.name) || `Waypoint ${waypoints.length + 1}`, description: str(wpt.desc) }); + } + } + + // 2) Parse routes as polyline-places (one place per route with route_geometry) + if (importRoutes) { + for (const rte of gpx.rte ?? []) { + const pts = (rte.rtept ?? []) + .map((pt: Record) => ({ lat: num(pt['@_lat']), lng: num(pt['@_lon']), ele: num(pt['ele']) })) + .filter((p: { lat: number | null; lng: number | null; ele: number | null }) => p.lat !== null && p.lng !== null) as Array<{ lat: number; lng: number; ele: number | null }>; + if (pts.length === 0) continue; + const hasAllEle = pts.every(p => p.ele !== null); + const routeGeometry = pts.map(p => hasAllEle ? [p.lat, p.lng, p.ele] : [p.lat, p.lng]); + waypoints.push({ lat: pts[0].lat, lng: pts[0].lng, name: geoName(str(rte.name), 'GPX Route'), description: str(rte.desc), routeGeometry: JSON.stringify(routeGeometry) }); + } + } + + // 3) Extract full track geometry from + if (importTracks) { + for (const trk of gpx.trk ?? []) { + const trackPoints: { lat: number; lng: number; ele: number | null }[] = []; + for (const seg of trk.trkseg ?? []) { + for (const pt of seg.trkpt ?? []) { + const lat = num(pt['@_lat']); + const lng = num(pt['@_lon']); + if (lat === null || lng === null) continue; + trackPoints.push({ lat, lng, ele: num(pt.ele) }); + } + } + if (trackPoints.length === 0) continue; + const start = trackPoints[0]; + const hasAllEle = trackPoints.every(p => p.ele !== null); + const routeGeometry = trackPoints.map(p => hasAllEle ? [p.lat, p.lng, p.ele] : [p.lat, p.lng]); + waypoints.push({ lat: start.lat, lng: start.lng, name: geoName(str(trk.name), 'GPX Track'), description: str(trk.desc), routeGeometry: JSON.stringify(routeGeometry) }); + } + } + + if (waypoints.length === 0) return null; + + const dedup = buildDedupSet(tripId); + const insertStmt = db.prepare(` + INSERT INTO places (trip_id, name, description, lat, lng, transport_mode, route_geometry) + VALUES (?, ?, ?, ?, ?, 'walking', ?) + `); + const created: any[] = []; + let skipped = 0; + const insertAll = db.transaction(() => { + for (const wp of waypoints) { + if (isPlaceDuplicate({ name: wp.name, lat: wp.lat, lng: wp.lng }, dedup)) { + skipped++; + continue; + } + const result = insertStmt.run(tripId, wp.name, wp.description, wp.lat, wp.lng, wp.routeGeometry || null); + const place = getPlaceWithTags(Number(result.lastInsertRowid)); + created.push(place); + trackInsertedInDedupSet({ name: wp.name, lat: wp.lat, lng: wp.lng }, dedup); + } + }); + insertAll(); + + return { places: created, count: created.length, skipped }; +} + +export function importKmlPlaces(tripId: string, fileBuffer: Buffer, opts: KmlImportOptions = {}): PlaceImportResult { + const { importPoints = true, importPaths = true } = opts; + const decoded = decodeUtf8WithWarning(fileBuffer); + + const validationResult = XMLValidator.validate(decoded.text); + if (validationResult !== true) { + throw new Error('Malformed KML: invalid XML structure'); + } + + const parsed = kmlParser.parse(decoded.text); + const kmlRoot = parsed?.kml ?? parsed; + + if (!kmlRoot || typeof kmlRoot !== 'object') { + throw new Error('Malformed KML: could not parse XML'); + } + + const placemarkNodes = extractKmlPlacemarkNodes(kmlRoot); + const summary = createKmlImportSummary(placemarkNodes.length); + + if (decoded.warning) { + summary.warnings.push(decoded.warning); + } + + const categories = db.prepare('SELECT id, name FROM categories').all() as { id: number; name: string }[]; + const categoryLookup = buildCategoryNameLookup(categories); + const dedup = buildDedupSet(tripId); + const created: any[] = []; + let dupCount = 0; + + const insertStmt = db.prepare(` + INSERT INTO places (trip_id, name, description, lat, lng, category_id, transport_mode, route_geometry) + VALUES (?, ?, ?, ?, ?, ?, 'walking', ?) + `); + + const insertAll = db.transaction(() => { + let fallbackIndex = 1; + for (const node of placemarkNodes) { + const parsedPlacemark = parsePlacemarkNode(node); + const isPath = parsedPlacemark.routeGeometry !== null; + + // Unsupported geometry type (polygon, multi-geometry, no geometry, etc.) + if (parsedPlacemark.lat === null || parsedPlacemark.lng === null) { + summary.skippedCount += 1; + summary.errors.push(`Skipped Placemark ${fallbackIndex}: unsupported geometry type.`); + fallbackIndex += 1; + continue; + } + + // Type filtering: respect importPoints / importPaths opts + if (isPath && !importPaths) { + summary.skippedCount += 1; + fallbackIndex += 1; + continue; + } + if (!isPath && !importPoints) { + summary.skippedCount += 1; + fallbackIndex += 1; + continue; + } + + const fallbackName = `Placemark ${fallbackIndex}`; + const name = parsedPlacemark.name || fallbackName; + + if (isPlaceDuplicate({ name, lat: parsedPlacemark.lat, lng: parsedPlacemark.lng }, dedup)) { + summary.skippedCount += 1; + dupCount++; + fallbackIndex += 1; + continue; + } + + const categoryId = resolveCategoryIdForFolder(parsedPlacemark.folderName, categoryLookup); + + const result = insertStmt.run( + tripId, + name, + parsedPlacemark.description, + parsedPlacemark.lat, + parsedPlacemark.lng, + categoryId, + parsedPlacemark.routeGeometry, + ); + + const place = getPlaceWithTags(Number(result.lastInsertRowid)); + created.push(place); + trackInsertedInDedupSet({ name, lat: parsedPlacemark.lat, lng: parsedPlacemark.lng }, dedup); + summary.createdCount += 1; + fallbackIndex += 1; + } + }); + + insertAll(); + + if (dupCount > 0) { + summary.warnings.push(`${dupCount} place${dupCount > 1 ? 's' : ''} skipped (already in trip).`); + } + + if (summary.totalPlacemarks === 0) { + summary.errors.push('No Placemarks found in KML file.'); + } + + return { places: created, count: created.length, summary }; +} + +export async function unpackKmzToKml( + kmzBuffer: Buffer, + decompressedSizeLimit = KMZ_DECOMPRESSED_SIZE_LIMIT, +): Promise { + let zip; + try { + zip = await unzipper.Open.buffer(kmzBuffer); + } catch { + throw new Error('Invalid KMZ archive.'); + } + + const kmlEntries = zip.files.filter((entry) => !entry.path.endsWith('/') && entry.path.toLowerCase().endsWith('.kml')); + if (kmlEntries.length === 0) { + throw new Error('KMZ archive does not contain a KML file.'); + } + + const preferredEntry = kmlEntries.find((entry) => entry.path.toLowerCase().endsWith('doc.kml')) || kmlEntries[0]; + + if (preferredEntry.uncompressedSize > decompressedSizeLimit) { + throw new Error('KMZ archive exceeds the maximum allowed decompressed size.'); + } + + return preferredEntry.buffer(); +} + +export async function importKmzPlaces(tripId: string, kmzBuffer: Buffer, opts: KmlImportOptions = {}): Promise { + const kmlBuffer = await unpackKmzToKml(kmzBuffer); + return importKmlPlaces(tripId, kmlBuffer, opts); +} + +export async function importMapFile(tripId: string, fileBuffer: Buffer, filename: string, opts: KmlImportOptions = {}): Promise { + const ext = filename.toLowerCase().split('.').pop(); + if (ext === 'kmz') return importKmzPlaces(tripId, fileBuffer, opts); + if (ext === 'kml') return importKmlPlaces(tripId, fileBuffer, opts); + throw new Error(`Unsupported map file format: .${ext}. Please upload a .kml or .kmz file.`); +} + +// --------------------------------------------------------------------------- +// Import Google Maps list +// --------------------------------------------------------------------------- + +export async function importGoogleList(tripId: string, url: string, opts?: ListImportOptions) { + let listId: string | null = null; + let resolvedUrl = url; + + // SSRF guard: validate user-supplied URL before fetching + const ssrf = await checkSsrf(url); + if (!ssrf.allowed) return { error: 'URL is not allowed', status: 400 }; + + // Follow redirects for short URLs (maps.app.goo.gl, goo.gl). Redirects are + // followed manually so every hop is re-checked against the SSRF guard — a + // short link that 302s to an internal IP is blocked even though the initial + // host is public. + if (url.includes('goo.gl') || url.includes('maps.app')) { + try { + const redirectRes = await safeFetchFollow(url, { signal: AbortSignal.timeout(10000) }); + resolvedUrl = redirectRes.url; + } catch (err) { + if (err instanceof SsrfBlockedError) return { error: 'URL is not allowed', status: 400 }; + throw err; + } + } + + // Pattern: /placelists/list/{ID} + const plMatch = resolvedUrl.match(/placelists\/list\/([A-Za-z0-9_-]+)/); + if (plMatch) listId = plMatch[1]; + + // Pattern: !2s{ID} in data URL params + if (!listId) { + const dataMatch = resolvedUrl.match(/!2s([A-Za-z0-9_-]{15,})/); + if (dataMatch) listId = dataMatch[1]; + } + + if (!listId) { + return { error: 'Could not extract list ID from URL. Please use a shared Google Maps list link.', status: 400 }; + } + + // Fetch list data from Google Maps internal API + const apiUrl = `https://www.google.com/maps/preview/entitylist/getlist?authuser=0&hl=en&gl=us&pb=!1m1!1s${encodeURIComponent(listId)}!2e2!3e2!4i500!16b1`; + const apiRes = await fetch(apiUrl, { + headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' }, + signal: AbortSignal.timeout(15000), + }); + + if (!apiRes.ok) { + return { error: 'Failed to fetch list from Google Maps', status: 502 }; + } + + const rawText = await apiRes.text(); + const jsonStr = rawText.substring(rawText.indexOf('\n') + 1); + const listData = JSON.parse(jsonStr); + + const meta = listData[0]; + if (!meta) { + return { error: 'Invalid list data received from Google Maps', status: 400 }; + } + + const listName = meta[4] || 'Google Maps List'; + const items = meta[8]; + + if (!Array.isArray(items) || items.length === 0) { + return { error: 'List is empty or could not be read', status: 400 }; + } + + // Parse place data from items + const places: { name: string; lat: number; lng: number; notes: string | null }[] = []; + for (const item of items) { + const coords = item?.[1]?.[5]; + const lat = coords?.[2]; + const lng = coords?.[3]; + const name = item?.[2]; + const note = item?.[3] || null; + + if (name && typeof lat === 'number' && typeof lng === 'number' && !isNaN(lat) && !isNaN(lng)) { + places.push({ name, lat, lng, notes: note || null }); + } + } + + if (places.length === 0) { + return { error: 'No places with coordinates found in list', status: 400 }; + } + + const dedup = buildDedupSet(tripId); + const insertStmt = db.prepare(` + INSERT INTO places (trip_id, name, lat, lng, notes, transport_mode) + VALUES (?, ?, ?, ?, ?, 'walking') + `); + const created: any[] = []; + let skipped = 0; + const insertAll = db.transaction(() => { + for (const p of places) { + if (isPlaceDuplicate({ name: p.name, lat: p.lat, lng: p.lng }, dedup)) { + skipped++; + continue; + } + const result = insertStmt.run(tripId, p.name, p.lat, p.lng, p.notes); + const place = getPlaceWithTags(Number(result.lastInsertRowid)); + created.push(place); + trackInsertedInDedupSet({ name: p.name, lat: p.lat, lng: p.lng }, dedup); + } + }); + insertAll(); + + if (opts?.enrich && opts.userId && created.length) { + void enrichImportedPlaces(tripId, opts.userId, created as EnrichablePlace[], opts.lang); + } + + return { places: created, listName, skipped }; +} + +// --------------------------------------------------------------------------- +// Import Naver Maps list +// --------------------------------------------------------------------------- + +export async function importNaverList( + tripId: string, + url: string, + opts?: ListImportOptions, +): Promise<{ places: any[]; listName: string; skipped: number } | { error: string; status: number }> { + let resolvedUrl = url; + const limit = 20; + + // SSRF guard: validate user-supplied URL before fetching + const ssrf = await checkSsrf(url); + if (!ssrf.allowed) return { error: 'URL is not allowed', status: 400 }; + + // Resolve naver.me short links to the canonical map.naver.com folder URL. + // Redirects are followed manually so each hop is re-validated against the + // SSRF guard (a short link could otherwise 302 to an internal address). + let parsedUrl: URL; + try { parsedUrl = new URL(url); } catch { return { error: 'Invalid URL', status: 400 }; } + if (parsedUrl.hostname === 'naver.me') { + try { + const redirectRes = await safeFetchFollow(url, { signal: AbortSignal.timeout(10000) }); + resolvedUrl = redirectRes.url; + } catch (err) { + if (err instanceof SsrfBlockedError) return { error: 'URL is not allowed', status: 400 }; + throw err; + } + } + + const folderMatch = resolvedUrl.match(/favorite\/myPlace\/folder\/([A-Za-z0-9_-]+)/i); + const folderId = folderMatch?.[1] || null; + if (!folderId) { + return { error: 'Could not extract folder ID from URL. Please use a shared Naver Maps list link.', status: 400 }; + } + + const fetchPage = async (start: number) => { + const apiUrl = `https://pages.map.naver.com/save-pages/api/maps-bookmark/v3/shares/${encodeURIComponent(folderId)}/bookmarks?placeInfo=true&start=${start}&limit=${limit}&sort=lastUseTime&mcids=ALL&createIdNo=true`; + const apiRes = await fetch(apiUrl, { + headers: { + Accept: 'application/json', + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36', + }, + signal: AbortSignal.timeout(15000), + }); + + if (!apiRes.ok) { + return { error: 'Failed to fetch list from Naver Maps', status: 502 } as const; + } + + try { + const data = await apiRes.json() as { + folder?: { bookmarkCount?: number; name?: string }; + bookmarkList?: any[]; + }; + return { data } as const; + } catch { + return { error: 'Invalid list data received from Naver Maps', status: 400 } as const; + } + }; + + const firstPage = await fetchPage(0); + if ('error' in firstPage) { + return { error: firstPage.error, status: firstPage.status }; + } + + const listName = firstPage.data.folder?.name || 'Naver Maps List'; + const totalCount = typeof firstPage.data.folder?.bookmarkCount === 'number' + ? firstPage.data.folder.bookmarkCount + : (firstPage.data.bookmarkList?.length || 0); + + const allItems: any[] = [...(firstPage.data.bookmarkList || [])]; + for (let start = limit; start < totalCount; start += limit) { + const page = await fetchPage(start); + if ('error' in page) { + return { error: page.error, status: page.status }; + } + const pageItems = page.data.bookmarkList || []; + if (!Array.isArray(pageItems) || pageItems.length === 0) break; + allItems.push(...pageItems); + } + + if (allItems.length === 0) { + return { error: 'List is empty or could not be read', status: 400 }; + } + + const places: { name: string; lat: number; lng: number; notes: string | null; address: string | null }[] = []; + for (const item of allItems) { + const lat = Number(item?.py); + const lng = Number(item?.px); + const name = typeof item?.name === 'string' && item.name.trim() + ? item.name.trim() + : (typeof item?.displayName === 'string' ? item.displayName.trim() : ''); + const note = typeof item?.memo === 'string' && item.memo.trim() ? item.memo.trim() : null; + const address = typeof item?.address === 'string' && item.address.trim() ? item.address.trim() : null; + + if (name && Number.isFinite(lat) && Number.isFinite(lng)) { + places.push({ name, lat, lng, notes: note, address }); + } + } + + if (places.length === 0) { + return { error: 'No places with coordinates found in list', status: 400 }; + } + + const dedup = buildDedupSet(tripId); + const insertStmt = db.prepare(` + INSERT INTO places (trip_id, name, lat, lng, address, notes, transport_mode) + VALUES (?, ?, ?, ?, ?, ?, 'walking') + `); + const created: any[] = []; + let skipped = 0; + const insertAll = db.transaction(() => { + for (const p of places) { + if (isPlaceDuplicate({ name: p.name, lat: p.lat, lng: p.lng }, dedup)) { + skipped++; + continue; + } + const result = insertStmt.run(tripId, p.name, p.lat, p.lng, p.address, p.notes); + const place = getPlaceWithTags(Number(result.lastInsertRowid)); + created.push(place); + trackInsertedInDedupSet({ name: p.name, lat: p.lat, lng: p.lng }, dedup); + } + }); + insertAll(); + + if (opts?.enrich && opts.userId && created.length) { + void enrichImportedPlaces(tripId, opts.userId, created as EnrichablePlace[], opts.lang); + } + + return { places: created, listName, skipped }; +} + +// --------------------------------------------------------------------------- +// Search place image (Unsplash) +// --------------------------------------------------------------------------- + +export async function searchPlaceImage(tripId: string, placeId: string, userId: number) { + const place = db.prepare('SELECT * FROM places WHERE id = ? AND trip_id = ?').get(placeId, tripId) as Place | undefined; + if (!place) return { error: 'Place not found', status: 404 }; + + const user = db.prepare('SELECT unsplash_api_key FROM users WHERE id = ?').get(userId) as { unsplash_api_key: string | null } | undefined; + if (!user || !user.unsplash_api_key) { + return { error: 'No Unsplash API key configured', status: 400 }; + } + + const query = encodeURIComponent(place.name + (place.address ? ' ' + place.address : '')); + const response = await fetch( + `https://api.unsplash.com/search/photos?query=${query}&per_page=5&client_id=${user.unsplash_api_key}`, + ); + const data = await response.json() as UnsplashSearchResponse; + + if (!response.ok) { + return { error: data.errors?.[0] || 'Unsplash API error', status: response.status }; + } + + const photos = (data.results || []).map((p: NonNullable[number]) => ({ + id: p.id, + url: p.urls?.regular, + thumb: p.urls?.thumb, + description: p.description || p.alt_description, + photographer: p.user?.name, + link: p.links?.html, + })); + + return { photos }; +} diff --git a/server/src/services/queryHelpers.ts b/server/src/services/queryHelpers.ts new file mode 100644 index 0000000000000000000000000000000000000000..76135181b6901b27bb22d321bfb74a6a1a7f8790 --- /dev/null +++ b/server/src/services/queryHelpers.ts @@ -0,0 +1,96 @@ +import { db } from '../db/database'; +import { AssignmentRow, Tag, Participant } from '../types'; + +interface TagRow extends Tag { + place_id: number; +} + +interface ParticipantRow { + assignment_id: number; + user_id: number; + username: string; + avatar: string | null; +} + +/** Batch-load tags for multiple places in a single query, indexed by place ID. */ +function loadTagsByPlaceIds(placeIds: number[], { compact }: { compact?: boolean } = {}): Record[]> { + const tagsByPlaceId: Record[]> = {}; + if (placeIds.length > 0) { + const placeholders = placeIds.map(() => '?').join(','); + const allTags = db.prepare(` + SELECT t.*, pt.place_id FROM tags t + JOIN place_tags pt ON t.id = pt.tag_id + WHERE pt.place_id IN (${placeholders}) + `).all(...placeIds) as TagRow[]; + + for (const tag of allTags) { + const pid = tag.place_id; + if (!tagsByPlaceId[pid]) tagsByPlaceId[pid] = []; + if (compact) { + tagsByPlaceId[pid].push({ id: tag.id, name: tag.name, color: tag.color, created_at: tag.created_at }); + } else { + const { place_id, ...rest } = tag; + tagsByPlaceId[pid].push(rest); + } + } + } + return tagsByPlaceId; +} + +/** Batch-load participants for multiple day-assignments in a single query, indexed by assignment ID. */ +function loadParticipantsByAssignmentIds(assignmentIds: number[]): Record { + const participantsByAssignment: Record = {}; + if (assignmentIds.length > 0) { + const allParticipants = db.prepare(`SELECT ap.assignment_id, ap.user_id, u.username, u.avatar FROM assignment_participants ap JOIN users u ON ap.user_id = u.id WHERE ap.assignment_id IN (${assignmentIds.map(() => '?').join(',')})`) + .all(...assignmentIds) as ParticipantRow[]; + for (const p of allParticipants) { + if (!participantsByAssignment[p.assignment_id]) participantsByAssignment[p.assignment_id] = []; + participantsByAssignment[p.assignment_id].push({ user_id: p.user_id, username: p.username, avatar: p.avatar }); + } + } + return participantsByAssignment; +} + +/** Reshape a flat assignment+place DB row into the nested API response shape with embedded place, tags, and participants. */ +function formatAssignmentWithPlace(a: AssignmentRow, tags: Partial[], participants: Participant[]) { + return { + id: a.id, + day_id: a.day_id, + place_id: a.place_id, + order_index: a.order_index, + notes: a.notes, + assignment_time: a.assignment_time ?? null, + assignment_end_time: a.assignment_end_time ?? null, + participants: participants || [], + created_at: a.created_at, + place: { + id: a.place_id, + name: a.place_name, + description: a.place_description, + lat: a.lat, + lng: a.lng, + address: a.address, + category_id: a.category_id, + price: a.price, + currency: a.place_currency, + place_time: a.place_time, + end_time: a.end_time, + duration_minutes: a.duration_minutes, + notes: a.place_notes, + image_url: a.image_url, + transport_mode: a.transport_mode, + google_place_id: a.google_place_id, + website: a.website, + phone: a.phone, + category: a.category_id ? { + id: a.category_id, + name: a.category_name, + color: a.category_color, + icon: a.category_icon, + } : null, + tags: tags || [], + } + }; +} + +export { loadTagsByPlaceIds, loadParticipantsByAssignmentIds, formatAssignmentWithPlace }; diff --git a/server/src/services/reservationService.ts b/server/src/services/reservationService.ts new file mode 100644 index 0000000000000000000000000000000000000000..5385c6a916dfcc79a3796d186418b3aec040a6f3 --- /dev/null +++ b/server/src/services/reservationService.ts @@ -0,0 +1,461 @@ +import { db } from '../db/database'; +import { Reservation } from '../types'; + +export { verifyTripAccess } from './tripAccess'; + +export interface ReservationEndpoint { + id?: number; + reservation_id?: number; + role: 'from' | 'to' | 'stop'; + sequence: number; + name: string; + code: string | null; + lat: number; + lng: number; + timezone: string | null; + local_time: string | null; + local_date: string | null; +} + +type EndpointInput = Omit & { sequence?: number }; + +function loadEndpointsByTrip(tripId: string | number): Map { + const rows = db.prepare(` + SELECT e.* FROM reservation_endpoints e + JOIN reservations r ON e.reservation_id = r.id + WHERE r.trip_id = ? + ORDER BY e.reservation_id, e.sequence + `).all(tripId) as ReservationEndpoint[]; + const map = new Map(); + for (const r of rows) { + const list = map.get(r.reservation_id!) ?? []; + list.push(r); + map.set(r.reservation_id!, list); + } + return map; +} + +function loadEndpoints(reservationId: number): ReservationEndpoint[] { + return db.prepare( + 'SELECT * FROM reservation_endpoints WHERE reservation_id = ? ORDER BY sequence' + ).all(reservationId) as ReservationEndpoint[]; +} + +// Resolve the day row whose date matches the date portion of an ISO-ish +// timestamp. Used to keep `day_id` / `end_day_id` in sync with +// `reservation_time` / `reservation_end_time` so non-transport bookings +// (tours, restaurants, events, ...) end up on the right day in the UI, +// which now filters by day_id instead of reservation_time. +function resolveDayIdFromTime( + tripId: string | number, + time: string | null | undefined, +): number | null { + if (!time) return null; + const datePart = time.slice(0, 10); + if (!/^\d{4}-\d{2}-\d{2}$/.test(datePart)) return null; + const row = db + .prepare('SELECT id FROM days WHERE trip_id = ? AND date = ? LIMIT 1') + .get(tripId, datePart) as { id: number } | undefined; + return row?.id ?? null; +} + +function saveEndpoints(reservationId: number, endpoints: EndpointInput[]): void { + // Bind the transaction lazily on each call. Binding at module load time + // captures the DB connection that was open then, which becomes invalid + // after demo-reset / restore-from-backup closes and reinitialises the + // connection — every later endpoint save would throw + // "The database connection is not open". + const tx = db.transaction((rid: number, eps: EndpointInput[]) => { + db.prepare('DELETE FROM reservation_endpoints WHERE reservation_id = ?').run(rid); + const insert = db.prepare(` + INSERT INTO reservation_endpoints (reservation_id, role, sequence, name, code, lat, lng, timezone, local_time, local_date) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `); + eps.forEach((e, i) => { + insert.run(rid, e.role, e.sequence ?? i, e.name, e.code ?? null, e.lat, e.lng, e.timezone ?? null, e.local_time ?? null, e.local_date ?? null); + }); + }); + tx(reservationId, endpoints); +} + +export function listReservations(tripId: string | number) { + const reservations = db.prepare(` + SELECT r.*, d.day_number, p.name as place_name, r.assignment_id, + ap.place_id as accommodation_place_id, acc_p.name as accommodation_name, + ap.start_day_id as accommodation_start_day_id, ap.end_day_id as accommodation_end_day_id + FROM reservations r + LEFT JOIN days d ON r.day_id = d.id + LEFT JOIN places p ON r.place_id = p.id + LEFT JOIN day_accommodations ap ON r.accommodation_id = ap.id + LEFT JOIN places acc_p ON ap.place_id = acc_p.id + WHERE r.trip_id = ? + ORDER BY r.reservation_time ASC, r.created_at ASC + `).all(tripId) as any[]; + + const dayPositions = db.prepare(` + SELECT rdp.reservation_id, rdp.day_id, rdp.position + FROM reservation_day_positions rdp + JOIN reservations r ON rdp.reservation_id = r.id + WHERE r.trip_id = ? + `).all(tripId) as { reservation_id: number; day_id: number; position: number }[]; + + const posMap = new Map>(); + for (const dp of dayPositions) { + if (!posMap.has(dp.reservation_id)) posMap.set(dp.reservation_id, {}); + posMap.get(dp.reservation_id)![dp.day_id] = dp.position; + } + + const endpointsMap = loadEndpointsByTrip(tripId); + + for (const r of reservations) { + r.day_positions = posMap.get(r.id) || null; + r.endpoints = endpointsMap.get(r.id) || []; + } + + return reservations; +} + +/** + * Upcoming reservations across all of a user's active trips, soonest first. + * Used by the dashboard's "Upcoming reservations" widget. A reservation counts + * as upcoming when its own time is in the future, or — for timeless entries — + * when its day falls on or after today. Cancelled bookings are skipped. + */ +export function getUpcomingReservations(userId: number, limit = 6) { + const today = new Date().toISOString().slice(0, 10); + const now = new Date().toISOString(); + + const reservations = db.prepare(` + SELECT r.id, r.trip_id, r.title, r.type, r.status, r.location, + r.reservation_time, r.confirmation_number, + t.title as trip_title, t.cover_image as trip_cover, + d.date as day_date, p.name as place_name, p.image_url as place_image + FROM reservations r + JOIN trips t ON t.id = r.trip_id + LEFT JOIN trip_members tm ON tm.trip_id = t.id AND tm.user_id = ? + LEFT JOIN days d ON r.day_id = d.id + LEFT JOIN places p ON r.place_id = p.id + WHERE (t.user_id = ? OR tm.user_id IS NOT NULL) + AND t.is_archived = 0 + AND r.status != 'cancelled' + AND ( + (r.reservation_time IS NOT NULL AND r.reservation_time >= ?) + OR (r.reservation_time IS NULL AND d.date IS NOT NULL AND d.date >= ?) + ) + ORDER BY COALESCE(r.reservation_time, d.date) ASC + LIMIT ? + `).all(userId, userId, now, today, limit) as any[]; + + return reservations; +} + +export function getReservationWithJoins(id: string | number) { + const row = db.prepare(` + SELECT r.*, d.day_number, p.name as place_name, r.assignment_id, + ap.place_id as accommodation_place_id, acc_p.name as accommodation_name, + ap.start_day_id as accommodation_start_day_id, ap.end_day_id as accommodation_end_day_id + FROM reservations r + LEFT JOIN days d ON r.day_id = d.id + LEFT JOIN places p ON r.place_id = p.id + LEFT JOIN day_accommodations ap ON r.accommodation_id = ap.id + LEFT JOIN places acc_p ON ap.place_id = acc_p.id + WHERE r.id = ? + `).get(id) as any; + if (!row) return undefined; + row.endpoints = loadEndpoints(row.id); + return row; +} + +interface CreateAccommodation { + place_id?: number; + start_day_id?: number; + end_day_id?: number; + check_in?: string; + check_out?: string; + confirmation?: string; +} + +interface CreateReservationData { + title: string; + reservation_time?: string; + reservation_end_time?: string; + location?: string; + confirmation_number?: string; + notes?: string; + day_id?: number; + end_day_id?: number; + place_id?: number; + assignment_id?: number; + status?: string; + type?: string; + accommodation_id?: number; + metadata?: any; + create_accommodation?: CreateAccommodation; + endpoints?: EndpointInput[]; + needs_review?: boolean; +} + +export function createReservation(tripId: string | number, data: CreateReservationData): { reservation: any; accommodationCreated: boolean } { + const { + title, reservation_time, reservation_end_time, location, + confirmation_number, notes, day_id, end_day_id, place_id, assignment_id, + status, type, accommodation_id, metadata, create_accommodation, + endpoints, needs_review + } = data; + + let accommodationCreated = false; + + // Auto-create accommodation for hotel reservations + let resolvedAccommodationId: number | null = accommodation_id || null; + if (type === 'hotel' && !resolvedAccommodationId && create_accommodation) { + const { place_id: accPlaceId, start_day_id, end_day_id, check_in, check_out, confirmation: accConf } = create_accommodation; + if (start_day_id && end_day_id) { + const accResult = db.prepare( + 'INSERT INTO day_accommodations (trip_id, place_id, start_day_id, end_day_id, check_in, check_out, confirmation) VALUES (?, ?, ?, ?, ?, ?, ?)' + ).run(tripId, accPlaceId || null, start_day_id, end_day_id, check_in || null, check_out || null, accConf || confirmation_number || null); + resolvedAccommodationId = Number(accResult.lastInsertRowid); + accommodationCreated = true; + } + } + + // Derive day_id / end_day_id from reservation_time when the client + // didn't explicitly set them (non-hotel bookings only — hotels store + // their date range on the linked day_accommodation). + const resolvedType = type || 'other'; + let resolvedDayId: number | null = day_id ?? null; + if (resolvedDayId == null && resolvedType !== 'hotel' && reservation_time) { + resolvedDayId = resolveDayIdFromTime(tripId, reservation_time); + } + let resolvedEndDayId: number | null = end_day_id ?? null; + if (resolvedEndDayId == null && resolvedType !== 'hotel' && reservation_end_time) { + resolvedEndDayId = resolveDayIdFromTime(tripId, reservation_end_time); + } + + const result = db.prepare(` + INSERT INTO reservations (trip_id, day_id, end_day_id, place_id, assignment_id, title, reservation_time, reservation_end_time, location, confirmation_number, notes, status, type, accommodation_id, metadata, needs_review) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `).run( + tripId, + resolvedDayId, + resolvedEndDayId, + place_id || null, + assignment_id || null, + title, + reservation_time || null, + reservation_end_time || null, + location || null, + confirmation_number || null, + notes || null, + status || 'pending', + resolvedType, + resolvedAccommodationId, + metadata ? JSON.stringify(metadata) : null, + needs_review ? 1 : 0 + ); + + if (endpoints && endpoints.length > 0) { + saveEndpoints(Number(result.lastInsertRowid), endpoints); + } + + // Sync check-in/out to accommodation if linked + if (accommodation_id && metadata) { + const meta = typeof metadata === 'string' ? JSON.parse(metadata) : metadata; + if (meta.check_in_time || meta.check_in_end_time || meta.check_out_time) { + db.prepare('UPDATE day_accommodations SET check_in = COALESCE(?, check_in), check_in_end = COALESCE(?, check_in_end), check_out = COALESCE(?, check_out) WHERE id = ?') + .run(meta.check_in_time || null, meta.check_in_end_time || null, meta.check_out_time || null, accommodation_id); + } + if (confirmation_number) { + db.prepare('UPDATE day_accommodations SET confirmation = COALESCE(?, confirmation) WHERE id = ?') + .run(confirmation_number, accommodation_id); + } + } + + const reservation = getReservationWithJoins(Number(result.lastInsertRowid)); + return { reservation, accommodationCreated }; +} + +export function updatePositions(tripId: string | number, positions: { id: number; day_plan_position: number }[], dayId?: number | string) { + if (dayId) { + // Per-day positions for multi-day reservations + const stmt = db.prepare('INSERT OR REPLACE INTO reservation_day_positions (reservation_id, day_id, position) VALUES (?, ?, ?)'); + const updateMany = db.transaction((items: { id: number; day_plan_position: number }[]) => { + for (const item of items) { + stmt.run(item.id, dayId, item.day_plan_position); + } + }); + updateMany(positions); + } else { + // Legacy: update global position + const stmt = db.prepare('UPDATE reservations SET day_plan_position = ? WHERE id = ? AND trip_id = ?'); + const updateMany = db.transaction((items: { id: number; day_plan_position: number }[]) => { + for (const item of items) { + stmt.run(item.day_plan_position, item.id, tripId); + } + }); + updateMany(positions); + } +} + +export function getReservation(id: string | number, tripId: string | number) { + return db.prepare('SELECT * FROM reservations WHERE id = ? AND trip_id = ?').get(id, tripId) as Reservation | undefined; +} + +interface UpdateReservationData { + title?: string; + reservation_time?: string; + reservation_end_time?: string; + location?: string; + confirmation_number?: string; + notes?: string; + day_id?: number; + end_day_id?: number | null; + place_id?: number; + assignment_id?: number; + status?: string; + type?: string; + accommodation_id?: number; + metadata?: any; + create_accommodation?: CreateAccommodation; + endpoints?: EndpointInput[]; + needs_review?: boolean; +} + +export function updateReservation(id: string | number, tripId: string | number, data: UpdateReservationData, current: Reservation): { reservation: any; accommodationChanged: boolean } { + const { + title, reservation_time, reservation_end_time, location, + confirmation_number, notes, day_id, end_day_id, place_id, assignment_id, + status, type, accommodation_id, metadata, create_accommodation, + endpoints, needs_review + } = data; + + let accommodationChanged = false; + + // Update or create accommodation for hotel reservations + let resolvedAccId: number | null = accommodation_id !== undefined ? (accommodation_id || null) : (current.accommodation_id ?? null); + if (resolvedAccId) { + const accExists = db.prepare('SELECT id FROM day_accommodations WHERE id = ?').get(resolvedAccId); + if (!accExists) resolvedAccId = null; + } + if (type === 'hotel' && create_accommodation) { + const { place_id: accPlaceId, start_day_id, end_day_id, check_in, check_out, confirmation: accConf } = create_accommodation; + if (start_day_id && end_day_id) { + if (resolvedAccId) { + db.prepare('UPDATE day_accommodations SET place_id = ?, start_day_id = ?, end_day_id = ?, check_in = ?, check_out = ?, confirmation = ? WHERE id = ?') + .run(accPlaceId || null, start_day_id, end_day_id, check_in || null, check_out || null, accConf || confirmation_number || null, resolvedAccId); + } else if (accPlaceId) { + const accResult = db.prepare( + 'INSERT INTO day_accommodations (trip_id, place_id, start_day_id, end_day_id, check_in, check_out, confirmation) VALUES (?, ?, ?, ?, ?, ?, ?)' + ).run(tripId, accPlaceId, start_day_id, end_day_id, check_in || null, check_out || null, accConf || confirmation_number || null); + resolvedAccId = Number(accResult.lastInsertRowid); + } + accommodationChanged = true; + } + } + + const resolvedType = (type ?? current.type) || 'other'; + const nextReservationTime = resolvedType === 'hotel' + ? null + : (reservation_time !== undefined ? (reservation_time || null) : current.reservation_time); + const nextReservationEndTime = resolvedType === 'hotel' + ? null + : (reservation_end_time !== undefined ? (reservation_end_time || null) : current.reservation_end_time); + + // day_id / end_day_id: honour an explicit value from the client, + // otherwise derive from the (possibly updated) reservation_time so the + // planner renders the booking on the correct day. + let nextDayId: number | null; + if (day_id !== undefined) { + nextDayId = day_id || null; + } else if (reservation_time !== undefined && resolvedType !== 'hotel') { + nextDayId = resolveDayIdFromTime(tripId, nextReservationTime); + } else { + nextDayId = current.day_id ?? null; + } + + let nextEndDayId: number | null; + if (end_day_id !== undefined) { + nextEndDayId = end_day_id ?? null; + } else if (reservation_end_time !== undefined && resolvedType !== 'hotel') { + nextEndDayId = resolveDayIdFromTime(tripId, nextReservationEndTime); + } else { + nextEndDayId = (current as any).end_day_id ?? null; + } + + db.prepare(` + UPDATE reservations SET + title = COALESCE(?, title), + reservation_time = ?, + reservation_end_time = ?, + location = ?, + confirmation_number = ?, + notes = ?, + day_id = ?, + end_day_id = ?, + place_id = ?, + assignment_id = ?, + status = COALESCE(?, status), + type = COALESCE(?, type), + accommodation_id = ?, + metadata = ?, + needs_review = COALESCE(?, needs_review) + WHERE id = ? + `).run( + title || null, + nextReservationTime, + nextReservationEndTime, + location !== undefined ? (location || null) : current.location, + confirmation_number !== undefined ? (confirmation_number || null) : current.confirmation_number, + notes !== undefined ? (notes || null) : current.notes, + nextDayId, + nextEndDayId, + place_id !== undefined ? (place_id || null) : current.place_id, + assignment_id !== undefined ? (assignment_id || null) : current.assignment_id, + status || null, + type || null, + resolvedAccId, + metadata !== undefined ? (metadata ? JSON.stringify(metadata) : null) : current.metadata, + needs_review === undefined ? null : (needs_review ? 1 : 0), + id + ); + + if (endpoints !== undefined) { + saveEndpoints(Number(id), endpoints); + } + + // Sync check-in/out to accommodation if linked + const resolvedMeta = metadata !== undefined ? metadata : (current.metadata ? JSON.parse(current.metadata as string) : null); + if (resolvedAccId && resolvedMeta) { + const meta = typeof resolvedMeta === 'string' ? JSON.parse(resolvedMeta) : resolvedMeta; + if (meta.check_in_time || meta.check_in_end_time || meta.check_out_time) { + db.prepare('UPDATE day_accommodations SET check_in = COALESCE(?, check_in), check_in_end = COALESCE(?, check_in_end), check_out = COALESCE(?, check_out) WHERE id = ?') + .run(meta.check_in_time || null, meta.check_in_end_time || null, meta.check_out_time || null, resolvedAccId); + } + const resolvedConf = confirmation_number !== undefined ? confirmation_number : current.confirmation_number; + if (resolvedConf) { + db.prepare('UPDATE day_accommodations SET confirmation = COALESCE(?, confirmation) WHERE id = ?') + .run(resolvedConf, resolvedAccId); + } + } + + const reservation = getReservationWithJoins(id); + return { reservation, accommodationChanged }; +} + +export function deleteReservation(id: string | number, tripId: string | number): { deleted: { id: number; title: string; type: string; accommodation_id: number | null } | undefined; accommodationDeleted: boolean; deletedBudgetItemId: number | null } { + const reservation = db.prepare('SELECT id, title, type, accommodation_id FROM reservations WHERE id = ? AND trip_id = ?').get(id, tripId) as { id: number; title: string; type: string; accommodation_id: number | null } | undefined; + if (!reservation) return { deleted: undefined, accommodationDeleted: false, deletedBudgetItemId: null }; + + let accommodationDeleted = false; + if (reservation.accommodation_id) { + db.prepare('DELETE FROM day_accommodations WHERE id = ?').run(reservation.accommodation_id); + accommodationDeleted = true; + } + + const linkedBudget = db.prepare('SELECT id FROM budget_items WHERE trip_id = ? AND reservation_id = ?').get(tripId, id) as { id: number } | undefined; + if (linkedBudget) { + db.prepare('DELETE FROM budget_items WHERE id = ?').run(linkedBudget.id); + } + + db.prepare('DELETE FROM reservations WHERE id = ?').run(id); + return { deleted: reservation, accommodationDeleted, deletedBudgetItemId: linkedBudget ? linkedBudget.id : null }; +} diff --git a/server/src/services/settingsService.ts b/server/src/services/settingsService.ts new file mode 100644 index 0000000000000000000000000000000000000000..138d7025c5cb33e49fee7c647259fba5953a3bc0 --- /dev/null +++ b/server/src/services/settingsService.ts @@ -0,0 +1,153 @@ +import { db } from '../db/database'; +import { decrypt_api_key, maybe_encrypt_api_key } from './apiKeyCrypto'; + +const ENCRYPTED_SETTING_KEYS = new Set(['webhook_url', 'ntfy_token', 'mapbox_access_token']); +// Encrypted keys that are masked (••••••••) when returned to the client. +// Keys not in this set but in ENCRYPTED_SETTING_KEYS are decrypted and returned. +const MASKED_SETTING_KEYS = new Set(['webhook_url', 'ntfy_token']); + +export const DEFAULTABLE_USER_SETTING_KEYS = [ + 'temperature_unit', + 'dark_mode', + 'time_format', + 'blur_booking_codes', + 'map_tile_url', + // Instance-wide Mapbox defaults: an admin can set a shared token + style so the + // whole instance uses Mapbox without each user pasting their own key (#920). + 'map_provider', + 'mapbox_access_token', + 'mapbox_style', + 'mapbox_3d_enabled', + 'mapbox_quality_mode', +] as const; + +type DefaultableKey = typeof DEFAULTABLE_USER_SETTING_KEYS[number]; + +const VALID_VALUES: Partial> = { + temperature_unit: ['fahrenheit', 'celsius'], + time_format: ['12h', '24h'], + dark_mode: [true, false, 'light', 'dark', 'auto'], + map_provider: ['leaflet', 'mapbox-gl'], +}; + +const BOOLEAN_KEYS = new Set(['blur_booking_codes', 'mapbox_3d_enabled', 'mapbox_quality_mode']); + +function parseValue(raw: string): unknown { + try { return JSON.parse(raw); } catch { return raw; } +} + +export function getAdminUserDefaults(): Record { + const rows = db.prepare( + "SELECT key, value FROM app_settings WHERE key LIKE 'default_user_setting_%'" + ).all() as { key: string; value: string }[]; + const defaults: Record = {}; + for (const row of rows) { + const settingKey = row.key.slice('default_user_setting_'.length); + if (ENCRYPTED_SETTING_KEYS.has(settingKey)) { + defaults[settingKey] = row.value ? (decrypt_api_key(row.value) ?? '') : ''; + } else { + defaults[settingKey] = parseValue(row.value); + } + } + return defaults; +} + +export function setAdminUserDefaults(partial: Record): void { + const upsert = db.prepare( + `INSERT INTO app_settings (key, value) VALUES (?, ?) + ON CONFLICT(key) DO UPDATE SET value = excluded.value` + ); + const del = db.prepare("DELETE FROM app_settings WHERE key = ?"); + + db.exec('BEGIN'); + try { + for (const [key, value] of Object.entries(partial)) { + if (!(DEFAULTABLE_USER_SETTING_KEYS as readonly string[]).includes(key)) { + throw new Error(`Invalid setting key: ${key}`); + } + const typedKey = key as DefaultableKey; + const appKey = `default_user_setting_${key}`; + + // null/undefined means "reset to built-in default" — delete the row + if (value === null || value === undefined) { + del.run(appKey); + continue; + } + + if (BOOLEAN_KEYS.has(typedKey) && typeof value !== 'boolean') { + throw new Error(`Setting ${key} must be a boolean`); + } + const allowed = VALID_VALUES[typedKey]; + if (allowed && !allowed.includes(value)) { + throw new Error(`Invalid value for ${key}: ${value}`); + } + + // Encrypt sensitive defaults (the shared Mapbox token) at rest, like the + // per-user equivalents; everything else is stored as plain JSON. + const stored = ENCRYPTED_SETTING_KEYS.has(key) + ? (maybe_encrypt_api_key(String(value)) ?? String(value)) + : JSON.stringify(value); + upsert.run(appKey, stored); + } + db.exec('COMMIT'); + } catch (err) { + db.exec('ROLLBACK'); + throw err; + } +} + +export function getUserSettings(userId: number): Record { + const adminDefaults = getAdminUserDefaults(); + + const rows = db.prepare('SELECT key, value FROM settings WHERE user_id = ?').all(userId) as { key: string; value: string }[]; + const userSettings: Record = {}; + for (const row of rows) { + if (MASKED_SETTING_KEYS.has(row.key)) { + userSettings[row.key] = row.value ? '••••••••' : ''; + continue; + } + if (ENCRYPTED_SETTING_KEYS.has(row.key)) { + userSettings[row.key] = row.value ? (decrypt_api_key(row.value) ?? '') : ''; + continue; + } + try { + userSettings[row.key] = JSON.parse(row.value); + } catch { + userSettings[row.key] = row.value; + } + } + + // Admin defaults fill in only for keys the user hasn't explicitly set + return { ...adminDefaults, ...userSettings }; +} + +function serializeValue(key: string, value: unknown): string { + const raw = typeof value === 'object' ? JSON.stringify(value) : String(value !== undefined ? value : ''); + if (ENCRYPTED_SETTING_KEYS.has(key)) return maybe_encrypt_api_key(raw) ?? raw; + return raw; +} + +export function upsertSetting(userId: number, key: string, value: unknown) { + db.prepare(` + INSERT INTO settings (user_id, key, value) VALUES (?, ?, ?) + ON CONFLICT(user_id, key) DO UPDATE SET value = excluded.value + `).run(userId, key, serializeValue(key, value)); +} + +export function bulkUpsertSettings(userId: number, settings: Record) { + const upsert = db.prepare(` + INSERT INTO settings (user_id, key, value) VALUES (?, ?, ?) + ON CONFLICT(user_id, key) DO UPDATE SET value = excluded.value + `); + db.exec('BEGIN'); + try { + for (const [key, value] of Object.entries(settings)) { + upsert.run(userId, key, serializeValue(key, value)); + } + db.exec('COMMIT'); + } catch (err) { + db.exec('ROLLBACK'); + throw err; + } + return Object.keys(settings).length; +} diff --git a/server/src/services/shareService.ts b/server/src/services/shareService.ts new file mode 100644 index 0000000000000000000000000000000000000000..7021ce60f4acff1b1e204451d1ab1a8496889983 --- /dev/null +++ b/server/src/services/shareService.ts @@ -0,0 +1,253 @@ +import { db, canAccessTrip } from '../db/database'; +import crypto from 'crypto'; +import { loadTagsByPlaceIds } from './queryHelpers'; +import { serveFilePath } from './placePhotoCache'; + +const PLACE_PHOTO_PROXY_PREFIX = '/api/maps/place-photo/'; + +/** + * Place photo proxy URLs (`/api/maps/place-photo//bytes`) are served by the + * JWT-guarded MapsController, so they 401 for an unauthenticated shared-trip + * viewer. Rewrite them to the public, token-scoped equivalent + * (`/api/shared//place-photo//bytes`) so thumbnails load in a shared + * link. A simple prefix swap keeps the already-encoded placeId segment intact, so + * the URL round-trips. Non-proxy URLs (data:, /uploads/, null) pass through. + */ +function rewritePlacePhotoUrl(url: string | null | undefined, token: string): string | null { + if (typeof url === 'string' && url.startsWith(PLACE_PHOTO_PROXY_PREFIX)) { + return `/api/shared/${token}/place-photo/${url.slice(PLACE_PHOTO_PROXY_PREFIX.length)}`; + } + return url ?? null; +} + +interface SharePermissions { + share_map?: boolean; + share_bookings?: boolean; + share_packing?: boolean; + share_budget?: boolean; + share_collab?: boolean; +} + +interface ShareTokenInfo { + token: string; + created_at: string; + share_map: boolean; + share_bookings: boolean; + share_packing: boolean; + share_budget: boolean; + share_collab: boolean; +} + +/** + * Creates a new share link or updates the permissions on an existing one. + * Returns an object with the token string and whether it was newly created. + */ +export function createOrUpdateShareLink( + tripId: string, + createdBy: number, + permissions: SharePermissions +): { token: string; created: boolean } { + const { + share_map = true, + share_bookings = true, + share_packing = false, + share_budget = false, + share_collab = false, + } = permissions; + + const existing = db.prepare('SELECT token FROM share_tokens WHERE trip_id = ?').get(tripId) as { token: string } | undefined; + if (existing) { + db.prepare('UPDATE share_tokens SET share_map = ?, share_bookings = ?, share_packing = ?, share_budget = ?, share_collab = ? WHERE trip_id = ?') + .run(share_map ? 1 : 0, share_bookings ? 1 : 0, share_packing ? 1 : 0, share_budget ? 1 : 0, share_collab ? 1 : 0, tripId); + return { token: existing.token, created: false }; + } + + // New share links default to a 90-day TTL. Existing tokens that were + // created before the expires_at migration keep NULL here and remain + // valid indefinitely until the owner rotates them; that preserves + // behaviour for anyone who's already sharing a link. + const token = crypto.randomBytes(24).toString('base64url'); + const expiresAt = new Date(Date.now() + 90 * 24 * 60 * 60 * 1000).toISOString(); + db.prepare('INSERT INTO share_tokens (trip_id, token, created_by, share_map, share_bookings, share_packing, share_budget, share_collab, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)') + .run(tripId, token, createdBy, share_map ? 1 : 0, share_bookings ? 1 : 0, share_packing ? 1 : 0, share_budget ? 1 : 0, share_collab ? 1 : 0, expiresAt); + return { token, created: true }; +} + +/** + * Returns share token info for a trip, or null if no share link exists. + */ +export function getShareLink(tripId: string): ShareTokenInfo | null { + const row = db.prepare('SELECT * FROM share_tokens WHERE trip_id = ?').get(tripId) as any; + if (!row) return null; + return { + token: row.token, + created_at: row.created_at, + share_map: !!row.share_map, + share_bookings: !!row.share_bookings, + share_packing: !!row.share_packing, + share_budget: !!row.share_budget, + share_collab: !!row.share_collab, + }; +} + +/** + * Deletes the share token for a trip. + */ +export function deleteShareLink(tripId: string): void { + db.prepare('DELETE FROM share_tokens WHERE trip_id = ?').run(tripId); +} + +/** + * Loads the full public trip data for a share token, filtered by the token's + * permission flags. Returns null if the token is invalid or the trip is gone. + */ +export function getSharedTripData(token: string): Record | null { + const shareRow = db.prepare( + "SELECT * FROM share_tokens WHERE token = ? AND (expires_at IS NULL OR expires_at > datetime('now'))" + ).get(token) as any; + if (!shareRow) return null; + + const tripId = shareRow.trip_id; + + // Trip + const trip = db.prepare('SELECT id, title, description, start_date, end_date, cover_image, currency FROM trips WHERE id = ?').get(tripId); + if (!trip) return null; + + // Days with assignments + const days = db.prepare('SELECT * FROM days WHERE trip_id = ? ORDER BY day_number ASC').all(tripId) as any[]; + const dayIds = days.map(d => d.id); + + let assignments: Record = {}; + let dayNotes: Record = {}; + if (dayIds.length > 0) { + const ph = dayIds.map(() => '?').join(','); + const allAssignments = db.prepare(` + SELECT da.*, p.id as place_id, p.name as place_name, p.description as place_description, + p.lat, p.lng, p.address, p.category_id, p.price, p.currency as place_currency, + COALESCE(da.assignment_time, p.place_time) as place_time, + COALESCE(da.assignment_end_time, p.end_time) as end_time, + p.duration_minutes, p.notes as place_notes, p.image_url, p.transport_mode, + c.name as category_name, c.color as category_color, c.icon as category_icon + FROM day_assignments da + JOIN places p ON da.place_id = p.id + LEFT JOIN categories c ON p.category_id = c.id + WHERE da.day_id IN (${ph}) + ORDER BY da.order_index ASC, da.created_at ASC + `).all(...dayIds); + + const placeIds = [...new Set(allAssignments.map((a: any) => a.place_id))]; + const tagsByPlace = loadTagsByPlaceIds(placeIds, { compact: true }); + + const byDay: Record = {}; + for (const a of allAssignments as any[]) { + if (!byDay[a.day_id]) byDay[a.day_id] = []; + byDay[a.day_id].push({ + id: a.id, day_id: a.day_id, order_index: a.order_index, notes: a.notes, + place: { + id: a.place_id, name: a.place_name, description: a.place_description, + lat: a.lat, lng: a.lng, address: a.address, category_id: a.category_id, + price: a.price, place_time: a.place_time, end_time: a.end_time, + image_url: rewritePlacePhotoUrl(a.image_url, token), transport_mode: a.transport_mode, + category: a.category_id ? { id: a.category_id, name: a.category_name, color: a.category_color, icon: a.category_icon } : null, + tags: tagsByPlace[a.place_id] || [], + } + }); + } + assignments = byDay; + + const allNotes = db.prepare(`SELECT * FROM day_notes WHERE day_id IN (${ph}) ORDER BY sort_order ASC, created_at ASC`).all(...dayIds); + const notesByDay: Record = {}; + for (const n of allNotes as any[]) { + if (!notesByDay[n.day_id]) notesByDay[n.day_id] = []; + notesByDay[n.day_id].push(n); + } + dayNotes = notesByDay; + } + + // Places + const places = (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.trip_id = ? ORDER BY p.created_at DESC + `).all(tripId) as any[]).map((p) => ({ ...p, image_url: rewritePlacePhotoUrl(p.image_url, token) })); + + // Reservations — include per-day positions so the client can render the same order as the planner + const reservations = db.prepare('SELECT * FROM reservations WHERE trip_id = ? ORDER BY reservation_time ASC').all(tripId) as any[]; + + const dayPositions = db.prepare(` + SELECT rdp.reservation_id, rdp.day_id, rdp.position + FROM reservation_day_positions rdp + JOIN reservations r ON rdp.reservation_id = r.id + WHERE r.trip_id = ? + `).all(tripId) as { reservation_id: number; day_id: number; position: number }[]; + + const posMap = new Map>(); + for (const dp of dayPositions) { + if (!posMap.has(dp.reservation_id)) posMap.set(dp.reservation_id, {}); + posMap.get(dp.reservation_id)![dp.day_id] = dp.position; + } + for (const r of reservations) { + r.day_positions = posMap.get(r.id) || null; + } + + // Accommodations + const accommodations = db.prepare(` + SELECT a.*, p.name as place_name, p.address as place_address, p.lat as place_lat, p.lng as place_lng + FROM day_accommodations a JOIN places p ON a.place_id = p.id + WHERE a.trip_id = ? + `).all(tripId); + + // Packing + const packing = db.prepare('SELECT * FROM packing_items WHERE trip_id = ? ORDER BY sort_order ASC').all(tripId); + + // Budget + const budget = db.prepare('SELECT * FROM budget_items WHERE trip_id = ? ORDER BY category ASC').all(tripId); + + // Categories + const categories = db.prepare('SELECT * FROM categories').all(); + + const permissions = { + share_map: !!shareRow.share_map, + share_bookings: !!shareRow.share_bookings, + share_packing: !!shareRow.share_packing, + share_budget: !!shareRow.share_budget, + share_collab: !!shareRow.share_collab, + }; + + // Collab messages (only if owner chose to share) + const collabMessages = permissions.share_collab + ? db.prepare('SELECT m.*, u.username, u.avatar FROM collab_messages m JOIN users u ON m.user_id = u.id WHERE m.trip_id = ? AND m.deleted = 0 ORDER BY m.created_at').all(tripId) + : []; + + return { + trip, days, assignments, dayNotes, places, categories, permissions, + reservations: permissions.share_bookings ? reservations : [], + accommodations: permissions.share_bookings ? accommodations : [], + packing: permissions.share_packing ? packing : [], + budget: permissions.share_budget ? budget : [], + collab: collabMessages, + }; +} + +/** + * Resolves the on-disk path for a cached place photo requested through a public + * share link. Validates that the token is valid + unexpired and that the place + * actually belongs to that token's trip (matched via the stored proxy URL, which + * covers both Google `placeId` and Wikimedia `coords:` pseudo-IDs without + * depending on google_place_id). Returns null — never throws — so the caller + * answers a plain 404, mirroring the authenticated bytes endpoint. + */ +export function getSharedPlacePhotoPath(token: string, placeId: string): string | null { + const shareRow = db.prepare( + "SELECT trip_id FROM share_tokens WHERE token = ? AND (expires_at IS NULL OR expires_at > datetime('now'))" + ).get(token) as { trip_id: string } | undefined; + if (!shareRow) return null; + + const expectedUrl = `${PLACE_PHOTO_PROXY_PREFIX}${encodeURIComponent(placeId)}/bytes`; + const place = db.prepare( + 'SELECT 1 FROM places WHERE trip_id = ? AND image_url = ?' + ).get(shareRow.trip_id, expectedUrl); + if (!place) return null; + + return serveFilePath(placeId); +} diff --git a/server/src/services/tagService.ts b/server/src/services/tagService.ts new file mode 100644 index 0000000000000000000000000000000000000000..ef17b58879c579cef18f12f9e431a0cc0b34508d --- /dev/null +++ b/server/src/services/tagService.ts @@ -0,0 +1,26 @@ +import { db } from '../db/database'; + +export function listTags(userId: number) { + return db.prepare('SELECT * FROM tags WHERE user_id = ? ORDER BY name ASC').all(userId); +} + +export function createTag(userId: number, name: string, color?: string) { + const result = db.prepare( + 'INSERT INTO tags (user_id, name, color) VALUES (?, ?, ?)' + ).run(userId, name, color || '#10b981'); + return db.prepare('SELECT * FROM tags WHERE id = ?').get(result.lastInsertRowid); +} + +export function getTagByIdAndUser(tagId: number | string, userId: number) { + return db.prepare('SELECT * FROM tags WHERE id = ? AND user_id = ?').get(tagId, userId); +} + +export function updateTag(tagId: number | string, name?: string, color?: string) { + db.prepare('UPDATE tags SET name = COALESCE(?, name), color = COALESCE(?, color) WHERE id = ?') + .run(name || null, color || null, tagId); + return db.prepare('SELECT * FROM tags WHERE id = ?').get(tagId); +} + +export function deleteTag(tagId: number | string) { + db.prepare('DELETE FROM tags WHERE id = ?').run(tagId); +} diff --git a/server/src/services/todoService.ts b/server/src/services/todoService.ts new file mode 100644 index 0000000000000000000000000000000000000000..d86c541d6aff4d5c9f4f2ce3e338f798fd005c23 --- /dev/null +++ b/server/src/services/todoService.ts @@ -0,0 +1,120 @@ +import { db } from '../db/database'; + +export { verifyTripAccess } from './tripAccess'; + +// ── Items ────────────────────────────────────────────────────────────────── + +export function listItems(tripId: string | number) { + return db.prepare( + 'SELECT * FROM todo_items WHERE trip_id = ? ORDER BY sort_order ASC, created_at ASC' + ).all(tripId); +} + +export function createItem(tripId: string | number, data: { + name: string; category?: string; due_date?: string; description?: string; assigned_user_id?: number; priority?: number; +}) { + const maxOrder = db.prepare('SELECT MAX(sort_order) as max FROM todo_items WHERE trip_id = ?').get(tripId) as { max: number | null }; + const sortOrder = (maxOrder.max !== null ? maxOrder.max : -1) + 1; + + const result = db.prepare( + 'INSERT INTO todo_items (trip_id, name, checked, category, sort_order, due_date, description, assigned_user_id, priority) VALUES (?, ?, 0, ?, ?, ?, ?, ?, ?)' + ).run( + tripId, data.name, data.category || null, sortOrder, + data.due_date || null, data.description || null, data.assigned_user_id || null, data.priority || 0 + ); + + return db.prepare('SELECT * FROM todo_items WHERE id = ?').get(result.lastInsertRowid); +} + +export function updateItem( + tripId: string | number, + id: string | number, + data: { name?: string; checked?: number; category?: string; due_date?: string | null; description?: string | null; assigned_user_id?: number | null; priority?: number | null }, + bodyKeys: string[] +) { + const item = db.prepare('SELECT * FROM todo_items WHERE id = ? AND trip_id = ?').get(id, tripId); + if (!item) return null; + + db.prepare(` + UPDATE todo_items SET + name = COALESCE(?, name), + checked = CASE WHEN ? IS NOT NULL THEN ? ELSE checked END, + category = COALESCE(?, category), + due_date = CASE WHEN ? THEN ? ELSE due_date END, + description = CASE WHEN ? THEN ? ELSE description END, + assigned_user_id = CASE WHEN ? THEN ? ELSE assigned_user_id END, + priority = CASE WHEN ? THEN ? ELSE priority END + WHERE id = ? + `).run( + data.name || null, + data.checked !== undefined ? 1 : null, + data.checked ? 1 : 0, + data.category || null, + bodyKeys.includes('due_date') ? 1 : 0, + data.due_date ?? null, + bodyKeys.includes('description') ? 1 : 0, + data.description ?? null, + bodyKeys.includes('assigned_user_id') ? 1 : 0, + data.assigned_user_id ?? null, + bodyKeys.includes('priority') ? 1 : 0, + data.priority ?? 0, + id + ); + + return db.prepare('SELECT * FROM todo_items WHERE id = ?').get(id); +} + +export function deleteItem(tripId: string | number, id: string | number) { + const item = db.prepare('SELECT id FROM todo_items WHERE id = ? AND trip_id = ?').get(id, tripId); + if (!item) return false; + + db.prepare('DELETE FROM todo_items WHERE id = ?').run(id); + return true; +} + +// ── Category Assignees ───────────────────────────────────────────────────── + +export function getCategoryAssignees(tripId: string | number) { + const rows = db.prepare(` + SELECT tca.category_name, tca.user_id, u.username, u.avatar + FROM todo_category_assignees tca + JOIN users u ON tca.user_id = u.id + WHERE tca.trip_id = ? + `).all(tripId); + + const assignees: Record = {}; + for (const row of rows as any[]) { + if (!assignees[row.category_name]) assignees[row.category_name] = []; + assignees[row.category_name].push({ user_id: row.user_id, username: row.username, avatar: row.avatar }); + } + + return assignees; +} + +export function updateCategoryAssignees(tripId: string | number, categoryName: string, userIds: number[] | undefined) { + db.prepare('DELETE FROM todo_category_assignees WHERE trip_id = ? AND category_name = ?').run(tripId, categoryName); + + if (Array.isArray(userIds) && userIds.length > 0) { + const insert = db.prepare('INSERT OR IGNORE INTO todo_category_assignees (trip_id, category_name, user_id) VALUES (?, ?, ?)'); + for (const uid of userIds) insert.run(tripId, categoryName, uid); + } + + return db.prepare(` + SELECT tca.user_id, u.username, u.avatar + FROM todo_category_assignees tca + JOIN users u ON tca.user_id = u.id + WHERE tca.trip_id = ? AND tca.category_name = ? + `).all(tripId, categoryName); +} + +// ── Reorder ──────────────────────────────────────────────────────────────── + +export function reorderItems(tripId: string | number, orderedIds: number[]) { + const update = db.prepare('UPDATE todo_items SET sort_order = ? WHERE id = ? AND trip_id = ?'); + const updateMany = db.transaction((ids: number[]) => { + ids.forEach((id, index) => { + update.run(index, id, tripId); + }); + }); + updateMany(orderedIds); +} diff --git a/server/src/services/tripAccess.ts b/server/src/services/tripAccess.ts new file mode 100644 index 0000000000000000000000000000000000000000..10b91c3fa45f0243e442427a18404b28b318a4c2 --- /dev/null +++ b/server/src/services/tripAccess.ts @@ -0,0 +1,9 @@ +import { canAccessTrip } from '../db/database'; + +/** + * Returns the trip row if the user is the owner or a member, otherwise undefined. + * Shared by the domain services so each one exposes the same access check. + */ +export function verifyTripAccess(tripId: string | number, userId: number) { + return canAccessTrip(tripId, userId); +} diff --git a/server/src/services/tripService.ts b/server/src/services/tripService.ts new file mode 100644 index 0000000000000000000000000000000000000000..3893bd2ebe85e84539b7871880472d7a593c9fb5 --- /dev/null +++ b/server/src/services/tripService.ts @@ -0,0 +1,799 @@ +import path from 'path'; +import fs from 'fs'; +import { db, isOwner } from '../db/database'; +import { Trip, User } from '../types'; +import { listDays, listAccommodations } from './dayService'; +import { listBudgetItems } from './budgetService'; +import { listItems as listPackingItems } from './packingService'; +import { listReservations } from './reservationService'; +import { listNotes as listCollabNotes } from './collabService'; +import { shiftOwnerEntriesForTripWindow } from './vacayService'; + +export const MS_PER_DAY = 86400000; +export const MAX_TRIP_DAYS = 365; + +export const TRIP_SELECT = ` + SELECT t.*, + (SELECT COUNT(*) FROM days d WHERE d.trip_id = t.id) as day_count, + (SELECT COUNT(*) FROM places p WHERE p.trip_id = t.id) as place_count, + CASE WHEN t.user_id = :userId THEN 1 ELSE 0 END as is_owner, + u.username as owner_username, + (SELECT COUNT(*) FROM trip_members tm WHERE tm.trip_id = t.id) as shared_count + FROM trips t + JOIN users u ON u.id = t.user_id +`; + +// ── Access helpers ──────────────────────────────────────────────────────── + +export { verifyTripAccess } from './tripAccess'; +export { isOwner }; + +// ── Day generation ──────────────────────────────────────────────────────── + +export function generateDays(tripId: number | bigint | string, startDate: string | null, endDate: string | null, maxDays?: number, dayCount?: number) { + const existing = db.prepare('SELECT id, day_number, date FROM days WHERE trip_id = ?').all(tripId) as { id: number; day_number: number; date: string | null }[]; + const setDayNumber = db.prepare('UPDATE days SET day_number = ? WHERE id = ?'); + + // Helper: two-phase renumber to avoid UNIQUE(trip_id, day_number) collisions + function renumber(days: { id: number }[]) { + days.forEach((d, i) => setDayNumber.run(-(i + 1), d.id)); + days.forEach((d, i) => setDayNumber.run(i + 1, d.id)); + } + + if (!startDate || !endDate) { + // Nullify all dated days instead of deleting them — preserves assignments/notes/accommodations + const withDates = existing.filter(d => d.date); + if (withDates.length > 0) { + const nullify = db.prepare('UPDATE days SET date = NULL WHERE id = ?'); + for (const d of withDates) nullify.run(d.id); + } + // Now all days are dateless — adjust count toward dayCount target + const allDays = db.prepare('SELECT id FROM days WHERE trip_id = ? ORDER BY day_number').all(tripId) as { id: number }[]; + const targetCount = Math.min(Math.max(dayCount ?? (allDays.length || 7), 1), MAX_TRIP_DAYS); + const needed = targetCount - allDays.length; + if (needed > 0) { + const insert = db.prepare('INSERT INTO days (trip_id, day_number, date) VALUES (?, ?, NULL)'); + for (let i = 0; i < needed; i++) insert.run(tripId, allDays.length + i + 1); + } else if (needed < 0) { + // Only trim trailing empty days to avoid destroying content + const candidates = db.prepare( + `SELECT d.id FROM days d + WHERE d.trip_id = ? + AND NOT EXISTS (SELECT 1 FROM day_assignments da WHERE da.day_id = d.id) + AND NOT EXISTS (SELECT 1 FROM day_notes dn WHERE dn.day_id = d.id) + AND NOT EXISTS (SELECT 1 FROM day_accommodations dac WHERE dac.start_day_id = d.id OR dac.end_day_id = d.id) + ORDER BY d.day_number DESC + LIMIT ?` + ).all(tripId, -needed) as { id: number }[]; + const del = db.prepare('DELETE FROM days WHERE id = ?'); + for (const d of candidates) del.run(d.id); + } + const remaining = db.prepare('SELECT id FROM days WHERE trip_id = ? ORDER BY day_number').all(tripId) as { id: number }[]; + renumber(remaining); + return; + } + + const [sy, sm, sd] = startDate.split('-').map(Number); + const [ey, em, ed] = endDate.split('-').map(Number); + const startMs = Date.UTC(sy, sm - 1, sd); + const endMs = Date.UTC(ey, em - 1, ed); + const numDays = Math.min(Math.floor((endMs - startMs) / MS_PER_DAY) + 1, maxDays ?? MAX_TRIP_DAYS); + + const targetDates: string[] = []; + for (let i = 0; i < numDays; i++) { + const d = new Date(startMs + i * MS_PER_DAY); + const yyyy = d.getUTCFullYear(); + const mm = String(d.getUTCMonth() + 1).padStart(2, '0'); + const dd = String(d.getUTCDate()).padStart(2, '0'); + targetDates.push(`${yyyy}-${mm}-${dd}`); + } + + // Split into dated (sorted by day_number = position) and dateless (spare pool) + const dated = existing.filter(d => d.date).sort((a, b) => a.day_number - b.day_number); + const dateless = existing.filter(d => !d.date).sort((a, b) => a.day_number - b.day_number); + + // Phase 1: stamp all existing days with negative day_numbers to free up slots + const allExisting = [...dated, ...dateless]; + allExisting.forEach((d, i) => setDayNumber.run(-(i + 1), d.id)); + + const assignDay = db.prepare('UPDATE days SET date = ?, day_number = ? WHERE id = ?'); + const insert = db.prepare('INSERT INTO days (trip_id, day_number, date) VALUES (?, ?, ?)'); + + let datelessIdx = 0; + + for (let i = 0; i < targetDates.length; i++) { + const date = targetDates[i]; + if (i < dated.length) { + // Positional remap: existing dated day i gets new date — keeps all children + assignDay.run(date, i + 1, dated[i].id); + } else if (datelessIdx < dateless.length) { + // Reuse a dateless day — keeps its assignments, notes, etc. + assignDay.run(date, i + 1, dateless[datelessIdx].id); + datelessIdx++; + } else { + insert.run(tripId, i + 1, date); + } + } + + // Overflow dated days (trip shrunk): delete them (issue #909). + // Cascade removes their assignments, notes, and accommodations. + const del = db.prepare('DELETE FROM days WHERE id = ?'); + for (let i = targetDates.length; i < dated.length; i++) { + del.run(dated[i].id); + } + + // Any remaining unused dateless days: drop the empty placeholders so day_count + // reflects the dated range, but keep ones that still hold content (assignments, + // notes, accommodations) — mirrors the dateless-path trimming above (#1083). + // Base must be max(targetDates.length, dated.length) to avoid colliding with + // positives already assigned by the main loop or the overflow loop above. + const isEmptyDay = db.prepare( + `SELECT NOT EXISTS (SELECT 1 FROM day_assignments da WHERE da.day_id = @id) + AND NOT EXISTS (SELECT 1 FROM day_notes dn WHERE dn.day_id = @id) + AND NOT EXISTS (SELECT 1 FROM day_accommodations dac WHERE dac.start_day_id = @id OR dac.end_day_id = @id) AS empty` + ); + const maxAssigned = Math.max(targetDates.length, dated.length); + let keptDateless = 0; + for (let i = datelessIdx; i < dateless.length; i++) { + const empty = (isEmptyDay.get({ id: dateless[i].id }) as { empty: number }).empty; + if (empty) { + del.run(dateless[i].id); + } else { + setDayNumber.run(maxAssigned + keptDateless + 1, dateless[i].id); + keptDateless++; + } + } + + // Final renumber to compact and eliminate any gaps/negatives + const remaining = db.prepare('SELECT id FROM days WHERE trip_id = ? ORDER BY day_number').all(tripId) as { id: number }[]; + renumber(remaining); +} + +// ── Trip CRUD ───────────────────────────────────────────────────────────── + +export function listTrips(userId: number, archived: number | null) { + if (archived === null) { + return db.prepare(` + ${TRIP_SELECT} + LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = :userId + WHERE (t.user_id = :userId OR m.user_id IS NOT NULL) + ORDER BY t.created_at DESC + `).all({ userId }); + } + return db.prepare(` + ${TRIP_SELECT} + LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = :userId + WHERE (t.user_id = :userId OR m.user_id IS NOT NULL) AND t.is_archived = :archived + ORDER BY t.created_at DESC + `).all({ userId, archived }); +} + +interface CreateTripData { + title: string; + description?: string | null; + start_date?: string | null; + end_date?: string | null; + currency?: string; + reminder_days?: number; + day_count?: number; +} + +export function createTrip(userId: number, data: CreateTripData, maxDays?: number) { + const rd = data.reminder_days !== undefined + ? (Number(data.reminder_days) >= 0 && Number(data.reminder_days) <= 30 ? Number(data.reminder_days) : 3) + : 3; + + const result = db.prepare(` + INSERT INTO trips (user_id, title, description, start_date, end_date, currency, reminder_days) + VALUES (?, ?, ?, ?, ?, ?, ?) + `).run(userId, data.title, data.description || null, data.start_date || null, data.end_date || null, data.currency || 'EUR', rd); + + const tripId = result.lastInsertRowid; + generateDays(tripId, data.start_date || null, data.end_date || null, maxDays, data.day_count); + + const trip = db.prepare(`${TRIP_SELECT} WHERE t.id = :tripId`).get({ userId, tripId }); + return { trip, tripId: Number(tripId), reminderDays: rd }; +} + +export function getTrip(tripId: string | number, userId: number) { + return db.prepare(` + ${TRIP_SELECT} + LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = :userId + WHERE t.id = :tripId AND (t.user_id = :userId OR m.user_id IS NOT NULL) + `).get({ userId, tripId }) as Trip | undefined; +} + +interface UpdateTripData { + title?: string; + description?: string; + start_date?: string; + end_date?: string; + currency?: string; + is_archived?: boolean | number; + cover_image?: string; + reminder_days?: number; + day_count?: number; +} + +export interface UpdateTripResult { + updatedTrip: any; + changes: Record; + isAdminEdit: boolean; + ownerEmail?: string; + newTitle: string; + newReminder: number; + oldReminder: number; +} + +export function updateTrip(tripId: string | number, userId: number, data: UpdateTripData, userRole: string): UpdateTripResult { + const trip = db.prepare('SELECT * FROM trips WHERE id = ?').get(tripId) as Trip & { reminder_days?: number } | undefined; + if (!trip) throw new NotFoundError('Trip not found'); + + const { title, description, start_date, end_date, currency, is_archived, cover_image, reminder_days } = data; + + if (start_date && end_date && new Date(end_date) < new Date(start_date)) + throw new ValidationError('End date must be after start date'); + + const newTitle = title || trip.title; + const newDesc = description !== undefined ? description : trip.description; + const newStart = start_date !== undefined ? start_date : trip.start_date; + const newEnd = end_date !== undefined ? end_date : trip.end_date; + const newCurrency = currency || trip.currency; + const newArchived = is_archived !== undefined ? (is_archived ? 1 : 0) : trip.is_archived; + const newCover = cover_image !== undefined ? cover_image : trip.cover_image; + const oldReminder = (trip as any).reminder_days ?? 3; + const newReminder = reminder_days !== undefined + ? (Number(reminder_days) >= 0 && Number(reminder_days) <= 30 ? Number(reminder_days) : oldReminder) + : oldReminder; + + db.prepare(` + UPDATE trips SET title=?, description=?, start_date=?, end_date=?, + currency=?, is_archived=?, cover_image=?, reminder_days=?, updated_at=CURRENT_TIMESTAMP + WHERE id=? + `).run(newTitle, newDesc, newStart || null, newEnd || null, newCurrency, newArchived, newCover, newReminder, tripId); + + if (trip.start_date && trip.end_date && newStart && newStart !== trip.start_date) + shiftOwnerEntriesForTripWindow(trip.user_id, trip.start_date, trip.end_date, newStart); + + const dayCount = data.day_count ? Math.min(Math.max(Number(data.day_count) || 7, 1), MAX_TRIP_DAYS) : undefined; + if (newStart !== trip.start_date || newEnd !== trip.end_date || dayCount) + generateDays(tripId, newStart || null, newEnd || null, undefined, dayCount); + + const changes: Record = {}; + if (title && title !== trip.title) changes.title = title; + if (newStart !== trip.start_date) changes.start_date = newStart; + if (newEnd !== trip.end_date) changes.end_date = newEnd; + if (newReminder !== oldReminder) changes.reminder_days = newReminder === 0 ? 'none' : `${newReminder} days`; + if (is_archived !== undefined && newArchived !== trip.is_archived) changes.archived = !!newArchived; + + const isAdminEdit = userRole === 'admin' && trip.user_id !== userId; + let ownerEmail: string | undefined; + if (Object.keys(changes).length > 0 && isAdminEdit) { + ownerEmail = (db.prepare('SELECT email FROM users WHERE id = ?').get(trip.user_id) as { email: string } | undefined)?.email; + } + + const updatedTrip = db.prepare(`${TRIP_SELECT} WHERE t.id = :tripId`).get({ userId, tripId }); + + return { updatedTrip, changes, isAdminEdit, ownerEmail, newTitle, newReminder, oldReminder }; +} + +// ── Delete ───────────────────────────────────────────────────────────────── + +export interface DeleteTripInfo { + tripId: number; + title: string; + ownerId: number; + isAdminDelete: boolean; + ownerEmail?: string; +} + +export function deleteTrip(tripId: string | number, userId: number, userRole: string): DeleteTripInfo { + const trip = db.prepare('SELECT title, user_id FROM trips WHERE id = ?').get(tripId) as { title: string; user_id: number } | undefined; + if (!trip) throw new NotFoundError('Trip not found'); + + const isAdminDelete = userRole === 'admin' && trip.user_id !== userId; + let ownerEmail: string | undefined; + if (isAdminDelete) { + ownerEmail = (db.prepare('SELECT email FROM users WHERE id = ?').get(trip.user_id) as { email: string } | undefined)?.email; + } + + // Clean up journey entries synced from this trip before deleting + // Delete skeleton entries (unfilled synced places) + db.prepare(` + DELETE FROM journey_entries + WHERE source_trip_id = ? AND type = 'skeleton' + `).run(tripId); + // Detach filled entries (keep user's written content, just remove trip link) + db.prepare(` + UPDATE journey_entries SET source_trip_id = NULL, source_place_id = NULL + WHERE source_trip_id = ? + `).run(tripId); + + db.prepare('DELETE FROM trips WHERE id = ?').run(tripId); + + return { tripId: Number(tripId), title: trip.title, ownerId: trip.user_id, isAdminDelete, ownerEmail }; +} + +// ── Cover image ─────────────────────────────────────────────────────────── + +export function deleteOldCover(coverImage: string | null | undefined) { + if (!coverImage) return; + // cover_image is client-supplied, so treat it as untrusted: covers live in + // uploads/covers as a flat filename — use basename() and confine the unlink + // to that directory. + const coversDir = path.resolve(__dirname, '../../uploads/covers'); + const resolvedPath = path.resolve(path.join(coversDir, path.basename(coverImage))); + if (resolvedPath.startsWith(coversDir + path.sep) && fs.existsSync(resolvedPath)) { + fs.unlinkSync(resolvedPath); + } +} + +export function updateCoverImage(tripId: string | number, coverUrl: string) { + db.prepare('UPDATE trips SET cover_image=?, updated_at=CURRENT_TIMESTAMP WHERE id=?').run(coverUrl, tripId); +} + +export function getTripRaw(tripId: string | number): Trip | undefined { + return db.prepare('SELECT * FROM trips WHERE id = ?').get(tripId) as Trip | undefined; +} + +export function getTripOwner(tripId: string | number): { user_id: number } | undefined { + return db.prepare('SELECT user_id FROM trips WHERE id = ?').get(tripId) as { user_id: number } | undefined; +} + +// ── Members ─────────────────────────────────────────────────────────────── + +export function listMembers(tripId: string | number, tripOwnerId: number) { + const members = db.prepare(` + SELECT u.id, u.username, u.email, u.avatar, + CASE WHEN u.id = ? THEN 'owner' ELSE 'member' END as role, + m.added_at, + ib.username as invited_by_username + FROM trip_members m + JOIN users u ON u.id = m.user_id + LEFT JOIN users ib ON ib.id = m.invited_by + WHERE m.trip_id = ? + ORDER BY m.added_at ASC + `).all(tripOwnerId, tripId) as { id: number; username: string; email: string; avatar: string | null; role: string; added_at: string; invited_by_username: string | null }[]; + + const owner = db.prepare('SELECT id, username, email, avatar FROM users WHERE id = ?').get(tripOwnerId) as Pick; + + return { + owner: { ...owner, role: 'owner', avatar_url: owner.avatar ? `/uploads/avatars/${owner.avatar}` : null }, + members: members.map(m => ({ ...m, avatar_url: m.avatar ? `/uploads/avatars/${m.avatar}` : null })), + }; +} + +export interface AddMemberResult { + member: { id: number; username: string; email: string; avatar?: string | null; role: string; avatar_url: string | null }; + targetUserId: number; + tripTitle: string; +} + +export function addMember(tripId: string | number, identifier: string, tripOwnerId: number, invitedByUserId: number): AddMemberResult { + if (!identifier) throw new ValidationError('Email or username required'); + + const target = db.prepare( + 'SELECT id, username, email, avatar FROM users WHERE email = ? OR username = ?' + ).get(identifier.trim(), identifier.trim()) as Pick | undefined; + + if (!target) throw new NotFoundError('User not found'); + + if (target.id === tripOwnerId) + throw new ValidationError('Trip owner is already a member'); + + const existing = db.prepare('SELECT id FROM trip_members WHERE trip_id = ? AND user_id = ?').get(tripId, target.id); + if (existing) throw new ValidationError('User already has access'); + + db.prepare('INSERT INTO trip_members (trip_id, user_id, invited_by) VALUES (?, ?, ?)').run(tripId, target.id, invitedByUserId); + + const tripInfo = db.prepare('SELECT title FROM trips WHERE id = ?').get(tripId) as { title: string } | undefined; + + return { + member: { ...target, role: 'member', avatar_url: target.avatar ? `/uploads/avatars/${target.avatar}` : null }, + targetUserId: target.id, + tripTitle: tripInfo?.title || 'Untitled', + }; +} + +export function removeMember(tripId: string | number, targetUserId: number) { + db.prepare('DELETE FROM trip_members WHERE trip_id = ? AND user_id = ?').run(tripId, targetUserId); +} + +// ── ICS export ──────────────────────────────────────────────────────────── + +export function exportICS(tripId: string | number): { ics: string; filename: string } { + const trip = db.prepare('SELECT * FROM trips WHERE id = ?').get(tripId) as any; + if (!trip) throw new NotFoundError('Trip not found'); + + const reservations = db.prepare('SELECT * FROM reservations WHERE trip_id = ?').all(tripId) as any[]; + + const esc = (s: string) => s + .replace(/\\/g, '\\\\') + .replace(/;/g, '\\;') + .replace(/,/g, '\\,') + .replace(/\r?\n/g, '\\n') + .replace(/\r/g, ''); + const fmtDate = (d: string) => d.replace(/-/g, ''); + const now = new Date().toISOString().replace(/[-:]/g, '').split('.')[0] + 'Z'; + const uid = (id: number, type: string) => `trek-${type}-${id}@trek`; + + // Format datetime: handles full ISO "2026-03-30T09:00" and time-only "10:00" + // iCal requires exactly YYYYMMDDTHHMMSS format + const fmtDateTime = (d: string, refDate?: string) => { + if (d.includes('T')) { + const raw = d.replace(/[-:]/g, '').split('.')[0]; + // Pad to 15 chars (YYYYMMDDTHHMMSS) — add missing seconds + return raw.length === 13 ? raw + '00' : raw; + } + // Time-only: combine with reference date + if (refDate && d.match(/^\d{2}:\d{2}/)) { + const datePart = refDate.split('T')[0]; + return `${datePart}T${d.replace(/:/g, '')}00`.replace(/-/g, ''); + } + return d.replace(/[-:]/g, ''); + }; + + let ics = 'BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//TREK//Travel Planner//EN\r\nCALSCALE:GREGORIAN\r\nMETHOD:PUBLISH\r\n'; + ics += `X-WR-CALNAME:${esc(trip.title || 'TREK Trip')}\r\n`; + + // Trip as all-day event + if (trip.start_date && trip.end_date) { + const endNext = new Date(trip.end_date + 'T00:00:00'); + endNext.setDate(endNext.getDate() + 1); + const endStr = endNext.toISOString().split('T')[0].replace(/-/g, ''); + ics += `BEGIN:VEVENT\r\nUID:${uid(trip.id, 'trip')}\r\nDTSTAMP:${now}\r\nDTSTART;VALUE=DATE:${fmtDate(trip.start_date)}\r\nDTEND;VALUE=DATE:${endStr}\r\nSUMMARY:${esc(trip.title || 'Trip')}\r\n`; + if (trip.description) ics += `DESCRIPTION:${esc(trip.description)}\r\n`; + ics += `END:VEVENT\r\n`; + } + + // Days with assignments and notes + const days = db.prepare('SELECT * FROM days WHERE trip_id = ? ORDER BY day_number ASC').all(tripId) as any[]; + for (const day of days) { + if (!day.date) continue; + + const assignments = db.prepare(` + SELECT da.*, p.name as place_name, p.address as place_address, + COALESCE(da.assignment_time, p.place_time) as effective_time, + COALESCE(da.assignment_end_time, p.end_time) as effective_end_time + FROM day_assignments da + JOIN places p ON da.place_id = p.id + WHERE da.day_id = ? + ORDER BY da.order_index ASC, da.created_at ASC + `).all(day.id) as any[]; + + const notes = db.prepare( + 'SELECT * FROM day_notes WHERE day_id = ? ORDER BY sort_order ASC, created_at ASC' + ).all(day.id) as any[]; + + const timed = assignments.filter(a => a.effective_time); + const untimed = assignments.filter(a => !a.effective_time); + + // Timed assignments → individual events + for (const a of timed) { + ics += `BEGIN:VEVENT\r\nUID:${uid(a.id, 'assign')}\r\nDTSTAMP:${now}\r\n`; + ics += `DTSTART:${fmtDateTime(a.effective_time, day.date + 'T00:00')}\r\n`; + if (a.effective_end_time) { + ics += `DTEND:${fmtDateTime(a.effective_end_time, day.date + 'T00:00')}\r\n`; + } + ics += `SUMMARY:${esc(a.place_name)}\r\n`; + let desc = ''; + if (a.notes) desc += a.notes; + if (a.place_address) desc += (desc ? '\n' : '') + a.place_address; + if (desc) ics += `DESCRIPTION:${esc(desc)}\r\n`; + if (a.place_address) ics += `LOCATION:${esc(a.place_address)}\r\n`; + ics += `END:VEVENT\r\n`; + } + + // Build all-day summary event if there are untimed activities or notes + if (untimed.length > 0 || notes.length > 0) { + const dayTitle = day.title || `Day ${day.day_number}`; + const endNext = new Date(day.date + 'T00:00:00'); + endNext.setDate(endNext.getDate() + 1); + const endStr = endNext.toISOString().split('T')[0].replace(/-/g, ''); + + ics += `BEGIN:VEVENT\r\nUID:${uid(day.id, 'day')}\r\nDTSTAMP:${now}\r\n`; + ics += `DTSTART;VALUE=DATE:${fmtDate(day.date)}\r\nDTEND;VALUE=DATE:${endStr}\r\n`; + ics += `SUMMARY:${esc(dayTitle)}\r\n`; + + let desc = ''; + if (untimed.length > 0) { + desc += untimed.map(a => { + let line = `• ${a.place_name}`; + if (a.place_address) line += ` (${a.place_address})`; + if (a.notes) line += ` — ${a.notes}`; + return line; + }).join('\n'); + } + if (notes.length > 0) { + if (desc) desc += '\n\n'; + desc += 'Notes:\n' + notes.map(n => { + let line = n.time ? `${n.time} — ${n.text}` : `• ${n.text}`; + return line; + }).join('\n'); + } + if (desc) ics += `DESCRIPTION:${esc(desc)}\r\n`; + ics += `END:VEVENT\r\n`; + } + } + + // Reservations as events + for (const r of reservations) { + if (!r.reservation_time) continue; + // Skip time-only values (no calendar date — occurs on relative "Day N" trips) + const hasDate = r.reservation_time.includes('T') + ? /^\d{4}-\d{2}-\d{2}$/.test(r.reservation_time.split('T')[0]) + : /^\d{4}-\d{2}-\d{2}$/.test(r.reservation_time); + if (!hasDate) continue; + const hasTime = r.reservation_time.includes('T'); + const meta = r.metadata ? (typeof r.metadata === 'string' ? JSON.parse(r.metadata) : r.metadata) : {}; + + ics += `BEGIN:VEVENT\r\nUID:${uid(r.id, 'res')}\r\nDTSTAMP:${now}\r\n`; + if (hasTime) { + ics += `DTSTART:${fmtDateTime(r.reservation_time)}\r\n`; + if (r.reservation_end_time) { + const endDt = fmtDateTime(r.reservation_end_time, r.reservation_time); + if (endDt.length >= 15) ics += `DTEND:${endDt}\r\n`; + } + } else { + ics += `DTSTART;VALUE=DATE:${fmtDate(r.reservation_time)}\r\n`; + } + ics += `SUMMARY:${esc(r.title)}\r\n`; + + let desc = r.type ? `Type: ${r.type}` : ''; + if (r.confirmation_number) desc += `\nConfirmation: ${r.confirmation_number}`; + if (meta.airline) desc += `\nAirline: ${meta.airline}`; + if (meta.flight_number) desc += `\nFlight: ${meta.flight_number}`; + if (Array.isArray(meta.legs) && meta.legs.length > 1) { + // Multi-leg flight: show the whole route (FRA → BER → HND) on one event. + const stops = [meta.legs[0]?.from, ...meta.legs.map((l: { to?: string }) => l.to)].filter(Boolean); + if (stops.length) desc += `\nRoute: ${stops.join(' → ')}`; + } else { + if (meta.departure_airport) desc += `\nFrom: ${meta.departure_airport}`; + if (meta.arrival_airport) desc += `\nTo: ${meta.arrival_airport}`; + } + if (meta.train_number) desc += `\nTrain: ${meta.train_number}`; + if (r.notes) desc += `\n${r.notes}`; + if (desc) ics += `DESCRIPTION:${esc(desc)}\r\n`; + if (r.location) ics += `LOCATION:${esc(r.location)}\r\n`; + ics += `END:VEVENT\r\n`; + } + + ics += 'END:VCALENDAR\r\n'; + + const safeFilename = (trip.title || 'trek-trip').replace(/["\r\n]/g, '').replace(/[^\w\s.-]/g, '_'); + return { ics, filename: `${safeFilename}.ics` }; +} + +// ── Copy / duplicate ───────────────────────────────────────────────────── + +/** + * Duplicates a trip (all days, places, assignments, accommodations, reservations, + * budget, packing bags/items, day notes) into a new trip owned by `newOwnerId`. + * Packing items are reset to unchecked. Budget paid status is cleared. + * Returns the new trip's ID. + */ +export function copyTripById(sourceTripId: string | number, newOwnerId: number, title?: string): number { + const src = db.prepare('SELECT * FROM trips WHERE id = ?').get(sourceTripId) as any; + if (!src) throw new NotFoundError('Trip not found'); + + const newTitle = title || src.title; + + const fn = db.transaction(() => { + const tripResult = db.prepare(` + INSERT INTO trips (user_id, title, description, start_date, end_date, currency, cover_image, is_archived, reminder_days) + VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?) + `).run(newOwnerId, newTitle, src.description, src.start_date, src.end_date, src.currency, src.cover_image, src.reminder_days ?? 3); + const newTripId = tripResult.lastInsertRowid; + + const oldDays = db.prepare('SELECT * FROM days WHERE trip_id = ? ORDER BY day_number').all(sourceTripId) as any[]; + const dayMap = new Map(); + const insertDay = db.prepare('INSERT INTO days (trip_id, day_number, date, notes, title) VALUES (?, ?, ?, ?, ?)'); + for (const d of oldDays) { + const r = insertDay.run(newTripId, d.day_number, d.date, d.notes, d.title); + dayMap.set(d.id, r.lastInsertRowid); + } + + const oldPlaces = db.prepare('SELECT * FROM places WHERE trip_id = ?').all(sourceTripId) as any[]; + const placeMap = new Map(); + const insertPlace = db.prepare(` + INSERT INTO places (trip_id, name, description, lat, lng, address, category_id, price, currency, + reservation_status, reservation_notes, reservation_datetime, place_time, end_time, + duration_minutes, notes, image_url, google_place_id, website, phone, transport_mode, osm_id) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `); + for (const p of oldPlaces) { + const r = insertPlace.run(newTripId, p.name, p.description, p.lat, p.lng, p.address, p.category_id, + p.price, p.currency, p.reservation_status, p.reservation_notes, p.reservation_datetime, + p.place_time, p.end_time, p.duration_minutes, p.notes, p.image_url, p.google_place_id, + p.website, p.phone, p.transport_mode, p.osm_id); + placeMap.set(p.id, r.lastInsertRowid); + } + + const oldTags = db.prepare(` + SELECT pt.* FROM place_tags pt JOIN places p ON p.id = pt.place_id WHERE p.trip_id = ? + `).all(sourceTripId) as any[]; + const insertTag = db.prepare('INSERT OR IGNORE INTO place_tags (place_id, tag_id) VALUES (?, ?)'); + for (const t of oldTags) { + const newPlaceId = placeMap.get(t.place_id); + if (newPlaceId) insertTag.run(newPlaceId, t.tag_id); + } + + const oldAssignments = db.prepare(` + SELECT da.* FROM day_assignments da JOIN days d ON d.id = da.day_id WHERE d.trip_id = ? + `).all(sourceTripId) as any[]; + const assignmentMap = new Map(); + const insertAssignment = db.prepare(` + INSERT INTO day_assignments (day_id, place_id, order_index, notes, reservation_status, reservation_notes, reservation_datetime, assignment_time, assignment_end_time) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + `); + for (const a of oldAssignments) { + const newDayId = dayMap.get(a.day_id); + const newPlaceId = placeMap.get(a.place_id); + if (newDayId && newPlaceId) { + const r = insertAssignment.run(newDayId, newPlaceId, a.order_index, a.notes, + a.reservation_status, a.reservation_notes, a.reservation_datetime, + a.assignment_time, a.assignment_end_time); + assignmentMap.set(a.id, r.lastInsertRowid); + } + } + + const oldAccom = db.prepare('SELECT * FROM day_accommodations WHERE trip_id = ?').all(sourceTripId) as any[]; + const accomMap = new Map(); + const insertAccom = db.prepare(` + INSERT INTO day_accommodations (trip_id, place_id, start_day_id, end_day_id, check_in, check_out, confirmation, notes) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + `); + for (const a of oldAccom) { + const newPlaceId = placeMap.get(a.place_id); + const newStartDay = dayMap.get(a.start_day_id); + const newEndDay = dayMap.get(a.end_day_id); + if (newPlaceId && newStartDay && newEndDay) { + const r = insertAccom.run(newTripId, newPlaceId, newStartDay, newEndDay, a.check_in, a.check_out, a.confirmation, a.notes); + accomMap.set(a.id, r.lastInsertRowid); + } + } + + const oldReservations = db.prepare('SELECT * FROM reservations WHERE trip_id = ?').all(sourceTripId) as any[]; + const insertReservation = db.prepare(` + INSERT INTO reservations (trip_id, day_id, end_day_id, place_id, assignment_id, accommodation_id, title, reservation_time, reservation_end_time, + location, confirmation_number, notes, status, type, metadata, day_plan_position, needs_review) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `); + for (const r of oldReservations) { + insertReservation.run(newTripId, + r.day_id ? (dayMap.get(r.day_id) ?? null) : null, + // end_day_id is a day reference too (multi-day transport) — remap it like + // day_id, otherwise the duplicated trip loses the reservation's end-day link. + r.end_day_id ? (dayMap.get(r.end_day_id) ?? null) : null, + r.place_id ? (placeMap.get(r.place_id) ?? null) : null, + r.assignment_id ? (assignmentMap.get(r.assignment_id) ?? null) : null, + r.accommodation_id ? (accomMap.get(r.accommodation_id) ?? null) : null, + r.title, r.reservation_time, r.reservation_end_time, + r.location, r.confirmation_number, r.notes, r.status, r.type, + r.metadata, r.day_plan_position, r.needs_review ?? 0); + } + + const oldBudget = db.prepare('SELECT * FROM budget_items WHERE trip_id = ?').all(sourceTripId) as any[]; + const insertBudget = db.prepare(` + INSERT INTO budget_items (trip_id, category, name, total_price, persons, days, note, sort_order) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + `); + for (const b of oldBudget) { + insertBudget.run(newTripId, b.category, b.name, b.total_price, b.persons, b.days, b.note, b.sort_order); + } + + const oldBags = db.prepare('SELECT * FROM packing_bags WHERE trip_id = ?').all(sourceTripId) as any[]; + const bagMap = new Map(); + const insertBag = db.prepare(` + INSERT INTO packing_bags (trip_id, name, color, weight_limit_grams, sort_order) + VALUES (?, ?, ?, ?, ?) + `); + for (const bag of oldBags) { + const r = insertBag.run(newTripId, bag.name, bag.color, bag.weight_limit_grams, bag.sort_order); + bagMap.set(bag.id, r.lastInsertRowid); + } + + const oldPacking = db.prepare('SELECT * FROM packing_items WHERE trip_id = ?').all(sourceTripId) as any[]; + const insertPacking = db.prepare(` + INSERT INTO packing_items (trip_id, name, checked, category, sort_order, weight_grams, bag_id) + VALUES (?, ?, 0, ?, ?, ?, ?) + `); + for (const p of oldPacking) { + insertPacking.run(newTripId, p.name, p.category, p.sort_order, p.weight_grams, + p.bag_id ? (bagMap.get(p.bag_id) ?? null) : null); + } + + const oldNotes = db.prepare('SELECT * FROM day_notes WHERE trip_id = ?').all(sourceTripId) as any[]; + const insertNote = db.prepare(` + INSERT INTO day_notes (day_id, trip_id, text, time, icon, sort_order) + VALUES (?, ?, ?, ?, ?, ?) + `); + for (const n of oldNotes) { + const newDayId = dayMap.get(n.day_id); + if (newDayId) insertNote.run(newDayId, newTripId, n.text, n.time, n.icon, n.sort_order); + } + + const oldTodos = db.prepare('SELECT * FROM todo_items WHERE trip_id = ?').all(sourceTripId) as any[]; + const insertTodo = db.prepare(` + INSERT INTO todo_items (trip_id, name, checked, category, sort_order, due_date, description, assigned_user_id, priority) + VALUES (?, ?, 0, ?, ?, ?, ?, NULL, ?) + `); + for (const t of oldTodos) { + insertTodo.run(newTripId, t.name, t.category, t.sort_order, t.due_date, t.description, t.priority); + } + + const oldCategoryOrder = db.prepare('SELECT category, sort_order FROM budget_category_order WHERE trip_id = ?').all(sourceTripId) as any[]; + const insertCategoryOrder = db.prepare(` + INSERT INTO budget_category_order (trip_id, category, sort_order) + VALUES (?, ?, ?) + `); + for (const o of oldCategoryOrder) { + insertCategoryOrder.run(newTripId, o.category, o.sort_order); + } + + return Number(newTripId); + }); + + return fn(); +} + +// ── Trip summary (used by MCP get_trip_summary tool) ────────────────────── + +export function getTripSummary(tripId: number) { + const trip = db.prepare('SELECT * FROM trips WHERE id = ?').get(tripId) as Record | undefined; + if (!trip) return null; + + const ownerRow = getTripOwner(tripId); + if (!ownerRow) return null; + const { owner, members } = listMembers(tripId, ownerRow.user_id); + + const { days: rawDays } = listDays(tripId); + const days = rawDays.map(({ notes_items, ...day }) => ({ ...day, notes: notes_items })); + + const accommodations = listAccommodations(tripId); + + const budgetItems = listBudgetItems(tripId); + const budget = { + items: budgetItems, + item_count: budgetItems.length, + total: budgetItems.reduce((sum, i) => sum + (i.total_price || 0), 0), + currency: trip.currency, + }; + + const packingItems = listPackingItems(tripId); + const packing = { + items: packingItems, + total: packingItems.length, + checked: (packingItems as { checked: number }[]).filter(i => i.checked).length, + }; + + const reservations = listReservations(tripId); + const collab_notes = listCollabNotes(tripId); + + return { + trip, + members: { owner, collaborators: members }, + days, + accommodations, + budget, + packing, + reservations, + collab_notes, + }; +} + +// ── Custom error types ──────────────────────────────────────────────────── + +export class NotFoundError extends Error { + constructor(message: string) { + super(message); + this.name = 'NotFoundError'; + } +} + +export class ValidationError extends Error { + constructor(message: string) { + super(message); + this.name = 'ValidationError'; + } +} diff --git a/server/src/services/userCleanupService.ts b/server/src/services/userCleanupService.ts new file mode 100644 index 0000000000000000000000000000000000000000..842394492679ef810ac0f3285a7442dee93568c4 --- /dev/null +++ b/server/src/services/userCleanupService.ts @@ -0,0 +1,21 @@ +import { db } from '../db/database'; + +function cleanupUserReferences(userId: number): void { + db.prepare('UPDATE trip_members SET invited_by = NULL WHERE invited_by = ?').run(userId); + db.prepare('UPDATE budget_items SET paid_by_user_id = NULL WHERE paid_by_user_id = ?').run(userId); + db.prepare('DELETE FROM share_tokens WHERE created_by = ?').run(userId); + db.prepare('DELETE FROM journey_share_tokens WHERE created_by = ?').run(userId); + // Owned journeys cascade-delete their entries/contributors/share_tokens/photos via journey_id FKs + db.prepare('DELETE FROM journeys WHERE user_id = ?').run(userId); + // Entries authored on other users' journeys (not covered by the cascade above) + db.prepare('DELETE FROM journey_entries WHERE author_id = ?').run(userId); + db.prepare('DELETE FROM journey_contributors WHERE user_id = ?').run(userId); +} + +export function deleteUserCompletely(userId: number): void { + const tx = db.transaction((id: number) => { + cleanupUserReferences(id); + db.prepare('DELETE FROM users WHERE id = ?').run(id); + }); + tx(userId); +} diff --git a/server/src/services/vacayService.ts b/server/src/services/vacayService.ts new file mode 100644 index 0000000000000000000000000000000000000000..a894e73b90f441cf00c4d119ef79a27800d6c827 --- /dev/null +++ b/server/src/services/vacayService.ts @@ -0,0 +1,714 @@ +import { db } from '../db/database'; + +// --------------------------------------------------------------------------- +// Types +// --------------------------------------------------------------------------- + +export interface VacayPlan { + id: number; + owner_id: number; + block_weekends: number; + holidays_enabled: number; + holidays_region: string | null; + company_holidays_enabled: number; + carry_over_enabled: number; +} + +export interface VacayUserYear { + user_id: number; + plan_id: number; + year: number; + vacation_days: number; + carried_over: number; +} + +export interface VacayUser { + id: number; + username: string; + email: string; +} + +export interface VacayPlanMember { + id: number; + plan_id: number; + user_id: number; + status: string; + created_at?: string; +} + +export interface Holiday { + date: string; + localName?: string; + name?: string; + global?: boolean; + counties?: string[] | null; +} + +export interface VacayHolidayCalendar { + id: number; + plan_id: number; + region: string; + label: string | null; + color: string; + sort_order: number; +} + +// --------------------------------------------------------------------------- +// Holiday cache (shared in-process) +// --------------------------------------------------------------------------- + +const holidayCache = new Map(); +const CACHE_TTL = 24 * 60 * 60 * 1000; + +// --------------------------------------------------------------------------- +// Color palette for auto-assign +// --------------------------------------------------------------------------- + +const COLORS = [ + '#6366f1', '#ec4899', '#14b8a6', '#8b5cf6', '#ef4444', + '#3b82f6', '#22c55e', '#06b6d4', '#f43f5e', '#a855f7', + '#10b981', '#0ea5e9', '#64748b', '#be185d', '#0d9488', +]; + +// --------------------------------------------------------------------------- +// Plan management +// --------------------------------------------------------------------------- + +export function getOwnPlan(userId: number): VacayPlan { + let plan = db.prepare('SELECT * FROM vacay_plans WHERE owner_id = ?').get(userId) as VacayPlan | undefined; + if (!plan) { + db.prepare('INSERT INTO vacay_plans (owner_id) VALUES (?)').run(userId); + plan = db.prepare('SELECT * FROM vacay_plans WHERE owner_id = ?').get(userId) as VacayPlan; + const yr = new Date().getFullYear(); + db.prepare('INSERT OR IGNORE INTO vacay_years (plan_id, year) VALUES (?, ?)').run(plan.id, yr); + db.prepare('INSERT OR IGNORE INTO vacay_user_years (user_id, plan_id, year, vacation_days, carried_over) VALUES (?, ?, ?, 30, 0)').run(userId, plan.id, yr); + db.prepare('INSERT OR IGNORE INTO vacay_user_colors (user_id, plan_id, color) VALUES (?, ?, ?)').run(userId, plan.id, '#6366f1'); + } + return plan; +} + +export function getActivePlan(userId: number): VacayPlan { + const membership = db.prepare(` + SELECT plan_id FROM vacay_plan_members WHERE user_id = ? AND status = 'accepted' + `).get(userId) as { plan_id: number } | undefined; + if (membership) { + return db.prepare('SELECT * FROM vacay_plans WHERE id = ?').get(membership.plan_id) as VacayPlan; + } + return getOwnPlan(userId); +} + +export function getActivePlanId(userId: number): number { + return getActivePlan(userId).id; +} + +export function shiftOwnerEntriesForTripWindow( + ownerId: number, + oldStart: string, + oldEnd: string, + newStart: string +): void { + const row = db.prepare( + 'SELECT CAST(julianday(?) - julianday(?) AS INTEGER) AS days' + ).get(newStart, oldStart) as { days: number } | undefined; + const offset = row?.days ?? 0; + if (offset === 0) return; + + const plan = getOwnPlan(ownerId); + + db.prepare( + `UPDATE OR IGNORE vacay_entries + SET date = date(date, ? || ' days') + WHERE plan_id = ? + AND user_id = ? + AND date BETWEEN ? AND ?` + ).run(`${offset >= 0 ? '+' : ''}${offset}`, plan.id, ownerId, oldStart, oldEnd); +} + +export function getPlanUsers(planId: number): VacayUser[] { + const plan = db.prepare('SELECT * FROM vacay_plans WHERE id = ?').get(planId) as VacayPlan | undefined; + if (!plan) return []; + const owner = db.prepare('SELECT id, username, email FROM users WHERE id = ?').get(plan.owner_id) as VacayUser; + const members = db.prepare(` + SELECT u.id, u.username, u.email FROM vacay_plan_members m + JOIN users u ON m.user_id = u.id + WHERE m.plan_id = ? AND m.status = 'accepted' + `).all(planId) as VacayUser[]; + return [owner, ...members]; +} + +// --------------------------------------------------------------------------- +// WebSocket notifications +// --------------------------------------------------------------------------- + +export function notifyPlanUsers(planId: number, excludeSid: string | undefined, event = 'vacay:update'): void { + try { + const { broadcastToUser } = require('../websocket'); + const plan = db.prepare('SELECT owner_id FROM vacay_plans WHERE id = ?').get(planId) as { owner_id: number } | undefined; + if (!plan) return; + const userIds = [plan.owner_id]; + const members = db.prepare("SELECT user_id FROM vacay_plan_members WHERE plan_id = ? AND status = 'accepted'").all(planId) as { user_id: number }[]; + members.forEach(m => userIds.push(m.user_id)); + userIds.forEach(id => broadcastToUser(id, { type: event }, excludeSid)); + } catch { /* websocket not available */ } +} + +// --------------------------------------------------------------------------- +// Holiday calendar helpers +// --------------------------------------------------------------------------- + +export async function applyHolidayCalendars(planId: number): Promise { + const plan = db.prepare('SELECT holidays_enabled FROM vacay_plans WHERE id = ?').get(planId) as { holidays_enabled: number } | undefined; + if (!plan?.holidays_enabled) return; + const calendars = db.prepare('SELECT * FROM vacay_holiday_calendars WHERE plan_id = ? ORDER BY sort_order, id').all(planId) as VacayHolidayCalendar[]; + if (calendars.length === 0) return; + const years = db.prepare('SELECT year FROM vacay_years WHERE plan_id = ?').all(planId) as { year: number }[]; + for (const cal of calendars) { + const country = cal.region.split('-')[0]; + const region = cal.region.includes('-') ? cal.region : null; + for (const { year } of years) { + try { + const cacheKey = `${year}-${country}`; + let holidays = holidayCache.get(cacheKey)?.data as Holiday[] | undefined; + if (!holidays) { + const resp = await fetch(`https://date.nager.at/api/v3/PublicHolidays/${year}/${country}`); + holidays = await resp.json() as Holiday[]; + holidayCache.set(cacheKey, { data: holidays, time: Date.now() }); + } + const hasRegions = holidays.some((h: Holiday) => h.counties && h.counties.length > 0); + if (hasRegions && !region) continue; + for (const h of holidays) { + if (h.global || !h.counties || (region && h.counties.includes(region))) { + db.prepare('DELETE FROM vacay_entries WHERE plan_id = ? AND date = ?').run(planId, h.date); + db.prepare('DELETE FROM vacay_company_holidays WHERE plan_id = ? AND date = ?').run(planId, h.date); + } + } + } catch { /* API error, skip */ } + } + } +} + +export async function migrateHolidayCalendars(planId: number, plan: VacayPlan): Promise { + const existing = db.prepare('SELECT id FROM vacay_holiday_calendars WHERE plan_id = ?').get(planId); + if (existing) return; + if (plan.holidays_enabled && plan.holidays_region) { + db.prepare( + 'INSERT INTO vacay_holiday_calendars (plan_id, region, label, color, sort_order) VALUES (?, ?, NULL, ?, 0)' + ).run(planId, plan.holidays_region, '#fecaca'); + } +} + +// --------------------------------------------------------------------------- +// Plan settings +// --------------------------------------------------------------------------- + +export interface UpdatePlanBody { + block_weekends?: boolean; + holidays_enabled?: boolean; + holidays_region?: string; + company_holidays_enabled?: boolean; + carry_over_enabled?: boolean; + weekend_days?: string; + week_start?: number; +} + +export async function updatePlan(planId: number, body: UpdatePlanBody, socketId: string | undefined) { + const { block_weekends, holidays_enabled, holidays_region, company_holidays_enabled, carry_over_enabled, weekend_days, week_start } = body; + + const updates: string[] = []; + const params: (string | number)[] = []; + if (block_weekends !== undefined) { updates.push('block_weekends = ?'); params.push(block_weekends ? 1 : 0); } + if (holidays_enabled !== undefined) { updates.push('holidays_enabled = ?'); params.push(holidays_enabled ? 1 : 0); } + if (holidays_region !== undefined) { updates.push('holidays_region = ?'); params.push(holidays_region); } + if (company_holidays_enabled !== undefined) { updates.push('company_holidays_enabled = ?'); params.push(company_holidays_enabled ? 1 : 0); } + if (carry_over_enabled !== undefined) { updates.push('carry_over_enabled = ?'); params.push(carry_over_enabled ? 1 : 0); } + if (weekend_days !== undefined) { updates.push('weekend_days = ?'); params.push(String(weekend_days)); } + if (week_start !== undefined) { updates.push('week_start = ?'); params.push(week_start === 0 ? 0 : 1); } + + if (updates.length > 0) { + params.push(planId); + db.prepare(`UPDATE vacay_plans SET ${updates.join(', ')} WHERE id = ?`).run(...params); + } + + if (company_holidays_enabled === true) { + const companyDates = db.prepare('SELECT date FROM vacay_company_holidays WHERE plan_id = ?').all(planId) as { date: string }[]; + for (const { date } of companyDates) { + db.prepare('DELETE FROM vacay_entries WHERE plan_id = ? AND date = ?').run(planId, date); + } + } + + const updatedPlan = db.prepare('SELECT * FROM vacay_plans WHERE id = ?').get(planId) as VacayPlan; + await migrateHolidayCalendars(planId, updatedPlan); + await applyHolidayCalendars(planId); + + if (carry_over_enabled === false) { + db.prepare('UPDATE vacay_user_years SET carried_over = 0 WHERE plan_id = ?').run(planId); + } + + if (carry_over_enabled === true) { + const years = db.prepare('SELECT year FROM vacay_years WHERE plan_id = ? ORDER BY year').all(planId) as { year: number }[]; + const users = getPlanUsers(planId); + for (let i = 0; i < years.length - 1; i++) { + const yr = years[i].year; + const nextYr = years[i + 1].year; + for (const u of users) { + const used = (db.prepare("SELECT COUNT(*) as count FROM vacay_entries WHERE user_id = ? AND plan_id = ? AND date LIKE ?").get(u.id, planId, `${yr}-%`) as { count: number }).count; + const config = db.prepare('SELECT * FROM vacay_user_years WHERE user_id = ? AND plan_id = ? AND year = ?').get(u.id, planId, yr) as VacayUserYear | undefined; + const total = (config ? config.vacation_days : 30) + (config ? config.carried_over : 0); + const carry = Math.max(0, total - used); + db.prepare(` + INSERT INTO vacay_user_years (user_id, plan_id, year, vacation_days, carried_over) VALUES (?, ?, ?, 30, ?) + ON CONFLICT(user_id, plan_id, year) DO UPDATE SET carried_over = ? + `).run(u.id, planId, nextYr, carry, carry); + } + } + } + + notifyPlanUsers(planId, socketId, 'vacay:settings'); + + const updated = db.prepare('SELECT * FROM vacay_plans WHERE id = ?').get(planId) as VacayPlan; + const updatedCalendars = db.prepare('SELECT * FROM vacay_holiday_calendars WHERE plan_id = ? ORDER BY sort_order, id').all(planId) as VacayHolidayCalendar[]; + return { + plan: { + ...updated, + block_weekends: !!updated.block_weekends, + holidays_enabled: !!updated.holidays_enabled, + company_holidays_enabled: !!updated.company_holidays_enabled, + carry_over_enabled: !!updated.carry_over_enabled, + holiday_calendars: updatedCalendars, + }, + }; +} + +// --------------------------------------------------------------------------- +// Holiday calendars CRUD +// --------------------------------------------------------------------------- + +export function addHolidayCalendar(planId: number, region: string, label: string | null, color: string | undefined, sortOrder: number | undefined, socketId: string | undefined) { + const result = db.prepare( + 'INSERT INTO vacay_holiday_calendars (plan_id, region, label, color, sort_order) VALUES (?, ?, ?, ?, ?)' + ).run(planId, region, label || null, color || '#fecaca', sortOrder ?? 0); + const cal = db.prepare('SELECT * FROM vacay_holiday_calendars WHERE id = ?').get(result.lastInsertRowid) as VacayHolidayCalendar; + notifyPlanUsers(planId, socketId, 'vacay:settings'); + return cal; +} + +export function updateHolidayCalendar( + calId: number, + planId: number, + body: { region?: string; label?: string | null; color?: string; sort_order?: number }, + socketId: string | undefined, +): VacayHolidayCalendar | null { + const cal = db.prepare('SELECT * FROM vacay_holiday_calendars WHERE id = ? AND plan_id = ?').get(calId, planId) as VacayHolidayCalendar | undefined; + if (!cal) return null; + const { region, label, color, sort_order } = body; + const updates: string[] = []; + const params: (string | number | null)[] = []; + if (region !== undefined) { updates.push('region = ?'); params.push(region); } + if (label !== undefined) { updates.push('label = ?'); params.push(label); } + if (color !== undefined) { updates.push('color = ?'); params.push(color); } + if (sort_order !== undefined) { updates.push('sort_order = ?'); params.push(sort_order); } + if (updates.length > 0) { + params.push(calId); + db.prepare(`UPDATE vacay_holiday_calendars SET ${updates.join(', ')} WHERE id = ?`).run(...params); + } + const updated = db.prepare('SELECT * FROM vacay_holiday_calendars WHERE id = ?').get(calId) as VacayHolidayCalendar; + notifyPlanUsers(planId, socketId, 'vacay:settings'); + return updated; +} + +export function deleteHolidayCalendar(calId: number, planId: number, socketId: string | undefined): boolean { + const cal = db.prepare('SELECT * FROM vacay_holiday_calendars WHERE id = ? AND plan_id = ?').get(calId, planId); + if (!cal) return false; + db.prepare('DELETE FROM vacay_holiday_calendars WHERE id = ?').run(calId); + notifyPlanUsers(planId, socketId, 'vacay:settings'); + return true; +} + +// --------------------------------------------------------------------------- +// User colors +// --------------------------------------------------------------------------- + +export function setUserColor(userId: number, planId: number, color: string | undefined, socketId: string | undefined): void { + db.prepare(` + INSERT INTO vacay_user_colors (user_id, plan_id, color) VALUES (?, ?, ?) + ON CONFLICT(user_id, plan_id) DO UPDATE SET color = excluded.color + `).run(userId, planId, color || '#6366f1'); + notifyPlanUsers(planId, socketId, 'vacay:update'); +} + +// --------------------------------------------------------------------------- +// Invitations +// --------------------------------------------------------------------------- + +export function sendInvite(planId: number, inviterId: number, inviterUsername: string, inviterEmail: string, targetUserId: number): { error?: string; status?: number } { + if (targetUserId === inviterId) return { error: 'Cannot invite yourself', status: 400 }; + + const targetUser = db.prepare('SELECT id, username FROM users WHERE id = ?').get(targetUserId); + if (!targetUser) return { error: 'User not found', status: 404 }; + + const existing = db.prepare('SELECT id, status FROM vacay_plan_members WHERE plan_id = ? AND user_id = ?').get(planId, targetUserId) as { id: number; status: string } | undefined; + if (existing) { + if (existing.status === 'accepted') return { error: 'Already fused', status: 400 }; + if (existing.status === 'pending') return { error: 'Invite already pending', status: 400 }; + } + + const targetFusion = db.prepare("SELECT id FROM vacay_plan_members WHERE user_id = ? AND status = 'accepted'").get(targetUserId); + if (targetFusion) return { error: 'User is already fused with another plan', status: 400 }; + + db.prepare('INSERT INTO vacay_plan_members (plan_id, user_id, status) VALUES (?, ?, ?)').run(planId, targetUserId, 'pending'); + + try { + const { broadcastToUser } = require('../websocket'); + broadcastToUser(targetUserId, { + type: 'vacay:invite', + from: { id: inviterId, username: inviterUsername }, + planId, + }); + } catch { /* websocket not available */ } + + // Notify invited user + import('../services/notificationService').then(({ send }) => { + send({ event: 'vacay_invite', actorId: inviterId, scope: 'user', targetId: targetUserId, params: { actor: inviterEmail, planId: String(planId) } }).catch(() => {}); + }); + + return {}; +} + +export function acceptInvite(userId: number, planId: number, socketId: string | undefined): { error?: string; status?: number } { + const invite = db.prepare("SELECT * FROM vacay_plan_members WHERE plan_id = ? AND user_id = ? AND status = 'pending'").get(planId, userId) as VacayPlanMember | undefined; + if (!invite) return { error: 'No pending invite', status: 404 }; + + db.prepare("UPDATE vacay_plan_members SET status = 'accepted' WHERE id = ?").run(invite.id); + + // Migrate data from user's own plan + const ownPlan = db.prepare('SELECT id FROM vacay_plans WHERE owner_id = ?').get(userId) as { id: number } | undefined; + if (ownPlan && ownPlan.id !== planId) { + db.prepare('UPDATE vacay_entries SET plan_id = ? WHERE plan_id = ? AND user_id = ?').run(planId, ownPlan.id, userId); + const ownYears = db.prepare('SELECT * FROM vacay_user_years WHERE user_id = ? AND plan_id = ?').all(userId, ownPlan.id) as VacayUserYear[]; + for (const y of ownYears) { + db.prepare('INSERT OR IGNORE INTO vacay_user_years (user_id, plan_id, year, vacation_days, carried_over) VALUES (?, ?, ?, ?, ?)').run(userId, planId, y.year, y.vacation_days, y.carried_over); + } + const colorRow = db.prepare('SELECT color FROM vacay_user_colors WHERE user_id = ? AND plan_id = ?').get(userId, ownPlan.id) as { color: string } | undefined; + if (colorRow) { + db.prepare('INSERT OR IGNORE INTO vacay_user_colors (user_id, plan_id, color) VALUES (?, ?, ?)').run(userId, planId, colorRow.color); + } + } + + // Auto-assign unique color + const existingColors = (db.prepare('SELECT color FROM vacay_user_colors WHERE plan_id = ? AND user_id != ?').all(planId, userId) as { color: string }[]).map(r => r.color); + const myColor = db.prepare('SELECT color FROM vacay_user_colors WHERE user_id = ? AND plan_id = ?').get(userId, planId) as { color: string } | undefined; + const effectiveColor = myColor?.color || '#6366f1'; + if (existingColors.includes(effectiveColor)) { + const available = COLORS.find(c => !existingColors.includes(c)); + if (available) { + db.prepare(`INSERT INTO vacay_user_colors (user_id, plan_id, color) VALUES (?, ?, ?) + ON CONFLICT(user_id, plan_id) DO UPDATE SET color = excluded.color`).run(userId, planId, available); + } + } else if (!myColor) { + db.prepare('INSERT OR IGNORE INTO vacay_user_colors (user_id, plan_id, color) VALUES (?, ?, ?)').run(userId, planId, effectiveColor); + } + + // Ensure user has rows for all plan years + const targetYears = db.prepare('SELECT year FROM vacay_years WHERE plan_id = ?').all(planId) as { year: number }[]; + for (const y of targetYears) { + db.prepare('INSERT OR IGNORE INTO vacay_user_years (user_id, plan_id, year, vacation_days, carried_over) VALUES (?, ?, ?, 30, 0)').run(userId, planId, y.year); + } + + notifyPlanUsers(planId, socketId, 'vacay:accepted'); + return {}; +} + +export function declineInvite(userId: number, planId: number, socketId: string | undefined): void { + db.prepare("DELETE FROM vacay_plan_members WHERE plan_id = ? AND user_id = ? AND status = 'pending'").run(planId, userId); + notifyPlanUsers(planId, socketId, 'vacay:declined'); +} + +export function cancelInvite(planId: number, targetUserId: number): void { + db.prepare("DELETE FROM vacay_plan_members WHERE plan_id = ? AND user_id = ? AND status = 'pending'").run(planId, targetUserId); + + try { + const { broadcastToUser } = require('../websocket'); + broadcastToUser(targetUserId, { type: 'vacay:cancelled' }); + } catch { /* */ } +} + +// --------------------------------------------------------------------------- +// Plan dissolution +// --------------------------------------------------------------------------- + +export function dissolvePlan(userId: number, socketId: string | undefined): void { + const plan = getActivePlan(userId); + const isOwnerFlag = plan.owner_id === userId; + + const allUserIds = getPlanUsers(plan.id).map(u => u.id); + const companyHolidays = db.prepare('SELECT date, note FROM vacay_company_holidays WHERE plan_id = ?').all(plan.id) as { date: string; note: string }[]; + + if (isOwnerFlag) { + const members = db.prepare("SELECT user_id FROM vacay_plan_members WHERE plan_id = ? AND status = 'accepted'").all(plan.id) as { user_id: number }[]; + for (const m of members) { + const memberPlan = getOwnPlan(m.user_id); + db.prepare('UPDATE vacay_entries SET plan_id = ? WHERE plan_id = ? AND user_id = ?').run(memberPlan.id, plan.id, m.user_id); + for (const ch of companyHolidays) { + db.prepare('INSERT OR IGNORE INTO vacay_company_holidays (plan_id, date, note) VALUES (?, ?, ?)').run(memberPlan.id, ch.date, ch.note); + } + } + db.prepare('DELETE FROM vacay_plan_members WHERE plan_id = ?').run(plan.id); + } else { + const ownPlan = getOwnPlan(userId); + db.prepare('UPDATE vacay_entries SET plan_id = ? WHERE plan_id = ? AND user_id = ?').run(ownPlan.id, plan.id, userId); + for (const ch of companyHolidays) { + db.prepare('INSERT OR IGNORE INTO vacay_company_holidays (plan_id, date, note) VALUES (?, ?, ?)').run(ownPlan.id, ch.date, ch.note); + } + db.prepare("DELETE FROM vacay_plan_members WHERE plan_id = ? AND user_id = ?").run(plan.id, userId); + } + + try { + const { broadcastToUser } = require('../websocket'); + allUserIds.filter(id => id !== userId).forEach(id => broadcastToUser(id, { type: 'vacay:dissolved' })); + } catch { /* */ } +} + +// --------------------------------------------------------------------------- +// Available users +// --------------------------------------------------------------------------- + +export function getAvailableUsers(userId: number, planId: number) { + return db.prepare(` + SELECT u.id, u.username, u.email FROM users u + WHERE u.id != ? + AND u.id NOT IN (SELECT user_id FROM vacay_plan_members WHERE plan_id = ?) + AND u.id NOT IN (SELECT user_id FROM vacay_plan_members WHERE status = 'accepted') + AND u.id NOT IN (SELECT owner_id FROM vacay_plans WHERE id IN ( + SELECT plan_id FROM vacay_plan_members WHERE status = 'accepted' + )) + ORDER BY u.username + `).all(userId, planId); +} + +// --------------------------------------------------------------------------- +// Years +// --------------------------------------------------------------------------- + +export function listYears(planId: number): number[] { + const rows = db.prepare('SELECT year FROM vacay_years WHERE plan_id = ? ORDER BY year').all(planId) as { year: number }[]; + return rows.map(y => y.year); +} + +export function addYear(planId: number, year: number, socketId: string | undefined): number[] { + try { + db.prepare('INSERT INTO vacay_years (plan_id, year) VALUES (?, ?)').run(planId, year); + const plan = db.prepare('SELECT * FROM vacay_plans WHERE id = ?').get(planId) as VacayPlan | undefined; + const carryOverEnabled = plan ? !!plan.carry_over_enabled : true; + const users = getPlanUsers(planId); + for (const u of users) { + let carriedOver = 0; + if (carryOverEnabled) { + const prevConfig = db.prepare('SELECT * FROM vacay_user_years WHERE user_id = ? AND plan_id = ? AND year = ?').get(u.id, planId, year - 1) as VacayUserYear | undefined; + if (prevConfig) { + const used = (db.prepare("SELECT COUNT(*) as count FROM vacay_entries WHERE user_id = ? AND plan_id = ? AND date LIKE ?").get(u.id, planId, `${year - 1}-%`) as { count: number }).count; + const total = prevConfig.vacation_days + prevConfig.carried_over; + carriedOver = Math.max(0, total - used); + } + } + db.prepare('INSERT OR IGNORE INTO vacay_user_years (user_id, plan_id, year, vacation_days, carried_over) VALUES (?, ?, ?, 30, ?)').run(u.id, planId, year, carriedOver); + } + } catch { /* year already exists */ } + notifyPlanUsers(planId, socketId, 'vacay:settings'); + return listYears(planId); +} + +export function deleteYear(planId: number, year: number, socketId: string | undefined): number[] { + db.prepare('DELETE FROM vacay_years WHERE plan_id = ? AND year = ?').run(planId, year); + db.prepare("DELETE FROM vacay_entries WHERE plan_id = ? AND date LIKE ?").run(planId, `${year}-%`); + db.prepare("DELETE FROM vacay_company_holidays WHERE plan_id = ? AND date LIKE ?").run(planId, `${year}-%`); + db.prepare('DELETE FROM vacay_user_years WHERE plan_id = ? AND year = ?').run(planId, year); + + // Recalculate carry-over for year+1 if it exists, since its previous year has changed + const nextYearExists = db.prepare('SELECT id FROM vacay_years WHERE plan_id = ? AND year = ?').get(planId, year + 1); + if (nextYearExists) { + const plan = db.prepare('SELECT * FROM vacay_plans WHERE id = ?').get(planId) as VacayPlan | undefined; + const carryOverEnabled = plan ? !!plan.carry_over_enabled : true; + const users = getPlanUsers(planId); + const prevYear = db.prepare('SELECT year FROM vacay_years WHERE plan_id = ? AND year < ? ORDER BY year DESC LIMIT 1').get(planId, year + 1) as { year: number } | undefined; + + for (const u of users) { + let carry = 0; + if (carryOverEnabled && prevYear) { + const prevConfig = db.prepare('SELECT * FROM vacay_user_years WHERE user_id = ? AND plan_id = ? AND year = ?').get(u.id, planId, prevYear.year) as VacayUserYear | undefined; + if (prevConfig) { + const used = (db.prepare("SELECT COUNT(*) as count FROM vacay_entries WHERE user_id = ? AND plan_id = ? AND date LIKE ?").get(u.id, planId, `${prevYear.year}-%`) as { count: number }).count; + const total = prevConfig.vacation_days + prevConfig.carried_over; + carry = Math.max(0, total - used); + } + } + db.prepare('UPDATE vacay_user_years SET carried_over = ? WHERE user_id = ? AND plan_id = ? AND year = ?').run(carry, u.id, planId, year + 1); + } + } + + notifyPlanUsers(planId, socketId, 'vacay:settings'); + return listYears(planId); +} + +// --------------------------------------------------------------------------- +// Entries +// --------------------------------------------------------------------------- + +export function getEntries(planId: number, year: string) { + const entries = db.prepare(` + SELECT e.*, u.username as person_name, COALESCE(c.color, '#6366f1') as person_color + FROM vacay_entries e + JOIN users u ON e.user_id = u.id + LEFT JOIN vacay_user_colors c ON c.user_id = e.user_id AND c.plan_id = e.plan_id + WHERE e.plan_id = ? AND e.date LIKE ? + `).all(planId, `${year}-%`); + const companyHolidays = db.prepare("SELECT * FROM vacay_company_holidays WHERE plan_id = ? AND date LIKE ?").all(planId, `${year}-%`); + return { entries, companyHolidays }; +} + +export function toggleEntry(userId: number, planId: number, date: string, socketId: string | undefined): { action: string } { + const existing = db.prepare('SELECT id FROM vacay_entries WHERE user_id = ? AND date = ? AND plan_id = ?').get(userId, date, planId) as { id: number } | undefined; + if (existing) { + db.prepare('DELETE FROM vacay_entries WHERE id = ?').run(existing.id); + notifyPlanUsers(planId, socketId); + return { action: 'removed' }; + } else { + db.prepare('INSERT INTO vacay_entries (plan_id, user_id, date, note) VALUES (?, ?, ?, ?)').run(planId, userId, date, ''); + notifyPlanUsers(planId, socketId); + return { action: 'added' }; + } +} + +export function toggleCompanyHoliday(planId: number, date: string, note: string | undefined, socketId: string | undefined): { action: string } { + const existing = db.prepare('SELECT id FROM vacay_company_holidays WHERE plan_id = ? AND date = ?').get(planId, date) as { id: number } | undefined; + if (existing) { + db.prepare('DELETE FROM vacay_company_holidays WHERE id = ?').run(existing.id); + notifyPlanUsers(planId, socketId); + return { action: 'removed' }; + } else { + db.prepare('INSERT INTO vacay_company_holidays (plan_id, date, note) VALUES (?, ?, ?)').run(planId, date, note || ''); + db.prepare('DELETE FROM vacay_entries WHERE plan_id = ? AND date = ?').run(planId, date); + notifyPlanUsers(planId, socketId); + return { action: 'added' }; + } +} + +// --------------------------------------------------------------------------- +// Stats +// --------------------------------------------------------------------------- + +export function getStats(planId: number, year: number) { + const plan = db.prepare('SELECT * FROM vacay_plans WHERE id = ?').get(planId) as VacayPlan | undefined; + const carryOverEnabled = plan ? !!plan.carry_over_enabled : true; + const users = getPlanUsers(planId); + + return users.map(u => { + const used = (db.prepare("SELECT COUNT(*) as count FROM vacay_entries WHERE user_id = ? AND plan_id = ? AND date LIKE ?").get(u.id, planId, `${year}-%`) as { count: number }).count; + const config = db.prepare('SELECT * FROM vacay_user_years WHERE user_id = ? AND plan_id = ? AND year = ?').get(u.id, planId, year) as VacayUserYear | undefined; + const vacationDays = config ? config.vacation_days : 30; + const carriedOver = carryOverEnabled ? (config ? config.carried_over : 0) : 0; + const total = vacationDays + carriedOver; + const remaining = total - used; + const colorRow = db.prepare('SELECT color FROM vacay_user_colors WHERE user_id = ? AND plan_id = ?').get(u.id, planId) as { color: string } | undefined; + + const nextYearExists = db.prepare('SELECT id FROM vacay_years WHERE plan_id = ? AND year = ?').get(planId, year + 1); + if (nextYearExists && carryOverEnabled) { + const carry = Math.max(0, remaining); + db.prepare(` + INSERT INTO vacay_user_years (user_id, plan_id, year, vacation_days, carried_over) VALUES (?, ?, ?, 30, ?) + ON CONFLICT(user_id, plan_id, year) DO UPDATE SET carried_over = ? + `).run(u.id, planId, year + 1, carry, carry); + } + + return { + user_id: u.id, person_name: u.username, person_color: colorRow?.color || '#6366f1', + year, vacation_days: vacationDays, carried_over: carriedOver, + total_available: total, used, remaining, + }; + }); +} + +export function updateStats(userId: number, planId: number, year: number, vacationDays: number, socketId: string | undefined): void { + db.prepare(` + INSERT INTO vacay_user_years (user_id, plan_id, year, vacation_days, carried_over) VALUES (?, ?, ?, ?, 0) + ON CONFLICT(user_id, plan_id, year) DO UPDATE SET vacation_days = excluded.vacation_days + `).run(userId, planId, year, vacationDays); + notifyPlanUsers(planId, socketId); +} + +// --------------------------------------------------------------------------- +// GET /plan composite +// --------------------------------------------------------------------------- + +export function getPlanData(userId: number) { + const plan = getActivePlan(userId); + const activePlanId = plan.id; + + const users = getPlanUsers(activePlanId).map(u => { + const colorRow = db.prepare('SELECT color FROM vacay_user_colors WHERE user_id = ? AND plan_id = ?').get(u.id, activePlanId) as { color: string } | undefined; + return { ...u, color: colorRow?.color || '#6366f1' }; + }); + + const pendingInvites = db.prepare(` + SELECT m.id, m.user_id, u.username, u.email, m.created_at + FROM vacay_plan_members m JOIN users u ON m.user_id = u.id + WHERE m.plan_id = ? AND m.status = 'pending' + `).all(activePlanId); + + const incomingInvites = db.prepare(` + SELECT m.id, m.plan_id, u.username, u.email, m.created_at + FROM vacay_plan_members m + JOIN vacay_plans p ON m.plan_id = p.id + JOIN users u ON p.owner_id = u.id + WHERE m.user_id = ? AND m.status = 'pending' + `).all(userId); + + const holidayCalendars = db.prepare('SELECT * FROM vacay_holiday_calendars WHERE plan_id = ? ORDER BY sort_order, id').all(activePlanId) as VacayHolidayCalendar[]; + + return { + plan: { + ...plan, + block_weekends: !!plan.block_weekends, + holidays_enabled: !!plan.holidays_enabled, + company_holidays_enabled: !!plan.company_holidays_enabled, + carry_over_enabled: !!plan.carry_over_enabled, + holiday_calendars: holidayCalendars, + }, + users, + pendingInvites, + incomingInvites, + isOwner: plan.owner_id === userId, + isFused: users.length > 1, + }; +} + +// --------------------------------------------------------------------------- +// Holidays (nager.at proxy with cache) +// --------------------------------------------------------------------------- + +export async function getCountries(): Promise<{ data?: unknown; error?: string }> { + const cacheKey = 'countries'; + const cached = holidayCache.get(cacheKey); + if (cached && Date.now() - cached.time < CACHE_TTL) return { data: cached.data }; + try { + const resp = await fetch('https://date.nager.at/api/v3/AvailableCountries'); + const data = await resp.json(); + holidayCache.set(cacheKey, { data, time: Date.now() }); + return { data }; + } catch { + return { error: 'Failed to fetch countries' }; + } +} + +export async function getHolidays(year: string, country: string): Promise<{ data?: unknown; error?: string }> { + const cacheKey = `${year}-${country}`; + const cached = holidayCache.get(cacheKey); + if (cached && Date.now() - cached.time < CACHE_TTL) return { data: cached.data }; + try { + const resp = await fetch(`https://date.nager.at/api/v3/PublicHolidays/${year}/${country}`); + const data = await resp.json(); + holidayCache.set(cacheKey, { data, time: Date.now() }); + return { data }; + } catch { + return { error: 'Failed to fetch holidays' }; + } +} diff --git a/server/src/services/weatherService.ts b/server/src/services/weatherService.ts new file mode 100644 index 0000000000000000000000000000000000000000..75ea5d5ee2cf3ef6750f555121513c34e62c3bed --- /dev/null +++ b/server/src/services/weatherService.ts @@ -0,0 +1,513 @@ + +// ── Interfaces ────────────────────────────────────────────────────────── + +export interface WeatherResult { + temp: number; + temp_max?: number; + temp_min?: number; + main: string; + description: string; + type: string; + sunrise?: string | null; + sunset?: string | null; + precipitation_sum?: number; + precipitation_probability_max?: number; + wind_max?: number; + hourly?: HourlyEntry[]; + error?: string; +} + +export interface HourlyEntry { + hour: number; + temp: number; + precipitation: number; + precipitation_probability: number; + main: string; + wind: number; + humidity: number; +} + +interface OpenMeteoForecast { + error?: boolean; + reason?: string; + current?: { temperature_2m: number; weathercode: number }; + daily?: { + time: string[]; + temperature_2m_max: number[]; + temperature_2m_min: number[]; + weathercode: number[]; + precipitation_sum?: number[]; + precipitation_probability_max?: number[]; + windspeed_10m_max?: number[]; + sunrise?: string[]; + sunset?: string[]; + }; + hourly?: { + time: string[]; + temperature_2m: number[]; + precipitation_probability?: number[]; + precipitation?: number[]; + weathercode?: number[]; + windspeed_10m?: number[]; + relativehumidity_2m?: number[]; + }; +} + +// ── WMO code mappings ─────────────────────────────────────────────────── + +const WMO_MAP: Record = { + 0: 'Clear', 1: 'Clear', 2: 'Clouds', 3: 'Clouds', + 45: 'Fog', 48: 'Fog', + 51: 'Drizzle', 53: 'Drizzle', 55: 'Drizzle', 56: 'Drizzle', 57: 'Drizzle', + 61: 'Rain', 63: 'Rain', 65: 'Rain', 66: 'Rain', 67: 'Rain', + 71: 'Snow', 73: 'Snow', 75: 'Snow', 77: 'Snow', + 80: 'Rain', 81: 'Rain', 82: 'Rain', + 85: 'Snow', 86: 'Snow', + 95: 'Thunderstorm', 96: 'Thunderstorm', 99: 'Thunderstorm', +}; + +const WMO_DESCRIPTION_DE: Record = { + 0: 'Klar', 1: 'Uberwiegend klar', 2: 'Teilweise bewolkt', 3: 'Bewolkt', + 45: 'Nebel', 48: 'Nebel mit Reif', + 51: 'Leichter Nieselregen', 53: 'Nieselregen', 55: 'Starker Nieselregen', + 56: 'Gefrierender Nieselregen', 57: 'Starker gefr. Nieselregen', + 61: 'Leichter Regen', 63: 'Regen', 65: 'Starker Regen', + 66: 'Gefrierender Regen', 67: 'Starker gefr. Regen', + 71: 'Leichter Schneefall', 73: 'Schneefall', 75: 'Starker Schneefall', 77: 'Schneekorner', + 80: 'Leichte Regenschauer', 81: 'Regenschauer', 82: 'Starke Regenschauer', + 85: 'Leichte Schneeschauer', 86: 'Starke Schneeschauer', + 95: 'Gewitter', 96: 'Gewitter mit Hagel', 99: 'Starkes Gewitter mit Hagel', +}; + +const WMO_DESCRIPTION_EN: Record = { + 0: 'Clear sky', 1: 'Mainly clear', 2: 'Partly cloudy', 3: 'Overcast', + 45: 'Fog', 48: 'Rime fog', + 51: 'Light drizzle', 53: 'Drizzle', 55: 'Heavy drizzle', + 56: 'Freezing drizzle', 57: 'Heavy freezing drizzle', + 61: 'Light rain', 63: 'Rain', 65: 'Heavy rain', + 66: 'Freezing rain', 67: 'Heavy freezing rain', + 71: 'Light snowfall', 73: 'Snowfall', 75: 'Heavy snowfall', 77: 'Snow grains', + 80: 'Light rain showers', 81: 'Rain showers', 82: 'Heavy rain showers', + 85: 'Light snow showers', 86: 'Heavy snow showers', + 95: 'Thunderstorm', 96: 'Thunderstorm with hail', 99: 'Severe thunderstorm with hail', +}; + +// ── Cache management ──────────────────────────────────────────────────── + +const weatherCache = new Map(); +const inFlight = new Map>(); +const CACHE_MAX_ENTRIES = 1000; +const CACHE_PRUNE_TARGET = 500; +const CACHE_CLEANUP_INTERVAL = 5 * 60 * 1000; // 5 minutes + +setInterval(() => { + const now = Date.now(); + for (const [key, entry] of weatherCache) { + if (now > entry.expiresAt) weatherCache.delete(key); + } + if (weatherCache.size > CACHE_MAX_ENTRIES) { + const entries = [...weatherCache.entries()].sort((a, b) => a[1].expiresAt - b[1].expiresAt); + const toDelete = entries.slice(0, entries.length - CACHE_PRUNE_TARGET); + toDelete.forEach(([key]) => weatherCache.delete(key)); + } +}, CACHE_CLEANUP_INTERVAL); + +const TTL_FORECAST_MS = 60 * 60 * 1000; // 1 hour +const TTL_CURRENT_MS = 15 * 60 * 1000; // 15 minutes +const TTL_CLIMATE_MS = 24 * 60 * 60 * 1000; // 24 hours + +export function cacheKey(lat: string, lng: string, date?: string): string { + const rlat = parseFloat(lat).toFixed(2); + const rlng = parseFloat(lng).toFixed(2); + return `${rlat}_${rlng}_${date || 'current'}`; +} + +function getCached(key: string): WeatherResult | null { + const entry = weatherCache.get(key); + if (!entry) return null; + if (Date.now() > entry.expiresAt) { + weatherCache.delete(key); + return null; + } + return entry.data; +} + +function setCache(key: string, data: WeatherResult, ttlMs: number): void { + weatherCache.set(key, { data, expiresAt: Date.now() + ttlMs }); +} + +// ── Helpers ───────────────────────────────────────────────────────────── + +export function estimateCondition(tempAvg: number, precipMm: number): string { + if (precipMm > 5) return tempAvg <= 0 ? 'Snow' : 'Rain'; + if (precipMm > 1) return tempAvg <= 0 ? 'Snow' : 'Drizzle'; + if (precipMm > 0.3) return 'Clouds'; + return tempAvg > 15 ? 'Clear' : 'Clouds'; +} + +// ── getWeather ────────────────────────────────────────────────────────── + +async function _getWeatherImpl( + lat: string, + lng: string, + date: string | undefined, + lang: string, +): Promise { + const ck = cacheKey(lat, lng, date); + + if (date) { + const cached = getCached(ck); + if (cached) return cached; + + const targetDate = new Date(date); + const now = new Date(); + const diffDays = (targetDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24); + + // Forecast range (-1 .. +16 days) + if (diffDays >= -1 && diffDays <= 16) { + const url = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lng}&daily=temperature_2m_max,temperature_2m_min,weathercode&timezone=auto&forecast_days=16`; + const response = await fetch(url); + const data = await response.json() as OpenMeteoForecast; + + if (!response.ok || data.error) { + throw new ApiError(response.status || 500, data.reason || 'Open-Meteo API error'); + } + + const dateStr = targetDate.toISOString().slice(0, 10); + const idx = (data.daily?.time || []).indexOf(dateStr); + + if (idx !== -1) { + const code = data.daily!.weathercode[idx]; + const descriptions = lang === 'de' ? WMO_DESCRIPTION_DE : WMO_DESCRIPTION_EN; + + const result: WeatherResult = { + temp: Math.round((data.daily!.temperature_2m_max[idx] + data.daily!.temperature_2m_min[idx]) / 2), + temp_max: Math.round(data.daily!.temperature_2m_max[idx]), + temp_min: Math.round(data.daily!.temperature_2m_min[idx]), + main: WMO_MAP[code] || 'Clouds', + description: descriptions[code] || '', + type: 'forecast', + }; + + setCache(ck, result, TTL_FORECAST_MS); + return result; + } + } + + // Past date: use archive API for the actual date + if (diffDays < -1) { + const dateStr = targetDate.toISOString().slice(0, 10); + const url = `https://archive-api.open-meteo.com/v1/archive?latitude=${lat}&longitude=${lng}&start_date=${dateStr}&end_date=${dateStr}&daily=temperature_2m_max,temperature_2m_min,weathercode,precipitation_sum&timezone=auto`; + const response = await fetch(url); + const data = await response.json() as OpenMeteoForecast; + + if (!response.ok || data.error) { + throw new ApiError(response.status || 500, data.reason || 'Open-Meteo Archive API error'); + } + + const daily = data.daily; + if (daily && daily.time && daily.time.length > 0 && daily.temperature_2m_max[0] != null) { + const code = daily.weathercode?.[0]; + const descriptions = lang === 'de' ? WMO_DESCRIPTION_DE : WMO_DESCRIPTION_EN; + const tMax = daily.temperature_2m_max[0]; + const tMin = daily.temperature_2m_min[0]; + const result: WeatherResult = { + temp: Math.round((tMax + tMin) / 2), + temp_max: Math.round(tMax), + temp_min: Math.round(tMin), + main: WMO_MAP[code!] || estimateCondition((tMax + tMin) / 2, daily.precipitation_sum?.[0] || 0), + description: descriptions[code!] || '', + type: 'forecast', + }; + setCache(ck, result, TTL_CLIMATE_MS); + return result; + } + return { temp: 0, main: '', description: '', type: '', error: 'no_forecast' }; + } + + // Climate / archive fallback (far-future dates) + if (diffDays > -1) { + const month = targetDate.getMonth() + 1; + const day = targetDate.getDate(); + let refYear = targetDate.getFullYear() - 1; + // Archive API only has data up to yesterday — go back further if needed + const yesterday = new Date(now.getTime() - 86400000); + if (new Date(refYear, month - 1, day + 2) > yesterday) refYear--; + const startDate = new Date(refYear, month - 1, day - 2); + const endDate = new Date(refYear, month - 1, day + 2); + const startStr = startDate.toISOString().slice(0, 10); + const endStr = endDate.toISOString().slice(0, 10); + + const url = `https://archive-api.open-meteo.com/v1/archive?latitude=${lat}&longitude=${lng}&start_date=${startStr}&end_date=${endStr}&daily=temperature_2m_max,temperature_2m_min,precipitation_sum&timezone=auto`; + const response = await fetch(url); + const data = await response.json() as OpenMeteoForecast; + + if (!response.ok || data.error) { + throw new ApiError(response.status || 500, data.reason || 'Open-Meteo Climate API error'); + } + + const daily = data.daily; + if (!daily || !daily.time || daily.time.length === 0) { + return { temp: 0, main: '', description: '', type: '', error: 'no_forecast' }; + } + + let sumMax = 0, sumMin = 0, sumPrecip = 0, count = 0; + for (let i = 0; i < daily.time.length; i++) { + if (daily.temperature_2m_max[i] != null && daily.temperature_2m_min[i] != null) { + sumMax += daily.temperature_2m_max[i]; + sumMin += daily.temperature_2m_min[i]; + sumPrecip += daily.precipitation_sum![i] || 0; + count++; + } + } + + if (count === 0) { + return { temp: 0, main: '', description: '', type: '', error: 'no_forecast' }; + } + + const avgMax = sumMax / count; + const avgMin = sumMin / count; + const avgTemp = (avgMax + avgMin) / 2; + const avgPrecip = sumPrecip / count; + const main = estimateCondition(avgTemp, avgPrecip); + + const result: WeatherResult = { + temp: Math.round(avgTemp), + temp_max: Math.round(avgMax), + temp_min: Math.round(avgMin), + main, + description: '', + type: 'climate', + }; + + setCache(ck, result, TTL_CLIMATE_MS); + return result; + } + + return { temp: 0, main: '', description: '', type: '', error: 'no_forecast' }; + } + + // No date supplied -> current weather + const cached = getCached(ck); + if (cached) return cached; + + const url = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lng}¤t=temperature_2m,weathercode&timezone=auto`; + const response = await fetch(url); + const data = await response.json() as OpenMeteoForecast; + + if (!response.ok || data.error) { + throw new ApiError(response.status || 500, data.reason || 'Open-Meteo API error'); + } + + const code = data.current!.weathercode; + const descriptions = lang === 'de' ? WMO_DESCRIPTION_DE : WMO_DESCRIPTION_EN; + + const result: WeatherResult = { + temp: Math.round(data.current!.temperature_2m), + main: WMO_MAP[code] || 'Clouds', + description: descriptions[code] || '', + type: 'current', + }; + + setCache(ck, result, TTL_CURRENT_MS); + return result; +} + +export async function getWeather( + lat: string, + lng: string, + date: string | undefined, + lang: string, +): Promise { + const ck = cacheKey(lat, lng, date); + const cached = getCached(ck); + if (cached) return cached; + + const inFlightKey = `${ck}:${lang}`; + const existing = inFlight.get(inFlightKey); + if (existing) return existing; + const promise = _getWeatherImpl(lat, lng, date, lang); + inFlight.set(inFlightKey, promise); + try { return await promise; } finally { inFlight.delete(inFlightKey); } +} + +// ── getDetailedWeather ────────────────────────────────────────────────── + +async function _getDetailedWeatherImpl( + lat: string, + lng: string, + date: string, + lang: string, +): Promise { + const ck = `detailed_${cacheKey(lat, lng, date)}`; + + const cached = getCached(ck); + if (cached) return cached; + + const targetDate = new Date(date); + const now = new Date(); + const diffDays = (targetDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24); + const dateStr = targetDate.toISOString().slice(0, 10); + const descriptions = lang === 'de' ? WMO_DESCRIPTION_DE : WMO_DESCRIPTION_EN; + + // Climate / archive path (> 16 days out) + if (diffDays > 16) { + let refYear = targetDate.getFullYear() - 1; + // Archive API only has data up to yesterday — go back further if needed + const yesterday = new Date(now.getTime() - 86400000); + if (new Date(refYear, targetDate.getMonth(), targetDate.getDate()) > yesterday) refYear--; + const refDateStr = `${refYear}-${String(targetDate.getMonth() + 1).padStart(2, '0')}-${String(targetDate.getDate()).padStart(2, '0')}`; + + const url = `https://archive-api.open-meteo.com/v1/archive?latitude=${lat}&longitude=${lng}` + + `&start_date=${refDateStr}&end_date=${refDateStr}` + + `&hourly=temperature_2m,precipitation,weathercode,windspeed_10m,relativehumidity_2m` + + `&daily=temperature_2m_max,temperature_2m_min,weathercode,precipitation_sum,windspeed_10m_max,sunrise,sunset` + + `&timezone=auto`; + const response = await fetch(url); + const data = await response.json() as OpenMeteoForecast; + + if (!response.ok || data.error) { + throw new ApiError(response.status || 500, data.reason || 'Open-Meteo Climate API error'); + } + + const daily = data.daily; + const hourly = data.hourly; + if (!daily || !daily.time || daily.time.length === 0) { + return { temp: 0, main: '', description: '', type: '', error: 'no_forecast' }; + } + + const idx = 0; + const code = daily.weathercode?.[idx]; + const avgMax = daily.temperature_2m_max[idx]; + const avgMin = daily.temperature_2m_min[idx]; + + const hourlyData: HourlyEntry[] = []; + if (hourly?.time) { + for (let i = 0; i < hourly.time.length; i++) { + const hour = new Date(hourly.time[i]).getHours(); + const hCode = hourly.weathercode?.[i]; + hourlyData.push({ + hour, + temp: Math.round(hourly.temperature_2m[i]), + precipitation: hourly.precipitation?.[i] || 0, + precipitation_probability: 0, + main: WMO_MAP[hCode!] || 'Clouds', + wind: Math.round(hourly.windspeed_10m?.[i] || 0), + humidity: hourly.relativehumidity_2m?.[i] || 0, + }); + } + } + + let sunrise: string | null = null, sunset: string | null = null; + if (daily.sunrise?.[idx]) sunrise = daily.sunrise[idx].split('T')[1]?.slice(0, 5); + if (daily.sunset?.[idx]) sunset = daily.sunset[idx].split('T')[1]?.slice(0, 5); + + const result: WeatherResult = { + type: 'climate', + temp: Math.round((avgMax + avgMin) / 2), + temp_max: Math.round(avgMax), + temp_min: Math.round(avgMin), + main: WMO_MAP[code!] || estimateCondition((avgMax + avgMin) / 2, daily.precipitation_sum?.[idx] || 0), + description: descriptions[code!] || '', + precipitation_sum: Math.round((daily.precipitation_sum?.[idx] || 0) * 10) / 10, + wind_max: Math.round(daily.windspeed_10m_max?.[idx] || 0), + sunrise, + sunset, + hourly: hourlyData, + }; + + setCache(ck, result, TTL_CLIMATE_MS); + return result; + } + + // Forecast path (<= 16 days) + const url = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lng}` + + `&hourly=temperature_2m,precipitation_probability,precipitation,weathercode,windspeed_10m,relativehumidity_2m` + + `&daily=temperature_2m_max,temperature_2m_min,weathercode,sunrise,sunset,precipitation_probability_max,precipitation_sum,windspeed_10m_max` + + `&timezone=auto&start_date=${dateStr}&end_date=${dateStr}`; + + const response = await fetch(url); + const data = await response.json() as OpenMeteoForecast; + + if (!response.ok || data.error) { + throw new ApiError(response.status || 500, data.reason || 'Open-Meteo API error'); + } + + const daily = data.daily; + const hourly = data.hourly; + + if (!daily || !daily.time || daily.time.length === 0) { + return { temp: 0, main: '', description: '', type: '', error: 'no_forecast' }; + } + + const dayIdx = 0; + const code = daily.weathercode[dayIdx]; + + const formatTime = (isoStr: string) => { + if (!isoStr) return ''; + const d = new Date(isoStr); + return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`; + }; + + const hourlyData: HourlyEntry[] = []; + if (hourly && hourly.time) { + for (let i = 0; i < hourly.time.length; i++) { + const h = new Date(hourly.time[i]).getHours(); + hourlyData.push({ + hour: h, + temp: Math.round(hourly.temperature_2m[i]), + precipitation_probability: hourly.precipitation_probability![i] || 0, + precipitation: hourly.precipitation![i] || 0, + main: WMO_MAP[hourly.weathercode![i]] || 'Clouds', + wind: Math.round(hourly.windspeed_10m![i] || 0), + humidity: Math.round(hourly.relativehumidity_2m![i] || 0), + }); + } + } + + const result: WeatherResult = { + type: 'forecast', + temp: Math.round((daily.temperature_2m_max[dayIdx] + daily.temperature_2m_min[dayIdx]) / 2), + temp_max: Math.round(daily.temperature_2m_max[dayIdx]), + temp_min: Math.round(daily.temperature_2m_min[dayIdx]), + main: WMO_MAP[code] || 'Clouds', + description: descriptions[code] || '', + sunrise: formatTime(daily.sunrise![dayIdx]), + sunset: formatTime(daily.sunset![dayIdx]), + precipitation_sum: daily.precipitation_sum![dayIdx] || 0, + precipitation_probability_max: daily.precipitation_probability_max![dayIdx] || 0, + wind_max: Math.round(daily.windspeed_10m_max![dayIdx] || 0), + hourly: hourlyData, + }; + + setCache(ck, result, TTL_FORECAST_MS); + return result; +} + +export async function getDetailedWeather( + lat: string, + lng: string, + date: string, + lang: string, +): Promise { + const ck = `detailed_${cacheKey(lat, lng, date)}`; + const cached = getCached(ck); + if (cached) return cached; + + const inFlightKey = `${ck}:${lang}`; + const existing = inFlight.get(inFlightKey); + if (existing) return existing; + const promise = _getDetailedWeatherImpl(lat, lng, date, lang); + inFlight.set(inFlightKey, promise); + try { return await promise; } finally { inFlight.delete(inFlightKey); } +} + +// ── ApiError ──────────────────────────────────────────────────────────── + +export class ApiError extends Error { + status: number; + constructor(status: number, message: string) { + super(message); + this.status = status; + } +} diff --git a/server/src/services/webauthnConfig.ts b/server/src/services/webauthnConfig.ts new file mode 100644 index 0000000000000000000000000000000000000000..d6fcf924df65e76ebc9bfe6bc1cb9f3720c01730 --- /dev/null +++ b/server/src/services/webauthnConfig.ts @@ -0,0 +1,85 @@ +import { db } from '../db/database'; +import { getAppUrl } from './notifications'; + +/** + * Resolves the WebAuthn Relying Party ID + allowed origins for this deployment. + * + * SECURITY: the RP ID and the allowed origins are derived ONLY from server-side + * configuration — the `webauthn_rp_id` / `webauthn_origins` admin settings (or + * the matching env vars), falling back to APP_URL. They are NEVER taken from the + * request `Host` / `X-Forwarded-Host` header: a forged forwarded host would + * otherwise let an attacker bind credentials to a domain they control, or brick + * every enrolled user. This mirrors how OIDC derives its redirect URI from + * APP_URL (oidc.controller.ts) rather than from request input. + * + * Returns null when no usable RP ID can be resolved (bare IP host, or nothing + * configured) — the feature then reports itself as "not configured" and stays + * disabled so nobody can enrol a credential bound to the wrong origin. + */ + +function getSetting(key: string): string | null { + const raw = (db.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as { value: string } | undefined)?.value; + const trimmed = raw?.trim(); + return trimmed ? trimmed : null; +} + +function hostOf(url: string): string | null { + try { + return new URL(url).hostname || null; + } catch { + return null; + } +} + +/** WebAuthn RP IDs must be registrable domains — never bare IP literals. */ +function isIpHost(host: string): boolean { + if (/^\d{1,3}(\.\d{1,3}){3}$/.test(host)) return true; // IPv4 + if (host.includes(':')) return true; // IPv6 (hostname keeps the colons) + return false; +} + +export interface WebauthnConfig { + rpID: string; + rpName: string; + /** Exact allowed origins (scheme + host + port). One in prod; localhost dev adds the Vite/API ports. */ + origins: string[]; +} + +export function resolveWebauthnConfig(): WebauthnConfig | null { + // 1. Explicit operator config always wins. + const explicitRpId = (process.env.WEBAUTHN_RP_ID || getSetting('webauthn_rp_id'))?.trim() || null; + const explicitOrigins = (process.env.WEBAUTHN_ORIGINS || getSetting('webauthn_origins') || '') + .split(',') + .map((o) => o.trim().replace(/\/+$/, '')) + .filter(Boolean); + + const appUrl = getAppUrl(); + const appHost = hostOf(appUrl); + + // 2. Derive the RP ID from APP_URL when not explicitly set. + let rpID = explicitRpId; + if (!rpID && appHost && !isIpHost(appHost)) { + rpID = appHost; // a real domain, or "localhost" + } + if (!rpID) return null; // bare IP / unresolved → WebAuthn cannot be used here + + // 3. Resolve the allowed origins. Explicit list wins verbatim (operator's + // responsibility). Otherwise derive a SINGLE origin from APP_URL — we never + // silently union dev localhost origins into a production allow-list. + let origins = explicitOrigins; + if (origins.length === 0) { + if (appHost) origins = [appUrl.replace(/\/+$/, '')]; + if (rpID === 'localhost') { + // Dev: the browser origin is the Vite dev server (:5173), not the API port. + origins = Array.from(new Set([...origins, 'http://localhost:5173', 'http://localhost:3001'])); + } + } + if (origins.length === 0) return null; + + return { rpID, rpName: 'TREK', origins }; +} + +/** True when a usable RP ID resolves for this deployment (exposed as a pure boolean on app-config). */ +export function isPasskeyConfigured(): boolean { + return resolveWebauthnConfig() !== null; +} diff --git a/server/src/systemNotices/conditions.ts b/server/src/systemNotices/conditions.ts new file mode 100644 index 0000000000000000000000000000000000000000..97dd3eac4fa39cb3792e1724c3462f1c200883cf --- /dev/null +++ b/server/src/systemNotices/conditions.ts @@ -0,0 +1,72 @@ +import semver from 'semver'; +import { isAddonEnabled } from '../services/adminService.js'; +import type { NoticeCondition, SystemNotice } from './types.js'; + +interface ConditionContext { + user: { login_count: number; first_seen_version: string; role: string; noTrips: number }; + currentAppVersion: string; + now: Date; +} + +// Custom predicate registry — extensible without modifying this file +const customPredicates = new Map boolean>(); +export function registerPredicate(id: string, fn: (ctx: ConditionContext) => boolean): void { + customPredicates.set(id, fn); +} + +function evaluateOne(condition: NoticeCondition, ctx: ConditionContext): boolean { + switch (condition.kind) { + case 'always': + return true; + case 'firstLogin': + // login_count is incremented during login, so on the FIRST post-login fetch it's 1. + return ctx.user.login_count <= 1; + case 'noTrips': + return ctx.user.noTrips === 0; + + case 'existingUserBeforeVersion': { + // Show to users who existed BEFORE this version was released. + // Backfilled users have first_seen_version='0.0.0', so all pass semver.lt. + const userVersion = semver.valid(ctx.user.first_seen_version) ?? '0.0.0'; + const noticeVersion = semver.valid(condition.version); + if (!noticeVersion) return false; + // Strip prerelease/build metadata so '3.0.0-pre.42' is treated as '3.0.0'. + const appVersion = semver.coerce(ctx.currentAppVersion)?.version ?? '0.0.0'; + return ( + semver.lt(userVersion, noticeVersion) && + semver.gte(appVersion, noticeVersion) + ); + } + + case 'dateWindow': { + const start = new Date(condition.startsAt); + const end = condition.endsAt ? new Date(condition.endsAt) : null; + return ctx.now >= start && (end === null || ctx.now <= end); + } + + case 'role': + return condition.roles.includes(ctx.user.role as 'admin' | 'user'); + + case 'addonEnabled': + return isAddonEnabled(condition.addonId); + + case 'custom': { + const fn = customPredicates.get(condition.id); + if (!fn) { + console.warn(`[systemNotices] unknown custom predicate: "${condition.id}"`); + return false; + } + return fn(ctx); + } + + default: + return false; + } +} + +/** Returns true only if ALL conditions pass (AND logic). */ +export function evaluate(notice: SystemNotice, ctx: ConditionContext): boolean { + return notice.conditions.every(c => evaluateOne(c, ctx)); +} + +export type { ConditionContext }; diff --git a/server/src/systemNotices/registry.ts b/server/src/systemNotices/registry.ts new file mode 100644 index 0000000000000000000000000000000000000000..4f5320d8b1daa36af3e0c21ad9402d6de852b3b1 --- /dev/null +++ b/server/src/systemNotices/registry.ts @@ -0,0 +1,178 @@ +import type { SystemNotice } from './types.js'; +import { registerPredicate } from './conditions.js'; +import { db } from '../db/database.js'; + +registerPredicate('whitespace-collision-detected', () => { + const row = db.prepare("SELECT value FROM app_settings WHERE key = 'whitespace_migration_collision'").get() as { value: string } | undefined; + return row?.value === 'true'; +}); + +/** + * SYSTEM NOTICE REGISTRY + * + * Rules for authoring: + * - NEVER remove or renumber entries — dismissal tracking is keyed by `id`. + * - `id` must be globally unique and stable across deployments. + * - Title: ≤40 chars, sentence case, no trailing punctuation. + * - Body: markdown (modal) or plain text (banner/toast). ≤400/140/80 chars. + * - CTA label: ≤20 chars, a verb. + * - Never hardcode version numbers/dates in translated strings — use bodyParams. + * - See plans/system-notices/00-overview.md for full authoring guidelines. + */ +export const SYSTEM_NOTICES: SystemNotice[] = [ + // ── 3.0.0 upgrade notices (shown as a multipage modal to pre-3.0 users) ───── + + { + // Page 1 — breaking change first (warn → sorts before the two info notices) + id: 'v3-photos', + display: 'modal', + severity: 'warn', + icon: 'ImageOff', + titleKey: 'system_notice.v3_photos.title', + bodyKey: 'system_notice.v3_photos.body', + dismissible: true, + conditions: [{ kind: 'existingUserBeforeVersion', version: '3.0.0' }], + publishedAt: '2026-04-16T00:00:00Z', + priority: 90, + minVersion: '3.0.0', + maxVersion: '4.0.0', + }, + + { + // Page 2 — flagship feature (only when Journey addon is enabled) + id: 'v3-journey', + display: 'modal', + severity: 'info', + icon: 'BookOpen', + titleKey: 'system_notice.v3_journey.title', + bodyKey: 'system_notice.v3_journey.body', + highlights: [ + { labelKey: 'system_notice.v3_journey.highlight_timeline', iconName: 'CalendarDays' }, + { labelKey: 'system_notice.v3_journey.highlight_photos', iconName: 'Images' }, + { labelKey: 'system_notice.v3_journey.highlight_share', iconName: 'Globe' }, + { labelKey: 'system_notice.v3_journey.highlight_export', iconName: 'FileText' }, + ], + cta: { + kind: 'nav', + labelKey: 'system_notice.v3_journey.cta_label', + href: '/journey', + }, + dismissible: true, + conditions: [ + { kind: 'existingUserBeforeVersion', version: '3.0.0' }, + { kind: 'addonEnabled', addonId: 'journey' }, + ], + publishedAt: '2026-04-16T00:00:00Z', + priority: 80, + minVersion: '3.0.0', + maxVersion: '4.0.0', + }, + + { + // Page 3 — MCP OAuth 2.1 upgrade (only when MCP addon is enabled) + id: 'v3-mcp', + display: 'modal', + severity: 'warn', + icon: 'Bot', + titleKey: 'system_notice.v3_mcp.title', + bodyKey: 'system_notice.v3_mcp.body', + highlights: [ + { labelKey: 'system_notice.v3_mcp.highlight_oauth', iconName: 'KeyRound' }, + { labelKey: 'system_notice.v3_mcp.highlight_scopes', iconName: 'ShieldCheck' }, + { labelKey: 'system_notice.v3_mcp.highlight_deprecated', iconName: 'AlertTriangle' }, + { labelKey: 'system_notice.v3_mcp.highlight_tools', iconName: 'Wrench' }, + ], + dismissible: true, + conditions: [ + { kind: 'existingUserBeforeVersion', version: '3.0.0' }, + { kind: 'addonEnabled', addonId: 'mcp' }, + ], + publishedAt: '2026-04-16T00:00:00Z', + priority: 75, + minVersion: '3.0.0', + maxVersion: '4.0.0', + }, + + { + // Page 4 — other highlights + id: 'v3-features', + display: 'modal', + severity: 'info', + icon: 'Sparkles', + titleKey: 'system_notice.v3_features.title', + bodyKey: 'system_notice.v3_features.body', + highlights: [ + { labelKey: 'system_notice.v3_features.highlight_dashboard', iconName: 'LayoutDashboard' }, + { labelKey: 'system_notice.v3_features.highlight_offline', iconName: 'WifiOff' }, + { labelKey: 'system_notice.v3_features.highlight_search', iconName: 'Search' }, + { labelKey: 'system_notice.v3_features.highlight_import', iconName: 'FileInput' }, + ], + dismissible: true, + conditions: [{ kind: 'existingUserBeforeVersion', version: '3.0.0' }], + publishedAt: '2026-04-16T00:00:00Z', + priority: 70, + minVersion: '3.0.0', + maxVersion: '4.0.0', + }, + + { + // Page 1 — personal thank-you from the creator (shown first) + id: 'v3-thankyou', + display: 'modal', + severity: 'info', + icon: 'Heart', + titleKey: 'system_notice.v3_thankyou.title', + bodyKey: 'system_notice.v3_thankyou.body', + dismissible: true, + conditions: [{ kind: 'existingUserBeforeVersion', version: '3.0.0' }], + publishedAt: '2026-04-16T00:00:00Z', + priority: 95, + minVersion: '3.0.0', + maxVersion: '4.0.0', + }, + + // ── 3.0.14 admin notice — whitespace migration collision ─────────────────── + + { + id: 'v3014-whitespace-collision', + display: 'banner', + severity: 'warn', + icon: 'AlertTriangle', + titleKey: 'system_notice.v3014_whitespace_collision.title', + bodyKey: 'system_notice.v3014_whitespace_collision.body', + dismissible: true, + conditions: [ + { kind: 'existingUserBeforeVersion', version: '3.0.14' }, + { kind: 'role', roles: ['admin'] }, + { kind: 'custom', id: 'whitespace-collision-detected' }, + ], + publishedAt: '2026-05-03T00:00:00Z', + priority: 85, + minVersion: '3.0.14', + }, + + // ── Onboarding ───────────────────────────────────────────────────────────── + + { + id: 'welcome-v1', + display: 'modal', + severity: 'info', + icon: 'Sparkles', + titleKey: 'system_notice.welcome_v1.title', + bodyKey: 'system_notice.welcome_v1.body', + highlights: [ + { labelKey: 'system_notice.welcome_v1.highlight_plan', iconName: 'Map' }, + { labelKey: 'system_notice.welcome_v1.highlight_share', iconName: 'Users' }, + { labelKey: 'system_notice.welcome_v1.highlight_offline', iconName: 'WifiOff' }, + ], + cta: { + kind: 'action', + labelKey: 'system_notice.welcome_v1.cta_label', + actionId: 'open:trip-create', + }, + dismissible: true, + conditions: [{ kind: 'firstLogin' }], + publishedAt: '2026-04-16T00:00:00Z', + priority: 100, + }, +];