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 {}
@@ -0,0 +1,233 @@
/**
* Tours e2e for the Google Maps walk import (CW-06, CW-07): POST
* /api/trips/:tripId/tours/import/google-maps/preview through the real
* AddonGuard, JwtAuthGuard and TripAccessGuard, the Zod pipe and the response
* contract, against a migrated and seeded temp SQLite db. The short link
* resolver is the real one; only the name lookup and the global fetch are
* stubbed, so no request leaves the test and every one it would make is seen.
*
* Fixtures: user 1 owns trip 5, user 2 is a member whom the permission spy
* denies 'place_edit', user 3 has no access to the trip.
*/
import { Places } from '../../src/db/entities/Places.entity';
import { Tours } from '../../src/db/entities/Tours.entity';
import { Trips } from '../../src/db/entities/Trips.entity';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { JourneyDomainService } from '../../src/nest/journey/journey-domain.service';
import { MapsService } from '../../src/nest/maps/maps.service';
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
import { RealtimeService } from '../../src/nest/realtime/realtime.service';
import { ToursModule } from '../../src/nest/tours/tours.module';
import { PORTO_RIBEIRA } from '../fixtures/google-maps-walks';
import { createSnapshotTestDb } from '../helpers/db-mock';
import { countRows, insertRows } from '../helpers/factories/rows';
import { setAddonEnabled } from '../helpers/factories/settings';
import { addTripMember } from '../helpers/factories/trips';
import { makeUser } from '../helpers/factories/users';
import { FakeRealtimeService } from '../helpers/fake-realtime';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { sessionCookie } from './harness';
import { Test } from '@nestjs/testing';
import { WALK_IMPORT_URL_MAX } from '@trek/shared';
import cookieParser from 'cookie-parser';
import dns from 'dns/promises';
import type { Server } from 'http';
import request from 'supertest';
import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi, type MockInstance } from 'vitest';
vi.mock('../../src/nest/audit/audit-log.logger', () => ({
LOG_LEVEL: 'error',
logInfo: vi.fn(),
logDebug: vi.fn(),
logError: vi.fn(),
logWarn: vi.fn(),
}));
vi.mock('dns/promises', () => ({ default: { lookup: vi.fn() }, lookup: vi.fn() }));
const { journeyHooks } = vi.hoisted(() => ({
journeyHooks: {
reconcileTripSkeletons: vi.fn().mockResolvedValue(undefined),
onPlaceCreated: vi.fn().mockResolvedValue(undefined),
onPlaceUpdated: vi.fn().mockResolvedValue(undefined),
onPlaceDeleted: vi.fn().mockResolvedValue(undefined),
},
}));
const db = createSnapshotTestDb();
// The map search is never asked: a stop without a position is not looked up.
const maps = { geocodeQuery: vi.fn(), reverseGeocode: vi.fn(), searchPlaces: vi.fn(), poisAlong: vi.fn() };
const realtime = new FakeRealtimeService();
const lookup = vi.mocked(dns.lookup);
let orm: TestOrm;
let checkPermission: MockInstance;
const OWNER = 1;
const VIEWER = 2;
const OUTSIDER = 3;
const SHORT = 'https://maps.app.goo.gl/gwKHfs8TNxShEBBk7';
const ROUTE = 'https://www.google.com/maps/dir/Cathedral/Market/@48.1,11.5,15z/data=';
/** The requests one after another: supertest opens a listener of its own for each. */
function inTurn<T, R>(items: readonly T[], run: (item: T) => Promise<R>): Promise<R[]> {
return items.reduce<Promise<R[]>>(
(previous, item) => previous.then(async (done) => [...done, await run(item)]),
Promise.resolve([]),
);
}
const BLOCKS = '!1m5!1m1!1s0x0:0x0!2m2!1d11.5!2d48.1!1m5!1m1!1s0x0:0x0!2m2!1d11.51!2d48.11';
describe('Tours walk import e2e (real guards + temp SQLite)', () => {
let server: Server;
let app: Awaited<ReturnType<typeof build>>;
let fetchSpy: ReturnType<typeof vi.fn>;
async function build() {
const moduleRef = await Test.createTestingModule({
imports: [
await TestUnitOfWorkModule.forRoot(db),
await createTestMikroOrmModule(db),
RealtimeModule,
ToursModule,
],
})
.overrideProvider(RealtimeService)
.useValue(realtime)
.overrideProvider(JourneyDomainService)
.useValue(journeyHooks)
.overrideProvider(MapsService)
.useValue(maps)
.compile();
const nest = moduleRef.createNestApplication();
nest.use(cookieParser());
nest.useGlobalPipes(new ZodValidationPipe());
nest.useGlobalFilters(new TrekExceptionFilter());
await nest.init();
return nest;
}
const preview = (userId: number | null, body: unknown, tripId = 5) => {
const req = request(server).post(`/api/trips/${tripId}/tours/import/google-maps/preview`);
return (userId === null ? req : req.set('Cookie', sessionCookie(userId))).send(body as object);
};
beforeAll(async () => {
orm = await createTestOrm(db);
// Pinned ids: the session cookies sign for exactly these users.
await makeUser(orm, { id: 1, username: 'owner', email: 'owner@example.test', role: 'user', password_version: 0 });
await makeUser(orm, { id: 2, username: 'viewer', email: 'viewer@example.test', role: 'user', password_version: 0 });
await makeUser(orm, {
id: 3,
username: 'outsider',
email: 'outsider@example.test',
role: 'user',
password_version: 0,
});
await insertRows(orm, Trips, [{ id: 5, user: 1, title: 'Porto' }]);
await addTripMember(orm, 5, 2);
app = await build();
checkPermission = vi.spyOn(app.get(PermissionsService), 'checkPermission');
server = app.getHttpServer();
});
beforeEach(async () => {
checkPermission.mockImplementation(
(action: string, _role: string, _owner: number, userId: number) =>
!(action === 'place_edit' && userId === VIEWER),
);
await setAddonEnabled(orm, 'tours', true);
lookup.mockResolvedValue([{ address: '142.250.185.14', family: 4 }] as never);
fetchSpy = vi.fn();
vi.stubGlobal('fetch', fetchSpy);
for (const fn of Object.values(maps)) fn.mockReset();
});
afterEach(() => {
vi.unstubAllGlobals();
lookup.mockReset();
});
afterAll(async () => {
await app.close();
await orm.close();
});
it('401 without a session, 404 outside the trip or while the addon is off, 403 without place_edit', async () => {
const body = { url: PORTO_RIBEIRA };
expect((await preview(null, body)).status).toBe(401);
expect((await preview(OUTSIDER, body)).status).toBe(404);
expect((await preview(VIEWER, body)).status).toBe(403);
await setAddonEnabled(orm, 'tours', false);
const off = await preview(OWNER, body);
expect([off.status, off.body]).toEqual([404, { error: 'Tours addon is not enabled' }]);
expect(fetchSpy).not.toHaveBeenCalled();
});
it('400 from the contract for an empty link, one longer than a link may be, or a field it does not know', async () => {
const bodies = [{ url: ' ' }, { url: 'x'.repeat(WALK_IMPORT_URL_MAX + 1) }, { url: SHORT, mode: 'walk' }, {}];
const answers = await inTurn(bodies, async (body) => await preview(OWNER, body));
expect(answers.map((res) => res.status)).toEqual([400, 400, 400, 400]);
expect(fetchSpy).not.toHaveBeenCalled();
});
it('200 for a long walking link: its stops in order, with nothing asked of the network and nothing stored', async () => {
const res = await preview(OWNER, { url: PORTO_RIBEIRA });
expect(res.status).toBe(200);
expect(res.body.resolved_url).toBe(PORTO_RIBEIRA);
expect(res.body.stations).toHaveLength(5);
expect(res.body.stations[0]).toEqual({
name: 'Igreja de Santa Clara, Largo Primeiro de Dezembro, 4000-404 Porto, Portugal',
lat: 41.1425899,
lng: -8.6092477,
});
expect(fetchSpy).not.toHaveBeenCalled();
expect(lookup).not.toHaveBeenCalled();
expect(await countRows(orm, Places, {})).toBe(0);
expect(await countRows(orm, Tours, {})).toBe(0);
expect(realtime.broadcastMock).not.toHaveBeenCalled();
});
it('400 with its reason for a car route, a link that does not say, no route and no Google Maps link', async () => {
const cases: Array<[string, string]> = [
[`${ROUTE}!4m14!4m13${BLOCKS}!3e0`, 'not_walking'],
[`${ROUTE}!4m13!4m12${BLOCKS}`, 'mode_unknown'],
['https://www.google.com/maps/place/Cathedral/@48.1,11.5,17z', 'not_a_route'],
['https://example.com/maps/dir/Cathedral/Market/data=!3e2', 'not_google_maps'],
];
const answers = await inTurn(cases, async ([url]) => await preview(OWNER, { url }));
expect(answers.map((res) => [res.status, res.body.reason])).toEqual(cases.map(([, reason]) => [400, reason]));
for (const res of answers) expect(typeof res.body.error).toBe('string');
expect(fetchSpy).not.toHaveBeenCalled();
for (const fn of Object.values(maps)) expect(fn).not.toHaveBeenCalled();
});
it('follows a short link one hop to Google Maps, and refuses one that leads elsewhere after that one request', async () => {
fetchSpy.mockResolvedValueOnce(new Response(null, { status: 302, headers: { location: PORTO_RIBEIRA } }));
const res = await preview(OWNER, { url: SHORT });
expect(res.status).toBe(200);
expect(res.body.resolved_url).toBe(PORTO_RIBEIRA);
expect(fetchSpy).toHaveBeenCalledTimes(1);
fetchSpy.mockReset();
fetchSpy.mockResolvedValueOnce(
new Response(null, { status: 302, headers: { location: 'https://example.com/maps/dir/A/B/data=!3e2' } }),
);
const elsewhere = await preview(OWNER, { url: SHORT });
expect([elsewhere.status, elsewhere.body.reason]).toEqual([400, 'short_link_refused']);
expect(fetchSpy).toHaveBeenCalledTimes(1);
});
it('502 when the short link cannot be followed, and nothing stored', async () => {
fetchSpy.mockRejectedValueOnce(new TypeError('fetch failed'));
const res = await preview(OWNER, { url: SHORT });
expect(res.status).toBe(502);
expect(res.body).toEqual({
error: 'The short link could not be followed just now. Try again, or paste the long link.',
reason: 'short_link_failed',
});
expect(await countRows(orm, Tours, {})).toBe(0);
});
});
+71
View File
@@ -0,0 +1,71 @@
/**
* Real Google Maps walking routes (CW-07), as their short links answered on
* 2026-10-20: each `https://maps.app.goo.gl/<code>` gave one 302 straight to
* the www.google.com/maps/dir link below, with no consent page in between.
* Four walks through Porto shared by a travel blog; the query Google appends
* (entry, g_ep, skid) is left off. Every one ends in `!3e2`, on foot.
*
* Two of them are the hard case for reading positions: PORTO_ALIADOS drags its
* line through a point of its own between two stops, and PORTO_CLERIGOS does
* that and has two stops given as coordinates, so a count of the coordinate
* pairs no longer matches the stops.
*/
/** https://maps.app.goo.gl/G8RFU9t5AbTx3QEZA */
export const PORTO_CLERIGOS =
'https://www.google.com/maps/dir/Igreja+de+Santo+Ant%C3%B3nio+dos+Congregados,+R.+de+S%C3%A1+da+Bande' +
'ira+11,+4000-433+Porto,+Portugal/Torre+dos+Cl%C3%A9rigos,+R.+de+S%C3%A3o+Filipe+de+Nery,+4050-546+Po' +
'rto,+Portugal/Livraria+Lello,+R.+das+Carmelitas+144,+4050-161+Porto,+Portugal/Igreja+do+Carmo,+R.+do' +
'+Carmo,+4050-164+Porto,+Portugal/Restaurante+Carlos+Alberto,+Pra%C3%A7a+de+Carlos+Alberto+89,+4050-1' +
'58+Porto,+Portugal/Miradouro+da+Vit%C3%B3ria,+R.+de+S%C3%A3o+Bento+da+Vit%C3%B3ria+11,+4050-265+Port' +
'o,+Portugal/41.1442506,-8.6138221/Mercado+Ferreira+Borges,+R.+da+Bolsa+19,+4050-253+Porto,+Portugal/' +
'Pal%C3%A1cio+da+Bolsa,+R.+de+Ferreira+Borges+11,+4050-253+Porto,+Portugal/41.1403376,-8.6145436/@41.' +
'1443544,-8.6187204,1418m/data=!3m2!1e3!5s0xd2464e1c85c7cb9:0x8dcf9241515af39c!4m67!4m66!1m5!1m1!1s0x' +
'd2464e386381dd9:0x71fe2c588c0e5d5c!2m2!1d-8.6107393!2d41.1461867!1m5!1m1!1s0xd2464e251ced649:0x425ec' +
'51327127c21!2m2!1d-8.6145977!2d41.1456705!1m5!1m1!1s0xd2464e28c5e9a77:0x7f08405ee8a1e44f!2m2!1d-8.61' +
'48718!2d41.1468104!1m5!1m1!1s0xd2464e2992d6fc9:0x14e81d436806274!2m2!1d-8.6162729!2d41.1473563!1m15!' +
'1m1!1s0xd2464e2aef96389:0xfdd13b0f82024051!2m2!1d-8.6155251!2d41.1484332!3m4!1m2!1d-8.6175322!2d41.1' +
'457355!3s0xd24651da106d14d:0x3fc8d2a99969c3c9!3m4!1m2!1d-8.6158595!2d41.1453503!3s0xd2464e271988c81:' +
'0x9c8eada62d9eb19e!1m5!1m1!1s0xd2464e1fb67ccaf:0x83772eddb20da5!2m2!1d-8.6158324!2d41.1430829!1m5!3m' +
'4!1m2!1d-8.6147197!2d41.1430656!3s0xd2464e1932b9b77:0x52ecdbda923433b2!1m5!1m1!1s0xd2464e1c90c863d:0' +
'xbdf9a36d350cdbae!2m2!1d-8.615126!2d41.1419501!1m5!1m1!1s0xd2464e1c2820d41:0x69324171e40cd951!2m2!1d' +
'-8.6156725!2d41.1413772!1m0!3e2';
/** https://maps.app.goo.gl/VigUDiFTi652ZJ58A */
export const PORTO_ALIADOS =
'https://www.google.com/maps/dir/Sculpture+Dom+Pedro+IV/Porto+City+Hall,+PC+GEN+Humberto+Delgado,+404' +
'9-001+Porto,+Portugal/Igreja+da+Sant%C3%ADssima+Trindade,+Pra%C3%A7a+Trindade+170,+4000-539+Porto,+P' +
'ortugal/Chapel+of+Souls,+R.+de+Santa+Catarina+428,+4000-124+Porto,+Portugal/Majestic+Caf%C3%A9,+R.+d' +
'e+Santa+Catarina+112,+4000-442+Porto,+Portugal/Jardim+Marques+de+Oliveira,+Passeio+de+S%C3%A3o+L%C3%' +
'A1zaro+33,+4000-507+Porto,+Portugal/Church+of+Saint+Ildefonso,+Pra%C3%A7a+da+Batalha+s%2Fn,+4000-101' +
'+Porto,+Portugal/Pra%C3%A7a+da+Batalha,+R.+de+Augusto+Rosa,+4000-529+Porto,+Portugal/Porto+S%C3%A3o+' +
'Bento,+Pra%C3%A7a+de+Almeida+Garrett,+4000-069+Porto,+Portugal/@41.145893,-8.6093059,709m/data=!3m2!' +
'1e3!5s0xd2464fb7b6cb07b:0x89f066ff0f3967a4!4m61!4m60!1m5!1m1!1s0x0:0x3ef7f76b5b4253d6!2m2!1d-8.61157' +
'72!2d41.1463491!1m5!1m1!1s0xd2464fca6339107:0x5dc6096016a67879!2m2!1d-8.6107023!2d41.1499084!1m5!1m1' +
'!1s0xd2464fb615293c7:0x7c79e721d53d0f87!2m2!1d-8.6105681!2d41.1508419!1m5!1m1!1s0xd2464faae719e5f:0x' +
'11125f1ca37787b5!2m2!1d-8.6056554!2d41.1498821!1m5!1m1!1s0xd2464e5a52a2493:0x1dc3afde71cae5f4!2m2!1d' +
'-8.6065795!2d41.1472382!1m5!1m1!1s0xd2464ef2191b9e3:0xb0d8f9ac36dd3f2c!2m2!1d-8.602522!2d41.1459635!' +
'1m5!1m1!1s0xd2464e5bc4a1885:0x1d8d4eb48388fdc7!2m2!1d-8.6066989!2d41.1460999!1m10!1m1!1s0xd2464e6783' +
'e9b1f:0xb97ba181af122779!2m2!1d-8.6070394!2d41.1451574!3m4!1m2!1d-8.6082184!2d41.1461502!3s0xd2464e4' +
'44e45d6b:0xf1247bcc87b60d1d!1m5!1m1!1s0xd2464e4756ff947:0x124f921e49a8773e!2m2!1d-8.609544!2d41.1454' +
'92!3e2';
/** https://maps.app.goo.gl/gwKHfs8TNxShEBBk7 */
export const PORTO_RIBEIRA =
'https://www.google.com/maps/dir/Igreja+de+Santa+Clara,+Largo+Primeiro+de+Dezembro,+4000-404+Porto,+P' +
'ortugal/Porto+Cathedral,+Terreiro+da+S%C3%A9,+4050-573+Porto,+Portugal/Mosteiro+Santo+Agostinho+da+S' +
'erra+do+Pilar,+Largo+Aviz,+4430-329+Vila+Nova+de+Gaia,+Portugal/Mirador+de+Porto+y+Duero/Ribeira+de+' +
'Gaia/@41.139645,-8.6121024,1418m/data=!3m2!1e3!5s0xd2464e7415940f5:0x9c2de86e34f7d338!4m32!4m31!1m5!' +
'1m1!1s0xd2464e6c2a4163b:0xfde6dd68a1ab3e6c!2m2!1d-8.6092477!2d41.1425899!1m5!1m1!1s0xd2464e13991ebb9' +
':0x4a1cccaea07537e9!2m2!1d-8.6111165!2d41.1428531!1m5!1m1!1s0xd2464ddc3346ee7:0xab7221d21110d0a3!2m2' +
'!1d-8.6075262!2d41.138298!1m5!1m1!1s0xd24657223ef3713:0xc8700250c6991029!2m2!1d-8.609616!2d41.139145' +
'2!1m5!1m1!1s0xd2464de113e580d:0x7e3c5edb72fc8aa9!2m2!1d-8.6117899!2d41.1382776!3e2';
/** https://maps.app.goo.gl/sePQGivnkMLuTUd86 */
export const GAIA_CELLARS =
'https://www.google.com/maps/dir/Mercado+Municipal+de+Gaia,+Largo+Sampaio+Bruno+10,+4400-161+Vila+Nov' +
"a+de+Gaia,+Portugal/Cockburn's,+R.+de+Serpa+Pinto+346,+4400-307+Vila+Nova+de+Gaia,+Portugal/Croft+Po" +
'rt/Arco+e+Meio+-+Portuguese+Wine+Shop,+Tv.+de+C%C3%A2ndido+dos+Reis+9,+4430-999+Vila+Nova+de+Gaia,+P' +
'ortugal/@41.1352706,-8.620441,1418m/data=!3m2!1e3!4b1!4m26!4m25!1m5!1m1!1s0xd2465207829c837:0xa058d1' +
'5855e35382!2m2!1d-8.6162726!2d41.1369384!1m5!1m1!1s0xd246520d2b824a3:0xe5019341caefb9df!2m2!1d-8.618' +
'1478!2d41.133527!1m5!1m1!1s0xd246521b0dbd957:0x9a6db3995f97d21b!2m2!1d-8.615071!2d41.1349963!1m5!1m1' +
'!1s0xd2464def5bfcab3:0xef35a43b60659b42!2m2!1d-8.6121984!2d41.1365006!3e2';
+2
View File
@@ -2,6 +2,7 @@ import { PlaceImportService } from '../../src/nest/place-import/place-import.ser
import { CollectionGpxProvider } from '../../src/nest/place-import/providers/collection-gpx.provider';
import { GoogleDirectionsProvider } from '../../src/nest/place-import/providers/google-directions.provider';
import { GoogleListProvider } from '../../src/nest/place-import/providers/google-list.provider';
import { GoogleMapsShortLinkProvider } from '../../src/nest/place-import/providers/google-maps-short-link.provider';
import { GpxProvider } from '../../src/nest/place-import/providers/gpx.provider';
import { KmlProvider } from '../../src/nest/place-import/providers/kml.provider';
import { NaverListProvider } from '../../src/nest/place-import/providers/naver-list.provider';
@@ -18,5 +19,6 @@ export function buildPlaceImportService(): PlaceImportService {
new GoogleListProvider(),
new GoogleDirectionsProvider(),
new NaverListProvider(),
new GoogleMapsShortLinkProvider(),
);
}
@@ -0,0 +1,80 @@
/**
* Which Google Maps links a pasted link may be (GMH-*): the host shape the
* place and route imports check, and the narrower short and long link shapes
* the city walk import follows and reads (CW-06).
*/
import {
isGoogleMapsHost,
isGoogleMapsLongLink,
isGoogleMapsShortLink,
} from '../../../../src/nest/common/google-maps-hosts';
import { describe, expect, it } from 'vitest';
const url = (raw: string) => new URL(raw);
describe('isGoogleMapsHost', () => {
it('GMH-001: takes Google on every country domain and the short hosts, nothing that only looks like it', () => {
for (const host of [
'google.com',
'www.google.de',
'maps.google.co.uk',
'google.com.au',
'maps.app.goo.gl',
'goo.gl',
]) {
expect(isGoogleMapsHost(host)).toBe(true);
}
for (const host of ['google.evil.com', 'evilgoogle.com', 'maps.google.com.evil.io', 'mail.google.com']) {
expect(isGoogleMapsHost(host)).toBe(false);
}
});
});
describe('isGoogleMapsShortLink (CW-06)', () => {
it('GMH-010: follows a maps.app.goo.gl code and a goo.gl/maps code', () => {
expect(isGoogleMapsShortLink(url('https://maps.app.goo.gl/gwKHfs8TNxShEBBk7'))).toBe(true);
expect(isGoogleMapsShortLink(url('https://maps.app.goo.gl/AbC1/'))).toBe(true);
expect(isGoogleMapsShortLink(url('https://goo.gl/maps/AbC1'))).toBe(true);
// The default port is no port.
expect(isGoogleMapsShortLink(url('https://maps.app.goo.gl:443/AbC1'))).toBe(true);
});
it('GMH-011: refuses plain http, credentials, another port, other paths and look-alike hosts', () => {
for (const raw of [
'http://maps.app.goo.gl/AbC1',
'https://user:pw@maps.app.goo.gl/AbC1',
'https://user@maps.app.goo.gl/AbC1',
'https://maps.app.goo.gl:8443/AbC1',
'https://maps.app.goo.gl/',
'https://maps.app.goo.gl/a/b',
'https://goo.gl/xyz',
'https://goo.gl/maps/a/b',
'https://maps.app.goo.gl.evil.com/AbC1',
'https://www.google.com/maps/dir/A/B',
]) {
expect(isGoogleMapsShortLink(url(raw))).toBe(false);
}
});
});
describe('isGoogleMapsLongLink (CW-06)', () => {
it('GMH-020: reads Google Maps on a country domain', () => {
expect(isGoogleMapsLongLink(url('https://www.google.com/maps/dir/A/B'))).toBe(true);
expect(isGoogleMapsLongLink(url('https://www.google.de/maps/dir/A/B'))).toBe(true);
expect(isGoogleMapsLongLink(url('https://maps.google.co.uk/maps/dir/A/B'))).toBe(true);
});
it('GMH-021: refuses another host, a short host, credentials, another port and plain http', () => {
for (const raw of [
'https://google.evil.com/maps/dir/A/B',
'https://maps.app.goo.gl/AbC1',
'https://goo.gl/maps/AbC1',
'https://user:pw@www.google.com/maps/dir/A/B',
'https://www.google.com:8443/maps/dir/A/B',
'http://www.google.com/maps/dir/A/B',
]) {
expect(isGoogleMapsLongLink(url(raw))).toBe(false);
}
});
});
@@ -7,10 +7,12 @@
* that matter, because the full ones run to four hundred characters of protobuf.
*/
import {
directionsTravelMode,
isDirectionsUrl,
parseDirectionsUrl,
MAX_DIR_WAYPOINTS,
} from '../../../../src/nest/place-import/directions-url.helpers';
import { GAIA_CELLARS, PORTO_ALIADOS, PORTO_CLERIGOS, PORTO_RIBEIRA } from '../../../fixtures/google-maps-walks';
import { describe, it, expect } from 'vitest';
@@ -119,3 +121,143 @@ describe('parseDirectionsUrl', () => {
expect(parseDirectionsUrl('https://www.google.com/maps/dir/%E0%A4%A/Dresden')).toHaveLength(2);
});
});
describe('parseDirectionsUrl with stop blocks (CW-07)', () => {
const blocks = (url: string) => parseDirectionsUrl(url, MAX_DIR_WAYPOINTS, 'stop-blocks');
const placed = (url: string) => blocks(url).filter((stop) => stop.lat !== null).length;
it('MAPS-DIR-030: a real walk places every stop from its own block, in order and with its name', () => {
expect(blocks(PORTO_RIBEIRA)).toEqual([
{
name: 'Igreja de Santa Clara, Largo Primeiro de Dezembro, 4000-404 Porto, Portugal',
lat: 41.1425899,
lng: -8.6092477,
},
{ name: 'Porto Cathedral, Terreiro da Sé, 4050-573 Porto, Portugal', lat: 41.1428531, lng: -8.6111165 },
{
name: 'Mosteiro Santo Agostinho da Serra do Pilar, Largo Aviz, 4430-329 Vila Nova de Gaia, Portugal',
lat: 41.138298,
lng: -8.6075262,
},
{ name: 'Mirador de Porto y Duero', lat: 41.1391452, lng: -8.609616 },
{ name: 'Ribeira de Gaia', lat: 41.1382776, lng: -8.6117899 },
]);
// Where every stop has one pair, both readings agree.
expect(parseDirectionsUrl(PORTO_RIBEIRA)).toEqual(blocks(PORTO_RIBEIRA));
expect(placed(GAIA_CELLARS)).toBe(4);
});
it('MAPS-DIR-031: a point the line was dragged through is not taken for the stop it follows', () => {
const stops = blocks(PORTO_ALIADOS);
expect(stops).toHaveLength(9);
expect(stops.every((stop) => stop.lat !== null)).toBe(true);
// Praça da Batalha's own position, not the dragged point (41.1461502, -8.6082184) in its block.
expect(stops[7]).toEqual({
name: 'Praça da Batalha, R. de Augusto Rosa, 4000-529 Porto, Portugal',
lat: 41.1451574,
lng: -8.6070394,
});
// The pair count has one pair too many there, so the road trip reading places nothing.
expect(parseDirectionsUrl(PORTO_ALIADOS).every((stop) => stop.lat === null)).toBe(true);
});
it('MAPS-DIR-032: stops given as coordinates keep them, and the stops after them keep their own', () => {
const stops = blocks(PORTO_CLERIGOS);
expect(stops).toHaveLength(10);
expect(stops.slice(5, 10)).toEqual([
{
name: 'Miradouro da Vitória, R. de São Bento da Vitória 11, 4050-265 Porto, Portugal',
lat: 41.1430829,
lng: -8.6158324,
},
{ name: null, lat: 41.1442506, lng: -8.6138221 },
{ name: 'Mercado Ferreira Borges, R. da Bolsa 19, 4050-253 Porto, Portugal', lat: 41.1419501, lng: -8.615126 },
{
name: 'Palácio da Bolsa, R. de Ferreira Borges 11, 4050-253 Porto, Portugal',
lat: 41.1413772,
lng: -8.6156725,
},
{ name: null, lat: 41.1403376, lng: -8.6145436 },
]);
expect(placed(PORTO_CLERIGOS)).toBe(10);
expect(parseDirectionsUrl(PORTO_CLERIGOS).filter((stop) => stop.lat !== null)).toHaveLength(2);
});
it('MAPS-DIR-033: a blob that does not pair up with the stops places none of them', () => {
const route = 'https://www.google.com/maps/dir/Cathedral/Market/Park/';
const block = (lng: number, lat: number) => `!1m5!1m1!1s0x0:0x0!2m2!1d${lng}!2d${lat}`;
// Two blocks for three stops.
expect(placed(`${route}data=!4m13!4m12${block(11.5, 48.1)}${block(11.51, 48.11)}`)).toBe(0);
// A message that claims more than follows it, a token that is no field, a count that is no number.
expect(placed(`${route}data=!4m30!4m29${block(11.5, 48.1)}${block(11.51, 48.11)}${block(11.52, 48.12)}`)).toBe(0);
expect(placed(`${route}data=!4m19!4m18${block(11.5, 48.1)}${block(11.51, 48.11)}!zz${block(11.52, 48.12)}`)).toBe(
0,
);
expect(placed(`${route}data=!4mX${block(11.5, 48.1)}${block(11.51, 48.11)}${block(11.52, 48.12)}`)).toBe(0);
// No route message at all, and no blob.
expect(placed(`${route}data=!3m1!1e3`)).toBe(0);
expect(placed(route)).toBe(0);
});
it('MAPS-DIR-034: a stop whose block holds no position of its own, or one off the globe, stays without one', () => {
const route = 'https://www.google.com/maps/dir/Cathedral/Market/Park/';
const url = `${route}data=!4m14!4m13!1m0!1m5!1m1!1s0x0:0x0!2m2!1d11.51!2d48.11!1m5!1m1!1s0x0:0x0!2m2!1d11.5!2d99`;
expect(blocks(url)).toEqual([
{ name: 'Cathedral', lat: null, lng: null },
{ name: 'Market', lat: 48.11, lng: 11.51 },
{ name: 'Park', lat: null, lng: null },
]);
});
});
describe('directionsTravelMode (CW-07)', () => {
const dir = 'https://www.google.com/maps/dir/Cathedral/Market/@48.1,11.5,15z/';
it('MAPS-DIR-040: reads on foot from the data blob and from the documented parameter', () => {
expect(directionsTravelMode(`${dir}data=!4m2!4m1!3e2`)).toBe('walking');
expect(directionsTravelMode(`${dir}data=%214m2%214m1%213e2`)).toBe('walking');
expect(
directionsTravelMode('https://www.google.com/maps/dir/?api=1&origin=A&destination=B&travelmode=walking'),
).toBe('walking');
expect(
directionsTravelMode('https://www.google.com/maps/dir/?api=1&origin=A&destination=B&travelmode=WALKING'),
).toBe('walking');
for (const walk of [PORTO_RIBEIRA, PORTO_ALIADOS, PORTO_CLERIGOS, GAIA_CELLARS]) {
expect(directionsTravelMode(walk)).toBe('walking');
}
});
it('MAPS-DIR-041: tells a car, a bike and transit apart, and names any other mode as other', () => {
expect(directionsTravelMode(`${dir}data=!3e0`)).toBe('driving');
expect(directionsTravelMode(`${dir}data=!3e1`)).toBe('bicycling');
expect(directionsTravelMode(`${dir}data=!3e3`)).toBe('transit');
expect(directionsTravelMode(`${dir}data=!3e9`)).toBe('other');
expect(directionsTravelMode('https://www.google.com/maps/dir/?api=1&destination=B&travelmode=driving')).toBe(
'driving',
);
expect(directionsTravelMode('https://www.google.com/maps/dir/?api=1&destination=B&travelmode=bicycling')).toBe(
'bicycling',
);
expect(directionsTravelMode('https://www.google.com/maps/dir/?api=1&destination=B&travelmode=transit')).toBe(
'transit',
);
expect(directionsTravelMode('https://www.google.com/maps/dir/?api=1&destination=B&travelmode=two-wheeler')).toBe(
'other',
);
});
it('MAPS-DIR-042: a link that says nothing, or two different things, is unknown', () => {
expect(directionsTravelMode(dir)).toBe('unknown');
expect(directionsTravelMode(`${dir}data=!4m2!4m1!1m0`)).toBe('unknown');
expect(directionsTravelMode(`${dir}data=!3e2?travelmode=driving`)).toBe('unknown');
expect(directionsTravelMode(`${dir}data=!3e2!3e0`)).toBe('unknown');
// The same mode said twice is still one mode.
expect(directionsTravelMode(`${dir}data=!3e2?travelmode=walking`)).toBe('walking');
});
it('MAPS-DIR-043: !3e means the mode only in the data blob of a route', () => {
expect(directionsTravelMode(`${dir}?pb=!3e2`)).toBe('unknown');
expect(directionsTravelMode('https://www.google.com/maps/place/Cathedral/data=!3e2')).toBe('unknown');
expect(directionsTravelMode('not a link')).toBe('unknown');
});
});
@@ -0,0 +1,231 @@
/**
* GoogleMapsShortLinkProvider (CW-06, SHORT-*): a Google Maps short link
* followed for the city walk import. The real SSRF guard and the real pinned
* dispatcher run; only the resolver and the global fetch are stubbed, so every
* case can say which names were looked up and which requests went out.
*/
import {
GoogleMapsShortLinkProvider,
SHORT_LINK_LIMITS,
} from '../../../../src/nest/place-import/providers/google-maps-short-link.provider';
import { PORTO_RIBEIRA } from '../../../fixtures/google-maps-walks';
import dns from 'dns/promises';
import { Agent } from 'undici';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('dns/promises', () => ({ default: { lookup: vi.fn() }, lookup: vi.fn() }));
const lookup = vi.mocked(dns.lookup);
const SHORT = 'https://maps.app.goo.gl/gwKHfs8TNxShEBBk7';
const PUBLIC_IP = '142.250.185.14';
/** Every name resolves to the address its entry gives, a public one otherwise. */
function resolveAs(addresses: Record<string, string> = {}) {
lookup.mockImplementation((async (hostname: string) => [
{ address: addresses[hostname] ?? PUBLIC_IP, family: 4 },
]) as unknown as typeof dns.lookup);
}
function redirect(location: string, status = 302) {
return new Response(null, { status, headers: { location } });
}
/** The answers in order, one per request. */
function answers(...responses: Array<Response | object>) {
const fetchSpy = vi.fn();
for (const response of responses) fetchSpy.mockResolvedValueOnce(response);
vi.stubGlobal('fetch', fetchSpy);
return fetchSpy;
}
const lookedUp = () => lookup.mock.calls.map((call) => call[0]);
/** The cases one after another, each settled before the next starts, as the stubs are set per case. */
function inTurn<T>(items: readonly T[], run: (item: T) => Promise<void>): Promise<void> {
return items.reduce<Promise<void>>((previous, item) => previous.then(() => run(item)), Promise.resolve());
}
const provider = new GoogleMapsShortLinkProvider();
beforeEach(() => resolveAs());
afterEach(() => {
vi.unstubAllGlobals();
vi.unstubAllEnvs();
lookup.mockReset();
});
describe('GoogleMapsShortLinkProvider', () => {
it('SHORT-001: one hop to a Google Maps route is the answer, and the route itself is never asked', async () => {
const fetchSpy = answers(redirect(PORTO_RIBEIRA));
expect(await provider.resolve(SHORT)).toEqual({ ok: true, url: PORTO_RIBEIRA });
expect(fetchSpy).toHaveBeenCalledTimes(1);
expect(fetchSpy.mock.calls[0][0]).toBe(SHORT);
expect(lookedUp()).toEqual(['maps.app.goo.gl']);
});
it('SHORT-002: a hop that leaves the allow-list is refused before it is looked up or asked', async () => {
const locations = [
'https://evil.example/maps/dir/A/B',
'http://169.254.169.254/latest/meta-data/',
'https://www.google.com.evil.io/maps/dir/A/B',
'https://user:pw@www.google.com/maps/dir/A/B',
'https://goo.gl/xyz',
];
await inTurn(locations, async (location) => {
lookup.mockClear();
const fetchSpy = answers(redirect(location));
expect(await provider.resolve(SHORT)).toEqual({ ok: false, why: 'refused' });
expect(fetchSpy).toHaveBeenCalledTimes(1);
expect(lookedUp()).toEqual(['maps.app.goo.gl']);
});
});
it('SHORT-003: a short link whose name leads into this network is refused at that hop', async () => {
await inTurn(['127.0.0.1', '10.0.0.1', '169.254.169.254'], async (address) => {
resolveAs({ 'goo.gl': address });
const fetchSpy = answers(redirect('https://goo.gl/maps/next'));
expect(await provider.resolve(SHORT)).toEqual({ ok: false, why: 'refused' });
expect(fetchSpy).toHaveBeenCalledTimes(1);
});
// The first hop itself, too.
resolveAs({ 'maps.app.goo.gl': '192.168.1.5' });
const fetchSpy = answers();
expect(await provider.resolve(SHORT)).toEqual({ ok: false, why: 'refused' });
expect(fetchSpy).not.toHaveBeenCalled();
});
it('SHORT-004: ALLOW_INTERNAL_NETWORK and ALLOW_LINK_LOCAL_IPS do not open it', async () => {
vi.stubEnv('ALLOW_INTERNAL_NETWORK', 'true');
vi.stubEnv('ALLOW_LINK_LOCAL_IPS', '169.254.1.2');
vi.resetModules();
const fresh = await import('../../../../src/nest/place-import/providers/google-maps-short-link.provider');
const freshLookup = vi.mocked((await import('dns/promises')).default.lookup);
const strict = new fresh.GoogleMapsShortLinkProvider();
const fetchSpy = answers();
await inTurn(['10.0.0.1', '169.254.1.2', 'fd00::1'], async (address) => {
freshLookup.mockResolvedValue([{ address, family: address.includes(':') ? 6 : 4 }] as never);
expect(await strict.resolve(SHORT)).toEqual({ ok: false, why: 'refused' });
});
expect(fetchSpy).not.toHaveBeenCalled();
});
it('SHORT-005: three hops at most', async () => {
const fetchSpy = answers(
redirect('https://maps.app.goo.gl/two'),
redirect('https://maps.app.goo.gl/three'),
redirect('https://maps.app.goo.gl/four'),
);
expect(await provider.resolve(SHORT)).toEqual({ ok: false, why: 'too_many_redirects' });
expect(fetchSpy).toHaveBeenCalledTimes(SHORT_LINK_LIMITS.hops);
// Within the limit a short link may lead on to another one.
answers(redirect('https://goo.gl/maps/next', 301), redirect(PORTO_RIBEIRA, 307));
expect(await provider.resolve(SHORT)).toEqual({ ok: true, url: PORTO_RIBEIRA });
});
it('SHORT-006: one deadline over the whole chain, a name lookup that hangs included', async () => {
const hanging = vi.fn(
(_url: string, init: RequestInit) =>
new Promise((_resolve, reject) => {
init.signal?.addEventListener('abort', () => reject(init.signal?.reason));
}),
);
vi.stubGlobal('fetch', hanging);
expect(await provider.resolve(SHORT, { ...SHORT_LINK_LIMITS, deadlineMs: 20 })).toEqual({
ok: false,
why: 'unreachable',
});
expect(hanging).toHaveBeenCalledTimes(1);
lookup.mockImplementation((() => new Promise(() => undefined)) as unknown as typeof dns.lookup);
const fetchSpy = answers();
expect(await provider.resolve(SHORT, { ...SHORT_LINK_LIMITS, deadlineMs: 20 })).toEqual({
ok: false,
why: 'unreachable',
});
expect(fetchSpy).not.toHaveBeenCalled();
});
it('SHORT-007: a hop that answers after the deadline is not followed further', async () => {
resolveAs();
const late = vi.fn(
() => new Promise((resolve) => setTimeout(() => resolve(redirect('https://maps.app.goo.gl/next')), 40)),
);
vi.stubGlobal('fetch', late);
expect(await provider.resolve(SHORT, { ...SHORT_LINK_LIMITS, deadlineMs: 10 })).toEqual({
ok: false,
why: 'unreachable',
});
expect(late).toHaveBeenCalledTimes(1);
});
it('SHORT-008: no body is read, and a Location longer than a link is refused', async () => {
const cancel = vi.fn().mockResolvedValue(undefined);
const getReader = vi.fn();
const huge = {
status: 302,
headers: new Headers({
location: `https://www.google.com/maps/dir/${'A/'.repeat(SHORT_LINK_LIMITS.locationChars)}`,
'content-length': String(10 ** 9),
}),
body: { cancel, getReader },
};
answers(huge);
expect(await provider.resolve(SHORT)).toEqual({ ok: false, why: 'unreachable' });
expect(cancel).toHaveBeenCalledTimes(1);
expect(getReader).not.toHaveBeenCalled();
});
it('SHORT-009: nothing of the caller goes along, and nothing is followed by fetch itself', async () => {
const fetchSpy = answers(redirect(PORTO_RIBEIRA));
await provider.resolve(SHORT);
const init = fetchSpy.mock.calls[0][1] as RequestInit & { dispatcher?: unknown };
expect(init).toMatchObject({
method: 'GET',
redirect: 'manual',
credentials: 'omit',
referrerPolicy: 'no-referrer',
});
expect(init.signal).toBeInstanceOf(AbortSignal);
expect(init.dispatcher).toBeDefined();
const headers = new Headers(init.headers);
expect(headers.has('cookie')).toBe(false);
expect(headers.has('authorization')).toBe(false);
});
it('SHORT-010: an answer that is no redirect, and a redirect relative to the short host', async () => {
answers(new Response('not found', { status: 404 }));
expect(await provider.resolve(SHORT)).toEqual({ ok: false, why: 'no_redirect' });
answers(redirect('/elsewhere'), redirect(PORTO_RIBEIRA));
expect(await provider.resolve(SHORT)).toEqual({ ok: true, url: PORTO_RIBEIRA });
// A 3xx without a Location leads nowhere.
answers(new Response(null, { status: 302 }));
expect(await provider.resolve(SHORT)).toEqual({ ok: false, why: 'no_redirect' });
});
it('SHORT-011: a start that is no short link, or no link, is refused without a request', async () => {
const fetchSpy = answers();
const answered = await Promise.all(
['not a link', 'https://www.google.com/maps/dir/A/B', 'https://bit.ly/abc'].map((raw) => provider.resolve(raw)),
);
expect(answered).toEqual(Array(3).fill({ ok: false, why: 'refused' }));
expect(fetchSpy).not.toHaveBeenCalled();
expect(lookup).not.toHaveBeenCalled();
});
it('SHORT-012: a Location that is no link at all is refused', async () => {
answers(redirect('https://['));
expect(await provider.resolve(SHORT)).toEqual({ ok: false, why: 'refused' });
});
it('SHORT-013: a request that fails is unreachable, and a dispatcher that will not close changes no answer', async () => {
vi.stubGlobal('fetch', vi.fn().mockRejectedValue('socket hang up'));
expect(await provider.resolve(SHORT)).toEqual({ ok: false, why: 'unreachable' });
const close = vi.spyOn(Agent.prototype, 'close').mockRejectedValueOnce(new Error('busy') as never);
answers(redirect(PORTO_RIBEIRA));
expect(await provider.resolve(SHORT)).toEqual({ ok: true, url: PORTO_RIBEIRA });
expect(close).toHaveBeenCalledTimes(1);
close.mockRestore();
});
});
@@ -10,6 +10,7 @@ import {
createGpxParser,
writeGpx,
} from '../../../../src/nest/place-import/gpx.codec';
import { GoogleMapsShortLinkProvider } from '../../../../src/nest/place-import/providers/google-maps-short-link.provider';
import { buildPlaceImportService } from '../../../helpers/place-import';
import { COLLECTION_FILE_FORMAT, COLLECTION_FILE_VERSION } from '@trek/shared';
@@ -69,6 +70,20 @@ describe('PlaceImportService: directions', () => {
});
});
describe('PlaceImportService: Google Maps short links (CW-06)', () => {
it('hands a short link to its own narrow resolver and its answer back as it stands', async () => {
const resolve = vi
.spyOn(GoogleMapsShortLinkProvider.prototype, 'resolve')
.mockResolvedValue({ ok: false, why: 'too_many_redirects' });
expect(await buildPlaceImportService().resolveGoogleShortLink('https://maps.app.goo.gl/abc')).toEqual({
ok: false,
why: 'too_many_redirects',
});
expect(resolve).toHaveBeenCalledWith('https://maps.app.goo.gl/abc');
resolve.mockRestore();
});
});
describe('PlaceImportService: files and lists', () => {
const svc = buildPlaceImportService();
@@ -0,0 +1,49 @@
/**
* TourWalkImportController (CW-07): the route metadata of the Google Maps
* walk preview and its delegation to TourWalkImportService.
*/
import 'reflect-metadata';
import { AddonGuard } from '../../../src/nest/addons/addon.guard';
import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';
import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';
import { TRIP_PERMISSION_KEY, TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';
import { TourWalkImportController } from '../../../src/nest/tours/tour-walk-import.controller';
import type { TourWalkImportService } from '../../../src/nest/tours/tour-walk-import.service';
import { RequestMethod } from '@nestjs/common';
import { GUARDS_METADATA, HTTP_CODE_METADATA, METHOD_METADATA, PATH_METADATA } from '@nestjs/common/constants';
import type { WalkImportPreviewResponse } from '@trek/shared';
import { describe, expect, it, vi } from 'vitest';
const answer: WalkImportPreviewResponse = {
stations: [
{ name: 'Cathedral', lat: 48.1, lng: 11.5 },
{ name: 'Market', lat: null, lng: null },
],
resolved_url: 'https://www.google.com/maps/dir/Cathedral/Market/data=!3e2',
};
describe('TourWalkImportController', () => {
it('WALK-IMPORT-CTL-001: sits behind the addon guard before auth and trip access, and needs place_edit', () => {
expect(Reflect.getMetadata(PATH_METADATA, TourWalkImportController)).toBe('api/trips/:tripId/tours');
expect(Reflect.getMetadata(GUARDS_METADATA, TourWalkImportController)).toEqual([
AddonGuard,
JwtAuthGuard,
TripAccessGuard,
]);
expect(Reflect.getMetadata(REQUIRE_ADDON, TourWalkImportController)).toEqual({ addonId: 'tours', label: 'Tours' });
const handler = TourWalkImportController.prototype.preview;
expect(Reflect.getMetadata(METHOD_METADATA, handler)).toBe(RequestMethod.POST);
expect(Reflect.getMetadata(PATH_METADATA, handler)).toBe('import/google-maps/preview');
expect(Reflect.getMetadata(HTTP_CODE_METADATA, handler)).toBe(200);
expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, handler)).toBe('place_edit');
});
it('WALK-IMPORT-CTL-002: hands the link to the service and answers what it answers', async () => {
const service = { preview: vi.fn(async () => answer) };
const controller = new TourWalkImportController(service as unknown as TourWalkImportService);
expect(await controller.preview({ url: 'https://maps.app.goo.gl/abc' })).toBe(answer);
expect(service.preview).toHaveBeenCalledExactlyOnceWith('https://maps.app.goo.gl/abc');
});
});
@@ -0,0 +1,95 @@
/**
* TourWalkImportMcp (CW-07, WALK-IMPORT-MCP-*): the Google Maps walk preview
* over MCP, with the same service and checks as REST. The subject comes from
* the container over a snapshot test db; the refusal text comes back through
* the registry's error mapper, as a client sees it.
*/
import { trekMcpErrorMapper } from '../../../src/mcp/nest-mcp-policy';
import type { McpContext } from '../../../src/nest-mcp';
import { DomainError, catchDomainError } from '../../../src/nest/common/domain-error';
import { McpToolGuardsService } from '../../../src/nest/mcp-shared/mcp-tool-guards.service';
import { GoogleMapsShortLinkProvider } from '../../../src/nest/place-import/providers/google-maps-short-link.provider';
import { TourWalkImportMcp } from '../../../src/nest/tours/tour-walk-import.mcp';
import { ToursModule } from '../../../src/nest/tours/tours.module';
import { PORTO_RIBEIRA } from '../../fixtures/google-maps-walks';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { createTrip, createUser } from '../../helpers/factories';
import { resetTestDb } from '../../helpers/test-db';
import { createTestModule, type TestModule } from '../../helpers/test-module';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const db = createSnapshotTestDb();
const resolve = vi.fn();
let t: TestModule;
let mcp: TourWalkImportMcp;
beforeAll(async () => {
t = await createTestModule({
db,
imports: [ToursModule],
overrides: [{ provide: GoogleMapsShortLinkProvider, useValue: { resolve } }],
});
mcp = t.get(TourWalkImportMcp);
});
beforeEach(() => {
resetTestDb(db);
resolve.mockReset();
});
afterAll(async () => {
await t.close();
db.close();
});
const ctx = (userId: number) => ({ userId }) as McpContext;
function read(result: { content: Array<{ type: string; text: string }>; isError?: boolean }) {
const text = result.content[0]?.text ?? '';
return result.isError ? { error: text } : JSON.parse(text);
}
function fixture() {
const { user } = createUser(db);
const { user: outsider } = createUser(db);
const trip = createTrip(db, user.id, { title: 'Porto' });
return { user, outsider, trip };
}
describe('TourWalkImportMcp', () => {
it('WALK-IMPORT-MCP-001: preview_google_maps_walk reads the stops of a walking route and stores nothing', async () => {
const { user, trip } = fixture();
const answer = read(await mcp.previewGoogleMapsWalk({ tripId: trip.id, url: PORTO_RIBEIRA }, ctx(user.id)));
expect(answer.resolved_url).toBe(PORTO_RIBEIRA);
expect(answer.stations).toHaveLength(5);
expect(answer.stations[3]).toEqual({ name: 'Mirador de Porto y Duero', lat: 41.1391452, lng: -8.609616 });
expect(resolve).not.toHaveBeenCalled();
});
it('WALK-IMPORT-MCP-002: nothing for someone outside the trip, nor for a member who may not edit places', async () => {
const { user, outsider, trip } = fixture();
expect((await mcp.previewGoogleMapsWalk({ tripId: trip.id, url: PORTO_RIBEIRA }, ctx(outsider.id))).isError).toBe(
true,
);
const denied = vi.spyOn(t.get(McpToolGuardsService), 'hasTripPermission').mockResolvedValue(false);
const result = await mcp.previewGoogleMapsWalk({ tripId: trip.id, url: PORTO_RIBEIRA }, ctx(user.id));
expect(result.isError).toBe(true);
expect(denied).toHaveBeenCalledWith('place_edit', trip.id, user.id);
denied.mockRestore();
});
it('WALK-IMPORT-MCP-003: a route not on foot is refused with the English text REST sends', async () => {
const { user, trip } = fixture();
const car = PORTO_RIBEIRA.replace(/!3e2$/, '!3e0');
const err = await catchDomainError(() => mcp.previewGoogleMapsWalk({ tripId: trip.id, url: car }, ctx(user.id)));
expect(err).toBeInstanceOf(DomainError);
expect(trekMcpErrorMapper(err)).toEqual({
content: [
{
type: 'text',
text: 'That route is not planned on foot. Switch Google Maps to walking and share the route again.',
},
],
isError: true,
});
});
});
@@ -0,0 +1,153 @@
/**
* TourWalkImportService (CW-07, WALK-IMPORT-*): a Google Maps walking route
* read into the stops of a city walk. The short link resolver and the map
* search are stubs: the first so no request leaves the test, the second to
* show it is never asked, since a stop without a position is not guessed.
*/
import { DomainError, catchDomainError } from '../../../src/nest/common/domain-error';
import { MapsService } from '../../../src/nest/maps/maps.service';
import { GoogleMapsShortLinkProvider } from '../../../src/nest/place-import/providers/google-maps-short-link.provider';
import { TourWalkImportService } from '../../../src/nest/tours/tour-walk-import.service';
import { ToursModule } from '../../../src/nest/tours/tours.module';
import { PORTO_ALIADOS, PORTO_RIBEIRA } from '../../fixtures/google-maps-walks';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { createTestModule, type TestModule } from '../../helpers/test-module';
import { TOUR_STATION_NAME_MAX, WALK_IMPORT_STATIONS_MAX, type WalkImportRefusal } from '@trek/shared';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const db = createSnapshotTestDb();
const resolve = vi.fn();
const maps = { geocodeQuery: vi.fn(), reverseGeocode: vi.fn(), searchPlaces: vi.fn() };
let t: TestModule;
let service: TourWalkImportService;
beforeAll(async () => {
t = await createTestModule({
db,
imports: [ToursModule],
overrides: [
{ provide: GoogleMapsShortLinkProvider, useValue: { resolve } },
{ provide: MapsService, useValue: maps },
],
});
service = t.get(TourWalkImportService);
});
beforeEach(() => {
resolve.mockReset();
for (const fn of Object.values(maps)) fn.mockReset();
});
afterAll(async () => {
await t.close();
db.close();
});
const DIR = 'https://www.google.com/maps/dir/';
const block = (lng: number, lat: number) => `!1m5!1m1!1s0x0:0x0!2m2!1d${lng}!2d${lat}`;
/** A walking route through the stops named, each with its position in the blob. */
function walk(names: string[], mode = '!3e2'): string {
const blocks = names.map((_, i) => block(11.5 + i / 100, 48.1 + i / 100)).join('');
const inner = names.length * 6 + (mode ? 1 : 0);
return `${DIR}${names.map(encodeURIComponent).join('/')}/@48.1,11.5,15z/data=!4m${inner + 1}!4m${inner}${blocks}${mode}`;
}
async function refusal(raw: string): Promise<{ status: number; reason: WalkImportRefusal; error: string }> {
const err = await catchDomainError(() => service.preview(raw));
if (!(err instanceof DomainError)) throw new Error('expected a refusal');
return { status: err.getStatus(), reason: err.details?.reason as WalkImportRefusal, error: err.publicMessage };
}
describe('TourWalkImportService.preview', () => {
it('WALK-IMPORT-001: a long walking link answers its stops in order and the link it read, with no request made', async () => {
const answer = await service.preview(` ${PORTO_RIBEIRA} `);
expect(answer.resolved_url).toBe(PORTO_RIBEIRA);
expect(answer.stations.map((station) => station.name)).toEqual([
'Igreja de Santa Clara, Largo Primeiro de Dezembro, 4000-404 Porto, Portugal',
'Porto Cathedral, Terreiro da Sé, 4050-573 Porto, Portugal',
'Mosteiro Santo Agostinho da Serra do Pilar, Largo Aviz, 4430-329 Vila Nova de Gaia, Portugal',
'Mirador de Porto y Duero',
'Ribeira de Gaia',
]);
expect(answer.stations[0]).toMatchObject({ lat: 41.1425899, lng: -8.6092477 });
expect(resolve).not.toHaveBeenCalled();
// A line dragged through a point of its own still places each stop on its own position.
expect((await service.preview(PORTO_ALIADOS)).stations.every((station) => station.lat !== null)).toBe(true);
});
it('WALK-IMPORT-002: a short link is read where the narrow resolver says it leads', async () => {
resolve.mockResolvedValue({ ok: true, url: PORTO_RIBEIRA });
const answer = await service.preview('https://maps.app.goo.gl/gwKHfs8TNxShEBBk7');
expect(resolve).toHaveBeenCalledExactlyOnceWith('https://maps.app.goo.gl/gwKHfs8TNxShEBBk7');
expect(answer.resolved_url).toBe(PORTO_RIBEIRA);
expect(answer.stations).toHaveLength(5);
});
it('WALK-IMPORT-003: names are trimmed and cut to a station name, and a stop given as coordinates has none', async () => {
const long = 'Museum '.repeat(40);
const answer = await service.preview(`${DIR}${encodeURIComponent(` ${long}`)}/48.12,11.52/data=!3e2`);
expect(answer.stations[0].name).toBe(long.trim().slice(0, TOUR_STATION_NAME_MAX).trim());
expect(answer.stations[0].name?.length).toBeLessThanOrEqual(TOUR_STATION_NAME_MAX);
expect(answer.stations[1]).toEqual({ name: null, lat: 48.12, lng: 11.52 });
});
it('WALK-IMPORT-004: a stop the link gives no position stays without one, and nothing is looked up', async () => {
// Three stops, two blocks: nothing lines up, so no stop takes a position from the blob.
const url = `${DIR}Cathedral/Market/Park/data=!4m14!4m13${block(11.5, 48.1)}${block(11.51, 48.11)}!3e2`;
const answer = await service.preview(url);
expect(answer.stations).toEqual([
{ name: 'Cathedral', lat: null, lng: null },
{ name: 'Market', lat: null, lng: null },
{ name: 'Park', lat: null, lng: null },
]);
for (const fn of Object.values(maps)) expect(fn).not.toHaveBeenCalled();
});
it('WALK-IMPORT-005: a car, a bike, transit or a link that does not say is refused with its reason', async () => {
expect(await refusal(walk(['A', 'B'], '!3e0'))).toMatchObject({ status: 400, reason: 'not_walking' });
expect(await refusal(walk(['A', 'B'], '!3e1'))).toMatchObject({ status: 400, reason: 'not_walking' });
expect(await refusal(walk(['A', 'B'], '!3e3'))).toMatchObject({ status: 400, reason: 'not_walking' });
expect(await refusal(walk(['A', 'B'], ''))).toMatchObject({ status: 400, reason: 'mode_unknown' });
expect(await refusal(`${walk(['A', 'B'])}?travelmode=driving`)).toEqual({
status: 400,
reason: 'mode_unknown',
error:
'The link does not say clearly that the route is on foot. Choose walking in Google Maps and share it again.',
});
});
it('WALK-IMPORT-006: a link that is no Google Maps route is refused for what it is', async () => {
expect(await refusal('not a link')).toMatchObject({ status: 400, reason: 'not_google_maps' });
expect(await refusal('https://example.com/maps/dir/A/B/data=!3e2')).toMatchObject({ reason: 'not_google_maps' });
expect(await refusal('https://www.google.evil.io/maps/dir/A/B/data=!3e2')).toMatchObject({
reason: 'not_google_maps',
});
expect(await refusal('https://bit.ly/walk')).toMatchObject({ reason: 'not_google_maps' });
expect(await refusal('https://www.google.com/maps/place/Cathedral/@48.1,11.5,17z')).toMatchObject({
status: 400,
reason: 'not_a_route',
});
expect(resolve).not.toHaveBeenCalled();
});
it('WALK-IMPORT-007: a short link the resolver refuses or cannot follow says which, the second as Google’s failure', async () => {
resolve.mockResolvedValueOnce({ ok: false, why: 'refused' });
expect(await refusal('https://maps.app.goo.gl/abc')).toMatchObject({ status: 400, reason: 'short_link_refused' });
// Each one Google's failure, not the link's.
const failed = await Promise.all(
(['unreachable', 'too_many_redirects', 'no_redirect'] as const).map((why) => {
resolve.mockResolvedValueOnce({ ok: false, why });
return refusal('https://maps.app.goo.gl/abc');
}),
);
expect(failed.map(({ status, reason }) => [status, reason])).toEqual(Array(3).fill([502, 'short_link_failed']));
});
it('WALK-IMPORT-008: fewer than two stops, or more than a walk takes, are refused', async () => {
expect(await refusal(`${DIR}Cathedral/data=!3e2`)).toMatchObject({ status: 400, reason: 'too_few_stops' });
const many = Array.from({ length: WALK_IMPORT_STATIONS_MAX + 1 }, (_, i) => `Stop${i}`);
expect(await refusal(walk(many))).toMatchObject({ status: 400, reason: 'too_many_stops' });
const most = await service.preview(walk(many.slice(0, WALK_IMPORT_STATIONS_MAX)));
expect(most.stations).toHaveLength(WALK_IMPORT_STATIONS_MAX);
expect(most.stations.every((station) => station.lat !== null)).toBe(true);
});
});