diff --git a/server/src/mcp/scopes.ts b/server/src/mcp/scopes.ts index c897a41d6..3def32e59 100644 --- a/server/src/mcp/scopes.ts +++ b/server/src/mcp/scopes.ts @@ -65,7 +65,7 @@ export const SCOPE_INFO: Record = { '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' }, + 'geo:read': { label: 'Maps, geocoding & transit', description: 'Search locations and public transit routes, 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' }, diff --git a/server/src/mcp/tools.ts b/server/src/mcp/tools.ts index 7d12b8def..bb9e9a2ba 100644 --- a/server/src/mcp/tools.ts +++ b/server/src/mcp/tools.ts @@ -14,6 +14,7 @@ import { registerPackingTools } from './tools/packing'; import { registerCollabTools } from './tools/collab'; import { registerTripTools } from './tools/trips'; import { registerTransportTools } from './tools/transports'; +import { registerTransitTools } from './tools/transit'; import { registerVacayTools } from './tools/vacay'; import { registerMcpPrompts } from './tools/prompts'; @@ -44,6 +45,8 @@ export function registerTools(server: McpServer, userId: number, scopes: string[ registerTransportTools(server, userId, scopes); + registerTransitTools(server, userId, scopes); + registerJourneyTools(server, userId, scopes); registerVacayTools(server, userId, scopes); diff --git a/server/src/mcp/tools/_shared.ts b/server/src/mcp/tools/_shared.ts index 161725c39..041f6a251 100644 --- a/server/src/mcp/tools/_shared.ts +++ b/server/src/mcp/tools/_shared.ts @@ -1,6 +1,6 @@ -import { broadcast } from '../../websocket'; import { db } from '../../db/database'; import { checkPermission } from '../../services/permissions'; +import { broadcast } from '../../websocket'; export function safeBroadcast(tripId: number, event: string, payload: Record): void { try { @@ -19,6 +19,11 @@ export const TOOL_ANNOTATIONS_READONLY = { openWorldHint: false, } as const; +export const TOOL_ANNOTATIONS_OPEN_WORLD_READONLY = { + ...TOOL_ANNOTATIONS_READONLY, + openWorldHint: true, +} as const; + export const TOOL_ANNOTATIONS_WRITE = { readOnlyHint: false, destructiveHint: false, @@ -40,6 +45,11 @@ export const TOOL_ANNOTATIONS_NON_IDEMPOTENT = { openWorldHint: false, } as const; +export const TOOL_ANNOTATIONS_OPEN_WORLD_NON_IDEMPOTENT = { + ...TOOL_ANNOTATIONS_NON_IDEMPOTENT, + openWorldHint: true, +} as const; + export function demoDenied() { return { content: [{ type: 'text' as const, text: 'Write operations are disabled in demo mode.' }], isError: true }; } @@ -49,7 +59,10 @@ export function noAccess() { } export function permissionDenied() { - return { content: [{ type: 'text' as const, text: 'You do not have permission to perform this action on this trip.' }], isError: true }; + return { + content: [{ type: 'text' as const, text: 'You do not have permission to perform this action on this trip.' }], + isError: true, + }; } /** diff --git a/server/src/mcp/tools/transit.ts b/server/src/mcp/tools/transit.ts new file mode 100644 index 000000000..467bc1c5c --- /dev/null +++ b/server/src/mcp/tools/transit.ts @@ -0,0 +1,217 @@ +import { canAccessTrip } from '../../db/database'; +import { RateLimitService } from '../../nest/auth/rate-limit.service'; +import { isDemoUser } from '../../services/authService'; +import { getDay, listDays } from '../../services/dayService'; +import { createReservation, notifyBookingChange } from '../../services/reservationService'; +import { + buildTransitReservationParts, + cleanTransitItineraryNames, + transitCoordinatesMatch, + transitCoordinatesSchema, + transitItinerarySchema, + transitPlaceSchema, +} from '../../services/transitItineraryService'; +import { geocode, plan, SCHEDULED_TRANSIT_MODES } from '../../services/transitService'; +import { canRead, canWrite } from '../scopes'; +import { + demoDenied, + hasTripPermission, + noAccess, + ok, + permissionDenied, + safeBroadcast, + TOOL_ANNOTATIONS_OPEN_WORLD_NON_IDEMPOTENT, + TOOL_ANNOTATIONS_OPEN_WORLD_READONLY, +} from './_shared'; +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp'; + +import { z } from 'zod'; + +const TRANSIT_RATE_WINDOW = 15 * 60 * 1000; +const transitRateLimiter = new RateLimitService(); + +const transitModes = z.enum(['TRANSIT', ...SCHEDULED_TRANSIT_MODES]); + +function errorResult(err: unknown, fallback: string) { + return { + content: [{ type: 'text' as const, text: err instanceof Error ? err.message : fallback }], + isError: true, + }; +} + +function rateLimit(userId: number, bucket: string, max: number) { + if (transitRateLimiter.check(bucket, String(userId), max, TRANSIT_RATE_WINDOW, Date.now())) return null; + return { + content: [{ type: 'text' as const, text: 'Too many transit requests. Please try again later.' }], + isError: true, + }; +} + +export function registerTransitTools(server: McpServer, userId: number, scopes: string[] | null): void { + if (canRead(scopes, 'geo')) { + server.registerTool( + 'search_transit_stops', + { + description: + 'Search real public-transit stops and stations via Transitous. Use the returned coordinates with search_transit_routes.', + inputSchema: { + query: z.string().min(2).max(200), + language: z.string().min(2).max(5).optional(), + near: z + .object(transitCoordinatesSchema.shape) + .optional() + .describe('Optional coordinates used to bias nearby results'), + }, + annotations: TOOL_ANNOTATIONS_OPEN_WORLD_READONLY, + }, + async ({ query, language, near }) => { + const limited = rateLimit(userId, 'mcp_transit_geocode', 300); + if (limited) return limited; + try { + return ok(await geocode(query, language, near ? `${near.lat},${near.lng}` : undefined)); + } catch (err) { + return errorResult(err, 'Transit stop search failed.'); + } + }, + ); + + server.registerTool( + 'search_transit_routes', + { + description: + 'Search scheduled public-transit routes via Transitous between two coordinates. Returns itineraries that can be passed unchanged to create_transit_journey. `dropped` counts provider itineraries that failed validation and are therefore absent from the results — a non-zero value means the provider offered routes this tool could not represent.', + inputSchema: { + from: transitPlaceSchema, + to: transitPlaceSchema, + time: z + .string() + .datetime({ offset: true }) + .optional() + .describe('ISO 8601 departure or arrival time with timezone offset'), + arriveBy: z.boolean().optional().default(false), + modes: z.array(transitModes).max(14).optional(), + maxTransfers: z.number().int().min(0).max(10).optional(), + }, + annotations: TOOL_ANNOTATIONS_OPEN_WORLD_READONLY, + }, + async ({ from, to, time, arriveBy, modes, maxTransfers }) => { + const limited = rateLimit(userId, 'mcp_transit_plan', 60); + if (limited) return limited; + try { + const result = await plan({ + from: `${from.lat},${from.lng}`, + to: `${to.lat},${to.lng}`, + time, + arriveBy, + modes: modes?.join(','), + maxTransfers, + }); + const itineraries = result.itineraries.flatMap((itinerary) => { + const parsed = transitItinerarySchema.safeParse(cleanTransitItineraryNames(itinerary, from.name, to.name)); + if (!parsed.success) return []; + const firstStop = parsed.data.legs[0].from; + const lastStop = parsed.data.legs[parsed.data.legs.length - 1].to; + return transitCoordinatesMatch(from, firstStop) && transitCoordinatesMatch(to, lastStop) + ? [parsed.data] + : []; + }); + // A rejected itinerary is provider data we could not vouch for, but dropping it + // silently is indistinguishable from "no routes exist" — report the count so the + // caller knows the difference. + return ok({ itineraries, dropped: result.itineraries.length - itineraries.length }); + } catch (err) { + return errorResult(err, 'Transit route search failed.'); + } + }, + ); + } + + if (!canWrite(scopes, 'reservations')) return; + + server.registerTool( + 'create_transit_journey', + { + description: + 'Add one itinerary returned by search_transit_routes to a trip day as a first-class automated public-transit journey.', + inputSchema: { + tripId: z.number().int().positive(), + dayId: z.number().int().positive().describe('Trip day on which the journey departs'), + from: transitPlaceSchema, + to: transitPlaceSchema, + itinerary: transitItinerarySchema, + notes: z.string().max(1000).optional(), + }, + annotations: TOOL_ANNOTATIONS_OPEN_WORLD_NON_IDEMPOTENT, + }, + async ({ tripId, dayId, from, to, itinerary, notes }) => { + if (isDemoUser(userId)) return demoDenied(); + if (!canAccessTrip(tripId, userId)) return noAccess(); + if (!hasTripPermission('reservation_edit', tripId, userId)) return permissionDenied(); + const day = getDay(dayId, tripId); + if (!day) { + return { content: [{ type: 'text' as const, text: 'dayId does not belong to this trip.' }], isError: true }; + } + + const cleaned = cleanTransitItineraryNames(itinerary, from.name, to.name); + const firstStop = cleaned.legs[0].from; + const lastStop = cleaned.legs[cleaned.legs.length - 1].to; + if (!transitCoordinatesMatch(from, firstStop) || !transitCoordinatesMatch(to, lastStop)) { + return { + content: [ + { type: 'text' as const, text: 'The itinerary does not match the requested origin and destination.' }, + ], + isError: true, + }; + } + let reservationParts: ReturnType; + try { + reservationParts = buildTransitReservationParts(from, to, cleaned); + } catch (err) { + return errorResult(err, 'Unable to resolve the transit journey timezones.'); + } + const { endpoints, metadata } = reservationParts; + const departure = endpoints[0]; + const arrival = endpoints[endpoints.length - 1]; + if (!day.date) { + return { + content: [{ type: 'text' as const, text: 'Automated transit requires a dated trip day.' }], + isError: true, + }; + } + if (departure.local_date !== day.date) { + return { + content: [ + { + type: 'text' as const, + text: `The journey departs on ${departure.local_date}, but dayId is ${day.date}.`, + }, + ], + isError: true, + }; + } + const endDay = listDays(tripId).days.find((day) => day.date === arrival.local_date); + if (!endDay) { + return { + content: [{ type: 'text' as const, text: `No trip day exists for the arrival date ${arrival.local_date}.` }], + isError: true, + }; + } + const { reservation } = createReservation(tripId, { + title: `${from.name} → ${to.name}`, + type: 'transit', + status: 'confirmed', + day_id: dayId, + end_day_id: endDay.id, + reservation_time: `${departure.local_date}T${departure.local_time}`, + reservation_end_time: `${arrival.local_date}T${arrival.local_time}`, + notes, + metadata, + endpoints, + needs_review: false, + }); + safeBroadcast(tripId, 'reservation:created', { reservation }); + notifyBookingChange(tripId, userId, reservation.title, reservation.type || ''); + return ok({ reservation }); + }, + ); +} diff --git a/server/src/nest/plugins/host/create-rpc-host.ts b/server/src/nest/plugins/host/create-rpc-host.ts index 21d6590cc..48cb31883 100644 --- a/server/src/nest/plugins/host/create-rpc-host.ts +++ b/server/src/nest/plugins/host/create-rpc-host.ts @@ -34,7 +34,7 @@ import { listNotes, createNote, getNote, updateNote, deleteNote, dayExists as da import { listCollections, getCollection, createCollection, updateCollection, savePlace as saveCollectionPlaceSvc, copyToTrip as copyCollectionToTripSvc, deletePlace as deleteCollectionPlaceSvc } from '../../../services/collectionsService'; import { BudgetService } from '../../budget/budget.service'; import { ReservationsService } from '../../reservations/reservations.service'; -import type { User } from '../../../types'; +import { notifyBookingChange } from '../../../services/reservationService'; import { PluginDataDb } from './plugin-data.service'; import { DailyBudget, DEFAULT_DAILY_BUDGET } from './daily-budget'; import { PluginRpcHost, ForbiddenResource, BadParams } from './rpc-host'; @@ -57,16 +57,11 @@ function canEditTripAs(action: string, tripId: number, userId: number): boolean // Reused for costs.create so a plugin write frozen-FX and members/payers logic // matches a normal web-app budget write exactly (it has no injected deps). const budgetSvc = new BudgetService(); -// Same idea for reservations: the Nest service (no injected deps) encapsulates the -// accommodation/budget-sync/notification side effects 1:1 with the REST controller. const reservationsSvc = new ReservationsService(); - // The booking notification the REST controller sends after a create/update/delete -// (services/notificationService via reservationsSvc). Needs the acting User; a plugin -// only holds the id, so hydrate it host-side. Fire-and-forget — never blocks the write. +// is fire-and-forget, so it never blocks the plugin write. function notifyBooking(actingUserId: number, tripId: number, booking: string, type: string): void { - const actor = db.prepare('SELECT * FROM users WHERE id = ?').get(actingUserId) as User | undefined; - if (actor) reservationsSvc.notifyBookingChange(String(tripId), actor, booking, type); + notifyBookingChange(tripId, actingUserId, booking, type); } // A subsystem read is refused when its addon is off — parity with the app, where a diff --git a/server/src/nest/reservations/reservations.service.ts b/server/src/nest/reservations/reservations.service.ts index ba20c33b7..8aa63dfbd 100644 --- a/server/src/nest/reservations/reservations.service.ts +++ b/server/src/nest/reservations/reservations.service.ts @@ -128,15 +128,6 @@ export class ReservationsService { /** 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(() => {}); - }); + svc.notifyBookingChange(tripId, actor.id, booking, type); } } diff --git a/server/src/services/airtrail/airtrailMapper.ts b/server/src/services/airtrail/airtrailMapper.ts index 9198238a4..ede21172d 100644 --- a/server/src/services/airtrail/airtrailMapper.ts +++ b/server/src/services/airtrail/airtrailMapper.ts @@ -1,7 +1,9 @@ -import * as crypto from 'node:crypto'; +import { localParts } from '../timezoneService'; import type { AirtrailAirport, AirtrailFlightRaw, AirtrailNamedCode } from './airtrailClient'; import type { AirtrailFlight } from '@trek/shared'; +import * as crypto from 'node:crypto'; + /** Preferred display/lookup code for an airport. */ function airportCode(a: AirtrailAirport | null): string | null { return a?.iata || a?.icao || null; @@ -24,37 +26,6 @@ export function entityName(e: AirtrailNamedCode | null | undefined): string | nu return e?.name || 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 { @@ -69,7 +40,7 @@ export function normalizeFlight(raw: AirtrailFlightRaw): AirtrailFlight { airline: entityName(raw.airline), flightNumber: raw.flightNumber ?? null, aircraft: entityCode(raw.aircraft), - seatClass: (raw.seats?.find(s => s.userId) ?? raw.seats?.[0])?.seatClass ?? null, + seatClass: (raw.seats?.find((s) => s.userId) ?? raw.seats?.[0])?.seatClass ?? null, }; } @@ -153,7 +124,7 @@ export function mapFlightToReservation(raw: AirtrailFlightRaw): MappedReservatio needsReview = 1; } - const seat = raw.seats?.find(s => s.userId) ?? raw.seats?.[0]; + const seat = raw.seats?.find((s) => s.userId) ?? raw.seats?.[0]; const airlineName = entityName(raw.airline); const airlineCode = entityCode(raw.airline); const aircraftCode = entityCode(raw.aircraft); @@ -207,7 +178,7 @@ export function mapFlightsToMultiLegReservation( ): MappedReservation { if (flights.length === 1) return mapFlightToReservation(flights[0]); - let needsReview = flights.some(f => f.datePrecision && f.datePrecision !== 'day') ? 1 : 0; + let needsReview = flights.some((f) => f.datePrecision && f.datePrecision !== 'day') ? 1 : 0; const endpoints: MappedEndpoint[] = []; const legs: Record[] = []; @@ -250,13 +221,13 @@ export function mapFlightsToMultiLegReservation( lng: f.to.lon, timezone: f.to.tz, local_time: isLast ? arr.time : (nextDep?.time ?? null), - local_date: isLast ? arr.date : (next?.date || nextDep?.date || null), + local_date: isLast ? arr.date : next?.date || nextDep?.date || null, }); } else { needsReview = 1; } - const seat = f.seats?.find(s => s.userId) ?? f.seats?.[0]; + const seat = f.seats?.find((s) => s.userId) ?? f.seats?.[0]; const airline = entityName(f.airline); legs.push({ from: airportCode(f.from), @@ -270,7 +241,9 @@ export function mapFlightsToMultiLegReservation( ...(seat?.seatNumber ? { seat: seat.seatNumber } : {}), }); }); - endpoints.forEach((e, i) => { e.sequence = i; }); + endpoints.forEach((e, i) => { + e.sequence = i; + }); const last = flights[flights.length - 1]; const lastArr = localParts(last.arrivalScheduled ?? last.arrival, last.to?.tz ?? null); @@ -284,7 +257,7 @@ export function mapFlightsToMultiLegReservation( const aircraftCode = entityCode(first.aircraft); const metadata: Record = { legs, - airtrail_ids: flights.map(f => String(f.id)), + airtrail_ids: flights.map((f) => String(f.id)), }; if (airlineName) metadata.airline = airlineName; if (airlineCode) metadata.airline_code = airlineCode; @@ -294,8 +267,8 @@ export function mapFlightsToMultiLegReservation( if (toCode) metadata.arrival_airport = toCode; if (legs[0]?.seat) metadata.seat = legs[0].seat; - const route = [fromCode, ...flights.map(f => airportCode(f.to))].filter(Boolean).join(' → '); - const notes = [...new Set(flights.map(f => f.note?.trim()).filter((n): n is string => !!n))].join('\n') || null; + const route = [fromCode, ...flights.map((f) => airportCode(f.to))].filter(Boolean).join(' → '); + const notes = [...new Set(flights.map((f) => f.note?.trim()).filter((n): n is string => !!n))].join('\n') || null; return { title: route || first.flightNumber?.trim() || 'Flight', @@ -334,7 +307,7 @@ export function canonicalHash(raw: AirtrailFlightRaw): string { flightReason: raw.flightReason ?? null, note: raw.note ?? null, seats: (raw.seats ?? []) - .map(s => ({ + .map((s) => ({ userId: s.userId ?? null, guestName: s.guestName ?? null, seat: s.seat ?? null, diff --git a/server/src/services/distanceService.ts b/server/src/services/distanceService.ts index 559b81595..4b29dd885 100644 --- a/server/src/services/distanceService.ts +++ b/server/src/services/distanceService.ts @@ -1,7 +1,7 @@ import { db } from '../db/database'; // Great-circle distance between two points in kilometres. -function haversineKm(lat1: number, lng1: number, lat2: number, lng2: number): number { +export 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); diff --git a/server/src/services/reservationService.ts b/server/src/services/reservationService.ts index 7b1952437..de90348c8 100644 --- a/server/src/services/reservationService.ts +++ b/server/src/services/reservationService.ts @@ -19,6 +19,38 @@ export interface ReservationEndpoint { export type EndpointInput = Omit & { sequence?: number }; +export function notifyBookingChange( + tripId: string | number, + actorId: number, + booking: string, + type: string, +): void { + import('./notificationService') + .then(({ send }) => { + try { + const actor = db.prepare('SELECT email FROM users WHERE id = ?').get(actorId) as { email: string } | undefined; + if (!actor) return; + const trip = db.prepare('SELECT title FROM trips WHERE id = ?').get(tripId) as { title: string } | undefined; + send({ + event: 'booking_change', + actorId, + scope: 'trip', + targetId: Number(tripId), + params: { + trip: trip?.title || 'Untitled', + actor: actor.email, + booking, + type: type || 'booking', + tripId: String(tripId), + }, + }).catch(() => {}); + } catch { + // Notifications must never make the booking write fail. + } + }) + .catch(() => {}); +} + export function loadEndpointsByTrip(tripId: string | number): Map { const rows = db.prepare(` SELECT e.* FROM reservation_endpoints e diff --git a/server/src/services/timezoneService.ts b/server/src/services/timezoneService.ts new file mode 100644 index 000000000..5c5861153 --- /dev/null +++ b/server/src/services/timezoneService.ts @@ -0,0 +1,36 @@ +import tzlookup from 'tz-lookup'; + +/** Local calendar date and clock time for an instant in an IANA timezone. */ +export function localParts(iso: string | null, timezone: string | null): { date: string | null; time: string | null } { + if (!iso) return { date: null, time: null }; + try { + const date = new Date(iso); + if (Number.isNaN(date.getTime())) return { date: null, time: null }; + const parts = new Intl.DateTimeFormat('en-CA', { + timeZone: timezone || 'UTC', + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + hourCycle: 'h23', + }).formatToParts(date); + const value = (type: Intl.DateTimeFormatPartTypes) => parts.find((part) => part.type === type)?.value ?? ''; + const localDate = `${value('year')}-${value('month')}-${value('day')}`; + const localTime = `${value('hour')}:${value('minute')}`; + return /^\d{4}-\d{2}-\d{2}$/.test(localDate) ? { date: localDate, time: localTime } : { date: null, time: null }; + } catch { + return { date: null, time: null }; + } +} + +export function resolveTimeZone(lat: unknown, lng: unknown): string | null { + if (typeof lat !== 'number' || typeof lng !== 'number' || !Number.isFinite(lat) || !Number.isFinite(lng)) { + return null; + } + try { + return tzlookup(lat, lng); + } catch { + return null; + } +} diff --git a/server/src/services/transitItineraryService.ts b/server/src/services/transitItineraryService.ts new file mode 100644 index 000000000..3e1c2bbfd --- /dev/null +++ b/server/src/services/transitItineraryService.ts @@ -0,0 +1,287 @@ +import { haversineKm } from './distanceService'; +import type { EndpointInput } from './reservationService'; +import { localParts, resolveTimeZone } from './timezoneService'; +import { deriveTransitStats, type TransitItinerary, type TransitLeg } from './transitService'; + +import { z } from 'zod'; + +const MAX_ENDPOINT_DISTANCE_KM = 0.1; +const MAX_LEG_GAP_KM = 1; +const TIME_TOLERANCE_MS = 60_000; + +export const transitCoordinatesSchema = z.object({ + lat: z.number().min(-90).max(90), + lng: z.number().min(-180).max(180), +}); + +export const transitPlaceSchema = transitCoordinatesSchema.extend({ + name: z.string().min(1).max(300), +}); + +const transitStopSchema = transitPlaceSchema.extend({ + time: z.string().datetime({ offset: true }).nullable(), + scheduledTime: z.string().datetime({ offset: true }).nullable(), + track: z.string().max(100).nullable(), +}); + +// SCHEDULED_TRANSIT_MODES is the *request* whitelist — what a caller may filter by. The +// provider's response taxonomy is wider: MOTIS's default TRANSIT expands to +// TRAM,FERRY,AIRPLANE,BUS,COACH,RAIL,ODM,RIDE_SHARING,FUNICULAR,AERIAL_LIFT,OTHER, and a leg +// can also be a street mode (BIKE/CAR/RENTAL). Validating legs against the request whitelist +// silently dropped every itinerary containing e.g. an AIRPLANE leg. transitService already +// uppercases the mode and defaults it to WALK, so accept any mode token and let the +// "at least one non-WALK leg" rule below do the gating — exactly as the web client does, +// which treats mode as a free string. +const transitLegModes = z + .string() + .min(1) + .max(40) + .regex(/^[A-Z_]+$/); + +const colorSchema = z + .string() + .regex(/^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/) + .nullable(); + +const transitLegSchema = z.object({ + mode: transitLegModes, + from: transitStopSchema, + to: transitStopSchema, + duration: z.number().nonnegative(), + distance: z.number().nonnegative().nullable(), + headsign: z.string().max(300).nullable(), + line: z.string().max(100).nullable(), + lineColor: colorSchema, + lineTextColor: colorSchema, + agency: z.string().max(300).nullable(), + intermediateStops: z.number().int().nonnegative(), + geometry: z.string().max(60_000).nullable(), + geometryPrecision: z.number().int().min(0).max(10), +}); + +export function effectiveTransitStopTime(stop: { time?: string | null; scheduledTime?: string | null }): string | null { + return stop.time ?? stop.scheduledTime ?? null; +} + +export const transitItinerarySchema = z + .object({ + startTime: z.string().datetime({ offset: true }), + endTime: z.string().datetime({ offset: true }), + duration: z.number().nonnegative(), + transfers: z.number().int().nonnegative(), + walkSeconds: z.number().nonnegative(), + legs: z.array(transitLegSchema).min(1).max(20), + }) + .superRefine((itinerary, context) => { + const startTime = new Date(itinerary.startTime).getTime(); + const endTime = new Date(itinerary.endTime).getTime(); + if (endTime <= startTime) { + context.addIssue({ code: 'custom', message: 'endTime must be after startTime', path: ['endTime'] }); + } + if (!itinerary.legs.some((leg) => leg.mode !== 'WALK')) { + context.addIssue({ code: 'custom', message: 'At least one scheduled transit leg is required', path: ['legs'] }); + } + const maximumTransfers = Math.max(0, itinerary.legs.filter((leg) => leg.mode !== 'WALK').length - 1); + if (itinerary.transfers > maximumTransfers) { + context.addIssue({ + code: 'custom', + message: 'transfers exceeds the number of transit legs', + path: ['transfers'], + }); + } + const geometrySize = itinerary.legs.reduce((total, leg) => total + (leg.geometry?.length ?? 0), 0); + if (geometrySize > 60_000) { + context.addIssue({ code: 'custom', message: 'Combined transit geometry is too large', path: ['legs'] }); + } + itinerary.legs.forEach((leg, index) => { + const effectiveFromTime = effectiveTransitStopTime(leg.from); + const effectiveToTime = effectiveTransitStopTime(leg.to); + const fromTime = effectiveFromTime ? new Date(effectiveFromTime).getTime() : null; + const toTime = effectiveToTime ? new Date(effectiveToTime).getTime() : null; + if (fromTime === null || toTime === null) { + context.addIssue({ + code: 'custom', + message: 'Every leg requires departure and arrival times', + path: ['legs', index], + }); + return; + } + if (toTime < fromTime) { + context.addIssue({ code: 'custom', message: 'Leg arrival must not precede departure', path: ['legs', index] }); + } + if (Math.abs(toTime - fromTime - leg.duration * 1000) > TIME_TOLERANCE_MS) { + context.addIssue({ + code: 'custom', + message: 'Leg duration does not match its times', + path: ['legs', index, 'duration'], + }); + } + if (fromTime < startTime || toTime > endTime) { + context.addIssue({ + code: 'custom', + message: 'Leg times must stay within the itinerary', + path: ['legs', index], + }); + } + if (index === 0) return; + const previous = itinerary.legs[index - 1]; + if (haversineKm(previous.to.lat, previous.to.lng, leg.from.lat, leg.from.lng) > MAX_LEG_GAP_KM) { + context.addIssue({ code: 'custom', message: 'Adjacent legs are not connected', path: ['legs', index, 'from'] }); + } + const previousTime = effectiveTransitStopTime(previous.to); + if ( + previousTime && + effectiveFromTime && + new Date(effectiveFromTime).getTime() < new Date(previousTime).getTime() + ) { + context.addIssue({ + code: 'custom', + message: 'Adjacent legs are not chronological', + path: ['legs', index, 'from', 'time'], + }); + } + }); + const firstDeparture = effectiveTransitStopTime(itinerary.legs[0].from); + const lastArrival = effectiveTransitStopTime(itinerary.legs[itinerary.legs.length - 1].to); + if (!firstDeparture || Math.abs(new Date(firstDeparture).getTime() - startTime) > TIME_TOLERANCE_MS) { + context.addIssue({ + code: 'custom', + message: 'First leg must start with the itinerary', + path: ['legs', 0, 'from', 'time'], + }); + } + if (!lastArrival || Math.abs(new Date(lastArrival).getTime() - endTime) > TIME_TOLERANCE_MS) { + context.addIssue({ + code: 'custom', + message: 'Last leg must end with the itinerary', + path: ['legs', itinerary.legs.length - 1, 'to', 'time'], + }); + } + }); + +export type TransitPlaceInput = z.infer; + +export function transitCoordinatesMatch(expected: TransitPlaceInput, actual: TransitPlaceInput): boolean { + return haversineKm(expected.lat, expected.lng, actual.lat, actual.lng) <= MAX_ENDPOINT_DISTANCE_KM; +} + +export function cleanTransitItineraryNames( + itinerary: TransitItinerary, + fromName: string, + toName: string, +): TransitItinerary { + const clean = (name: string) => (name === 'START' ? fromName : name === 'END' ? toName : name); + return { + ...itinerary, + legs: itinerary.legs.map((leg) => ({ + ...leg, + from: { ...leg.from, name: clean(leg.from.name) }, + to: { ...leg.to, name: clean(leg.to.name) }, + })), + }; +} + +function transitLocalParts(iso: string, timezone: string): { date: string; time: string } { + const parts = localParts(iso, timezone); + if (!parts.date || !parts.time) throw new Error(`Unable to convert ${iso} to local time in ${timezone}.`); + return { date: parts.date, time: parts.time }; +} + +function timezoneAt(lat: number, lng: number): string { + const timezone = resolveTimeZone(lat, lng); + if (!timezone) throw new Error(`Unable to resolve timezone for ${lat},${lng}.`); + return timezone; +} + +export function buildTransitReservationParts( + from: TransitPlaceInput, + to: TransitPlaceInput, + itinerary: TransitItinerary, +) { + const fromTimezone = timezoneAt(from.lat, from.lng); + const toTimezone = timezoneAt(to.lat, to.lng); + const departure = transitLocalParts(itinerary.startTime, fromTimezone); + const arrival = transitLocalParts(itinerary.endTime, toTimezone); + const transitLegs = itinerary.legs.filter((leg) => leg.mode !== 'WALK'); + const endpoints: EndpointInput[] = [ + { + role: 'from', + sequence: 0, + name: from.name, + code: null, + lat: from.lat, + lng: from.lng, + timezone: fromTimezone, + local_date: departure.date, + local_time: departure.time, + }, + ]; + + transitLegs.slice(0, -1).forEach((leg, index) => { + const stop = leg.to; + const timezone = timezoneAt(stop.lat, stop.lng); + const stopTime = effectiveTransitStopTime(stop); + const local = stopTime ? transitLocalParts(stopTime, timezone) : null; + endpoints.push({ + role: 'stop', + sequence: index + 1, + name: stop.name, + code: null, + lat: stop.lat, + lng: stop.lng, + timezone, + local_date: local?.date ?? null, + local_time: local?.time ?? null, + }); + }); + + endpoints.push({ + role: 'to', + sequence: endpoints.length, + name: to.name, + code: null, + lat: to.lat, + lng: to.lng, + timezone: toTimezone, + local_date: arrival.date, + local_time: arrival.time, + }); + + const stats = deriveTransitStats(itinerary.startTime, itinerary.endTime, itinerary.legs, itinerary.transfers); + const metadata = { + transit: { + provider: 'transitous', + duration: stats.duration, + transfers: stats.transfers, + walk_seconds: stats.walkSeconds, + legs: itinerary.legs.map((leg: TransitLeg) => { + const fromTime = effectiveTransitStopTime(leg.from); + const toTime = effectiveTransitStopTime(leg.to); + return { + mode: leg.mode, + line: leg.line, + line_color: leg.lineColor, + line_text_color: leg.lineTextColor, + headsign: leg.headsign, + agency: leg.agency, + duration: leg.duration, + stops: leg.intermediateStops, + from: { + name: leg.from.name, + time: fromTime ? transitLocalParts(fromTime, timezoneAt(leg.from.lat, leg.from.lng)).time : null, + track: leg.from.track, + }, + to: { + name: leg.to.name, + time: toTime ? transitLocalParts(toTime, timezoneAt(leg.to.lat, leg.to.lng)).time : null, + track: leg.to.track, + }, + geometry: leg.geometry, + geometry_precision: leg.geometryPrecision, + }; + }), + }, + }; + + return { endpoints, metadata }; +} diff --git a/server/src/services/transitService.ts b/server/src/services/transitService.ts index 1dfe7b527..028814332 100644 --- a/server/src/services/transitService.ts +++ b/server/src/services/transitService.ts @@ -1,5 +1,5 @@ -import { getAppUrl } from './notifications'; import { buildUserAgent } from './mapsService'; +import { getAppUrl } from './notifications'; /** * Public transit routing (#1065) backed by Transitous (api.transitous.org), the @@ -14,17 +14,35 @@ import { buildUserAgent } from './mapsService'; */ const TRANSIT_API_BASE = (process.env.TRANSIT_API_URL || 'https://api.transitous.org').replace(/\/+$/, ''); -const UA = buildUserAgent(getAppUrl()); +let userAgent: string | null = null; + +function getUserAgent(): string { + userAgent ??= buildUserAgent(getAppUrl()); + return userAgent; +} // Modes the client may request — a strict whitelist so the proxy can't be used // to smuggle arbitrary query values upstream. TRANSIT covers everything; the // others let the user filter (RAIL already includes subway/suburban etc.). -const ALLOWED_MODES = new Set([ - 'TRANSIT', 'BUS', 'COACH', 'TRAM', 'SUBWAY', 'RAIL', 'FERRY', 'FUNICULAR', 'AERIAL_LIFT', +export const SCHEDULED_TRANSIT_MODES = [ + 'BUS', + 'COACH', + 'TRAM', + 'SUBWAY', + 'RAIL', + 'FERRY', + 'FUNICULAR', + 'AERIAL_LIFT', // Fine-grained rail modes so "train without subway" is expressible (RAIL // itself includes SUBWAY per the MOTIS mode taxonomy). - 'HIGHSPEED_RAIL', 'LONG_DISTANCE', 'NIGHT_RAIL', 'REGIONAL_RAIL', 'SUBURBAN', -]); + 'HIGHSPEED_RAIL', + 'LONG_DISTANCE', + 'NIGHT_RAIL', + 'REGIONAL_RAIL', + 'SUBURBAN', +] as const; + +const ALLOWED_MODES = new Set(['TRANSIT', ...SCHEDULED_TRANSIT_MODES]); // Short-lived response cache: planning is the expensive call per the Transitous // usage policy, and a user toggling filters re-requests identical plans. @@ -35,7 +53,10 @@ const cache = new Map(); function cacheGet(key: string): unknown | null { const hit = cache.get(key); if (!hit) return null; - if (Date.now() - hit.at > CACHE_TTL) { cache.delete(key); return null; } + if (Date.now() - hit.at > CACHE_TTL) { + cache.delete(key); + return null; + } return hit.data; } @@ -57,7 +78,7 @@ function isCoord(v: string): boolean { async function upstream(path: string, params: URLSearchParams): Promise { const url = `${TRANSIT_API_BASE}${path}?${params}`; - const res = await fetch(url, { headers: { 'User-Agent': UA, Accept: 'application/json' } }); + const res = await fetch(url, { headers: { 'User-Agent': getUserAgent(), Accept: 'application/json' } }); if (!res.ok) { const err = new Error(`Transit provider error (HTTP ${res.status})`) as Error & { status: number }; err.status = res.status === 429 ? 429 : 502; @@ -80,7 +101,11 @@ export interface TransitPlace { export async function geocode(query: string, language?: string, near?: string): Promise<{ results: TransitPlace[] }> { const text = (query || '').trim(); if (text.length < 2) return { results: [] }; - if (text.length > 200) { const e = new Error('Query too long') as Error & { status: number }; e.status = 400; throw e; } + if (text.length > 200) { + const e = new Error('Query too long') as Error & { status: number }; + e.status = 400; + throw e; + } const params = new URLSearchParams({ text }); if (language) params.set('language', language.slice(0, 5)); @@ -91,7 +116,10 @@ export async function geocode(query: string, language?: string, near?: string): if (cached) return cached as { results: TransitPlace[] }; const raw = (await upstream('/api/v1/geocode', params)) as Array<{ - name?: string; lat?: number; lon?: number; type?: string; + name?: string; + lat?: number; + lon?: number; + type?: string; areas?: Array<{ name?: string; matched?: boolean; default?: boolean }>; }>; @@ -152,6 +180,22 @@ export interface PlanQuery { maxTransfers?: number; } +export function deriveTransitStats( + startTime: string, + endTime: string, + legs: TransitLeg[], + reportedTransfers?: number, +): Pick { + return { + duration: Math.max(0, Math.round((new Date(endTime).getTime() - new Date(startTime).getTime()) / 1000)), + transfers: + typeof reportedTransfers === 'number' + ? reportedTransfers + : Math.max(0, legs.filter((leg) => leg.mode !== 'WALK').length - 1), + walkSeconds: legs.filter((leg) => leg.mode === 'WALK').reduce((total, leg) => total + leg.duration, 0), + }; +} + // GTFS colors come as bare hex ("FF0000"), with hash, or empty — normalise to // a #-prefixed value or null so the client can use them in CSS directly. function safeColor(v: unknown): string | null { @@ -161,10 +205,15 @@ function safeColor(v: unknown): string | null { } interface MotisPlaceRaw { - name?: string; lat?: number; lon?: number; - departure?: string; arrival?: string; - scheduledDeparture?: string; scheduledArrival?: string; - track?: string; scheduledTrack?: string; + name?: string; + lat?: number; + lon?: number; + departure?: string; + arrival?: string; + scheduledDeparture?: string; + scheduledArrival?: string; + track?: string; + scheduledTrack?: string; } function mapStop(p: MotisPlaceRaw | undefined, kind: 'departure' | 'arrival'): TransitLegStop { @@ -180,7 +229,11 @@ function mapStop(p: MotisPlaceRaw | undefined, kind: 'departure' | 'arrival'): T /** Route search between two coordinates. Returns compact itineraries for the picker. */ export async function plan(q: PlanQuery): Promise<{ itineraries: TransitItinerary[] }> { - const bad = (msg: string) => { const e = new Error(msg) as Error & { status: number }; e.status = 400; throw e; }; + const bad = (msg: string) => { + const e = new Error(msg) as Error & { status: number }; + e.status = 400; + throw e; + }; if (!q.from || !isCoord(q.from)) bad('from must be "lat,lng"'); if (!q.to || !isCoord(q.to)) bad('to must be "lat,lng"'); @@ -194,7 +247,10 @@ export async function plan(q: PlanQuery): Promise<{ itineraries: TransitItinerar if (q.arriveBy) params.set('arriveBy', 'true'); if (q.modes) { - const modes = q.modes.split(',').map((m) => m.trim().toUpperCase()).filter(Boolean); + const modes = q.modes + .split(',') + .map((m) => m.trim().toUpperCase()) + .filter(Boolean); if (modes.some((m) => !ALLOWED_MODES.has(m))) bad('unsupported transit mode'); if (modes.length > 0) params.set('transitModes', modes.join(',')); } @@ -213,11 +269,22 @@ export async function plan(q: PlanQuery): Promise<{ itineraries: TransitItinerar const raw = (await upstream('/api/v6/plan', params)) as { itineraries?: Array<{ - duration?: number; startTime?: string; endTime?: string; transfers?: number; + duration?: number; + startTime?: string; + endTime?: string; + transfers?: number; legs?: Array<{ - mode?: string; duration?: number; distance?: number; headsign?: string; - routeShortName?: string; displayName?: string; routeColor?: string; routeTextColor?: string; - agencyName?: string; from?: MotisPlaceRaw; to?: MotisPlaceRaw; + mode?: string; + duration?: number; + distance?: number; + headsign?: string; + routeShortName?: string; + displayName?: string; + routeColor?: string; + routeTextColor?: string; + agencyName?: string; + from?: MotisPlaceRaw; + to?: MotisPlaceRaw; intermediateStops?: unknown[]; legGeometry?: { points?: string; precision?: number }; }>; @@ -241,17 +308,17 @@ export async function plan(q: PlanQuery): Promise<{ itineraries: TransitItinerar geometry: leg.legGeometry?.points || null, geometryPrecision: leg.legGeometry?.precision ?? 6, })); - const walkSeconds = legs.filter((l) => l.mode === 'WALK').reduce((a, l) => a + l.duration, 0); - return [{ - startTime: it.startTime, - endTime: it.endTime, - // Wall-clock duration (start→end) so waits/transfers count — summing leg - // run-times would understate the journey and mis-slot it in the timeline. - duration: Math.max(0, Math.round((new Date(it.endTime).getTime() - new Date(it.startTime).getTime()) / 1000)), - transfers: typeof it.transfers === 'number' ? it.transfers : Math.max(0, legs.filter((l) => l.mode !== 'WALK').length - 1), - walkSeconds, - legs, - }]; + const stats = deriveTransitStats(it.startTime, it.endTime, legs, it.transfers); + return [ + { + startTime: it.startTime, + endTime: it.endTime, + // Wall-clock duration (start→end) so waits/transfers count — summing leg + // run-times would understate the journey and mis-slot it in the timeline. + ...stats, + legs, + }, + ]; }); const data = { itineraries }; diff --git a/server/src/services/tripService.ts b/server/src/services/tripService.ts index 59728f80b..65aa7d99d 100644 --- a/server/src/services/tripService.ts +++ b/server/src/services/tripService.ts @@ -1,5 +1,4 @@ import path from 'path'; -import tzlookup from 'tz-lookup'; import { avatarUrl } from './avatarUrl'; import fs from 'fs'; import { randomUUID } from 'crypto'; @@ -13,6 +12,7 @@ import { listItems as listPackingItems } from './packingService'; import { listReservations, loadEndpointsByTrip, resyncReservationDays } from './reservationService'; import { listNotes as listCollabNotes } from './collabService'; import { shiftOwnerEntriesForTripWindow } from './vacayService'; +import { resolveTimeZone } from './timezoneService'; export const MS_PER_DAY = 86400000; export const MAX_TRIP_DAYS = 365; @@ -563,25 +563,6 @@ function foldICS(ics: string): string { // Timed events must carry an explicit IANA zone; a bare "YYYYMMDDTHHMMSS" is an // RFC 5545 "floating" time that clients render in the *subscriber's* zone (#1453). -// Resolve an IANA zone (e.g. "Europe/Paris") from coordinates. Returns null for -// missing/invalid coords instead of throwing — tz-lookup throws RangeError when -// lat/lng are out of range. -function resolveZone(lat: unknown, lng: unknown): string | null { - if ( - typeof lat !== 'number' || - typeof lng !== 'number' || - !Number.isFinite(lat) || - !Number.isFinite(lng) - ) { - return null; - } - try { - return tzlookup(lat, lng); - } catch { - return null; - } -} - // A stored/plugin-provided timezone (e.g. a transport endpoint's `timezone`) is a // free string that need not be a real IANA zone. Intl.DateTimeFormat throws a // RangeError on an unknown zone, which — via buildVTimezone → tzOffsetString — @@ -737,7 +718,7 @@ export function exportICS(tripId: string | number): { ics: string; filename: str // Timed assignments → individual events for (const a of timed) { - const zone = resolveZone(a.place_lat, a.place_lng); + const zone = resolveTimeZone(a.place_lat, a.place_lng); ics += `BEGIN:VEVENT\r\nUID:${uid(a.id, 'assign')}\r\nDTSTAMP:${now}\r\n`; ics += dtLine('DTSTART', a.effective_time, zone, day.date + 'T00:00'); if (a.effective_end_time) { @@ -797,7 +778,7 @@ export function exportICS(tripId: string | number): { ics: string; filename: str if (!isDate(datePart)) return null; // time-only (relative "Day N" trips) if (r.reservation_time.includes('T')) { // Hotels/restaurants: derive the zone from the linked place, if any. - const zone = resolveZone(r.place_lat, r.place_lng); + const zone = resolveTimeZone(r.place_lat, r.place_lng); let out = dtLine('DTSTART', r.reservation_time, zone); if (r.reservation_end_time) { const endDt = fmtDateTime(r.reservation_end_time, r.reservation_time); @@ -817,10 +798,10 @@ export function exportICS(tripId: string | number): { ics: string; filename: str if (isTime(first.local_time)) { // Transport: departure endpoint zone drives DTSTART, arrival drives DTEND. // Prefer the stored IANA zone; fall back to the endpoint's coordinates. - const startZone = first.timezone || resolveZone(first.lat, first.lng); + const startZone = first.timezone || resolveTimeZone(first.lat, first.lng); let out = dtLine('DTSTART', `${first.local_date}T${first.local_time}`, startZone); if (last !== first && isDate(last.local_date) && isTime(last.local_time)) { - const endZone = last.timezone || resolveZone(last.lat, last.lng); + const endZone = last.timezone || resolveTimeZone(last.lat, last.lng); out += dtLine('DTEND', `${last.local_date}T${last.local_time}`, endZone); } return out; diff --git a/server/tests/e2e/reservations.e2e.test.ts b/server/tests/e2e/reservations.e2e.test.ts index 3261c26be..01dd01196 100644 --- a/server/tests/e2e/reservations.e2e.test.ts +++ b/server/tests/e2e/reservations.e2e.test.ts @@ -4,12 +4,15 @@ * budget services, the permission check, canAccessTrip and the WebSocket * broadcast are mocked. */ -import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest'; -import request from 'supertest'; +import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter'; +import { ReservationsModule } from '../../src/nest/reservations/reservations.module'; +import { seedUser, sessionCookie } from './harness'; +import { Test } from '@nestjs/testing'; + import cookieParser from 'cookie-parser'; import type { Server } from 'http'; -import { Test } from '@nestjs/testing'; -import { seedUser, sessionCookie } from './harness'; +import request from 'supertest'; +import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest'; const { db } = vi.hoisted(() => { // eslint-disable-next-line @typescript-eslint/no-require-imports @@ -24,7 +27,12 @@ const { db } = vi.hoisted(() => { const { canAccessTrip } = vi.hoisted(() => ({ canAccessTrip: vi.fn() })); vi.mock('../../src/db/database', () => ({ - db, canAccessTrip, isOwner: vi.fn(() => true), getPlaceWithTags: vi.fn(), closeDb: () => {}, reinitialize: () => {}, + db, + canAccessTrip, + isOwner: vi.fn(() => true), + getPlaceWithTags: vi.fn(), + closeDb: () => {}, + reinitialize: () => {}, })); vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() })); vi.mock('../../src/services/notificationService', () => ({ send: vi.fn().mockResolvedValue(undefined) })); @@ -34,22 +42,35 @@ vi.mock('../../src/services/permissions', () => ({ checkPermission })); const { resv, budget, day } = vi.hoisted(() => ({ resv: { - verifyTripAccess: vi.fn(), listReservations: vi.fn(), createReservation: vi.fn(), updatePositions: vi.fn(), - getReservation: vi.fn(), updateReservation: vi.fn(), deleteReservation: vi.fn(), getUpcomingReservations: vi.fn(), + verifyTripAccess: vi.fn(), + listReservations: vi.fn(), + createReservation: vi.fn(), + updatePositions: vi.fn(), + getReservation: vi.fn(), + updateReservation: vi.fn(), + deleteReservation: vi.fn(), + getUpcomingReservations: vi.fn(), + notifyBookingChange: vi.fn(), + }, + budget: { + createBudgetItem: vi.fn(), + updateBudgetItem: vi.fn(), + deleteBudgetItem: vi.fn(), + linkBudgetItemToReservation: vi.fn(), }, - budget: { createBudgetItem: vi.fn(), updateBudgetItem: vi.fn(), deleteBudgetItem: vi.fn(), linkBudgetItemToReservation: vi.fn() }, day: { - listAccommodations: vi.fn(), validateAccommodationRefs: vi.fn(), createAccommodation: vi.fn(), - getAccommodation: vi.fn(), updateAccommodation: vi.fn(), deleteAccommodation: vi.fn(), + listAccommodations: vi.fn(), + validateAccommodationRefs: vi.fn(), + createAccommodation: vi.fn(), + getAccommodation: vi.fn(), + updateAccommodation: vi.fn(), + deleteAccommodation: vi.fn(), }, })); vi.mock('../../src/services/reservationService', () => resv); vi.mock('../../src/services/budgetService', () => budget); vi.mock('../../src/services/dayService', () => day); -import { ReservationsModule } from '../../src/nest/reservations/reservations.module'; -import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter'; - describe('Reservations + accommodations e2e (real auth guard + temp SQLite)', () => { let server: Server; let app: Awaited>; @@ -113,9 +134,13 @@ describe('Reservations + accommodations e2e (real auth guard + temp SQLite)', () }); it('201 create reservation, 400 without title', async () => { - const ok = await request(server).post('/api/trips/5/reservations').set('Cookie', sessionCookie(1)).send({ title: 'Hotel' }); + const ok = await request(server) + .post('/api/trips/5/reservations') + .set('Cookie', sessionCookie(1)) + .send({ title: 'Hotel' }); expect(ok.status).toBe(201); expect(ok.body).toEqual({ reservation: { id: 9, title: 'Hotel' } }); + expect(resv.notifyBookingChange).toHaveBeenCalledWith('5', 1, 'Hotel', ''); const bad = await request(server).post('/api/trips/5/reservations').set('Cookie', sessionCookie(1)).send({}); expect(bad.status).toBe(400); expect(bad.body).toEqual({ error: 'Title is required' }); @@ -125,7 +150,10 @@ describe('Reservations + accommodations e2e (real auth guard + temp SQLite)', () const list = await request(server).get('/api/trips/5/accommodations').set('Cookie', sessionCookie(1)); expect(list.status).toBe(200); expect(list.body).toEqual({ accommodations: [{ id: 1 }] }); - const create = await request(server).post('/api/trips/5/accommodations').set('Cookie', sessionCookie(1)).send({ place_id: 2, start_day_id: 10, end_day_id: 11 }); + const create = await request(server) + .post('/api/trips/5/accommodations') + .set('Cookie', sessionCookie(1)) + .send({ place_id: 2, start_day_id: 10, end_day_id: 11 }); expect(create.status).toBe(201); expect(create.body).toEqual({ accommodation: { id: 9 } }); }); @@ -138,7 +166,10 @@ describe('Reservations + accommodations e2e (real auth guard + temp SQLite)', () }); it('400 accommodation create without refs', async () => { - const res = await request(server).post('/api/trips/5/accommodations').set('Cookie', sessionCookie(1)).send({ place_id: 2 }); + const res = await request(server) + .post('/api/trips/5/accommodations') + .set('Cookie', sessionCookie(1)) + .send({ place_id: 2 }); expect(res.status).toBe(400); expect(res.body).toEqual({ error: 'place_id, start_day_id, and end_day_id are required' }); }); diff --git a/server/tests/unit/mcp/tools-transit.test.ts b/server/tests/unit/mcp/tools-transit.test.ts new file mode 100644 index 000000000..ca2d5ee7c --- /dev/null +++ b/server/tests/unit/mcp/tools-transit.test.ts @@ -0,0 +1,521 @@ +import { runMigrations } from '../../../src/db/migrations'; +import { createTables } from '../../../src/db/schema'; +import { invalidatePermissionsCache, savePermissions } from '../../../src/services/permissions'; +import { addTripMember, createDay, createTrip, createUser } from '../../helpers/factories'; +import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness'; +import { resetTestDb } from '../../helpers/test-db'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +const { testDb, dbMock } = vi.hoisted(() => { + const Database = require('better-sqlite3'); + const db = new Database(':memory:'); + db.exec('PRAGMA foreign_keys = ON'); + const mock = { + db, + closeDb: () => {}, + reinitialize: () => {}, + getPlaceWithTags: () => null, + canAccessTrip: (tripId: number, userId: number) => + db + .prepare( + 'SELECT t.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), + isOwner: (tripId: number, userId: number) => + !!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId), + }; + return { testDb: db, dbMock: mock }; +}); + +const { geocodeMock, planMock, broadcastMock, notifyBookingChangeMock } = vi.hoisted(() => ({ + geocodeMock: vi.fn(), + planMock: vi.fn(), + broadcastMock: vi.fn(), + notifyBookingChangeMock: vi.fn(), +})); + +vi.mock('../../../src/db/database', () => dbMock); +vi.mock('../../../src/services/transitService', async (importOriginal) => ({ + ...(await importOriginal()), + geocode: geocodeMock, + plan: planMock, +})); +vi.mock('../../../src/websocket', () => ({ broadcast: broadcastMock })); +vi.mock('../../../src/services/reservationService', async (importOriginal) => ({ + ...(await importOriginal()), + notifyBookingChange: notifyBookingChangeMock, +})); +vi.mock('../../../src/config', () => ({ + JWT_SECRET: 'test-jwt-secret-for-trek-testing-only', + ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2', + updateJwtSecret: () => {}, +})); + +const from = { name: 'Namba', lat: 34.667, lng: 135.501 }; +const to = { name: 'Umeda', lat: 34.702, lng: 135.496 }; +const itinerary = { + startTime: '2026-12-03T00:00:00Z', + endTime: '2026-12-03T00:30:00Z', + duration: 1800, + transfers: 0, + walkSeconds: 300, + legs: [ + { + mode: 'WALK', + from: { ...from, name: 'START', time: '2026-12-03T00:00:00Z', scheduledTime: null, track: null }, + to: { + name: 'Namba Station', + lat: 34.666, + lng: 135.5, + time: '2026-12-03T00:05:00Z', + scheduledTime: null, + track: null, + }, + duration: 300, + distance: 300, + headsign: null, + line: null, + lineColor: null, + lineTextColor: null, + agency: null, + intermediateStops: 0, + geometry: null, + geometryPrecision: 6, + }, + { + mode: 'SUBWAY', + from: { + name: 'Namba Station', + lat: 34.666, + lng: 135.5, + time: '2026-12-03T00:05:00Z', + scheduledTime: null, + track: '1', + }, + to: { ...to, name: 'END', time: '2026-12-03T00:30:00Z', scheduledTime: null, track: '2' }, + duration: 1500, + distance: 5000, + headsign: 'Umeda', + line: 'M', + lineColor: '#E5171F', + lineTextColor: '#FFFFFF', + agency: 'Osaka Metro', + intermediateStops: 3, + geometry: 'encoded', + geometryPrecision: 6, + }, + ], +}; + +beforeAll(() => { + createTables(testDb); + runMigrations(testDb); +}); + +beforeEach(() => { + resetTestDb(testDb); + geocodeMock.mockReset(); + planMock.mockReset(); + broadcastMock.mockReset(); + notifyBookingChangeMock.mockReset(); + delete process.env.DEMO_MODE; + invalidatePermissionsCache(); +}); + +afterAll(() => testDb.close()); + +async function withHarness(userId: number, scopes: string[] | null, fn: (harness: McpHarness) => Promise) { + const harness = await createMcpHarness({ userId, scopes, withResources: false }); + try { + await fn(harness); + } finally { + await harness.cleanup(); + } +} + +describe('MCP transit tools', () => { + it('registers search tools for geo scope and create tool for reservations scope', async () => { + const { user } = createUser(testDb); + await withHarness(user.id, ['geo:read'], async (harness) => { + const names = (await harness.client.listTools()).tools.map((tool) => tool.name); + expect(names).toContain('search_transit_stops'); + expect(names).toContain('search_transit_routes'); + expect(names).not.toContain('create_transit_journey'); + }); + await withHarness(user.id, ['reservations:write'], async (harness) => { + const tools = (await harness.client.listTools()).tools; + const names = tools.map((tool) => tool.name); + expect(names).toContain('create_transit_journey'); + expect(names).not.toContain('search_transit_routes'); + expect(tools.find((tool) => tool.name === 'create_transit_journey')?.annotations?.openWorldHint).toBe(true); + }); + }); + + it('forwards stop and route searches and replaces provider endpoint names', async () => { + const { user } = createUser(testDb); + geocodeMock.mockResolvedValue({ results: [from] }); + planMock.mockResolvedValue({ + itineraries: [ + itinerary, + { ...itinerary, legs: [itinerary.legs[0]] }, + { + ...itinerary, + legs: itinerary.legs.map((leg, index) => (index === 0 ? { ...leg, from: { ...leg.from, lat: 35.5 } } : leg)), + }, + ], + }); + await withHarness(user.id, ['geo:read'], async (harness) => { + const stops = parseToolResult( + await harness.client.callTool({ + name: 'search_transit_stops', + arguments: { query: 'Namba', language: 'ja', near: { lat: 34.67, lng: 135.5 } }, + }), + ) as any; + expect(stops.results[0].name).toBe('Namba'); + expect(geocodeMock).toHaveBeenCalledWith('Namba', 'ja', '34.67,135.5'); + + const routes = parseToolResult( + await harness.client.callTool({ + name: 'search_transit_routes', + arguments: { from, to, time: '2026-12-03T09:00:00+09:00', modes: ['SUBWAY'] }, + }), + ) as any; + expect(routes.itineraries[0].legs[0].from.name).toBe('Namba'); + expect(routes.itineraries[0].legs[1].to.name).toBe('Umeda'); + expect(routes.itineraries).toHaveLength(1); + expect(planMock).toHaveBeenCalledWith(expect.objectContaining({ modes: 'SUBWAY' })); + + const invalidNear = await harness.client.callTool({ + name: 'search_transit_stops', + arguments: { query: 'Namba', near: { lat: 999, lng: 999 } }, + }); + expect(invalidNear.isError).toBe(true); + }); + }); + + it('persists a selected itinerary with local dates, endpoints, and transit metadata', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id, { start_date: '2026-12-03', end_date: '2026-12-04' }); + const day = testDb.prepare('SELECT * FROM days WHERE trip_id = ? AND date = ?').get(trip.id, '2026-12-03') as any; + await withHarness(user.id, ['reservations:write'], async (harness) => { + const result = parseToolResult( + await harness.client.callTool({ + name: 'create_transit_journey', + arguments: { + tripId: trip.id, + dayId: day.id, + from, + to, + itinerary: { ...itinerary, duration: 1, walkSeconds: 1 }, + }, + }), + ) as any; + expect(result.reservation.type).toBe('transit'); + expect(result.reservation.status).toBe('confirmed'); + expect(result.reservation.reservation_time).toBe('2026-12-03T09:00'); + expect(result.reservation.endpoints).toHaveLength(2); + expect(result.reservation.endpoints[0].timezone).toBe('Asia/Tokyo'); + const metadata = JSON.parse(result.reservation.metadata); + expect(metadata.transit.provider).toBe('transitous'); + expect(metadata.transit.duration).toBe(1800); + expect(metadata.transit.transfers).toBe(0); + expect(metadata.transit.walk_seconds).toBe(300); + expect(metadata.transit.legs[1].line_color).toBe('#E5171F'); + expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'reservation:created', expect.anything()); + expect(notifyBookingChangeMock).toHaveBeenCalledWith(trip.id, user.id, 'Namba → Umeda', 'transit'); + }); + }); + + it('rejects dateless, mismatched, and out-of-range journey dates', async () => { + const { user } = createUser(testDb); + const datelessTrip = createTrip(testDb, user.id); + const datelessDay = createDay(testDb, datelessTrip.id); + const datedTrip = createTrip(testDb, user.id, { start_date: '2026-12-02', end_date: '2026-12-03' }); + const datedDay = testDb + .prepare('SELECT * FROM days WHERE trip_id = ? AND date = ?') + .get(datedTrip.id, '2026-12-02') as any; + await withHarness(user.id, ['reservations:write'], async (harness) => { + const dateless = await harness.client.callTool({ + name: 'create_transit_journey', + arguments: { tripId: datelessTrip.id, dayId: datelessDay.id, from, to, itinerary }, + }); + expect(dateless.isError).toBe(true); + expect((dateless.content[0] as any).text).toContain('dated trip day'); + + const mismatch = await harness.client.callTool({ + name: 'create_transit_journey', + arguments: { tripId: datedTrip.id, dayId: datedDay.id, from, to, itinerary }, + }); + expect(mismatch.isError).toBe(true); + expect((mismatch.content[0] as any).text).toContain('departs on 2026-12-03'); + + const nextDayItinerary = { + ...itinerary, + endTime: '2026-12-04T00:30:00Z', + legs: itinerary.legs.map((leg, index) => + index === itinerary.legs.length - 1 + ? { ...leg, duration: 87_900, to: { ...leg.to, time: '2026-12-04T00:30:00Z' } } + : leg, + ), + }; + const startDay = testDb + .prepare('SELECT * FROM days WHERE trip_id = ? AND date = ?') + .get(datedTrip.id, '2026-12-03') as any; + const outside = await harness.client.callTool({ + name: 'create_transit_journey', + arguments: { tripId: datedTrip.id, dayId: startDay.id, from, to, itinerary: nextDayItinerary }, + }); + expect(outside.isError).toBe(true); + expect((outside.content[0] as any).text).toContain('No trip day exists'); + }); + }); + + it('rejects malformed provider data before persistence', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id, { start_date: '2026-12-03', end_date: '2026-12-03' }); + const day = testDb.prepare('SELECT * FROM days WHERE trip_id = ?').get(trip.id) as any; + const allWalk = { ...itinerary, legs: [itinerary.legs[0]] }; + await withHarness(user.id, ['reservations:write'], async (harness) => { + const result = await harness.client.callTool({ + name: 'create_transit_journey', + arguments: { tripId: trip.id, dayId: day.id, from, to, itinerary: allWalk }, + }); + expect(result.isError).toBe(true); + expect(testDb.prepare("SELECT COUNT(*) AS count FROM reservations WHERE type = 'transit'").get()).toEqual({ + count: 0, + }); + + const wrongDestination = { + ...itinerary, + legs: itinerary.legs.map((leg, index) => + index === itinerary.legs.length - 1 ? { ...leg, to: { ...leg.to, lat: 35.0 } } : leg, + ), + }; + const mismatch = await harness.client.callTool({ + name: 'create_transit_journey', + arguments: { tripId: trip.id, dayId: day.id, from, to, itinerary: wrongDestination }, + }); + expect(mismatch.isError).toBe(true); + expect((mismatch.content[0] as any).text).toContain('does not match'); + expect(testDb.prepare("SELECT COUNT(*) AS count FROM reservations WHERE type = 'transit'").get()).toEqual({ + count: 0, + }); + + const invalidTime = { + ...itinerary, + legs: itinerary.legs.map((leg, index) => + index === 0 ? { ...leg, from: { ...leg.from, time: '09:00' } } : leg, + ), + }; + const malformedTime = await harness.client.callTool({ + name: 'create_transit_journey', + arguments: { tripId: trip.id, dayId: day.id, from, to, itinerary: invalidTime }, + }); + expect(malformedTime.isError).toBe(true); + + const excessiveTransfers = await harness.client.callTool({ + name: 'create_transit_journey', + arguments: { tripId: trip.id, dayId: day.id, from, to, itinerary: { ...itinerary, transfers: 9 } }, + }); + expect(excessiveTransfers.isError).toBe(true); + + const unanchored = await harness.client.callTool({ + name: 'create_transit_journey', + arguments: { + tripId: trip.id, + dayId: day.id, + from, + to, + itinerary: { ...itinerary, endTime: '2026-12-04T00:30:00Z' }, + }, + }); + expect(unanchored.isError).toBe(true); + + const wrongDuration = await harness.client.callTool({ + name: 'create_transit_journey', + arguments: { + tripId: trip.id, + dayId: day.id, + from, + to, + itinerary: { + ...itinerary, + legs: itinerary.legs.map((leg, index) => (index === 0 ? { ...leg, duration: 1 } : leg)), + }, + }, + }); + expect(wrongDuration.isError).toBe(true); + + const overlappingLegs = await harness.client.callTool({ + name: 'create_transit_journey', + arguments: { + tripId: trip.id, + dayId: day.id, + from, + to, + itinerary: { + ...itinerary, + legs: itinerary.legs.map((leg, index) => + index === 0 ? { ...leg, duration: 600, to: { ...leg.to, time: '2026-12-03T00:10:00Z' } } : leg, + ), + }, + }, + }); + expect(overlappingLegs.isError).toBe(true); + + const missingTimes = await harness.client.callTool({ + name: 'create_transit_journey', + arguments: { + tripId: trip.id, + dayId: day.id, + from, + to, + itinerary: { + ...itinerary, + legs: itinerary.legs.map((leg, index) => + index === 1 ? { ...leg, from: { ...leg.from, time: null, scheduledTime: null } } : leg, + ), + }, + }, + }); + expect(missingTimes.isError).toBe(true); + + const disconnected = { + ...itinerary, + legs: itinerary.legs.map((leg, index) => (index === 1 ? { ...leg, from: { ...leg.from, lat: 35.5 } } : leg)), + }; + const disconnectedResult = await harness.client.callTool({ + name: 'create_transit_journey', + arguments: { tripId: trip.id, dayId: day.id, from, to, itinerary: disconnected }, + }); + expect(disconnectedResult.isError).toBe(true); + expect(testDb.prepare("SELECT COUNT(*) AS count FROM reservations WHERE type = 'transit'").get()).toEqual({ + count: 0, + }); + }); + }); + + it('enforces demo, trip access, and reservation permissions', async () => { + const { user: owner } = createUser(testDb); + const { user: demo } = createUser(testDb, { email: 'demo@trek.app' }); + const { user: stranger } = createUser(testDb); + const { user: member } = createUser(testDb); + const trip = createTrip(testDb, owner.id, { start_date: '2026-12-03', end_date: '2026-12-03' }); + const day = testDb.prepare('SELECT * FROM days WHERE trip_id = ?').get(trip.id) as any; + addTripMember(testDb, trip.id, demo.id); + addTripMember(testDb, trip.id, member.id); + + process.env.DEMO_MODE = 'true'; + await withHarness(demo.id, ['reservations:write'], async (harness) => { + const result = await harness.client.callTool({ + name: 'create_transit_journey', + arguments: { tripId: trip.id, dayId: day.id, from, to, itinerary }, + }); + expect(result.isError).toBe(true); + expect((result.content[0] as any).text).toContain('demo mode'); + }); + delete process.env.DEMO_MODE; + + await withHarness(stranger.id, ['reservations:write'], async (harness) => { + const result = await harness.client.callTool({ + name: 'create_transit_journey', + arguments: { tripId: trip.id, dayId: day.id, from, to, itinerary }, + }); + expect(result.isError).toBe(true); + expect((result.content[0] as any).text).toContain('access denied'); + }); + + savePermissions({ reservation_edit: 'trip_owner' }); + await withHarness(member.id, ['reservations:write'], async (harness) => { + const result = await harness.client.callTool({ + name: 'create_transit_journey', + arguments: { tripId: trip.id, dayId: day.id, from, to, itinerary }, + }); + expect(result.isError).toBe(true); + expect((result.content[0] as any).text).toContain('permission'); + }); + + expect(testDb.prepare("SELECT COUNT(*) AS count FROM reservations WHERE type = 'transit'").get()).toEqual({ + count: 0, + }); + expect(broadcastMock).not.toHaveBeenCalled(); + expect(notifyBookingChangeMock).not.toHaveBeenCalled(); + }); + + it('uses scheduled times when realtime stop times are unavailable', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id, { start_date: '2026-12-03', end_date: '2026-12-03' }); + const day = testDb.prepare('SELECT * FROM days WHERE trip_id = ?').get(trip.id) as any; + const scheduledOnly = { + ...itinerary, + legs: itinerary.legs.map((leg) => ({ + ...leg, + from: { ...leg.from, time: null, scheduledTime: leg.from.time }, + to: { ...leg.to, time: null, scheduledTime: leg.to.time }, + })), + }; + + await withHarness(user.id, ['reservations:write'], async (harness) => { + const result = parseToolResult( + await harness.client.callTool({ + name: 'create_transit_journey', + arguments: { tripId: trip.id, dayId: day.id, from, to, itinerary: scheduledOnly }, + }), + ) as any; + expect(result.reservation.reservation_time).toBe('2026-12-03T09:00'); + const metadata = JSON.parse(result.reservation.metadata); + expect(metadata.transit.legs[1].from.time).toBe('09:05'); + }); + }); + + // The provider's response taxonomy is wider than the mode whitelist a caller may request: + // MOTIS's default TRANSIT expands to include AIRPLANE, ODM, RIDE_SHARING and OTHER. Norway's + // GTFS, for one, routes Trondheim → Ålesund over AIRPLANE legs. Those itineraries must survive + // the search and be persistable, exactly as they are in the web app. + it('accepts provider leg modes outside the requestable mode whitelist', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id, { start_date: '2026-12-03', end_date: '2026-12-03' }); + const day = testDb.prepare('SELECT * FROM days WHERE trip_id = ?').get(trip.id) as any; + const flying = { + ...itinerary, + legs: itinerary.legs.map((leg) => (leg.mode === 'WALK' ? leg : { ...leg, mode: 'AIRPLANE' })), + }; + planMock.mockResolvedValue({ itineraries: [flying] }); + + await withHarness(user.id, ['geo:read'], async (harness) => { + const routes = parseToolResult( + await harness.client.callTool({ name: 'search_transit_routes', arguments: { from, to } }), + ) as any; + expect(routes.itineraries).toHaveLength(1); + expect(routes.itineraries[0].legs[1].mode).toBe('AIRPLANE'); + expect(routes.dropped).toBe(0); + }); + + await withHarness(user.id, ['reservations:write'], async (harness) => { + const result = parseToolResult( + await harness.client.callTool({ + name: 'create_transit_journey', + arguments: { tripId: trip.id, dayId: day.id, from, to, itinerary: flying }, + }), + ) as any; + expect(result.reservation.type).toBe('transit'); + const metadata = JSON.parse(result.reservation.metadata); + expect(metadata.transit.legs[1].mode).toBe('AIRPLANE'); + }); + }); + + it('reports how many provider itineraries failed validation', async () => { + const { user } = createUser(testDb); + const walkOnly = { ...itinerary, legs: [itinerary.legs[0]] }; + planMock.mockResolvedValue({ itineraries: [itinerary, walkOnly] }); + + await withHarness(user.id, ['geo:read'], async (harness) => { + const routes = parseToolResult( + await harness.client.callTool({ name: 'search_transit_routes', arguments: { from, to } }), + ) as any; + expect(routes.itineraries).toHaveLength(1); + expect(routes.dropped).toBe(1); + }); + }); +}); diff --git a/server/tests/unit/nest/reservations.service.test.ts b/server/tests/unit/nest/reservations.service.test.ts index b4caa283e..9e2f12616 100644 --- a/server/tests/unit/nest/reservations.service.test.ts +++ b/server/tests/unit/nest/reservations.service.test.ts @@ -22,6 +22,7 @@ const { resv } = vi.hoisted(() => ({ resv: { verifyTripAccess: vi.fn(), listReservations: vi.fn(), createReservation: vi.fn(), updatePositions: vi.fn(), getReservation: vi.fn(), updateReservation: vi.fn(), deleteReservation: vi.fn(), + notifyBookingChange: vi.fn(), }, })); vi.mock('../../../src/services/reservationService', () => resv); diff --git a/server/tests/unit/services/timezoneService.test.ts b/server/tests/unit/services/timezoneService.test.ts new file mode 100644 index 000000000..fff57e6a1 --- /dev/null +++ b/server/tests/unit/services/timezoneService.test.ts @@ -0,0 +1,17 @@ +import { localParts, resolveTimeZone } from '../../../src/services/timezoneService'; + +import { describe, expect, it } from 'vitest'; + +describe('timezoneService', () => { + it('resolves valid coordinates and rejects missing or invalid values', () => { + expect(resolveTimeZone(35.6762, 139.6503)).toBe('Asia/Tokyo'); + expect(resolveTimeZone(null, 139.6503)).toBeNull(); + expect(resolveTimeZone(91, 139.6503)).toBeNull(); + }); + + it('converts instants to local date and time', () => { + expect(localParts('2026-12-03T00:00:00Z', 'Asia/Tokyo')).toEqual({ date: '2026-12-03', time: '09:00' }); + expect(localParts('invalid', 'Asia/Tokyo')).toEqual({ date: null, time: null }); + expect(localParts(null, null)).toEqual({ date: null, time: null }); + }); +}); diff --git a/server/tests/unit/services/transitService.test.ts b/server/tests/unit/services/transitService.test.ts index 0700b320e..6864f5737 100644 --- a/server/tests/unit/services/transitService.test.ts +++ b/server/tests/unit/services/transitService.test.ts @@ -3,13 +3,13 @@ * The Transitous/MOTIS proxy (#1065): input validation, mode whitelist, * response mapping (colors, walk time, wall-clock duration) and caching. */ +import { deriveTransitStats, geocode, plan, type TransitLeg } from '../../../src/services/transitService'; + import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; vi.mock('../../../src/services/notifications', () => ({ getAppUrl: () => 'https://trek.example.com' })); vi.mock('../../../src/services/mapsService', () => ({ buildUserAgent: () => 'TREK-Test-UA' })); -import { geocode, plan } from '../../../src/services/transitService'; - const fetchMock = vi.fn(); beforeEach(() => { @@ -30,10 +30,12 @@ describe('geocode', () => { }); it('TRANSIT-SVC-002: maps matches to compact places and sends the UA', async () => { - fetchMock.mockResolvedValueOnce(okJson([ - { name: 'Alexanderplatz', lat: 52.52, lon: 13.41, type: 'STOP', areas: [{ name: 'Berlin', default: true }] }, - { name: 'no-coords' }, - ])); + fetchMock.mockResolvedValueOnce( + okJson([ + { name: 'Alexanderplatz', lat: 52.52, lon: 13.41, type: 'STOP', areas: [{ name: 'Berlin', default: true }] }, + { name: 'no-coords' }, + ]), + ); const r = await geocode('alexanderplatz-u1'); expect(r.results).toEqual([{ name: 'Alexanderplatz', lat: 52.52, lng: 13.41, type: 'STOP', area: 'Berlin' }]); const [url, init] = fetchMock.mock.calls[0]; @@ -56,13 +58,33 @@ describe('plan validation', () => { }); it('TRANSIT-SVC-005: rejects modes outside the whitelist', async () => { - await expect(plan({ from: '52.50,13.40', to: '52.51,13.41', modes: 'BUS,CAR' })).rejects.toMatchObject({ status: 400 }); + await expect(plan({ from: '52.50,13.40', to: '52.51,13.41', modes: 'BUS,CAR' })).rejects.toMatchObject({ + status: 400, + }); expect(fetchMock).not.toHaveBeenCalled(); }); it('TRANSIT-SVC-006: rejects out-of-range maxTransfers and bad time', async () => { - await expect(plan({ from: '52.50,13.40', to: '52.51,13.41', maxTransfers: 99 })).rejects.toMatchObject({ status: 400 }); - await expect(plan({ from: '52.50,13.40', to: '52.51,13.41', time: 'not-a-date' })).rejects.toMatchObject({ status: 400 }); + await expect(plan({ from: '52.50,13.40', to: '52.51,13.41', maxTransfers: 99 })).rejects.toMatchObject({ + status: 400, + }); + await expect(plan({ from: '52.50,13.40', to: '52.51,13.41', time: 'not-a-date' })).rejects.toMatchObject({ + status: 400, + }); + }); +}); + +describe('itinerary statistics', () => { + it('derives wall-clock duration, walking time, and transfers from canonical legs', () => { + const leg = (mode: string, duration: number) => ({ mode, duration }) as TransitLeg; + const stats = deriveTransitStats('2026-07-13T08:00:00Z', '2026-07-13T08:30:00Z', [ + leg('WALK', 300), + leg('BUS', 600), + leg('RAIL', 600), + ]); + + expect(stats).toEqual({ duration: 1800, transfers: 1, walkSeconds: 300 }); + expect(deriveTransitStats('2026-07-13T08:00:00Z', '2026-07-13T08:30:00Z', [leg('BUS', 1800)], 2).transfers).toBe(2); }); }); @@ -75,8 +97,25 @@ describe('plan mapping', () => { endTime: '2026-07-13T08:30:00Z', transfers: 1, legs: [ - { mode: 'WALK', duration: 300, distance: 250.7, from: { name: 'A', lat: 1, lon: 2, departure: '2026-07-13T08:00:00Z' }, to: { name: 'Stop 1', lat: 1.1, lon: 2.1, arrival: '2026-07-13T08:05:00Z' } }, - { mode: 'BUS', duration: 1200, routeShortName: '100', routeColor: 'FF0000', routeTextColor: '#ffffff', headsign: 'Zoo', agencyName: 'BVG', intermediateStops: [{}, {}], from: { name: 'Stop 1', lat: 1.1, lon: 2.1, departure: '2026-07-13T08:07:00Z', track: '2' }, to: { name: 'Stop 2', lat: 1.2, lon: 2.2, arrival: '2026-07-13T08:27:00Z' } }, + { + mode: 'WALK', + duration: 300, + distance: 250.7, + from: { name: 'A', lat: 1, lon: 2, departure: '2026-07-13T08:00:00Z' }, + to: { name: 'Stop 1', lat: 1.1, lon: 2.1, arrival: '2026-07-13T08:05:00Z' }, + }, + { + mode: 'BUS', + duration: 1200, + routeShortName: '100', + routeColor: 'FF0000', + routeTextColor: '#ffffff', + headsign: 'Zoo', + agencyName: 'BVG', + intermediateStops: [{}, {}], + from: { name: 'Stop 1', lat: 1.1, lon: 2.1, departure: '2026-07-13T08:07:00Z', track: '2' }, + to: { name: 'Stop 2', lat: 1.2, lon: 2.2, arrival: '2026-07-13T08:27:00Z' }, + }, ], }, ], @@ -102,7 +141,14 @@ describe('plan mapping', () => { it('TRANSIT-SVC-008: forwards only whitelisted params and pins directModes=WALK', async () => { fetchMock.mockResolvedValueOnce(okJson({ itineraries: [] })); - await plan({ from: '48.1000,11.5000', to: '48.2000,11.6000', modes: 'BUS,TRAM', maxTransfers: 2, arriveBy: true, time: '2026-07-13T09:00:00Z' }); + await plan({ + from: '48.1000,11.5000', + to: '48.2000,11.6000', + modes: 'BUS,TRAM', + maxTransfers: 2, + arriveBy: true, + time: '2026-07-13T09:00:00Z', + }); const url = String(fetchMock.mock.calls[0][0]); expect(url).toContain('/api/v6/plan?'); expect(url).toContain('transitModes=BUS%2CTRAM'); diff --git a/wiki/MCP-Scopes.md b/wiki/MCP-Scopes.md index 54190293f..3f48f03f9 100644 --- a/wiki/MCP-Scopes.md +++ b/wiki/MCP-Scopes.md @@ -32,7 +32,7 @@ TREK defines 27 scopes across 13 groups. | | `notifications:write` | Mark notifications as read or unread (individually or all at once) | | **Vacation** | `vacay:read` | Read vacation planning data, entries, and stats | | | `vacay:write` | Create and manage vacation entries, holidays, and team plans | -| **Geo** | `geo:read` | Search locations, resolve map URLs, and reverse-geocode coordinates | +| **Geo** | `geo:read` | Search locations and public transit routes, resolve map URLs, and reverse-geocode coordinates | | **Weather** | `weather:read` | Fetch weather forecasts for trip locations and dates | | **Journey** | `journey:read` | Read journeys, entries, and contributor list | | | `journey:write` | Create, update, and delete journeys and their entries | diff --git a/wiki/MCP-Tools-and-Resources.md b/wiki/MCP-Tools-and-Resources.md index 28f0ba545..7ff8fec2d 100644 --- a/wiki/MCP-Tools-and-Resources.md +++ b/wiki/MCP-Tools-and-Resources.md @@ -106,6 +106,16 @@ Requires `reservations:write` scope. | `update_transport` | Update an existing transport booking. Pass `endpoints[]` to replace all stops. | | `delete_transport` | Delete a transport booking from a trip. | +### Automated public transit + +Transit search is powered by Transitous and uses the existing `geo:read` and `reservations:write` scopes. + +| Tool | Scope required | Description | +|---|---|---| +| `search_transit_stops` | `geo:read` | Search real public-transit stops and stations, optionally biased around coordinates. | +| `search_transit_routes` | `geo:read` | Search scheduled routes between two coordinates with time, mode, and transfer filters. Also returns `dropped`, the number of provider itineraries that failed validation and are absent from the results. | +| `create_transit_journey` | `reservations:write` | Save a selected route as a first-class automated transit journey on a trip day. | + ### Reservations Requires `reservations:read` or `reservations:write` scope.