feat(collections): export and import a list as GPX

A list could leave the instance as a TREK file, which only another TREK
reads. Export now asks for a format, and GPX is the second one: the
places as waypoints, for OsmAnd, Organic Maps, a Garmin or gpx.studio.
Import takes a GPX in the same dialog as a list file. Asked for in
discussion #2301.

The GPX is written from the very list file the JSON export returns, so
what may leave the instance is still decided in one place. Name,
description and address, notes, website and category go into GPX's own
elements, where every app shows them. Labels, status, phone and the
rest travel in a TREK extension namespace, so a GPX made by TREK comes
back as the same list. A place without coordinates cannot be a
waypoint; it is left out and the export says how many were.

A GPX is read on the server, sent as text, with the XML library the
trip importer already uses. A document with a DOCTYPE is refused before
parsing, which closes both external entities and entity expansion. Size
is capped like the list file, and the element count is capped before a
tree is built. The reader only turns the GPX into a list file: the
browser previews it and imports it through the existing route, so one
contract, one transaction and one skipped counter cover both formats.
Waypoints and named route points become places; tracks and unnamed
route points are counted in the preview and not imported.

The two list-file routes get a body ceiling of twice the file limit.
The global 100 kB cap refused most real favourites files, and it
already refused list files well under the megabyte the contract allows.
This commit is contained in:
Maurice
2026-09-19 21:01:45 +02:00
parent bb6003684c
commit 80bb06c84f
57 changed files with 2506 additions and 109 deletions
+13 -2
View File
@@ -18,6 +18,7 @@ import { validateRouteGuards } from './nest/common/validate-route-guards';
import { validateManagedRoutes } from './nest/common/validate-managed-routes';
import { TrekWsAdapter } from './nest/realtime/trek-ws.adapter';
import { StorageService } from './nest/storage/storage.service';
import { MAX_COLLECTION_FILE_BYTES } from '@trek/shared';
/**
* Builds the unified TREK NestJS application that serves the ENTIRE surface — the
@@ -142,18 +143,28 @@ export async function buildApp(): Promise<INestApplication> {
* but a save that quietly fails and an editor that says "not saved" without
* saying why.
*
* So the book route, and only the book route, is measured against the size a
* book can actually be. Everything else keeps the tighter limit.
* So the book route is measured against the size a book can actually be.
*
* A list file is the same story at a smaller scale. Its contract allows a
* megabyte and the import posts it whole, yet a list of a few hundred places
* with notes is past a hundred kilobytes already, and so is the favourites
* GPX of anybody who uses OsmAnd (#2301). The two routes that carry one are
* measured against that megabyte, doubled for the JSON escaping of a
* document full of quotes. Everything else keeps the tighter limit.
*/
const bookBody = express.json({ limit: '8mb', verify: rawBodyKeeper });
const listFileBody = express.json({ limit: MAX_COLLECTION_FILE_BYTES * 2, verify: rawBodyKeeper });
const json = express.json({ limit: '100kb', verify: rawBodyKeeper });
const urlencoded = express.urlencoded({ limit: '100kb', extended: true, verify: rawBodyKeeper });
const isMcp = (req: Request) => req.path === '/mcp' || req.path === '/mcp/';
const isBookWrite = (req: Request) =>
req.method === 'PUT' && /^\/api\/journeys\/\d+\/book$/.test(req.path);
const listFilePaths = new Set(['/api/addons/collections/import', '/api/addons/collections/gpx/read']);
const isListFile = (req: Request) => req.method === 'POST' && listFilePaths.has(req.path);
instance.use(function jsonParser(req: Request, res: Response, next: NextFunction) {
if (isBookWrite(req)) return bookBody(req, res, next);
if (isListFile(req)) return listFileBody(req, res, next);
return isMcp(req) ? next() : json(req, res, next);
});
instance.use(function urlencodedParser(req: Request, res: Response, next: NextFunction) {
@@ -0,0 +1,483 @@
import { XMLParser } from 'fast-xml-parser';
import type { ZodType } from 'zod';
import {
COLLECTION_FILE_FORMAT,
COLLECTION_FILE_VERSION,
COLLECTION_GPX_NAMESPACE,
COLLECTION_GPX_PLACE_FIELDS,
MAX_COLLECTION_FILE_BYTES,
MAX_COLLECTION_FILE_LABELS,
MAX_COLLECTION_FILE_PLACES,
collectionFileLabelSchema,
collectionFilePlaceSchema,
collectionFileSchema,
collectionLinkSchema,
type CollectionFile,
type CollectionFileLabel,
type CollectionFilePlace,
type CollectionGpxExport,
type CollectionGpxProblem,
type CollectionGpxReadResult,
type CollectionLink,
} from '@trek/shared';
import { coord, gpxBuilder } from '../places/gpx-export.helpers';
/**
* A list as GPX and back (#2301).
*
* Both halves work on the list file from `collection-file.schema.ts`, never on
* rows: the writer is handed the file the JSON export returns, so it cannot
* carry anything the file does not, and the reader produces a file that is
* then imported like any other. The only thing this module decides is how the
* fields of a place map onto a waypoint, and that table lives in the contract
* (`COLLECTION_GPX_PLACE_FIELDS`).
*
* Same library as the trip importer and exporter in places/, with a reader of
* its own: the trip parser turns `<name>007</name>` into the number 7 and does
* not decode character references, which is fine for track geometry and wrong
* for the names and notes a list is made of.
*/
/** A list file as the exporter builds it, its places already in the file's shape. */
export type ExportedCollectionFile = Omit<CollectionFile, 'places'> & { places: CollectionFilePlace[] };
const GPX_NAMESPACE = 'http://www.topografix.com/GPX/1/1';
/** The prefix this writer binds; the reader looks the namespace up instead. */
const TREK = 'trek';
/** OsmAnd writes its favourites with the address in its own namespace. */
const OSMAND_NAMESPACES = ['https://osmand.net', 'http://osmand.net'];
const HTTP_URL = /^https?:\/\//i;
/** The extension fields that hold one value each; labels and links repeat. */
const SCALAR_EXTENSIONS = (Object.keys(COLLECTION_GPX_PLACE_FIELDS) as (keyof CollectionFilePlace)[]).filter(
field => COLLECTION_GPX_PLACE_FIELDS[field] === 'extension' && field !== 'labels' && field !== 'links',
);
// ---------------------------------------------------------------------------
// Writing
// ---------------------------------------------------------------------------
/**
* Text XML 1.0 can hold. The builder escapes markup but passes through the
* control characters the spec forbids outright, and one of those in a place
* name is enough for a strict reader to refuse the whole file.
*/
function xmlText(value: string): string {
return value.replace(/[\p{Cc}\p{Cs}\uFFFE\uFFFF]/gu, ch => (ch === '\t' || ch === '\n' || ch === '\r' ? ch : ''));
}
/** A value as element text, or nothing, since an empty element is noise to every reader. */
function textOf(value: string | number | null | undefined): string | undefined {
if (value === null || value === undefined) return undefined;
return xmlText(String(value)).trim() || undefined;
}
/**
* `<desc>` is what other apps show under the name, so it gets the place's
* description and, on a line of its own after it, the address: GPX has no
* element for an address, and without it a waypoint in OsmAnd is a pin with a
* name. The address also travels in the extension, which is what TREK reads
* back; the reader strips this copy again (see `withoutAddress`).
*/
function describe(place: CollectionFilePlace): string | undefined {
return textOf([place.description?.trim(), place.address?.trim()].filter(Boolean).join('\n\n'));
}
function placeExtensions(place: CollectionFilePlace): Record<string, unknown> | undefined {
const ext: Record<string, unknown> = {};
for (const field of SCALAR_EXTENSIONS) {
const value: unknown = place[field];
if (typeof value === 'string' || typeof value === 'number') ext[`${TREK}:${field}`] = textOf(value);
}
const labels = (place.labels ?? []).map(textOf).filter(Boolean);
if (labels.length) ext[`${TREK}:label`] = labels;
const links = (place.links ?? []).filter(link => HTTP_URL.test(link.url));
if (links.length) {
ext[`${TREK}:link`] = links.map(link => ({ '@_href': xmlText(link.url), '#text': textOf(link.label) }));
}
return Object.keys(ext).length ? ext : undefined;
}
/** Element order is the GPX 1.1 schema's: name, cmt, desc, link, type, extensions. */
function waypoint(place: CollectionFilePlace, lat: number, lng: number): Record<string, unknown> {
const website = place.website && HTTP_URL.test(place.website) ? xmlText(place.website) : undefined;
return {
'@_lat': coord(lat),
'@_lon': coord(lng),
name: xmlText(place.name),
cmt: textOf(place.notes),
desc: describe(place),
link: website ? { '@_href': website } : undefined,
type: textOf(place.category),
extensions: placeExtensions(place),
};
}
function metadata(file: ExportedCollectionFile): Record<string, unknown> {
const ext: Record<string, unknown> = {};
if (file.color) ext[`${TREK}:color`] = textOf(file.color);
if (file.icon) ext[`${TREK}:icon`] = textOf(file.icon);
if (file.labels?.length) {
ext[`${TREK}:label`] = file.labels.map(label => ({
...(label.color ? { '@_color': xmlText(label.color) } : {}),
'#text': xmlText(label.name),
}));
}
return {
name: xmlText(file.name),
desc: textOf(file.description),
time: file.exported_at,
extensions: Object.keys(ext).length ? ext : undefined,
};
}
/**
* The list as a GPX 1.1 document: one waypoint per place that has
* coordinates. A place without them cannot be a waypoint, so it is left out
* and counted, and the caller says how many.
*/
export function collectionFileToGpx(file: ExportedCollectionFile): CollectionGpxExport {
const wpt: Record<string, unknown>[] = [];
let omitted = 0;
for (const place of file.places) {
const { lat, lng } = place;
if (typeof lat !== 'number' || typeof lng !== 'number' || !Number.isFinite(lat) || !Number.isFinite(lng)) {
omitted += 1;
continue;
}
wpt.push(waypoint(place, lat, lng));
}
const gpx: string = gpxBuilder.build({
'?xml': { '@_version': '1.0', '@_encoding': 'UTF-8' },
gpx: {
'@_version': '1.1',
'@_creator': 'TREK',
'@_xmlns': GPX_NAMESPACE,
[`@_xmlns:${TREK}`]: COLLECTION_GPX_NAMESPACE,
'@_xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
'@_xsi:schemaLocation': `${GPX_NAMESPACE} ${GPX_NAMESPACE}/gpx.xsd`,
metadata: metadata(file),
...(wpt.length ? { wpt } : {}),
},
});
return { name: file.name, gpx, waypoints: wpt.length, omitted };
}
// ---------------------------------------------------------------------------
// Reading
// ---------------------------------------------------------------------------
/** Why a document was refused, carried to the controller as the response's `code`. */
export class CollectionGpxError extends Error {
constructor(
readonly code: CollectionGpxProblem,
message: string,
) {
super(message);
this.name = 'CollectionGpxError';
}
}
/**
* The most elements a document may open before it is parsed at all.
*
* The size cap already bounds this, but loosely: a megabyte of `<a/>` is a
* quarter of a million nodes for the parser to build. A real GPX of that size
* is a recorded track at three or four elements a point, around thirty
* thousand, so this sits well clear of every genuine file.
*/
export const MAX_GPX_ELEMENTS = 100_000;
/** Elements that may repeat, so they always parse as arrays. Matched on the local name. */
const REPEATED = new Set(['wpt', 'rte', 'rtept', 'trk', 'trkseg', 'trkpt', 'link', 'label']);
const localName = (name: string): string => name.slice(name.indexOf(':') + 1);
/**
* Text stays text (`parseTagValue: false`), so a waypoint called 007 keeps its
* zeros. `htmlEntities` is on for the numeric character references it also
* unlocks (`&#233;`), which this library otherwise leaves undecoded. Entities
* declared in a DOCTYPE never reach it: a document carrying one is refused
* before parsing.
*/
const reader = new XMLParser({
ignoreAttributes: false,
attributeNamePrefix: '@_',
parseTagValue: false,
parseAttributeValue: false,
htmlEntities: true,
isArray: (name, _path, _leaf, isAttribute) => !isAttribute && REPEATED.has(localName(name)),
});
type XmlNode = Record<string, unknown>;
function isNode(value: unknown): value is XmlNode {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
/** An element as an object; `<wpt/>` parses as an empty string, which has no fields either. */
function node(value: unknown): XmlNode {
return isNode(value) ? value : {};
}
/** An empty list reads as no list, the way the file itself leaves one out. */
function someOf<T>(items: T[]): T[] | undefined {
return items.length ? items : undefined;
}
function asArray(value: unknown): unknown[] {
if (Array.isArray(value)) return value;
return value === undefined || value === null ? [] : [value];
}
/** An element's text: plain, or beside attributes as `#text`. A repeated element counts once. */
function text(value: unknown): string | null {
if (Array.isArray(value)) return text(value[0]);
if (typeof value === 'string') return value.trim() || null;
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
if (isNode(value)) return text(value['#text']);
return null;
}
function attr(value: unknown, name: string): string | null {
const raw = node(value)[`@_${name}`];
return typeof raw === 'string' ? raw.trim() || null : null;
}
/** A coordinate attribute as a number, or null. The range is the contract's to check. */
function coordinate(value: unknown): number | null {
if (typeof value !== 'string' || value.trim() === '') return null;
const n = Number(value);
return Number.isFinite(n) ? n : null;
}
/** Cut to the contract's length without leaving half of a surrogate pair behind. */
function clip(value: string, max: number | null): string {
if (max === null || value.length <= max) return value;
const cut = value.slice(0, max);
return /[\uD800-\uDBFF]$/.test(cut) ? cut.slice(0, -1) : cut;
}
/** The prefix a document binds to one of these namespaces on its root, if any. */
function prefixFor(root: XmlNode, namespaces: readonly string[]): string | null {
for (const [key, value] of Object.entries(root)) {
if (key.startsWith('@_xmlns:') && typeof value === 'string' && namespaces.includes(value.trim())) {
return key.slice('@_xmlns:'.length);
}
}
return null;
}
/**
* `raw` in the shape `schema` accepts, or null.
*
* A field the schema refuses is dropped and the rest kept, which is the file
* contract's own rule: one unreadable field costs that field. Only a refused
* `required` field costs the whole thing, because without it nothing is left.
* The schema is the one place the limits live, so none are repeated here.
*/
function fit<T>(schema: ZodType<T>, raw: Record<string, unknown>, required: readonly string[]): T | null {
const given = Object.fromEntries(Object.entries(raw).filter(([, v]) => v !== null && v !== undefined));
const first = schema.safeParse(given);
if (first.success) return first.data;
const refused = new Set(first.error.issues.map(issue => String(issue.path[0])));
if (required.some(field => refused.has(field))) return null;
const second = schema.safeParse(Object.fromEntries(Object.entries(given).filter(([key]) => !refused.has(key))));
return second.success ? second.data : null;
}
const LABEL_NAME = collectionFilePlaceSchema.shape.labels.unwrap().element;
/** GPX 1.1 `<link href>`, or GPX 1.0's `<url>` beside `<urlname>`. */
function gpxLinks(el: XmlNode): CollectionLink[] {
const found = asArray(el.link).map(link => ({ url: attr(link, 'href'), label: text(node(link).text) }));
if (found.length === 0 && text(el.url)) found.push({ url: text(el.url), label: text(el.urlname) });
return found
.map(link => fit(collectionLinkSchema, link, ['url']))
.filter((link): link is CollectionLink => link !== null);
}
/**
* The description as the writer had it: when a TREK file put the address
* under it as a courtesy to other apps, the address comes back off.
*/
function withoutAddress(desc: string | null, address: string | null): string | null {
if (!desc || !address) return desc;
if (desc === address) return null;
const suffix = `\n\n${address}`;
return desc.endsWith(suffix) ? desc.slice(0, -suffix.length).trim() || null : desc;
}
/** The prefixes a document bound to the namespaces this reader understands. */
interface Prefixes {
trek: string | null;
osmand: string | null;
}
/**
* One waypoint (or named route point) as a place, or null when it cannot be one.
*
* Coordinates are the one thing a waypoint must have. A missing name is given
* one, `Waypoint N` after its position in the file, which is what the trip
* importer calls it too: an unnamed pin is still a place somebody marked, and
* the number is how they find it again in the app that made the file.
*/
function readPlace(value: unknown, fallbackName: string | null, prefixes: Prefixes): CollectionFilePlace | null {
const el = node(value);
const lat = coordinate(el['@_lat']);
const lng = coordinate(el['@_lon']);
const name = text(el.name) ?? fallbackName;
if (lat === null || lng === null || !name) return null;
const ext = node(el.extensions);
const own = (field: string): unknown => (prefixes.trek ? ext[`${prefixes.trek}:${field}`] : undefined);
const address = text(own('address')) ?? (prefixes.osmand ? text(ext[`${prefixes.osmand}:address`]) : null);
const desc = text(el.desc);
const cmt = text(el.cmt);
const [website, ...moreLinks] = gpxLinks(el);
const ownLinks = asArray(own('link'))
.map(link => fit(collectionLinkSchema, { url: attr(link, 'href'), label: text(link) }, ['url']))
.filter((link): link is CollectionLink => link !== null);
const raw: Record<string, unknown> = {
name: clip(name, collectionFilePlaceSchema.shape.name.maxLength),
lat,
lng,
description: prefixes.trek ? withoutAddress(desc, address) : desc,
// Garmin writes the same text into both; once is enough.
notes: !prefixes.trek && cmt === desc ? null : cmt,
website: website?.url,
// OsmAnd files its favourites into groups by <type>; Garmin has only <sym>.
category: text(el.type) ?? text(el.sym),
address,
labels: someOf(
asArray(own('label'))
.map(text)
.filter((label): label is string => label !== null && LABEL_NAME.safeParse(label).success)
.slice(0, MAX_COLLECTION_FILE_LABELS),
),
links: someOf([...moreLinks, ...ownLinks]),
};
for (const field of SCALAR_EXTENSIONS) {
const value = text(own(field));
if (field === 'address' || value === null) continue;
raw[field] = field === 'price' ? Number(value) : value;
}
return fit(collectionFilePlaceSchema, raw, ['name', 'lat', 'lng']);
}
function listName(root: XmlNode, meta: XmlNode, fileName: string | undefined): string {
const fromFile = fileName?.split(/[\\/]/).pop()?.replace(/\.gpx$/i, '').trim();
// GPX 1.1 keeps the name in <metadata>, GPX 1.0 on the root.
const name = text(meta.name) ?? text(root.name) ?? (fromFile || 'GPX');
return clip(name, collectionFileSchema.shape.name.maxLength);
}
/** Everything that can be refused without building a tree, checked before one is built. */
function refuseBeforeParsing(source: string): string {
// Bytes, not characters: the limit is the JSON file's, and a megabyte of
// text outside Latin-1 is fewer characters than that.
if (Buffer.byteLength(source, 'utf8') > MAX_COLLECTION_FILE_BYTES) {
throw new CollectionGpxError('too-large', 'That GPX file is too large');
}
const xml = source.replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n');
// GPX has no use for a DTD, and a DTD is where both classic XML attacks
// live: external entities that read files or URLs, and nested ones that
// expand a kilobyte into gigabytes. The parser refuses the first and caps
// the second; refusing the declaration outright means relying on neither.
if (/<!(?:DOCTYPE|ENTITY)/i.test(xml)) {
throw new CollectionGpxError('unreadable', 'A GPX file with a DOCTYPE is not read');
}
let elements = 0;
for (let at = xml.indexOf('<'); at !== -1; at = xml.indexOf('<', at + 1)) {
// `</`, `<!` and `<?` close an element or open a comment, CDATA or declaration.
const next = xml.charCodeAt(at + 1);
if (next !== 0x2f && next !== 0x21 && next !== 0x3f) elements += 1;
if (elements > MAX_GPX_ELEMENTS) throw new CollectionGpxError('unreadable', 'That GPX file has too many elements');
}
return xml;
}
/**
* A GPX document as the list file it amounts to.
*
* Every waypoint becomes a place, and so does a route point somebody named;
* an unnamed route point is a bend in the road and a track is a line, neither
* a place, so both are only counted for the importer to be told about.
*/
export function gpxToCollectionFile(source: string, fileName?: string): CollectionGpxReadResult {
const xml = refuseBeforeParsing(source);
let doc: unknown;
try {
doc = reader.parse(xml, true);
} catch {
throw new CollectionGpxError('unreadable', 'That GPX file is not well-formed XML');
}
const rootValue = node(doc).gpx;
if (rootValue === undefined) throw new CollectionGpxError('not-gpx', 'That is not a GPX file');
const root = node(rootValue);
const prefixes: Prefixes = {
trek: prefixFor(root, [COLLECTION_GPX_NAMESPACE]),
osmand: prefixFor(root, OSMAND_NAMESPACES),
};
const places: CollectionFilePlace[] = [];
const seen = new Set<string>();
let skipped = 0;
let trackPoints = 0;
const take = (value: unknown, fallbackName: string | null, routePoint: boolean) => {
const place = readPlace(value, fallbackName, prefixes);
if (!place) {
skipped += 1;
return;
}
// A route drawn through waypoints repeats each of them as a route point
// (Garmin does this for every route); the place is already on the list.
const key = `${place.lat},${place.lng},${place.name}`;
if (routePoint && seen.has(key)) return;
seen.add(key);
places.push(place);
};
asArray(root.wpt).forEach((wpt, i) => take(wpt, `Waypoint ${i + 1}`, false));
for (const rte of asArray(root.rte)) {
for (const point of asArray(node(rte).rtept)) {
if (text(node(point).name)) take(point, null, true);
else trackPoints += 1;
}
}
for (const trk of asArray(root.trk)) {
for (const segment of asArray(node(trk).trkseg)) trackPoints += asArray(node(segment).trkpt).length;
}
if (places.length > MAX_COLLECTION_FILE_PLACES) {
throw new CollectionGpxError('too-many-places', `That GPX file has more than ${MAX_COLLECTION_FILE_PLACES} places`);
}
const meta = node(root.metadata);
const metaExt = node(meta.extensions);
const own = (field: string): unknown => (prefixes.trek ? metaExt[`${prefixes.trek}:${field}`] : undefined);
const labels = asArray(own('label'))
.map(label => fit(collectionFileLabelSchema, { name: text(label), color: attr(label, 'color') }, ['name']))
.filter((label): label is CollectionFileLabel => label !== null)
.slice(0, MAX_COLLECTION_FILE_LABELS);
const file = fit(
collectionFileSchema,
{
format: COLLECTION_FILE_FORMAT,
version: COLLECTION_FILE_VERSION,
name: listName(root, meta, fileName),
description: text(meta.desc) ?? text(root.desc),
color: text(own('color')),
icon: text(own('icon')),
labels,
places,
},
['format', 'version', 'name', 'places'],
);
// The envelope above always fits today; this keeps a stricter contract from becoming a 500.
if (!file) throw new CollectionGpxError('unreadable', 'That GPX file could not be read as a list');
return { file, skipped, track_points: trackPoints };
}
@@ -52,8 +52,10 @@ import {
CollectionLabelUpdateDto,
CollectionLabelAssignDto,
CollectionImportDto,
CollectionGpxReadDto,
} from './collections.dto';
import { PlaceRatingDto } from '../places/places.dto';
import { CollectionGpxError } from './collection-gpx.helpers';
export const MAX_COVER_SIZE = 20 * 1024 * 1024;
// Duplicated on purpose from trips.controller.ts (historical parity — no
@@ -211,6 +213,24 @@ export class CollectionsController {
return this.collections.importCollection(user.id, body);
}
/**
* A GPX document read into the list file it amounts to (#2301). Creates
* nothing, hence 200: the browser shows what came out and sends it to
* /import above, so a GPX goes through the same contract and the same one
* transaction as a list file. A refusal carries a `code` the client
* translates, beside the English `error` every other route has.
*/
@Post('gpx/read')
@HttpCode(200)
readGpx(@Body() body: CollectionGpxReadDto) {
try {
return this.collections.readCollectionGpx(body);
} catch (err) {
if (!(err instanceof CollectionGpxError)) throw err;
throw new HttpException({ error: err.message, code: err.code }, err.code === 'too-large' ? 413 : 400);
}
}
@Post('copy-to-trip')
@HttpCode(200)
copyToTrip(@CurrentUser() user: User, @Body() body: CollectionCopyToTripDto) {
@@ -392,6 +412,17 @@ export class CollectionsController {
return this.collections.exportCollection(user.id, Number(id));
}
/**
* The list as GPX (#2301). JSON around the document rather than the bare
* XML, for the same reason the list file has no Content-Disposition: the
* browser makes the download, and it also needs to say how many places had
* no coordinates and were left out.
*/
@Get(':id/export/gpx')
exportCollectionGpx(@CurrentUser() user: User, @Param('id') id: string) {
return this.collections.exportCollectionGpx(user.id, Number(id));
}
@Get(':id/importable/:tripId')
importable(@CurrentUser() user: User, @Param('id') id: string, @Param('tripId') tripId: string) {
return this.collections.importablePlaces(user.id, Number(id), Number(tripId));
@@ -21,6 +21,7 @@ import {
collectionLabelUpdateRequestSchema,
collectionLabelAssignRequestSchema,
collectionImportRequestSchema,
collectionGpxReadRequestSchema,
} from '@trek/shared';
/**
@@ -51,3 +52,4 @@ export class CollectionLabelCreateDto extends createZodDto(collectionLabelCreate
export class CollectionLabelUpdateDto extends createZodDto(collectionLabelUpdateRequestSchema) {}
export class CollectionLabelAssignDto extends createZodDto(collectionLabelAssignRequestSchema) {}
export class CollectionImportDto extends createZodDto(collectionImportRequestSchema) {}
export class CollectionGpxReadDto extends createZodDto(collectionGpxReadRequestSchema) {}
@@ -19,11 +19,13 @@ import {
COLLECTION_FILE_VERSION,
MAX_COLLECTION_FILE_LABELS,
type PlaceMatchCandidate,
type CollectionFile,
type CollectionFileLabel,
type CollectionFilePlace,
type CollectionImportRequest,
type CollectionImportResult,
type CollectionGpxExport,
type CollectionGpxReadRequest,
type CollectionGpxReadResult,
} from '@trek/shared';
import type {
Collection,
@@ -44,6 +46,7 @@ import type {
CollectionImportablesResponse,
} from '@trek/shared';
import { NotificationsService } from '../notifications/notifications.service';
import { collectionFileToGpx, gpxToCollectionFile, type ExportedCollectionFile } from './collection-gpx.helpers';
/** Links are stored as a JSON TEXT column; parse on read, stringify on write. */
function parseLinks(raw: unknown): CollectionLink[] | undefined {
@@ -368,7 +371,7 @@ export class CollectionsService {
* and a viewer who can read all of this on screen loses nothing by having it
* as a file; what a viewer must not do is write, which no export does.
*/
exportCollection(userId: number, id: number): CollectionFile {
exportCollection(userId: number, id: number): ExportedCollectionFile {
this.assertAccess(userId, id);
const collection = this.getCollectionRow(id);
const labels = this.loadLabelsByCollection(id);
@@ -419,6 +422,25 @@ export class CollectionsService {
};
}
/**
* The list as GPX (#2301), written from the very file the export above
* returns. What may leave the instance is decided once, there, and a GPX can
* only ever carry less of it. Same access rule too, since it is the same read.
*/
exportCollectionGpx(userId: number, id: number): CollectionGpxExport {
return collectionFileToGpx(this.exportCollection(userId, id));
}
/**
* A GPX document read into the list file it amounts to. Touches no table:
* the file goes back to the browser to be shown, and comes back through
* importCollection like any other, so there is one import and one
* transaction whatever the format was.
*/
readCollectionGpx(body: CollectionGpxReadRequest): CollectionGpxReadResult {
return gpxToCollectionFile(body.gpx, body.file_name);
}
/**
* Read a file back as a new list of the caller's own.
*
+4 -3
View File
@@ -48,7 +48,7 @@ type Pt = { lat: number; lng: number; ele: number | null };
/** Coordinates are written with 7 decimals, ~11 mm, which is past what any consumer
* device resolves and keeps the file from carrying float noise. */
function coord(n: number): string {
export function coord(n: number): string {
return Number(n.toFixed(7)).toString();
}
@@ -81,7 +81,8 @@ function describe(place: GpxExportPlace): string | undefined {
return parts.length ? parts.join(', ') : undefined;
}
const builder = new XMLBuilder({
/** Shared with the list writer in collections/, which writes the same dialect. */
export const gpxBuilder = new XMLBuilder({
ignoreAttributes: false,
attributeNamePrefix: '@_',
format: true,
@@ -168,7 +169,7 @@ export function buildGpx(input: GpxExportInput, opts: GpxExportOptions = {}): st
},
};
return builder.build(doc);
return gpxBuilder.build(doc);
}
/** Filenames land on the receiving filesystem, so its reserved characters are
+42 -1
View File
@@ -4,7 +4,8 @@
* CollectionsModule) against a temp SQLite db (full schema). Only the addon
* flag, websocket and notification send are mocked. Covers: the addon gate
* (404 before auth), auth, CRUD happy paths, invite/accept/decline, copy-to-trip,
* cross-user 404s and the non-owner 403 on /:id/available-users (no enumeration).
* cross-user 404s, the non-owner 403 on /:id/available-users (no enumeration), and
* a list out as GPX and back in through the reader and the import (#2301).
*/
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
import request from 'supertest';
@@ -362,6 +363,46 @@ describe('Collections e2e (real auth guard + real service + temp SQLite)', () =>
expect((await request(server).get(`/api/addons/collections/${col.id}/importable/${tripId}`).set('Cookie', sessionCookie(otherId))).status).toBe(404);
});
// ── GPX (#2301) ──────────────────────────────────────────────────────────
it('COLLECTIONS-E2E-080: a list goes out as GPX and comes back through the reader and the import', async () => {
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
const col = (await request(server).post('/api/addons/collections').set(as(ownerId)).send({ name: 'Round trip' })).body;
await request(server).post('/api/addons/collections/places').set(as(ownerId))
.send({ collection_id: col.id, name: 'Pinned', lat: 41.9, lng: 12.48, status: 'want' });
await request(server).post('/api/addons/collections/places').set(as(ownerId)).send({ collection_id: col.id, name: 'Vague' });
const exported = await request(server).get(`/api/addons/collections/${col.id}/export/gpx`).set(as(ownerId));
expect(exported.status).toBe(200);
expect(exported.body).toMatchObject({ name: 'Round trip', waypoints: 1, omitted: 1 });
const read = await request(server).post('/api/addons/collections/gpx/read').set(as(otherId))
.send({ gpx: exported.body.gpx, file_name: 'round-trip.gpx' });
expect(read.status).toBe(200);
expect(read.body).toMatchObject({ skipped: 0, track_points: 0 });
const imported = await request(server).post('/api/addons/collections/import').set(as(otherId)).send({ file: read.body.file });
expect(imported.status).toBe(201);
expect(imported.body).toMatchObject({ imported: 1, skipped: 0 });
const detail = await request(server).get(`/api/addons/collections/${imported.body.collection.id}`).set(as(otherId));
expect(detail.body.places).toEqual([expect.objectContaining({ name: 'Pinned', lat: 41.9, lng: 12.48, status: 'want' })]);
});
it('COLLECTIONS-E2E-081: a refused GPX says why in a code, a body without one is refused by the contract', async () => {
const hostile = '<?xml version="1.0"?><!DOCTYPE gpx [<!ENTITY x SYSTEM "file:///etc/passwd">]>'
+ '<gpx><wpt lat="1" lon="1"><name>&x;</name></wpt></gpx>';
const refused = await request(server).post('/api/addons/collections/gpx/read').set('Cookie', sessionCookie(ownerId)).send({ gpx: hostile });
expect(refused.status).toBe(400);
expect(refused.body).toEqual({ error: expect.any(String), code: 'unreadable' });
expect((await request(server).post('/api/addons/collections/gpx/read').set('Cookie', sessionCookie(ownerId)).send({})).status).toBe(400);
expect((await request(server).post('/api/addons/collections/gpx/read').send({ gpx: '<gpx/>' })).status).toBe(401);
});
it('COLLECTIONS-E2E-082: a list the caller cannot see has no GPX either', async () => {
const col = (await request(server).post('/api/addons/collections').set('Cookie', sessionCookie(ownerId)).send({ name: 'Mine' })).body;
expect((await request(server).get(`/api/addons/collections/${col.id}/export/gpx`).set('Cookie', sessionCookie(otherId))).status).toBe(404);
});
// ── delete ───────────────────────────────────────────────────────────────
it('COLLECTIONS-E2E-050: owner deletes; non-owner member cannot (403)', async () => {
const col = (await request(server).post('/api/addons/collections').set('Cookie', sessionCookie(ownerId)).send({ name: 'Doomed' })).body;
+14
View File
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="Windows export" xmlns="http://www.topografix.com/GPX/1/1">
<metadata>
<name>Wien</name>
</metadata>
<wpt lat="48.208493" lon="16.373118">
<name>Stephansdom</name>
<desc>South tower first,
the north tower has the bell</desc>
</wpt>
<wpt lat="48.198558" lon="16.371867">
<name>Naschmarkt</name>
</wpt>
</gpx>
+59
View File
@@ -0,0 +1,59 @@
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<gpx xmlns="http://www.topografix.com/GPX/1/1" xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3" xmlns:wptx1="http://www.garmin.com/xmlschemas/WaypointExtension/v1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" creator="eTrex 32x" version="1.1" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www8.garmin.com/xmlschemas/GpxExtensionsv3.xsd http://www.garmin.com/xmlschemas/WaypointExtension/v1 http://www8.garmin.com/xmlschemas/WaypointExtensionv1.xsd">
<metadata>
<link href="http://www.garmin.com">
<text>Garmin International</text>
</link>
<time>2024-06-01T08:00:00Z</time>
</metadata>
<wpt lat="47.268120" lon="11.393510">
<ele>574.2</ele>
<time>2024-06-01T07:42:10Z</time>
<name>007</name>
<cmt>Parking at the old town</cmt>
<desc>Parking at the old town</desc>
<sym>Parking Area</sym>
<extensions>
<gpxx:WaypointExtension>
<gpxx:DisplayMode>SymbolAndName</gpxx:DisplayMode>
<gpxx:Address>
<gpxx:StreetAddress>Rennweg 1</gpxx:StreetAddress>
<gpxx:City>Innsbruck</gpxx:City>
</gpxx:Address>
</gpxx:WaypointExtension>
</extensions>
</wpt>
<wpt lat="47.268563" lon="11.393436">
<ele>574.0</ele>
<name>Goldenes Dachl</name>
<cmt>Built 1500</cmt>
<desc>Late Gothic oriel with 2,657 gilded copper tiles</desc>
<link href="https://www.innsbruck.info/">
<text>innsbruck.info</text>
</link>
<sym>Flag, Blue</sym>
</wpt>
<wpt lat="95.100000" lon="11.400000">
<name>Past the pole</name>
<sym>Flag, Red</sym>
</wpt>
<wpt lat="" lon="11.400000">
<name>No latitude</name>
</wpt>
<wpt lat="47.270035" lon="11.391221">
<ele>577.9</ele>
<sym>Flag, Green</sym>
</wpt>
<rte>
<name>Old town walk</name>
<rtept lat="47.268563" lon="11.393436">
<name>Goldenes Dachl</name>
<sym>Flag, Blue</sym>
</rtept>
<rtept lat="47.267201" lon="11.393102"/>
<rtept lat="47.266306" lon="11.393774">
<name>Triumphpforte</name>
<sym>Waypoint</sym>
</rtept>
</rte>
</gpx>
+36
View File
@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<gpx xmlns="http://www.topografix.com/GPX/1/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www8.garmin.com/xmlschemas/GpxExtensionsv3.xsd http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www8.garmin.com/xmlschemas/TrackPointExtensionv1.xsd" xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1" xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3" xmlns:gpxpx="http://www.garmin.com/xmlschemas/PowerExtension/v1" creator="https://gpx.studio" version="1.1">
<metadata>
<name>Sintra loop</name>
<author>
<name>gpx.studio</name>
<link href="https://gpx.studio"></link>
</author>
</metadata>
<wpt lat="38.787636" lon="-9.390587">
<ele>412.3</ele>
<name>Pena Palace</name>
<desc>Book the palace interior online, the park is walk-in</desc>
<sym>Flag, Blue</sym>
</wpt>
<wpt lat="38.792558" lon="-9.389433">
<ele>398.0</ele>
<name>Moorish Castle</name>
</wpt>
<trk>
<name>Sintra loop</name>
<type>Hiking</type>
<trkseg>
<trkpt lat="38.797642" lon="-9.388412"><ele>207.4</ele></trkpt>
<trkpt lat="38.795131" lon="-9.389120"><ele>256.9</ele></trkpt>
<trkpt lat="38.793880" lon="-9.389664"><ele>301.2</ele></trkpt>
<trkpt lat="38.792558" lon="-9.389433"><ele>398.0</ele></trkpt>
<trkpt lat="38.790412" lon="-9.389981"><ele>421.6</ele></trkpt>
<trkpt lat="38.787636" lon="-9.390587"><ele>412.3</ele></trkpt>
</trkseg>
<trkseg>
<trkpt lat="38.786201" lon="-9.392110"><ele>388.0</ele><extensions><gpxtpx:TrackPointExtension><gpxtpx:atemp>19</gpxtpx:atemp></gpxtpx:TrackPointExtension></extensions></trkpt>
<trkpt lat="38.790977" lon="-9.396511"><ele>331.5</ele></trkpt>
</trkseg>
</trk>
</gpx>
+17
View File
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE gpx [
<!ENTITY secret SYSTEM "file:///etc/passwd">
<!ENTITY lol "lol">
<!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
<!ENTITY lol2 "&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;">
<!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">
]>
<gpx version="1.1" creator="nobody in particular" xmlns="http://www.topografix.com/GPX/1/1">
<metadata>
<name>&lol3;</name>
</metadata>
<wpt lat="48.8566" lon="2.3522">
<name>&secret;</name>
<desc>&lol3;</desc>
</wpt>
</gpx>
+39
View File
@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<gpx xmlns="http://www.topografix.com/GPX/1/1" version="1.1" creator="Organic Maps" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">
<metadata>
<name>Kyoto &amp; Nara</name>
<desc>Temples, gardens and where to eat between them</desc>
</metadata>
<wpt lat="34.967146" lon="135.772695">
<name>伏見稲荷大社</name>
<desc>Start at 7, the upper gates are empty then</desc>
<extensions>
<color>#FFE51A1A</color>
</extensions>
</wpt>
<wpt lat="35.039370" lon="135.729243">
<name>Kinkaku-ji</name>
<desc><![CDATA[Golden Pavilion. Buy tickets at the gate & walk the garden loop clockwise.]]></desc>
<link href="https://www.shokoku-ji.jp/kinkakuji/"><text>shokoku-ji.jp</text></link>
<extensions>
<color>#FF0066CC</color>
</extensions>
</wpt>
<wpt lat="34.685087" lon="135.843012">
<name>Nara Park</name>
<link href="javascript:alert(1)"><text>Not a link</text></link>
</wpt>
<trk>
<name>Philosopher's Path</name>
<extensions>
<color>#FF1E96F0</color>
</extensions>
<trkseg>
<trkpt lat="35.026839" lon="135.794780"></trkpt>
<trkpt lat="35.024110" lon="135.795090"></trkpt>
<trkpt lat="35.020470" lon="135.795370"></trkpt>
<trkpt lat="35.016302" lon="135.795703"></trkpt>
<trkpt lat="35.011860" lon="135.795050"></trkpt>
</trkseg>
</trk>
</gpx>
+46
View File
@@ -0,0 +1,46 @@
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<gpx version="1.1" creator="OsmAnd Maps 4.7.10 (4.7.10.10)" xmlns="http://www.topografix.com/GPX/1/1" xmlns:osmand="https://osmand.net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">
<metadata>
<name>favorites</name>
</metadata>
<wpt lat="38.7071037" lon="-9.1459227">
<time>2024-05-02T10:14:03Z</time>
<name>Time Out Market</name>
<desc>Go before noon, the queues start at one</desc>
<type>Restaurant</type>
<extensions>
<osmand:address>Av. 24 de Julho 49, 1200-479 Lisboa</osmand:address>
<osmand:icon>restaurants</osmand:icon>
<osmand:background>circle</osmand:background>
<osmand:color>#eecc22</osmand:color>
<osmand:amenity_subtype>food_court</osmand:amenity_subtype>
</extensions>
</wpt>
<wpt lat="38.7117512" lon="-9.1301264">
<time>2024-05-02T10:21:47Z</time>
<name>Miradouro de Santa Luzia</name>
<type>Viewpoints</type>
<extensions>
<osmand:icon>special_star</osmand:icon>
<osmand:background>circle</osmand:background>
<osmand:color>#10c0f0</osmand:color>
</extensions>
</wpt>
<wpt lat="38.6975462" lon="-9.2032131">
<time>2024-05-03T08:02:11Z</time>
<name>Pastéis de Belém</name>
<desc>Past&#233;is warm from the oven</desc>
<extensions>
<osmand:address>R. de Belém 84 92, 1300-085 Lisboa</osmand:address>
<osmand:icon>shop_pastry</osmand:icon>
<osmand:color>#eecc22</osmand:color>
<osmand:hidden>false</osmand:hidden>
</extensions>
</wpt>
<extensions>
<osmand:points_groups>
<group name="Restaurant" color="#eecc22" icon="restaurants" background="circle" />
<group name="Viewpoints" color="#10c0f0" icon="special_star" background="circle" />
</osmand:points_groups>
</extensions>
</gpx>
+26
View File
@@ -165,4 +165,30 @@ describe('Request body ceiling', () => {
.send({ email: 'a@b.c', password: 'x'.repeat(1024) });
expect(res.status).not.toBe(413);
});
// A list file may be a megabyte (#2198), and the two routes that carry one
// whole are measured against that instead (#2301). Only those two.
it('MISC-011: a list file over 100kb reaches the import and the GPX reader', async () => {
for (const route of ['/api/addons/collections/import', '/api/addons/collections/gpx/read']) {
const res = await request(app)
.post(route)
.set('Content-Type', 'application/json')
.send({ gpx: 'x'.repeat(300 * 1024) });
expect(res.status, route).not.toBe(413);
}
});
it('MISC-012: a list file past twice the file limit is still refused, and no other route got the larger ceiling', async () => {
const huge = await request(app)
.post('/api/addons/collections/gpx/read')
.set('Content-Type', 'application/json')
.send({ gpx: 'x'.repeat(2 * 1024 * 1024 + 1) });
expect(huge.status).toBe(413);
const elsewhere = await request(app)
.post('/api/addons/collections')
.set('Content-Type', 'application/json')
.send({ name: 'x'.repeat(200 * 1024) });
expect(elsewhere.status).toBe(413);
});
});
@@ -0,0 +1,308 @@
/**
* A list as GPX and back (#2301). Pure helpers, so no DB and no container.
*
* The fixtures under tests/fixtures/gpx are modelled on what the apps people
* keep places in actually write: OsmAnd favourites, Organic Maps, gpx.studio,
* a Garmin handheld, a Windows tool that adds a BOM and CRLF, and one hostile
* document. The round trip at the end is the promise the TREK extension makes.
*/
import fs from 'fs';
import path from 'path';
import { describe, it, expect } from 'vitest';
import { XMLValidator } from 'fast-xml-parser';
import { COLLECTION_GPX_NAMESPACE, MAX_COLLECTION_FILE_BYTES, type CollectionFilePlace } from '@trek/shared';
import {
CollectionGpxError,
MAX_GPX_ELEMENTS,
collectionFileToGpx,
gpxToCollectionFile,
type ExportedCollectionFile,
} from '../../../src/nest/collections/collection-gpx.helpers';
const fixture = (name: string) => fs.readFileSync(path.join(__dirname, '../../fixtures/gpx', name), 'utf8');
const listFile = (over: Partial<ExportedCollectionFile> = {}): ExportedCollectionFile => ({
format: 'trek.collection', version: 1, name: 'Lisbon', places: [], ...over,
});
const place = (over: Partial<CollectionFilePlace> = {}): CollectionFilePlace => ({
name: 'Somewhere', lat: 38.7071, lng: -9.1459, status: 'idea', ...over,
});
/** The refusal a document gets, or a failure when it is read. */
function refusal(source: string): string {
try {
gpxToCollectionFile(source);
} catch (err) {
expect(err).toBeInstanceOf(CollectionGpxError);
return (err as CollectionGpxError).code;
}
throw new Error('expected the document to be refused');
}
const wptDoc = (body: string, rootAttrs = '') =>
`<?xml version="1.0"?><gpx version="1.1" xmlns="http://www.topografix.com/GPX/1/1"${rootAttrs}>${body}</gpx>`;
describe('collectionFileToGpx', () => {
it('GPX-COLL-001: writes each place as a waypoint in the order GPX 1.1 prescribes', () => {
const { gpx, waypoints, omitted } = collectionFileToGpx(listFile({
places: [place({
name: 'Time Out Market', description: 'Market hall', notes: 'Before noon',
address: 'Av. 24 de Julho 49', website: 'https://timeoutmarket.com/', category: 'Restaurant',
})],
}));
expect(XMLValidator.validate(gpx)).toBe(true);
expect({ waypoints, omitted }).toEqual({ waypoints: 1, omitted: 0 });
expect(gpx).toContain('<wpt lat="38.7071" lon="-9.1459">');
// name, cmt, desc, link, type, extensions: the xsd sequence, which strict readers enforce.
const order = ['<name>', '<cmt>', '<desc>', '<link ', '<type>', '<extensions>'].map(tag => gpx.indexOf(tag, gpx.indexOf('<wpt')));
expect(order.every((at, i) => at > -1 && (i === 0 || at > order[i - 1]))).toBe(true);
// Other apps show <desc>; the address rides under the description so they show it too.
expect(gpx).toContain('<desc>Market hall\n\nAv. 24 de Julho 49</desc>');
expect(gpx).toContain('<cmt>Before noon</cmt>');
expect(gpx).toContain('<link href="https://timeoutmarket.com/"/>');
expect(gpx).toContain('<type>Restaurant</type>');
});
it('GPX-COLL-002: carries what GPX has no element for in the TREK namespace', () => {
const { gpx } = collectionFileToGpx(listFile({
color: '#ef4444', icon: 'Utensils', description: 'Three days',
labels: [{ name: 'Must see', color: '#ff0000' }],
places: [place({
address: 'Rua 1', phone: '+351 1', status: 'want', price: 12.5, currency: 'EUR',
labels: ['Must see'], links: [{ url: 'https://menu.example', label: 'Menu' }, { url: 'https://bare.example' }],
})],
}));
expect(gpx).toContain(`xmlns:trek="${COLLECTION_GPX_NAMESPACE}"`);
for (const line of [
'<trek:address>Rua 1</trek:address>', '<trek:phone>+351 1</trek:phone>', '<trek:status>want</trek:status>',
'<trek:price>12.5</trek:price>', '<trek:currency>EUR</trek:currency>', '<trek:label>Must see</trek:label>',
'<trek:link href="https://menu.example">Menu</trek:link>', '<trek:link href="https://bare.example"/>',
'<trek:color>#ef4444</trek:color>', '<trek:icon>Utensils</trek:icon>', '<trek:label color="#ff0000">Must see</trek:label>',
]) expect(gpx, line).toContain(line);
expect(gpx).toContain('<metadata>\n <name>Lisbon</name>\n <desc>Three days</desc>');
});
it('GPX-COLL-003: leaves out a place without coordinates and says how many', () => {
const result = collectionFileToGpx(listFile({
places: [place({ name: 'Here' }), place({ name: 'Nowhere', lat: null, lng: null }), place({ name: 'Half', lng: null })],
}));
expect(result).toMatchObject({ name: 'Lisbon', waypoints: 1, omitted: 2 });
expect(result.gpx).toContain('<name>Here</name>');
expect(result.gpx).not.toContain('Nowhere');
});
it('GPX-COLL-004: writes a list with no coordinates at all as a valid, empty GPX', () => {
const result = collectionFileToGpx(listFile({ places: [place({ lat: null, lng: null })] }));
expect(result).toMatchObject({ waypoints: 0, omitted: 1 });
expect(XMLValidator.validate(result.gpx)).toBe(true);
expect(result.gpx).not.toContain('<wpt');
});
it('GPX-COLL-005: escapes markup and drops the characters XML cannot hold', () => {
const { gpx } = collectionFileToGpx(listFile({
name: 'Fish & Chips <best>',
places: [place({ name: 'A "quoted" & <tagged> place\u0001\u0008', description: "Bob's \u000bnotes" })],
}));
expect(XMLValidator.validate(gpx)).toBe(true);
expect(gpx).toContain('<name>Fish &amp; Chips &lt;best&gt;</name>');
const back = gpxToCollectionFile(gpx).file;
expect(back.name).toBe('Fish & Chips <best>');
expect(back.places[0]).toMatchObject({ name: 'A "quoted" & <tagged> place', description: "Bob's notes" });
});
it('GPX-COLL-006: never writes a link a reader should not follow', () => {
const { gpx } = collectionFileToGpx(listFile({
places: [place({ website: 'javascript:alert(1)', links: [{ url: 'ftp://files.example' }] })],
}));
expect(gpx).not.toContain('javascript:');
expect(gpx).not.toContain('ftp://');
});
});
describe('gpxToCollectionFile: what other apps write', () => {
it('GPX-COLL-010: OsmAnd favourites, with <type> as the group and the address in its namespace', () => {
const { file, skipped, track_points } = gpxToCollectionFile(fixture('osmand-favourites.gpx'), 'favourites.gpx');
expect({ skipped, track_points }).toEqual({ skipped: 0, track_points: 0 });
expect(file.name).toBe('favorites');
expect(file.places).toHaveLength(3);
expect(file.places[0]).toMatchObject({
name: 'Time Out Market', lat: 38.7071037, lng: -9.1459227, category: 'Restaurant',
description: 'Go before noon, the queues start at one', address: 'Av. 24 de Julho 49, 1200-479 Lisboa',
});
expect(file.places[1]).toMatchObject({ name: 'Miradouro de Santa Luzia', category: 'Viewpoints' });
// A numeric character reference is text like any other.
expect(file.places[2]).toMatchObject({ name: 'Pastéis de Belém', description: 'Pastéis warm from the oven' });
// OsmAnd's icon and colour are its own business, not TREK labels or statuses.
expect(file.places[0]).toMatchObject({ status: 'idea' });
expect(file.places[0]).not.toHaveProperty('labels', expect.arrayContaining([expect.anything()]));
});
it('GPX-COLL-011: Organic Maps, with CDATA, entities, a script link and a track', () => {
const { file, skipped, track_points } = gpxToCollectionFile(fixture('organic-maps.gpx'));
expect(file).toMatchObject({ name: 'Kyoto & Nara', description: 'Temples, gardens and where to eat between them' });
expect(file.places.map(p => (p as CollectionFilePlace).name)).toEqual(['伏見稲荷大社', 'Kinkaku-ji', 'Nara Park']);
expect(file.places[1]).toMatchObject({
description: 'Golden Pavilion. Buy tickets at the gate & walk the garden loop clockwise.',
website: 'https://www.shokoku-ji.jp/kinkakuji/',
});
// The javascript: link is gone; the park is not.
expect(file.places[2]).not.toHaveProperty('website');
expect({ skipped, track_points }).toEqual({ skipped: 0, track_points: 5 });
});
it('GPX-COLL-012: gpx.studio, waypoints beside a track of two segments', () => {
const { file, track_points } = gpxToCollectionFile(fixture('gpx-studio.gpx'));
// The metadata name, not the author's name nested under it.
expect(file.name).toBe('Sintra loop');
expect(file.places).toHaveLength(2);
expect(file.places[0]).toMatchObject({ name: 'Pena Palace', category: 'Flag, Blue' });
expect(track_points).toBe(8);
});
it('GPX-COLL-013: a Garmin handheld, with <sym>, twin <cmt>, bad waypoints and a route', () => {
const { file, skipped, track_points } = gpxToCollectionFile(fixture('garmin-sym.gpx'), 'C:\\GPS\\Innsbruck.gpx');
// No name in the document, so the file name it came in.
expect(file.name).toBe('Innsbruck');
expect(file.places.map(p => (p as CollectionFilePlace).name)).toEqual(['007', 'Goldenes Dachl', 'Waypoint 5', 'Triumphpforte']);
// A name of digits stays the text it was.
expect(file.places[0]).toMatchObject({ category: 'Parking Area', description: 'Parking at the old town' });
// Garmin writes <cmt> and <desc> alike; the copy is not kept twice.
expect(file.places[0]).not.toHaveProperty('notes');
expect(file.places[1]).toMatchObject({ notes: 'Built 1500', website: 'https://www.innsbruck.info/' });
// Past the pole and without a latitude: skipped, not guessed.
expect(skipped).toBe(2);
// The route's unnamed bend; its named points are places, the repeated one only once.
expect(track_points).toBe(1);
});
it('GPX-COLL-014: a file with a byte-order mark and CRLF line endings', () => {
const raw = fixture('bom-crlf.gpx');
// The fixture must really be what it claims, or this case tests nothing.
expect(raw.charCodeAt(0)).toBe(0xfeff);
expect(raw).toContain('\r\n');
const { file } = gpxToCollectionFile(raw);
expect(file.name).toBe('Wien');
expect(file.places).toHaveLength(2);
expect((file.places[0] as CollectionFilePlace).description).toBe('South tower first,\nthe north tower has the bell');
});
it('GPX-COLL-015: GPX 1.0 keeps the name on the root and a link as <url>', () => {
const { file } = gpxToCollectionFile(
'<gpx version="1.0" creator="old"><name>Old file</name><wpt lat="1" lon="2"><name>A</name>'
+ '<url>https://a.example</url><urlname>A site</urlname></wpt></gpx>',
);
expect(file.name).toBe('Old file');
expect(file.places[0]).toMatchObject({ website: 'https://a.example' });
});
});
describe('gpxToCollectionFile: what it refuses', () => {
it('GPX-COLL-020: a DOCTYPE, before anything is expanded or fetched', () => {
expect(refusal(fixture('hostile-doctype.gpx'))).toBe('unreadable');
expect(refusal(wptDoc('<wpt lat="1" lon="1"><name>x</name></wpt>').replace('<gpx', '<!ENTITY a "b"><gpx'))).toBe('unreadable');
});
it('GPX-COLL-021: a file that is not XML, not well-formed, or not GPX', () => {
expect(refusal('{"format":"trek.collection"}')).toBe('unreadable');
expect(refusal('<gpx><wpt lat="1" lon="2"><name>x</wpt></gpx>')).toBe('unreadable');
expect(refusal('<?xml version="1.0"?><kml><Document/></kml>')).toBe('not-gpx');
});
it('GPX-COLL-022: a file past the size limit, counted in bytes', () => {
// Three bytes a character: under the limit in characters, over it in bytes.
const wide = '€'.repeat(Math.floor(MAX_COLLECTION_FILE_BYTES / 2));
expect(wide.length).toBeLessThan(MAX_COLLECTION_FILE_BYTES);
expect(refusal(wptDoc(`<desc>${wide}</desc>`))).toBe('too-large');
});
it('GPX-COLL-023: a file opening more elements than any real GPX has', () => {
expect(refusal(wptDoc('<a/>'.repeat(MAX_GPX_ELEMENTS + 1)))).toBe('unreadable');
});
it('GPX-COLL-024: a file with more places than a list may hold', () => {
const many = Array.from({ length: 1001 }, (_, i) => `<wpt lat="1" lon="${i / 10}"/>`).join('');
expect(refusal(wptDoc(many))).toBe('too-many-places');
});
it('GPX-COLL-025: an empty GPX reads as a list of nothing, not as an error', () => {
expect(gpxToCollectionFile('<gpx/>', 'empty.gpx').file).toMatchObject({ name: 'empty', places: [] });
});
});
describe('gpxToCollectionFile: one bad field costs that field', () => {
it('GPX-COLL-030: drops what the contract refuses and keeps the place', () => {
const { file, skipped } = gpxToCollectionFile(wptDoc(
`<wpt lat="1" lon="2"><name>${'n'.repeat(600)}</name><desc>${'d'.repeat(6000)}</desc>`
+ '<type>Museum</type></wpt>',
));
expect(skipped).toBe(0);
const only = file.places[0] as CollectionFilePlace;
expect(only.name).toHaveLength(500);
expect(only).not.toHaveProperty('description');
expect(only.category).toBe('Museum');
});
it('GPX-COLL-031: reads the TREK extension by namespace, whatever the prefix', () => {
const body = '<wpt lat="1" lon="2"><name>A</name><extensions><t:status>visited</t:status><trek:status>want</trek:status></extensions></wpt>';
const ours = gpxToCollectionFile(wptDoc(body, ` xmlns:t="${COLLECTION_GPX_NAMESPACE}" xmlns:trek="https://elsewhere.example"`));
expect(ours.file.places[0]).toMatchObject({ status: 'visited' });
// Without the namespace bound, `trek:` is just somebody else's prefix.
const theirs = gpxToCollectionFile(wptDoc(body, ' xmlns:trek="https://elsewhere.example"'));
expect(theirs.file.places[0]).toMatchObject({ status: 'idea' });
});
it('GPX-COLL-032: an unknown status, a price that is not a number and a bad label cost only themselves', () => {
const { file } = gpxToCollectionFile(wptDoc(
'<wpt lat="1" lon="2"><name>A</name><extensions><trek:status>loved</trek:status><trek:price>cheap</trek:price>'
+ `<trek:label>Ok</trek:label><trek:label>${'x'.repeat(61)}</trek:label><trek:phone>+1</trek:phone></extensions></wpt>`,
` xmlns:trek="${COLLECTION_GPX_NAMESPACE}"`,
));
expect(file.places[0]).toMatchObject({ status: 'idea', labels: ['Ok'], phone: '+1' });
expect(file.places[0]).not.toHaveProperty('price');
});
});
describe('a GPX made by TREK comes back as the same list (#2301)', () => {
it('GPX-COLL-040: every field of every place, and the list around them', () => {
const places: CollectionFilePlace[] = [
{
name: 'Time Out Market', description: 'Market hall\nwith two floors', notes: 'Before noon',
lat: 38.70710371234, lng: -9.14592271234, address: 'Av. 24 de Julho 49', phone: '+351 210 606 040',
website: 'https://timeoutmarket.com/', category: 'Restaurant', status: 'want', price: 12.5, currency: 'EUR',
image_url: 'https://example.com/market.jpg', google_place_id: 'ChIJ123', google_ftid: '0x1:0x2', osm_id: 'node/1',
labels: ['Must see', 'Rainy day'], links: [{ url: 'https://menu.example/', label: 'Menu' }],
},
{ name: 'Address only', lat: 38.7, lng: -9.1, address: 'Rua 2', status: 'visited' },
{ name: 'Bare', lat: 0, lng: 0, status: 'idea' },
];
const original = listFile({
name: 'Lisbon', description: 'Three days', color: '#ef4444', icon: 'Utensils', exported_at: '2026-09-19T10:00:00.000Z',
labels: [{ name: 'Must see', color: '#ff0000' }, { name: 'Rainy day', color: null }],
places,
});
const { file } = gpxToCollectionFile(collectionFileToGpx(original).gpx);
expect(file).toMatchObject({ name: 'Lisbon', description: 'Three days', color: '#ef4444', icon: 'Utensils' });
expect(file.labels).toEqual([{ name: 'Must see', color: '#ff0000' }, { name: 'Rainy day' }]);
const back = file.places as CollectionFilePlace[];
expect(back).toHaveLength(3);
// Seven decimals is what the writer keeps, about a centimetre.
expect(back[0].lat).toBeCloseTo(places[0].lat!, 7);
expect(back[0].lng).toBeCloseTo(places[0].lng!, 7);
expect({ ...back[0], lat: 0, lng: 0 }).toEqual({ ...places[0], lat: 0, lng: 0 });
// The address that was also written under the description does not come back into it.
expect(back[1]).toEqual(places[1]);
expect(back[2]).toEqual(places[2]);
});
});
@@ -4,7 +4,9 @@ import { HttpException } from '@nestjs/common';
import { CollectionsController } from '../../../src/nest/collections/collections.controller';
import type { CollectionsService } from '../../../src/nest/collections/collections.service';
import type { StorageService } from '../../../src/nest/storage/storage.service';
import { CollectionGpxError } from '../../../src/nest/collections/collection-gpx.helpers';
import type { User } from '../../../src/types';
import type { CollectionGpxProblem } from '@trek/shared';
const storageStub = { put: vi.fn().mockResolvedValue(undefined) } as unknown as StorageService;
@@ -249,4 +251,43 @@ describe('CollectionsController', () => {
expect(svc.assignLabels).toHaveBeenCalledWith(1, [5], [9], true, 'sock');
});
});
describe('GPX (#2301)', () => {
it('exports the list as GPX for the caller, with the id as a number', () => {
const exported = { name: 'Lisbon', gpx: '<gpx/>', waypoints: 0, omitted: 0 };
const svc = makeService({ exportCollectionGpx: vi.fn().mockReturnValue(exported) });
const c = new CollectionsController(svc, new RuntimeEnvService(), storageStub);
expect(c.exportCollectionGpx(user, '3')).toBe(exported);
expect(svc.exportCollectionGpx).toHaveBeenCalledWith(1, 3);
});
it('hands back the file a GPX was read into', () => {
const read = { file: { name: 'Lisbon' }, skipped: 1, track_points: 4 };
const svc = makeService({ readCollectionGpx: vi.fn().mockReturnValue(read) });
const c = new CollectionsController(svc, new RuntimeEnvService(), storageStub);
expect(c.readGpx({ gpx: '<gpx/>', file_name: 'lisbon.gpx' })).toBe(read);
expect(svc.readCollectionGpx).toHaveBeenCalledWith({ gpx: '<gpx/>', file_name: 'lisbon.gpx' });
});
it('turns a refusal into a 400 with a code the client can translate, 413 for size', () => {
const refuse = (code: CollectionGpxProblem) => makeService({
readCollectionGpx: vi.fn(() => { throw new CollectionGpxError(code, 'refused'); }),
});
for (const code of ['unreadable', 'not-gpx', 'too-many-places'] as const) {
const c = new CollectionsController(refuse(code), new RuntimeEnvService(), storageStub);
expect(thrown(() => c.readGpx({ gpx: 'x' }))).toEqual({ status: 400, body: { error: 'refused', code } });
}
const big = new CollectionsController(refuse('too-large'), new RuntimeEnvService(), storageStub);
expect(thrown(() => big.readGpx({ gpx: 'x' }))).toEqual({ status: 413, body: { error: 'refused', code: 'too-large' } });
});
it('lets any other failure through untouched', () => {
const svc = makeService({ readCollectionGpx: vi.fn(() => { throw new Error('disk on fire'); }) });
const c = new CollectionsController(svc, new RuntimeEnvService(), storageStub);
expect(() => c.readGpx({ gpx: 'x' })).toThrow('disk on fire');
});
});
});
@@ -1283,3 +1283,82 @@ describe('exportCollection / importCollection (#2198)', () => {
expect(svc.listCollections(owner.id).collections).toHaveLength(before);
});
});
// ── The same list as GPX (#2301) ─────────────────────────────────────────────
describe('exportCollectionGpx / readCollectionGpx (#2301)', () => {
const fixture = (name: string) => fs.readFileSync(path.join(__dirname, '../../fixtures/gpx', name), 'utf8');
it('COLLECTIONS-SVC-120: a list that goes out as GPX comes back as the same list', () => {
const owner = createUser(testDb).user;
const other = createUser(testDb).user;
const cat = createCategory(testDb, { name: 'Restaurant' });
const col = svc.createCollection(owner.id, { name: 'Lisbon', description: 'Three days', color: '#ef4444' });
const must = svc.createLabel(owner.id, col.id, 'Must see', '#ff0000');
svc.createLabel(owner.id, col.id, 'Rainy day', '#00ff00');
const market = svc.savePlace(owner.id, {
collection_id: col.id, name: 'Time Out Market', description: 'Market hall', lat: 38.7071, lng: -9.1459,
address: 'Av. 24 de Julho 49', notes: 'Before noon', website: 'https://timeoutmarket.com/',
phone: '+351 210 606 040', osm_id: 'node/1', status: 'want', category_id: cat.id, price: 12.5, currency: 'EUR',
links: [{ url: 'https://menu.example/', label: 'Menu' }],
}).place!;
svc.savePlace(owner.id, { collection_id: col.id, name: 'Miradouro', lat: 38.7195, lng: -9.1327, status: 'visited' });
svc.assignLabels(owner.id, [must.id], [market.id], false);
const original = svc.exportCollection(owner.id, col.id);
const exported = svc.exportCollectionGpx(owner.id, col.id);
const read = svc.readCollectionGpx({ gpx: exported.gpx, file_name: 'lisbon.gpx' });
const result = svc.importCollection(other.id, { file: read.file });
expect(exported).toMatchObject({ name: 'Lisbon', waypoints: 2, omitted: 0 });
expect(read).toMatchObject({ skipped: 0, track_points: 0 });
expect(result).toMatchObject({ imported: 2, skipped: 0 });
// Names, coordinates, notes, website, category, labels, status and the rest:
// exported again from the copy, the file is the one the original gave.
const again = svc.exportCollection(other.id, (result.collection as { id: number }).id);
expect({ ...again, exported_at: undefined }).toEqual({ ...original, exported_at: undefined });
});
it('COLLECTIONS-SVC-121: a place without coordinates is left out and counted, and a stranger gets nothing', () => {
const owner = createUser(testDb).user;
const stranger = createUser(testDb).user;
const col = svc.createCollection(owner.id, { name: 'Mixed' });
svc.savePlace(owner.id, { collection_id: col.id, name: 'Pinned', lat: 1, lng: 2 });
svc.savePlace(owner.id, { collection_id: col.id, name: 'Somewhere vague' });
const result = svc.exportCollectionGpx(owner.id, col.id);
expect(result).toMatchObject({ name: 'Mixed', waypoints: 1, omitted: 1 });
expect(result.gpx).toContain('<name>Pinned</name>');
expect(result.gpx).not.toContain('Somewhere vague');
expect(() => svc.exportCollectionGpx(stranger.id, col.id)).toThrow(expect.objectContaining({ status: 404 }));
});
it('COLLECTIONS-SVC-122: OsmAnd favourites become a list, their groups matched against the palette', () => {
const owner = createUser(testDb).user;
createCategory(testDb, { name: 'Restaurant' });
const read = svc.readCollectionGpx({ gpx: fixture('osmand-favourites.gpx'), file_name: 'favourites.gpx' });
const created = svc.importCollection(owner.id, { file: read.file, name: 'Lisbon favourites' }).collection as { id: number };
const detail = svc.getCollection(owner.id, created.id);
expect(detail.collection.name).toBe('Lisbon favourites');
expect(detail.places.map(p => [p.name, p.category?.name ?? null, p.address ?? null])).toEqual([
['Time Out Market', 'Restaurant', 'Av. 24 de Julho 49, 1200-479 Lisboa'],
// No "Viewpoints" in this palette, and a file does not get to add one.
['Miradouro de Santa Luzia', null, null],
['Pastéis de Belém', null, 'R. de Belém 84 92, 1300-085 Lisboa'],
]);
});
it('COLLECTIONS-SVC-123: reading a GPX writes nothing, whatever is in it', () => {
const owner = createUser(testDb).user;
const before = testDb.prepare('SELECT COUNT(*) AS n FROM collections').get() as { n: number };
svc.readCollectionGpx({ gpx: fixture('garmin-sym.gpx') });
expect(() => svc.readCollectionGpx({ gpx: fixture('hostile-doctype.gpx') })).toThrow(expect.objectContaining({ code: 'unreadable' }));
expect(testDb.prepare('SELECT COUNT(*) AS n FROM collections').get()).toEqual(before);
expect(svc.listCollections(owner.id).collections).toHaveLength(0);
});
});