feat(tours): a city walk from a Google Maps walking route, its short link followed only to Google Maps (CW-06, CW-07)

"Add tour" in the planner now offers "Import walk from Google Maps". The
dialog takes the link of a route shared in Google Maps, either a
maps.app.goo.gl short link or the long google.com/maps/dir link, or the
share text of the Google Maps app with the one link in it. It shows the
stops in their order with their names, marks a stop the link gives no
position as such, says that the route comes from Google Maps with a link to
open it there, and that TREK plans the way between the stops itself and
does not take the line drawn in Google Maps over. Nothing is written until
"Load as walk": that opens a new, unsaved city walk in the planner with the
positioned stops and their names, routed on foot by TREK, and warns first
when it replaces unsaved work. A stop without a position is left out and
never looked up or guessed; with fewer than two positions nothing can be
loaded. While the walk is not saved, a calm notice in the planner says
where it came from, also after a reload of the draft. Cancelling or a
failure leaves every tour as it was.

Only a route the link marks unambiguously as on foot is read. A car, bike
or transit route, a link that does not say, or one that says two things is
refused with a reason the dialog gives in the reader's language. Each stop
takes its position from its own block of the link's data, so a line
dragged through extra points or a stop given as coordinates no longer
leaves the stops without positions or shifts them. The road trip and
places imports read links as before.

