From 51dc0e6a827c1ce968f3bb480b5bab09871205ae Mon Sep 17 00:00:00 2001 From: Maurice Date: Mon, 30 Nov 2026 14:23:55 +0100 Subject: [PATCH] feat(maps): MAP_EXTRA_CONNECT_HOSTS adds the operator's map hosts to the CSP A GL map fetches its tiles and its style, so a template on a host of the operator's own (a self-hosted tile server) was refused by connect-src while Leaflet drew it as images. The new variable lists such hosts; each entry becomes an https source in connect-src and the same list reaches the client as map_extra_connect_hosts in the app config, so the renderer choice and the policy can never disagree. The variable is owned by readEnv() like the rest of the maps namespace and read once when the middleware is applied. The boot refuses an entry outside the shared grammar; a path that skips the boot check drops it, so a bad value never widens the policy. Unset, the CSP and the app config are as before apart from an empty list. Documented in .env.example, docker-compose.yml, the Helm values and ConfigMap and the wiki. Making room for the app config field shrinks auth.service.ts by one line, and its size baseline follows. --- charts/trek/templates/configmap.yaml | 3 + charts/trek/values.yaml | 5 ++ docker-compose.yml | 1 + server/.env.example | 2 + server/scripts/size-baseline.json | 2 +- server/src/app-config/derive.ts | 9 ++- server/src/app-config/env.schema.ts | 10 +++- server/src/middleware/globalMiddleware.ts | 5 ++ server/src/nest/auth/auth.service.ts | 9 ++- .../e2e/map-extra-connect-hosts.e2e.test.ts | 59 +++++++++++++++++++ .../unit/app-config/config-templates.test.ts | 14 +++++ server/tests/unit/app-config/derive.test.ts | 17 ++++++ server/tests/unit/app-config/validate.test.ts | 11 ++++ .../middleware/globalMiddleware.csp.test.ts | 32 +++++++++- wiki/Environment-Variables.md | 8 +++ wiki/Install-Helm.md | 1 + 16 files changed, 179 insertions(+), 9 deletions(-) create mode 100644 server/tests/e2e/map-extra-connect-hosts.e2e.test.ts diff --git a/charts/trek/templates/configmap.yaml b/charts/trek/templates/configmap.yaml index b4545d287..bc07f5aee 100644 --- a/charts/trek/templates/configmap.yaml +++ b/charts/trek/templates/configmap.yaml @@ -136,6 +136,9 @@ data: {{- if .Values.env.AMAP_API_BASE }} AMAP_API_BASE: {{ .Values.env.AMAP_API_BASE | quote }} {{- end }} + {{- if .Values.env.MAP_EXTRA_CONNECT_HOSTS }} + MAP_EXTRA_CONNECT_HOSTS: {{ .Values.env.MAP_EXTRA_CONNECT_HOSTS | quote }} + {{- end }} {{- if .Values.env.VAPID_PUBLIC_KEY }} VAPID_PUBLIC_KEY: {{ .Values.env.VAPID_PUBLIC_KEY | quote }} {{- end }} diff --git a/charts/trek/values.yaml b/charts/trek/values.yaml index 175febec9..4f41dd003 100644 --- a/charts/trek/values.yaml +++ b/charts/trek/values.yaml @@ -170,6 +170,11 @@ env: # Send the Amap (高德地图) calls through an egress proxy, a cache or a gateway that speaks the same API instead of # restapi.amap.com directly. The key itself is a credential and goes under secretEnv.AMAP_API_KEY, or into # Admin > Settings > API Keys. Defaults to https://restapi.amap.com. + # MAP_EXTRA_CONNECT_HOSTS: "" + # Hosts of your own map tiles or vector styles that the GL maps may load, comma-separated, e.g. + # "tiles.example.com,*.maps.example.org:8443": a host name, optionally with a port or as a wildcard over + # its subdomains; https is implied. They are added to the Content-Security-Policy and told to the app. + # An entry that is not a plain host name aborts startup. # VAPID_PUBLIC_KEY: "" # Web Push key pair, public half (base64url, 65 bytes). Leave both halves empty and TREK generates a pair on # first start and keeps it in the database, so it travels with backups. To use your own pair, set this and diff --git a/docker-compose.yml b/docker-compose.yml index c1d110bc5..9642af249 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -72,6 +72,7 @@ services: # - AMAP_API_KEY= # Optional. Amap (高德地图) Web 服务 key for place search and geocoding inside mainland China. Overrides the key set in Admin > Settings > API Keys. A Web 端 (JS API) key is a different credential and is rejected with INVALID_USER_KEY. # - AMAP_API_SECRET= # Optional. The private secret (数字签名) of that key. Required exactly when the key was created with signing enabled, because such a key rejects every unsigned request. Leave unset otherwise. # - AMAP_API_BASE=https://restapi.amap.com # Optional. Send the Amap calls through an egress proxy, a cache or a gateway that speaks the same API instead of restapi.amap.com directly. (default: https://restapi.amap.com) +# - MAP_EXTRA_CONNECT_HOSTS= # Optional. Hosts of your own map tiles or vector styles that the GL maps (MapLibre, Mapbox) may load, comma-separated, e.g. a self-hosted tile server. Each entry is a host name (tiles.example.com), optionally with a port (tiles.example.com:8443) or as a wildcard over its subdomains (*.tiles.example.com); https is implied, so no scheme or path. They are added to the Content-Security-Policy and told to the app, which otherwise draws a map template on such a host with the classic 2D map. An entry that is not a plain host name aborts startup. Read once at startup. (default: none) # - VAPID_PUBLIC_KEY= # Optional. Web Push key pair, public half (base64url). Unset, TREK generates a pair on first start and keeps it in the database, so it travels with backups. Set it together with VAPID_PRIVATE_KEY to use your own, e.g. from `npx web-push generate-vapid-keys`. Changing the pair means every device has to turn push on again. # - VAPID_PRIVATE_KEY= # Optional. Web Push key pair, private half (base64url). Only used together with VAPID_PUBLIC_KEY; a mismatched pair, or only one half, turns push off with an error in the log until it is fixed, and every device stays registered. # - VAPID_SUBJECT=mailto:admin@example.com # Optional. The contact push services see with every message: a mailto: address or an https:// URL. Defaults to APP_URL when it is https, else the TREK project page. diff --git a/server/.env.example b/server/.env.example index 1b8c2a98d..4002f59b8 100644 --- a/server/.env.example +++ b/server/.env.example @@ -90,6 +90,8 @@ DEMO_MODE=false # Demo mode: resets data hourly # AMAP_API_SECRET= # The private secret (数字签名) of that key. Required exactly when the key was created with signing enabled, because such a key rejects every unsigned request. Leave unset otherwise. # AMAP_API_BASE=https://restapi.amap.com # Send the Amap calls through an egress proxy, a cache or a gateway that speaks the same API instead of restapi.amap.com directly. (default: https://restapi.amap.com) +# MAP_EXTRA_CONNECT_HOSTS=tiles.example.com # Hosts of your own map tiles or vector styles that the GL maps (MapLibre, Mapbox) may load, comma-separated, e.g. a self-hosted tile server. Each entry is a host name (tiles.example.com), optionally with a port (tiles.example.com:8443) or as a wildcard over its subdomains (*.tiles.example.com); https is implied, so no scheme or path. They are added to the Content-Security-Policy and told to the app, which otherwise draws a map template on such a host with the classic 2D map. An entry that is not a plain host name aborts startup. Read once at startup. (default: none) + # TRANSIT_API_URL=https://api.transitous.org # Base URL of the transit routing API the server proxies to. Point it at your own MOTIS instance to keep transit searches off third-party servers. A trailing slash is stripped. (default: https://api.transitous.org) # TREK_PLACE_PHOTO_DIR= # Directory for cached Google place photos, e.g. a dedicated volume. Unset, they live in uploads/photos/google. Read once at startup. (default: uploads/photos/google) diff --git a/server/scripts/size-baseline.json b/server/scripts/size-baseline.json index e1793a66c..350b03b2d 100644 --- a/server/scripts/size-baseline.json +++ b/server/scripts/size-baseline.json @@ -6,7 +6,7 @@ "src/db/repositories/Trips.repository.ts": 1120, "src/db/repositories/Users.repository.ts": 1421, "src/nest/atlas/atlas.service.ts": 1166, - "src/nest/auth/auth.service.ts": 1115, + "src/nest/auth/auth.service.ts": 1114, "src/nest/budget/budget.service.ts": 1607, "src/nest/collections/collections.service.ts": 1386, "src/nest/doc-sync/doc-sync.service.ts": 1060, diff --git a/server/src/app-config/derive.ts b/server/src/app-config/derive.ts index 16e346edf..c54188806 100644 --- a/server/src/app-config/derive.ts +++ b/server/src/app-config/derive.ts @@ -30,7 +30,7 @@ import { resolveSessionTtlMs, stripTrailingSlashes, } from './parsers'; -import { SUPPORTED_LANGUAGE_CODES } from '@trek/shared'; +import { SUPPORTED_LANGUAGE_CODES, parseMapConnectHosts } from '@trek/shared'; export type RawEnv = Record; @@ -193,6 +193,13 @@ export function deriveMaps(raw: RawEnv) { mapboxToken: raw.MAPBOX_ACCESS_TOKEN || undefined, /** CARTO basemap key; without one the tiles come back watermarked (#2054). Public too. */ cartoKey: raw.CARTO_API_KEY || undefined, + /** + * MAP_EXTRA_CONNECT_HOSTS: the tile and style hosts a GL map may fetch from + * beyond the ones TREK ships, added to the CSP connect-src and handed to the + * client in the app config, so both read one list. The boot refuses a bad + * entry; read without that check (tests), a bad entry is left out, never kept. + */ + extraConnectHosts: parseMapConnectHosts(raw.MAP_EXTRA_CONNECT_HOSTS).hosts, }; } diff --git a/server/src/app-config/env.schema.ts b/server/src/app-config/env.schema.ts index 6b7b1df82..9acaf78b4 100644 --- a/server/src/app-config/env.schema.ts +++ b/server/src/app-config/env.schema.ts @@ -18,7 +18,7 @@ import { parseDurationMs, parseLinkLocalAllowList, } from './parsers'; -import { SUPPORTED_LANGUAGE_CODES } from '@trek/shared'; +import { SUPPORTED_LANGUAGE_CODES, parseMapConnectHosts } from '@trek/shared'; import { z } from 'zod'; @@ -231,6 +231,14 @@ export const envSchema = z.object({ AMAP_API_SECRET: anyString, MAPBOX_ACCESS_TOKEN: anyString, CARTO_API_KEY: anyString, + // Tile and style hosts a GL map may fetch from beyond the ones TREK ships. Every + // entry widens the Content-Security-Policy, so one that is not a plain host name + // refuses the boot rather than being dropped or read loosely. + MAP_EXTRA_CONNECT_HOSTS: optionalWith( + (v) => parseMapConnectHosts(v).invalid.length === 0, + 'must be a comma-separated list of host names such as tiles.example.com, *.tiles.example.com or ' + + 'tiles.example.com:8443 (https is implied: no scheme, path or user)', + ), DEMO_MODE: boolStr, DEMO_ADMIN_USER: anyString, DEMO_ADMIN_EMAIL: anyString, diff --git a/server/src/middleware/globalMiddleware.ts b/server/src/middleware/globalMiddleware.ts index b05066fb2..db18ae235 100644 --- a/server/src/middleware/globalMiddleware.ts +++ b/server/src/middleware/globalMiddleware.ts @@ -155,6 +155,7 @@ export function applyGlobalMiddleware( const { http = httpConfig(), extraConnectSrc = [] } = opts; const liveHttp = readEnv().http; const { nodeEnv, isProduction } = readEnv().app; + const mapExtraConnectSrc = readEnv().maps.extraConnectHosts.map((host) => `https://${host}`); // Request correlation comes first, so the whole pipeline and every line the // request logs run under its id. An X-Request-Id set by the proxy in front is @@ -367,6 +368,10 @@ export function applyGlobalMiddleware( // this the browser blocks it silently: no error the app can catch, just legs // that never route (#1797). ...extraConnectSrc, + // The operator's own tile and style hosts (MAP_EXTRA_CONNECT_HOSTS). A GL map + // fetches its tiles and its style, so a host missing here draws nothing. The + // client reads the same list from the app config and draws only what it names. + ...mapExtraConnectSrc, ], workerSrc: ["'self'", 'blob:'], childSrc: ["'self'", 'blob:'], diff --git a/server/src/nest/auth/auth.service.ts b/server/src/nest/auth/auth.service.ts index bd045b2a4..205f3d50b 100644 --- a/server/src/nest/auth/auth.service.ts +++ b/server/src/nest/auth/auth.service.ts @@ -322,15 +322,12 @@ export class AuthService { const placesProvider = isPlacesProviderChoice(placesProviderRow) ? placesProviderRow : 'auto'; const oidcDisplayName = readEnv().oidc.displayName || settings.get('oidc_display_name') || null; const oidcConfigured = isOidcConfiguredIn(settings); - const requireMfaValue = settings.get('require_mfa'); const notifChannel = settings.get('notification_channel') || 'none'; - const tripReminderSetting = settings.get('notify_trip_reminder'); const hasSmtpHost = !!(readEnv().smtp.host || settings.get('smtp_host')); const notifChannelsRaw = settings.get('notification_channels') || notifChannel; const activeChannels = notifChannelsRaw === 'none' ? [] : notifChannelsRaw.split(',').map((c: string) => c.trim()).filter(Boolean); const hasWebhookEnabled = activeChannels.includes('webhook'); const hasPushEnabled = activeChannels.includes(WEB_PUSH_CHANNEL_ID); - const tripRemindersEnabled = tripReminderSetting !== 'false'; const setupComplete = userCount > 0 && (await this.usersRepo.findAdminNeedingPasswordChange()) === null; return { @@ -359,7 +356,7 @@ export class AuthService { places_provider: placesProvider, oidc_configured: oidcConfigured, oidc_display_name: oidcConfigured ? (oidcDisplayName || 'SSO') : undefined, - require_mfa: requireMfaValue === 'true', + require_mfa: settings.get('require_mfa') === 'true', // The canonical live-read: same query + DEFAULT_ALLOWED_EXTENSIONS // fallback the upload filters use, so the client's picker and the // server's acceptance can never drift (the historical inline copy here @@ -367,6 +364,8 @@ export class AuthService { allowed_file_types: await this.allowedFileTypes.get(), // FILE_UPLOAD_LIMIT_MB, so the pickers refuse a file before the upload starts (#1364). max_upload_mb: readEnv().files.uploadLimitMb, + // The operator's own map hosts, which the CSP lets a GL map fetch from (MAP_EXTRA_CONNECT_HOSTS). + map_extra_connect_hosts: readEnv().maps.extraConnectHosts, // Whether the configuration belongs to whoever operates this install // rather than to its admin. The client uses it to stop offering settings // the server would refuse anyway — it is an honesty flag for the UI, never @@ -379,7 +378,7 @@ export class AuthService { notification_channel: notifChannel, notification_channels: activeChannels, available_channels: { email: hasSmtpHost, webhook: hasWebhookEnabled, push: hasPushEnabled, inapp: true }, - trip_reminders_enabled: tripRemindersEnabled, + trip_reminders_enabled: settings.get('notify_trip_reminder') !== 'false', ...publicFeatureFlags(settings), permissions: authenticatedUser ? (await this.permissions.getAllPermissions()) : undefined, // Case-sensitive on purpose (legacy parity). diff --git a/server/tests/e2e/map-extra-connect-hosts.e2e.test.ts b/server/tests/e2e/map-extra-connect-hosts.e2e.test.ts new file mode 100644 index 000000000..58067b6d7 --- /dev/null +++ b/server/tests/e2e/map-extra-connect-hosts.e2e.test.ts @@ -0,0 +1,59 @@ +/** + * MAP_EXTRA_CONNECT_HOSTS end to end, on the whole app: the operator's own map + * hosts reach the Content-Security-Policy the server sends and the app config + * the client reads, as one list, so a GL map is only asked to draw what the + * browser lets it fetch. Without the variable both stay as they were. + */ +import { buildApp } from '../../src/bootstrap'; +import type { INestApplication } from '@nestjs/common'; +import { mapExtraConnectHostsSchema } from '@trek/shared'; + +import request from 'supertest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +let app: INestApplication | undefined; + +afterEach(async () => { + await app?.close(); + app = undefined; + vi.unstubAllEnvs(); +}); + +/** The connect-src sources and the app config of an app built with `hosts` as MAP_EXTRA_CONNECT_HOSTS. */ +async function bootWith(hosts: string) { + vi.stubEnv('MAP_EXTRA_CONNECT_HOSTS', hosts); + app = await buildApp(); + const res = await request(app.getHttpServer()).get('/api/auth/app-config'); + const connectSrc = + String(res.headers['content-security-policy'] ?? '') + .split(';') + .map((directive) => directive.trim()) + .find((directive) => directive.startsWith('connect-src')) + ?.split(/\s+/) + .slice(1) ?? []; + return { status: res.status, config: res.body as Record, connectSrc }; +} + +describe('the operator map hosts', () => { + it('MAPHOST-E2E-001: unset, the app config lists none and the policy names only the shipped hosts', async () => { + const { status, config, connectSrc } = await bootWith(''); + expect(status).toBe(200); + expect(config.map_extra_connect_hosts).toEqual([]); + expect(connectSrc).toContain('https://tiles.openfreemap.org'); + expect(connectSrc.some((source) => source.includes('example'))).toBe(false); + }); + + it('MAPHOST-E2E-002: set, both carry the same hosts, the config in the shared contract', async () => { + const { config, connectSrc } = await bootWith('Tiles.Example.com, *.maps.example.org:8443'); + const hosts = mapExtraConnectHostsSchema.parse(config.map_extra_connect_hosts); + expect(hosts).toEqual(['tiles.example.com', '*.maps.example.org:8443']); + for (const host of hosts) expect(connectSrc).toContain(`https://${host}`); + expect(connectSrc).toContain('https://tiles.openfreemap.org'); + }); + + it('MAPHOST-E2E-003: an entry the boot would refuse reaches neither the policy nor the client', async () => { + const { config, connectSrc } = await bootWith('tiles.example.com,https://evil.example.com,*.com'); + expect(config.map_extra_connect_hosts).toEqual(['tiles.example.com']); + expect(connectSrc.filter((source) => source.includes('evil') || source === 'https://*.com')).toEqual([]); + }); +}); diff --git a/server/tests/unit/app-config/config-templates.test.ts b/server/tests/unit/app-config/config-templates.test.ts index 9ae3b9626..34a7a25a8 100644 --- a/server/tests/unit/app-config/config-templates.test.ts +++ b/server/tests/unit/app-config/config-templates.test.ts @@ -90,6 +90,20 @@ describe('the Places and Amap switches in the templates', () => { }); }); +describe('MAP_EXTRA_CONNECT_HOSTS in the templates', () => { + // It widens the browser's policy, so an operator with a tile server of their + // own has to find it where they look, and the chart has to pass it through. + it('.env.example and docker-compose.yml document it', () => { + expect(envExample).toContain('# MAP_EXTRA_CONNECT_HOSTS='); + expect(compose).toContain('# - MAP_EXTRA_CONNECT_HOSTS='); + }); + + it('the Helm ConfigMap passes through what the values file documents', () => { + expect(helmValues).toContain('# MAP_EXTRA_CONNECT_HOSTS:'); + expect(helmConfigMap).toContain('MAP_EXTRA_CONNECT_HOSTS: {{ .Values.env.MAP_EXTRA_CONNECT_HOSTS | quote }}'); + }); +}); + describe('the Web Push keys in the templates', () => { // All optional, since TREK keeps a generated pair in its database; an // operator who wants their own pair has to find the names somewhere. diff --git a/server/tests/unit/app-config/derive.test.ts b/server/tests/unit/app-config/derive.test.ts index 1a199924f..6a040a739 100644 --- a/server/tests/unit/app-config/derive.test.ts +++ b/server/tests/unit/app-config/derive.test.ts @@ -519,6 +519,23 @@ describe('deriveMaps', () => { }); }); +describe('deriveMaps extraConnectHosts', () => { + it('reads MAP_EXTRA_CONNECT_HOSTS as a lower-cased list and nothing when unset', () => { + expect(deriveMaps({} as never).extraConnectHosts).toEqual([]); + expect( + deriveMaps({ MAP_EXTRA_CONNECT_HOSTS: ' Tiles.Example.com, *.maps.example.org:8443 ' } as never), + ).toMatchObject({ + extraConnectHosts: ['tiles.example.com', '*.maps.example.org:8443'], + }); + }); + + it('leaves out an entry the boot would refuse instead of widening the policy with it', () => { + // The schema aborts the boot on such a value; this covers the paths that skip validation. + const raw = { MAP_EXTRA_CONNECT_HOSTS: 'tiles.example.com,https://evil.example.com,*.com' }; + expect(deriveMaps(raw as never).extraConnectHosts).toEqual(['tiles.example.com']); + }); +}); + describe('derivePush', () => { it('passes the VAPID_* values through trimmed, blank counting as unset', () => { expect(derivePush({})).toEqual({ vapidPublicKey: undefined, vapidPrivateKey: undefined, vapidSubject: undefined }); diff --git a/server/tests/unit/app-config/validate.test.ts b/server/tests/unit/app-config/validate.test.ts index 3a490d041..250bf79c0 100644 --- a/server/tests/unit/app-config/validate.test.ts +++ b/server/tests/unit/app-config/validate.test.ts @@ -91,6 +91,17 @@ describe('validateEnvAtBoot', () => { expect(() => validateEnvAtBoot({ ALLOW_LINK_LOCAL_IPS: '' })).not.toThrow(); }); + it('refuses a MAP_EXTRA_CONNECT_HOSTS entry that is not a plain host name', () => { + // Every entry widens the CSP, so a value read loosely could open it far wider than meant. + expect(() => validateEnvAtBoot({ MAP_EXTRA_CONNECT_HOSTS: 'https://tiles.example.com' })).toThrow(); + expect(() => validateEnvAtBoot({ MAP_EXTRA_CONNECT_HOSTS: 'tiles.example.com,*.com' })).toThrow(); + expect(() => validateEnvAtBoot({ MAP_EXTRA_CONNECT_HOSTS: 'tiles.example.com/styles' })).toThrow(); + expect(() => + validateEnvAtBoot({ MAP_EXTRA_CONNECT_HOSTS: 'tiles.example.com, *.maps.example.org:8443' }), + ).not.toThrow(); + expect(() => validateEnvAtBoot({ MAP_EXTRA_CONNECT_HOSTS: '' })).not.toThrow(); + }); + it('checks the VAPID_* shapes and lets a well-formed set through', () => { // The application server pair from RFC 8291 Appendix A, in the form the Web Push tools print. const publicKey = 'BP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27mlmlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A8'; diff --git a/server/tests/unit/middleware/globalMiddleware.csp.test.ts b/server/tests/unit/middleware/globalMiddleware.csp.test.ts index 47f10d691..73922fff2 100644 --- a/server/tests/unit/middleware/globalMiddleware.csp.test.ts +++ b/server/tests/unit/middleware/globalMiddleware.csp.test.ts @@ -2,7 +2,7 @@ import { applyGlobalMiddleware, routingCspOrigins } from '../../../src/middlewar import express from 'express'; import request from 'supertest'; -import { describe, it, expect, afterEach } from 'vitest'; +import { describe, it, expect, afterEach, vi } from 'vitest'; async function directiveSources(name: string): Promise { const app = express(); @@ -275,3 +275,33 @@ describe('connect-src with a self-hosted router', () => { expect(connect).toContain('https://routing.openstreetmap.de/'); }); }); + +describe("connect-src with the operator's own map hosts (MAP_EXTRA_CONNECT_HOSTS)", () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it('CSP-MAPHOST-001: names nothing beyond the shipped hosts while the variable is unset', async () => { + vi.stubEnv('MAP_EXTRA_CONNECT_HOSTS', ''); + const sources = await connectSrcSources(); + expect(sources).not.toContain('https://tiles.example.com'); + expect(sources).toContain('https://tiles.openfreemap.org'); + }); + + it('CSP-MAPHOST-002: adds every listed host as an https source, ports and wildcards included', async () => { + vi.stubEnv('MAP_EXTRA_CONNECT_HOSTS', 'Tiles.Example.com, *.maps.example.org:8443'); + const sources = await connectSrcSources(); + expect(sources).toContain('https://tiles.example.com'); + expect(sources).toContain('https://*.maps.example.org:8443'); + // The shipped hosts stay, so an operator's list only ever adds. + expect(sources).toContain('https://tiles.openfreemap.org'); + }); + + it('CSP-MAPHOST-003: an entry outside the grammar widens nothing, even where the boot check was skipped', async () => { + vi.stubEnv('MAP_EXTRA_CONNECT_HOSTS', "tiles.example.com,https://evil.example.com,*.com,'unsafe-inline'"); + const sources = await connectSrcSources(); + expect(sources).toContain('https://tiles.example.com'); + expect(sources.filter((source) => source.includes('evil') || source === 'https://*.com')).toEqual([]); + expect(sources).not.toContain("'unsafe-inline'"); + }); +}); diff --git a/wiki/Environment-Variables.md b/wiki/Environment-Variables.md index 72fb77ec8..700c394ef 100644 --- a/wiki/Environment-Variables.md +++ b/wiki/Environment-Variables.md @@ -494,6 +494,14 @@ own website, which will differ by a few hundred metres. --- +## Map Hosts + +The GL maps (MapLibre GL and Mapbox GL) load their tiles and styles with `fetch`, which the Content-Security-Policy only allows from the hosts TREK ships with. The classic 2D map loads raster tiles as images, which any https host may serve. A map template on a host of your own, such as a self-hosted tile server, therefore needs that host listed here before a GL map can draw it. + +| Variable | Description | Default | +| ------------------------- | ----------- | ------- | +| `MAP_EXTRA_CONNECT_HOSTS` | Hosts of your own map tiles or vector styles, comma-separated. Each entry is a host name (`tiles.example.com`), optionally with a port (`tiles.example.com:8443`) or as a wildcard over its subdomains (`*.tiles.example.com`). https is implied, so an entry carries no scheme, path or user. Every entry is added to the Content-Security-Policy `connect-src` and told to the app, which draws a template on a host outside the list with the classic 2D map instead. The list is read once at startup, entries are compared in lower case, and an entry that is not a plain host name (`https://tiles.example.com`, `*.com`, `localhost`) aborts startup. A reverse proxy that sets its own Content-Security-Policy has to allow the same hosts. | unset | + ## Storage & Paths Storage backends and category assignment are configured in diff --git a/wiki/Install-Helm.md b/wiki/Install-Helm.md index 843feb414..0b233de9e 100644 --- a/wiki/Install-Helm.md +++ b/wiki/Install-Helm.md @@ -136,6 +136,7 @@ env: # TREK_PLACES_ENABLED: "false" # stop asking the TREK Places API # TREK_PLACES_URL: "" # a copy of the TREK Places API you run yourself # AMAP_API_BASE: "" # send the Amap calls through a proxy or gateway + # MAP_EXTRA_CONNECT_HOSTS: "" # hosts of your own map tiles or styles the GL maps may load # OIDC_ISSUER: "https://auth.example.com" # OIDC_CLIENT_ID: "trek" # OIDC_DISPLAY_NAME: "SSO"