A short link is followed by a resolver of its own: every hop is checked
against the Google Maps short link shapes and the strict SSRF guard before
it is looked up or asked, so ALLOW_INTERNAL_NETWORK and
ALLOW_LINK_LOCAL_IPS do not open it. Each request goes to the vetted
addresses only, follows nothing by itself, reads no body and carries no
credentials; the chain has one deadline including name lookups, at most
three hops and a cap on the Location header, and the long link it ends on
must be Google Maps and is never fetched. The preview is POST
/api/trips/:tripId/tours/import/google-maps/preview for members who may
edit places, with a 502 when Google could not be reached, and the MCP tool
preview_google_maps_walk reads the same.
This commit is contained in:
Maurice
2026-10-20 04:21:14 +00:00
parent 2203ff3a2e
commit 4ca5728072
67 changed files with 3770 additions and 68 deletions
@@ -17,3 +17,24 @@ export const GOOGLE_SHORT_HOSTS = ['goo.gl', 'maps.app.goo.gl'];
export function isGoogleMapsHost(hostname: string): boolean {
return GOOGLE_SHORT_HOSTS.includes(hostname) || /^(www\.|maps\.)?google\.[a-z]{2,3}(\.[a-z]{2})?$/.test(hostname);
}
/** No credentials, no other port, https only: the shape every hop of a walk import must have. */
function plainHttps(url: URL): boolean {
return url.protocol === 'https:' && !url.username && !url.password && url.port === '';
}
/**
* CW-06: the short links a walk import follows at all, `maps.app.goo.gl/<code>`
* and `goo.gl/maps/<code>`. Anything else on goo.gl was a general shortener
* and could lead anywhere, so it is not followed.
*/
export function isGoogleMapsShortLink(url: URL): boolean {
if (!plainHttps(url)) return false;
if (url.hostname === 'maps.app.goo.gl') return /^\/[A-Za-z0-9_-]+\/?$/.test(url.pathname);
return url.hostname === 'goo.gl' && /^\/maps\/[A-Za-z0-9_-]+\/?$/.test(url.pathname);
}
/** CW-06: where a short link may lead: Google Maps itself, which is read and never fetched. */
export function isGoogleMapsLongLink(url: URL): boolean {
return plainHttps(url) && isGoogleMapsHost(url.hostname) && !GOOGLE_SHORT_HOSTS.includes(url.hostname);
}
@@ -96,11 +96,11 @@ function fromQuery(url: URL): DirWaypoint[] {
.filter((wp): wp is DirWaypoint => wp !== null);
}
/** The path form, where the stops are the segments and the blob holds their positions. */
function fromPath(url: URL): DirWaypoint[] {
/** The path form's stops, as the segments name them, and the data blob after them. */
function pathStops(url: URL): { names: DirWaypoint[]; data: string } {
const parts = url.pathname.split('/').filter(Boolean);
const at = parts.indexOf('dir');
if (at < 0) return [];
if (at < 0) return { names: [], data: '' };
const names: DirWaypoint[] = [];
let data = '';
@@ -116,12 +116,16 @@ function fromPath(url: URL): DirWaypoint[] {
const wp = asWaypoint(decodeSegment(part));
if (wp) names.push(wp);
}
if (!names.length) return [];
return { names, data };
}
// Positions from the blob, but only when there is exactly one for each stop. A partial
// match cannot be lined up — Google drops the pair for "your location" and adds pairs
// of its own for a route through several countries — and half a link read confidently
// is worse than a link read as names and geocoded.
/**
* Positions from the blob, but only when there is exactly one for each stop. A partial
* match cannot be lined up: Google drops the pair for "your location" and adds pairs
* of its own for a route through several countries, and half a link read confidently
* is worse than a link read as names and geocoded.
*/
function withPairPositions(names: DirWaypoint[], data: string): DirWaypoint[] {
const pairs = [...data.matchAll(DATA_LNG_LAT)]
.map((m) => ({ lng: Number.parseFloat(m[1]), lat: Number.parseFloat(m[2]) }))
.filter((p) => onEarth(p.lat, p.lng));
@@ -130,13 +134,104 @@ function fromPath(url: URL): DirWaypoint[] {
return names.map((wp, i) => (wp.lat !== null ? wp : { name: wp.name, lat: pairs[i].lat, lng: pairs[i].lng }));
}
/** The path form, where the stops are the segments and the blob holds their positions. */
function fromPath(url: URL, positions: DirectionsPositions): DirWaypoint[] {
const { names, data } = pathStops(url);
if (!names.length) return [];
return positions === 'stop-blocks' ? withStopBlockPositions(names, data) : withPairPositions(names, data);
}
/**
* One field of the data blob. Google writes a protobuf message as `!<field><type><value>`
* tokens: `!4m66` is field 4, a message holding the 66 tokens after it (its own and its
* children's), `!1d-8.61` a double, `!1s0x…` a string, `!3e2` an enum.
*/
interface BlobField {
key: string;
value: string;
children: BlobField[];
}
const BLOB_TOKEN = /^(\d+)([A-Za-z])(.*)$/;
/**
* The blob as its tree of fields; null for a token that is not a field, or a message
* that claims more tokens than follow it.
*/
function blobFields(data: string): BlobField[] | null {
const tokens = decodeSegment(data.slice('data='.length)).split('!').filter(Boolean);
const root: BlobField = { key: '', value: '', children: [] };
const open: Array<{ field: BlobField; left: number }> = [{ field: root, left: tokens.length }];
for (const token of tokens) {
const match = BLOB_TOKEN.exec(token);
const parent = open.at(-1);
if (!match || !parent || open.some((entry) => entry.left < 1)) return null;
const field: BlobField = { key: match[1] + match[2], value: match[3], children: [] };
parent.field.children.push(field);
for (const entry of open) entry.left -= 1;
if (match[2] === 'm') open.push({ field, left: Number(match[3]) });
while (open.length > 1 && open.at(-1)?.left === 0) open.pop();
}
return open.length === 1 ? root.children : null;
}
/** The route message: the first `!4m` that lists two stop blocks (`!1m`) or more. */
function routeMessage(fields: readonly BlobField[]): BlobField | null {
for (const field of fields) {
if (field.key === '4m' && field.children.filter((child) => child.key === '1m').length >= 2) return field;
const inner = routeMessage(field.children);
if (inner) return inner;
}
return null;
}
/**
* A stop block's own position (`!2m2!1d<lng>!2d<lat>`). A point Google adds where the
* line was dragged sits in a `!3m` of the block and is not the stop.
*/
function blockPosition(block: BlobField): { lat: number; lng: number } | null {
const own = block.children.find((child) => child.key === '2m');
const lng = Number.parseFloat(own?.children.find((child) => child.key === '1d')?.value ?? '');
const lat = Number.parseFloat(own?.children.find((child) => child.key === '2d')?.value ?? '');
return onEarth(lat, lng) ? { lat, lng } : null;
}
/**
* CW-07: positions read from each stop's own block of the route message, so a line
* dragged through extra points or a stop given as coordinates cannot shift them onto the
* wrong stop. When the blocks and the stops do not pair up one to one, no stop takes a
* position from the blob: a stop the link does not place stays without one.
*/
function withStopBlockPositions(names: DirWaypoint[], data: string): DirWaypoint[] {
const fields = data ? blobFields(data) : null;
const route = fields ? routeMessage(fields) : null;
const blocks = route?.children.filter((child) => child.key === '1m') ?? [];
if (blocks.length !== names.length) return names;
return names.map((wp, i) => {
const position = wp.lat === null ? blockPosition(blocks[i]) : null;
return position ? { name: wp.name, ...position } : wp;
});
}
/**
* How the stops of the path form are placed from the data blob: `pairs` lines up the
* coordinate pairs with the stops when their counts agree (the road trip and places
* imports, which geocode what stays a name), `stop-blocks` reads each stop's own block
* and places nothing it cannot line up (the city walk import, which guesses nothing).
*/
export type DirectionsPositions = 'pairs' | 'stop-blocks';
/**
* The stops of a shared directions link, in the order they are driven.
*
* Empty when the link is not a route, or holds fewer than two stops — one stop is a
* place, and the place search box already takes those.
*/
export function parseDirectionsUrl(raw: string, limit = MAX_DIR_WAYPOINTS): DirWaypoint[] {
export function parseDirectionsUrl(
raw: string,
limit = MAX_DIR_WAYPOINTS,
positions: DirectionsPositions = 'pairs',
): DirWaypoint[] {
let url: URL;
try {
url = new URL(raw);
@@ -144,6 +239,51 @@ export function parseDirectionsUrl(raw: string, limit = MAX_DIR_WAYPOINTS): DirW
return [];
}
const fromParams = fromQuery(url);
const found = fromParams.length ? fromParams : fromPath(url);
const found = fromParams.length ? fromParams : fromPath(url, positions);
return found.length >= 2 ? found.slice(0, limit) : [];
}
/** How a directions link says its route is travelled; `unknown` when it does not say, or says two things. */
export type DirTravelMode = 'walking' | 'driving' | 'bicycling' | 'transit' | 'other' | 'unknown';
/** Google's travel-mode field in a route's data blob: !3e0 car, !3e1 bike, !3e2 on foot, !3e3 transit. */
const DATA_MODE = /!3e(\d+)/g;
const DATA_MODES: Readonly<Partial<Record<string, DirTravelMode>>> = {
'0': 'driving',
'1': 'bicycling',
'2': 'walking',
'3': 'transit',
};
const PARAM_MODES: Readonly<Partial<Record<string, DirTravelMode>>> = {
driving: 'driving',
walking: 'walking',
bicycling: 'bicycling',
transit: 'transit',
};
/** The `data=` path segment of a route, decoded; '' when there is none. Only there does !3e name the mode. */
function dataSegmentOf(url: URL): string {
const part = url.pathname.split('/').find((segment) => segment.startsWith('data='));
return part ? decodeSegment(part) : '';
}
/**
* CW-07: the travel mode a directions link states, from the documented
* `travelmode=` parameter or the `!3e` field of the path's data blob. Exactly one
* mode stated is the answer; none, or two different ones, is `unknown`.
*/
export function directionsTravelMode(raw: string): DirTravelMode {
let url: URL;
try {
url = new URL(raw);
} catch {
return 'unknown';
}
if (!isDirectionsUrl(url.href)) return 'unknown';
const said = new Set<DirTravelMode>();
const param = url.searchParams.get('travelmode');
if (param !== null) said.add(PARAM_MODES[param.trim().toLowerCase()] ?? 'other');
for (const [, code] of dataSegmentOf(url).matchAll(DATA_MODE)) said.add(DATA_MODES[code] ?? 'other');
const [only] = said;
return said.size === 1 && only ? only : 'unknown';
}
@@ -2,6 +2,7 @@ import { PlaceImportService } from './place-import.service';
import { CollectionGpxProvider } from './providers/collection-gpx.provider';
import { GoogleDirectionsProvider } from './providers/google-directions.provider';
import { GoogleListProvider } from './providers/google-list.provider';
import { GoogleMapsShortLinkProvider } from './providers/google-maps-short-link.provider';
import { GpxProvider } from './providers/gpx.provider';
import { KmlProvider } from './providers/kml.provider';
import { NaverListProvider } from './providers/naver-list.provider';
@@ -13,7 +14,9 @@ import { Module } from '@nestjs/common';
* table of its own: PlacesModule, CollectionsModule and ToursModule import it
* and persist what it reads. It imports no other
* domain: the stops of a directions link that carry only a name are geocoded
* through a function the importer hands in (MapsService.geocodeQuery).
* through a function the importer hands in (MapsService.geocodeQuery). A
* Google Maps short link the city walk import is given is followed through
* GoogleMapsShortLinkProvider, hop by hop against its own allow-list (CW-06).
*/
@Module({
providers: [
@@ -24,6 +27,7 @@ import { Module } from '@nestjs/common';
GoogleListProvider,
GoogleDirectionsProvider,
NaverListProvider,
GoogleMapsShortLinkProvider,
],
exports: [PlaceImportService],
})
@@ -8,10 +8,12 @@ import type {
ListRead,
NaverListPlace,
PreparedGpxPlace,
ShortLinkOutcome,
} from './place-import.types';
import { CollectionGpxProvider, type ExportedCollectionFile } from './providers/collection-gpx.provider';
import { GoogleDirectionsProvider } from './providers/google-directions.provider';
import { GoogleListProvider } from './providers/google-list.provider';
import { GoogleMapsShortLinkProvider } from './providers/google-maps-short-link.provider';
import { GpxProvider, type GpxExportInput, type GpxExportOptions, type GpxTourExport } from './providers/gpx.provider';
import { KmlProvider } from './providers/kml.provider';
import { NaverListProvider } from './providers/naver-list.provider';
@@ -19,8 +21,10 @@ import { Injectable } from '@nestjs/common';
import type { CollectionGpxExport, CollectionGpxReadResult } from '@trek/shared';
// The directions-link reading is also what the road trip planner reads a
// shared route with, and what the import routes dispatch on.
export { isDirectionsUrl, parseDirectionsUrl, MAX_DIR_WAYPOINTS } from './directions-url.helpers';
// shared route with, what the import routes dispatch on, and what the city
// walk import reads a walking route and its travel mode with (CW-07).
export { directionsTravelMode, isDirectionsUrl, parseDirectionsUrl, MAX_DIR_WAYPOINTS } from './directions-url.helpers';
export type { DirWaypoint } from './directions-url.helpers';
export type {
GpxExportDay,
GpxExportInput,
@@ -52,6 +56,7 @@ export class PlaceImportService {
private readonly googleList: GoogleListProvider,
private readonly googleDirections: GoogleDirectionsProvider,
private readonly naverList: NaverListProvider,
private readonly shortLinks: GoogleMapsShortLinkProvider,
) {}
// ── GPX ────────────────────────────────────────────────────────────────────
@@ -115,6 +120,11 @@ export class PlaceImportService {
return this.naverList.read(url);
}
/** CW-06: a Google Maps short link followed through its allow-list and the strict SSRF guard, hop by hop. */
resolveGoogleShortLink(url: string): Promise<ShortLinkOutcome> {
return this.shortLinks.resolve(url);
}
/**
* The stops of a shared directions link, placed on the map.
*
@@ -102,3 +102,12 @@ export class CollectionGpxError extends Error {
this.name = 'CollectionGpxError';
}
}
/**
* CW-06: where a Google Maps short link led. `refused` when a hop or the
* landing link is not one the walk import may follow or read, `unreachable`
* when the chain could not be followed in time or answered nonsense,
* `too_many_redirects` and `no_redirect` as they say.
*/
export type ShortLinkOutcome =
{ ok: true; url: string } | { ok: false; why: 'refused' | 'unreachable' | 'too_many_redirects' | 'no_redirect' };
@@ -0,0 +1,118 @@
/**
* CW-06: a Google Maps short link followed for the city walk import, and
* nothing else.
*
* This is deliberately not the general follower (`safeFetchFollow`). That one
* goes wherever a redirect points as long as the address is public; this one
* checks every hop against the short-link allow-list before anything is
* resolved or asked, and runs the SSRF guard in its strict form, so
* ALLOW_INTERNAL_NETWORK and ALLOW_LINK_LOCAL_IPS do not open it. Each request
* goes out pinned to the addresses the guard vetted, follows nothing by
* itself, reads no body and carries nothing of the caller's. The whole chain,
* name lookups included, has one deadline and at most three hops, and a
* Location header longer than a link can be is refused. Where the chain ends,
* the long link has to be Google Maps itself; it is read, never fetched.
*/
import { discardBody } from '../../../utils/cappedFetch';
import { checkSsrf, createOutboundDispatcher } from '../../../utils/ssrfGuard';
import { logDebug } from '../../audit/audit-log.logger';
import { isGoogleMapsLongLink, isGoogleMapsShortLink } from '../../common/google-maps-hosts';
import type { ShortLinkOutcome } from '../place-import.types';
import { Injectable } from '@nestjs/common';
export interface ShortLinkLimits {
/** Requests made at most, one per hop. */
hops: number;
/** One deadline over the whole chain, the name lookups included. */
deadlineMs: number;
/** The longest Location header taken; a longer one is no link. */
locationChars: number;
}
export const SHORT_LINK_LIMITS: ShortLinkLimits = { hops: 3, deadlineMs: 8_000, locationChars: 8_192 };
/** The lookup inside the SSRF guard cannot be aborted; this holds it to the chain's deadline as well. */
function beforeDeadline<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {
return new Promise<T>((resolve, reject) => {
if (signal.aborted) {
reject(signal.reason);
return;
}
const stop = () => reject(signal.reason);
signal.addEventListener('abort', stop, { once: true });
void work.then(resolve, reject).finally(() => signal.removeEventListener('abort', stop));
});
}
@Injectable()
export class GoogleMapsShortLinkProvider {
/** Where a maps.app.goo.gl or goo.gl/maps link leads; nothing outside Google Maps is ever asked. */
async resolve(raw: string, limits: ShortLinkLimits = SHORT_LINK_LIMITS): Promise<ShortLinkOutcome> {
let start: URL;
try {
start = new URL(raw);
} catch {
return { ok: false, why: 'refused' };
}
const signal = AbortSignal.timeout(limits.deadlineMs);
try {
return await this.hop(start, 0, signal, limits);
} catch (err: unknown) {
// A deadline passed, a name that does not resolve, a connection that failed.
logDebug(`[walk import] Google Maps short link not followed: ${err instanceof Error ? err.name : 'error'}`);
return { ok: false, why: 'unreachable' };
}
}
// Recursion rather than a loop: each hop waits for the one before it.
private async hop(
url: URL,
fetched: number,
signal: AbortSignal,
limits: ShortLinkLimits,
): Promise<ShortLinkOutcome> {
// Before any name lookup and before any request: only a short link is asked at all.
if (!isGoogleMapsShortLink(url)) return { ok: false, why: 'refused' };
if (fetched >= limits.hops) return { ok: false, why: 'too_many_redirects' };
// Strict: a private address stays refused whatever ALLOW_INTERNAL_NETWORK says.
const ssrf = await beforeDeadline(checkSsrf(url.href, true), signal);
const addresses = ssrf.allowed ? (ssrf.resolvedIps ?? []) : [];
if (addresses.length === 0) return { ok: false, why: 'refused' };
const location = await this.locationOf(url, addresses, signal);
if (location === null) return { ok: false, why: 'no_redirect' };
if (location.length > limits.locationChars) return { ok: false, why: 'unreachable' };
let next: URL;
try {
next = new URL(location, url);
} catch {
return { ok: false, why: 'refused' };
}
if (isGoogleMapsShortLink(next)) return this.hop(next, fetched + 1, signal, limits);
// The long link is read by the caller and never fetched here.
return isGoogleMapsLongLink(next) ? { ok: true, url: next.href } : { ok: false, why: 'refused' };
}
/** One request through the pinned dispatcher, nothing followed and no body read: the Location of a 3xx, or null. */
private async locationOf(url: URL, addresses: string[], signal: AbortSignal): Promise<string | null> {
const dispatcher = createOutboundDispatcher(url.href, addresses);
// Nothing of the caller's goes along: no cookie, no authorization, no referrer.
// Node's fetch keeps no cookie jar, and credentials 'omit' says so for the record.
const init: RequestInit = {
method: 'GET',
redirect: 'manual',
credentials: 'omit',
referrerPolicy: 'no-referrer',
headers: { accept: 'text/html' },
signal,
};
try {
// The pinned dispatcher is undici's own type, the init's that of Node's bundled copy;
// Object.assign joins the two without casting either away.
const response = await fetch(url.href, Object.assign(init, { dispatcher }));
discardBody(response);
return response.status >= 300 && response.status < 400 ? response.headers.get('location') : null;
} finally {
void dispatcher.close().catch((err: unknown) => logDebug(`[walk import] dispatcher not closed: ${String(err)}`));
}
}
}
@@ -0,0 +1,5 @@
import { walkImportPreviewRequestSchema } from '@trek/shared';
import { createZodDto } from 'nestjs-zod';
export class WalkImportPreviewDto extends createZodDto(walkImportPreviewRequestSchema) {}
@@ -0,0 +1,31 @@
import { ADDON_IDS } from '../../addons';
import { AddonGuard } from '../addons/addon.guard';
import { RequireAddon } from '../addons/require-addon.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { ResponseContract } from '../common/response-contract';
import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';
import { WalkImportPreviewDto } from './dto/tour-walk-import.dto';
import { TourWalkImportService } from './tour-walk-import.service';
import { Body, Controller, HttpCode, Post, UseGuards } from '@nestjs/common';
import { walkImportPreviewResponseSchema } from '@trek/shared';
/**
* CW-07 POST /api/trips/:tripId/tours/import/google-maps/preview: a Google
* Maps walking route read into its stops; nothing is stored. Like the GPX
* preview, the addon off or a trip out of reach answers 404, and a member who
* may not edit places 403, since what comes next creates a tour.
*/
@Controller('api/trips/:tripId/tours')
@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)
@RequireAddon(ADDON_IDS.TOURS, 'Tours')
export class TourWalkImportController {
constructor(private readonly walkImport: TourWalkImportService) {}
@RequirePermission('place_edit')
@Post('import/google-maps/preview')
@HttpCode(200)
@ResponseContract(walkImportPreviewResponseSchema)
async preview(@Body() body: WalkImportPreviewDto) {
return await this.walkImport.preview(body.url);
}
}
@@ -0,0 +1,48 @@
import { ADDON_IDS } from '../../addons';
import { noAccess, permissionDenied } from '../../mcp/tools/_shared';
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, ok, type McpContext } from '../../nest-mcp';
import { addonGate } from '../addons/addon-gate';
import { AddonsService } from '../addons/addons.service';
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
import { TripAccessService } from '../trip-membership/trip-access.service';
import { TourWalkImportService } from './tour-walk-import.service';
import { idSchema, walkImportPreviewRequestSchema } from '@trek/shared';
const preview = walkImportPreviewRequestSchema.shape;
/**
* CW-07: the stops of a Google Maps walking route read from its link, over
* the same service and the same checks as REST: access to the trip, and
* 'place_edit' on it, since what comes next creates a tour. A refusal of the
* link (a car route, a link that does not say, a short link leading elsewhere)
* is the service's DomainError, which the registry answers as an error result
* with the same English text REST sends.
*/
@McpController()
export class TourWalkImportMcp {
constructor(
private readonly walkImport: TourWalkImportService,
private readonly access: TripAccessService,
private readonly guards: McpToolGuardsService,
// Read by the addon gate of the tool here.
readonly addons: AddonsService,
) {}
@Tool({
name: 'preview_google_maps_walk',
description:
'Read the stops of a Google Maps walking route shared as a link (a maps.app.goo.gl short link or a google.com/maps/dir link), in order, for a city walk (tour_type walk): each stop with the name the link gives it and its position, or null coordinates when the link gives none (such a stop is not looked up or guessed), and resolved_url, the long link that was read. Only a route Google Maps marks as on foot is read; a car, bike or transit route, or one that does not say, is refused. Nothing is saved, and the line drawn in Google Maps is not taken over: TREK plans the way on foot between the stops again when the walk is created. Needs place editing permission on the trip.',
inputSchema: {
tripId: idSchema.describe('The trip the walk is meant for'),
url: preview.url,
},
annotations: TOOL_ANNOTATIONS_READONLY,
when: addonGate(ADDON_IDS.TOURS),
access: { group: 'trips', mode: 'read' },
})
async previewGoogleMapsWalk({ tripId, url }: { tripId: number; url: string }, ctx: McpContext) {
if (!(await this.access.findAccessible(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('place_edit', tripId, ctx.userId))) return permissionDenied();
return ok(await this.walkImport.preview(url));
}
}
@@ -0,0 +1,82 @@
import { DomainError } from '../common/domain-error';
import { isGoogleMapsLongLink, isGoogleMapsShortLink } from '../common/google-maps-hosts';
import {
directionsTravelMode,
isDirectionsUrl,
parseDirectionsUrl,
PlaceImportService,
type DirWaypoint,
} from '../place-import/place-import.service';
import { Injectable } from '@nestjs/common';
import {
TOUR_STATION_NAME_MAX,
WALK_IMPORT_STATIONS_MAX,
type WalkImportPreviewResponse,
type WalkImportRefusal,
type WalkImportStation,
} from '@trek/shared';
/** What API and MCP clients read; the planner says the same in the reader's language, by reason. */
const REFUSAL_TEXT: Readonly<Record<WalkImportRefusal, string>> = {
not_google_maps: 'Use a Google Maps route link: a maps.app.goo.gl short link or a google.com/maps/dir link.',
not_a_route: 'That Google Maps link is not a route. Plan the walk in Google Maps and share the route.',
not_walking: 'That route is not planned on foot. Switch Google Maps to walking and share the route again.',
mode_unknown:
'The link does not say clearly that the route is on foot. Choose walking in Google Maps and share it again.',
short_link_refused: 'The short link leads somewhere other than Google Maps, so it was not followed.',
short_link_failed: 'The short link could not be followed just now. Try again, or paste the long link.',
too_few_stops: 'Fewer than two stops could be read from that link.',
too_many_stops: 'That route has more stops than a walk can take.',
};
/** Reasons that are Google's answer rather than the link's. */
const UPSTREAM: ReadonlySet<WalkImportRefusal> = new Set<WalkImportRefusal>(['short_link_failed']);
function refuse(reason: WalkImportRefusal): DomainError {
return new DomainError(UPSTREAM.has(reason) ? 502 : 400, REFUSAL_TEXT[reason], { code: reason, details: { reason } });
}
/** A stop as the walk takes it: its name as the link spells it, cut to a station's length; no position guessed. */
function stationOf(stop: DirWaypoint): WalkImportStation {
const name = stop.name?.trim().slice(0, TOUR_STATION_NAME_MAX).trim() || null;
return { name, lat: stop.lat, lng: stop.lng };
}
/**
* CW-07: the stops of a Google Maps walking route shared as a link, in their
* order, for the planner to show before anything is taken over. Only a route
* the link marks as on foot is read. A stop the link gives no position stays
* without one: nothing is looked up or guessed. A short link is followed only
* through the narrow resolver of CW-06. Nothing is stored.
*/
@Injectable()
export class TourWalkImportService {
constructor(private readonly placeImport: PlaceImportService) {}
async preview(raw: string): Promise<WalkImportPreviewResponse> {
const link = this.linkOf(raw);
const route = isGoogleMapsShortLink(link) ? await this.followed(link) : link;
if (!isGoogleMapsLongLink(route)) throw refuse('not_google_maps');
if (!isDirectionsUrl(route.href)) throw refuse('not_a_route');
const mode = directionsTravelMode(route.href);
if (mode !== 'walking') throw refuse(mode === 'unknown' ? 'mode_unknown' : 'not_walking');
const stops = parseDirectionsUrl(route.href, WALK_IMPORT_STATIONS_MAX + 1, 'stop-blocks');
if (stops.length > WALK_IMPORT_STATIONS_MAX) throw refuse('too_many_stops');
if (stops.length < 2) throw refuse('too_few_stops');
return { stations: stops.map(stationOf), resolved_url: route.href };
}
private linkOf(raw: string): URL {
try {
return new URL(raw.trim());
} catch {
throw refuse('not_google_maps');
}
}
private async followed(link: URL): Promise<URL> {
const outcome = await this.placeImport.resolveGoogleShortLink(link.href);
if ('why' in outcome) throw refuse(outcome.why === 'refused' ? 'short_link_refused' : 'short_link_failed');
return new URL(outcome.url);
}
}
+9 -1
View File
@@ -29,6 +29,9 @@ import { TourTrailGradeController } from './tour-trail-grade.controller';
import { TourTrailGradeService } from './tour-trail-grade.service';
import { TourVisitsController } from './tour-visits.controller';
import { TourVisitsService } from './tour-visits.service';
import { TourWalkImportController } from './tour-walk-import.controller';
import { TourWalkImportMcp } from './tour-walk-import.mcp';
import { TourWalkImportService } from './tour-walk-import.service';
import { ToursImportController } from './tours-import.controller';
import { ToursWandererController } from './tours-wanderer.controller';
import { ToursWandererService } from './tours-wanderer.service';
@@ -43,7 +46,9 @@ import { Module } from '@nestjs/common';
* persists the places through PlacesService (PlacesModule). The tour SQL lives in
* the Tours and TourWaypoints repositories; the owning place's route columns go
* through PlacesRepository, registered here because forFeature only reaches
* this module's own providers.
* this module's own providers. A Google Maps walking route is read into the
* stops of a city walk through PlaceImportModule as well (CW-07), its short
* link followed by the narrow resolver there (CW-06).
*/
@Module({
imports: [
@@ -77,6 +82,7 @@ import { Module } from '@nestjs/common';
TourPoiSearchController,
TourTrailGradeController,
TourVisitsController,
TourWalkImportController,
ToursController,
ToursImportController,
ToursWandererController,
@@ -94,8 +100,10 @@ import { Module } from '@nestjs/common';
TourPoiSearchService,
TourTrailGradeService,
TourVisitsService,
TourWalkImportService,
ToursMcp,
TourLibraryMcp,
TourWalkImportMcp,
],
})
export class ToursModule {}