fix(map): drop the retired OpenStreetMap tile subdomains (#1733)

The a/b/c shards stopped being necessary in 2022 and d has since lost its
DNS record. The map never asked for d — Leaflet defaults to abc — but the
offline prefetcher rotated over a to d, which is where the failing requests
came from, and it cached most tiles under a host the map never requests.

Presets and the prefetcher use the apex host now. A URL already saved in
user_settings is rewritten where it is read and written back, so existing
instances heal without a migration touching what someone typed themselves.

The CSP only allowed https://*.tile.openstreetmap.org, and a wildcard host
never matches the apex domain, so the prefetch fetch would have been blocked.
The service worker rule had the same gap and would have stopped filling the
tile cache.
This commit is contained in:
Maurice
2026-07-29 14:37:24 +02:00
committed by Maurice
parent f013c4964c
commit 9ecca404c5
18 changed files with 330 additions and 33 deletions
@@ -18,7 +18,7 @@ const MAPBOX_STANDARD = 'mapbox://styles/mapbox/standard';
const MAPBOX_DARK = 'mapbox://styles/mapbox/dark-v11';
const MAPBOX_NAV_NIGHT = 'mapbox://styles/mapbox/navigation-night-v1';
const OFM_LIBERTY = 'https://tiles.openfreemap.org/styles/liberty';
const TILE_PLACEHOLDER = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
const TILE_PLACEHOLDER = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png';
/** Stateful stand-in for the admin defaults endpoint: PUT merges, null deletes. */
function stubDefaults(initial: Record<string, unknown> = {}) {
@@ -8,6 +8,7 @@ import CustomSelect from '../shared/CustomSelect'
import { MapView } from '../Map/MapView'
import { SYMBOLS, currenciesWith } from '../Budget/BudgetPanel.constants'
import type { DistanceUnit, Place } from '../../types'
import { normalizeTileUrl } from '../../utils/tileUrl'
import {
MAPBOX_DEFAULT_STYLE,
defaultStyleForProvider,
@@ -19,7 +20,7 @@ import {
} from '../Map/glProviders'
const MAP_PRESETS = [
{ name: 'OpenStreetMap', url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' },
{ name: 'OpenStreetMap', url: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png' },
{ name: 'OpenStreetMap DE', url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png' },
{ name: 'CartoDB Light', url: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png' },
{ name: 'CartoDB Dark', url: 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png' },
@@ -114,7 +115,7 @@ export default function DefaultUserSettingsTab(): React.ReactElement {
adminApi.getDefaultUserSettings().then((data: Defaults) => {
const provider = normalizeProvider(data.map_provider)
setDefaults(data)
setMapTileUrl(data.map_tile_url || '')
setMapTileUrl(normalizeTileUrl(data.map_tile_url || ''))
setMapboxToken(data.mapbox_access_token || '')
setMapboxStyle(provider === 'leaflet' ? (data.mapbox_style || '') : styleForProvider(provider, provider === 'maplibre-gl' ? data.maplibre_style : data.mapbox_style))
setLoaded(true)
@@ -328,7 +329,7 @@ export default function DefaultUserSettingsTab(): React.ReactElement {
value={mapTileUrl}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setMapTileUrl(e.target.value)}
onBlur={() => save({ map_tile_url: mapTileUrl })}
placeholder="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
placeholder="https://tile.openstreetmap.org/{z}/{x}/{y}.png"
className="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:ring-2 focus:ring-slate-400 focus:border-transparent"
/>
<p className="text-xs mt-1 text-content-faint">{t('settings.mapDefaultHint')}</p>
@@ -24,7 +24,7 @@ interface MapPreset {
}
const MAP_PRESETS: MapPreset[] = [
{ name: 'OpenStreetMap', url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' },
{ name: 'OpenStreetMap', url: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png' },
{ name: 'OpenStreetMap DE', url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png' },
{ name: 'CartoDB Light', url: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png' },
{ name: 'CartoDB Dark', url: 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png' },
@@ -307,7 +307,7 @@ export default function MapSettingsTab(): React.ReactElement {
type="text"
value={mapTileUrl}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setMapTileUrl(e.target.value)}
placeholder="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
placeholder="https://tile.openstreetmap.org/{z}/{x}/{y}.png"
className="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:ring-2 focus:ring-slate-400 focus:border-transparent"
/>
<p className="text-xs text-slate-400 mt-1">{t('settings.mapDefaultHint')}</p>
@@ -6,6 +6,7 @@ import { useToast } from '../../../components/shared/Toast'
import { MapView } from '../../../components/Map/MapView'
import { SYMBOLS, currenciesWith } from '../../../components/Budget/BudgetPanel.constants'
import { getApiErrorMessage, type DistanceUnit, type Place } from '../../../types'
import { normalizeTileUrl } from '../../../utils/tileUrl'
import {
MAPBOX_DEFAULT_STYLE,
defaultStyleForProvider,
@@ -22,7 +23,7 @@ import { MSetSelectRow } from '../settings/MSettingsUi'
import MSetPickerSheet from '../settings/MSetPickerSheet'
const MAP_PRESETS = [
{ name: 'OpenStreetMap', url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' },
{ name: 'OpenStreetMap', url: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png' },
{ name: 'OpenStreetMap DE', url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png' },
{ name: 'CartoDB Light', url: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png' },
{ name: 'CartoDB Dark', url: 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png' },
@@ -76,7 +77,7 @@ export default function MAdminDefaultUserSettings(): React.ReactElement {
adminApi.getDefaultUserSettings().then((data: Defaults) => {
const provider = normalizeProvider(data.map_provider)
setDefaults(data)
setMapTileUrl(data.map_tile_url || '')
setMapTileUrl(normalizeTileUrl(data.map_tile_url || ''))
setMapboxToken(data.mapbox_access_token || '')
setMapboxStyle(provider === 'leaflet' ? (data.mapbox_style || '') : styleForProvider(provider, provider === 'maplibre-gl' ? data.maplibre_style : data.mapbox_style))
setLoaded(true)
@@ -282,7 +283,7 @@ export default function MAdminDefaultUserSettings(): React.ReactElement {
value={mapTileUrl}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setMapTileUrl(e.target.value)}
onBlur={() => save({ map_tile_url: mapTileUrl })}
placeholder="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
placeholder="https://tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
</MAdminField>
@@ -24,7 +24,7 @@ interface MapPreset {
}
const MAP_PRESETS: MapPreset[] = [
{ name: 'OpenStreetMap', url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' },
{ name: 'OpenStreetMap', url: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png' },
{ name: 'OpenStreetMap DE', url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png' },
{ name: 'CartoDB Light', url: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png' },
{ name: 'CartoDB Dark', url: 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png' },
@@ -185,7 +185,7 @@ export default function MSettingsMap() {
className="mt-[6px]"
value={mapTileUrl}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setMapTileUrl(e.target.value)}
placeholder="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
placeholder="https://tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<MSetHint>{t('settings.mapDefaultHint')}</MSetHint>
</>
+23 -6
View File
@@ -4,6 +4,7 @@ import type { Settings } from '../types'
import { DEFAULT_APPEARANCE } from '@trek/shared'
import { getApiErrorMessage } from '../types'
import { SUPPORTED_LANGUAGE_CODES } from '../i18n/supportedLanguages'
import { normalizeTileUrl } from '../utils/tileUrl'
interface SettingsState {
settings: Settings
@@ -56,6 +57,16 @@ export const DEFAULT_SETTINGS: Settings = {
// periodic) can all fire a retry at once — collapse them into one in-flight GET.
let _loadInFlight: Promise<void> | null = null
// Every tile consumer (planner map, journey map, tile prefetcher, the settings
// preview) reads the template from this store, so the retired
// {s}.tile.openstreetmap.org host is rewritten here — on the way in from the
// server and on the way out to it. Rewriting only on read would let a template
// typed by hand survive in the database until the next load put it back (#1733).
function withNormalizedTileUrl<T extends Partial<Settings>>(patch: T): T {
if (typeof patch.map_tile_url !== 'string') return patch
return { ...patch, map_tile_url: normalizeTileUrl(patch.map_tile_url) }
}
export const useSettingsStore = create<SettingsState>((set, get) => ({
settings: { ...DEFAULT_SETTINGS },
isLoaded: false,
@@ -65,8 +76,11 @@ export const useSettingsStore = create<SettingsState>((set, get) => ({
_loadInFlight = (async () => {
try {
const data = await settingsApi.get()
// Rewritten here so the Map settings input already shows the host that
// still resolves, and persists it on the next save.
const incoming = withNormalizedTileUrl({ ...data.settings } as Partial<Settings>)
set((state) => ({
settings: { ...state.settings, ...data.settings },
settings: { ...state.settings, ...incoming },
isLoaded: true,
}))
} catch (err: unknown) {
@@ -83,12 +97,14 @@ export const useSettingsStore = create<SettingsState>((set, get) => ({
},
updateSetting: async (key: keyof Settings, value: Settings[keyof Settings]) => {
const next =
key === 'map_tile_url' && typeof value === 'string' ? normalizeTileUrl(value) : value
set((state) => ({
settings: { ...state.settings, [key]: value },
settings: { ...state.settings, [key]: next },
}))
if (key === 'language') localStorage.setItem('app_language', value as string)
if (key === 'language') localStorage.setItem('app_language', next as string)
try {
await settingsApi.set(key, value)
await settingsApi.set(key, next)
} catch (err: unknown) {
console.error('Failed to save setting:', err)
throw new Error(getApiErrorMessage(err, 'Error saving setting'))
@@ -109,11 +125,12 @@ export const useSettingsStore = create<SettingsState>((set, get) => ({
},
updateSettings: async (settingsObj: Partial<Settings>) => {
const patch = withNormalizedTileUrl(settingsObj)
set((state) => ({
settings: { ...state.settings, ...settingsObj },
settings: { ...state.settings, ...patch },
}))
try {
await settingsApi.setBulk(settingsObj)
await settingsApi.setBulk(patch)
} catch (err: unknown) {
console.error('Failed to save settings:', err)
throw new Error(getApiErrorMessage(err, 'Error saving settings'))
+16 -4
View File
@@ -21,6 +21,7 @@
import type { Place } from '../types'
import { offlineDb, upsertSyncMeta } from '../db/offlineDb'
import { isAuthed } from './authGate'
import { normalizeTileUrl } from '../utils/tileUrl'
// ── Constants ─────────────────────────────────────────────────────────────────
@@ -52,14 +53,21 @@ const TILE_CACHE = 'map-tiles'
const DEFAULT_TILE_URL =
'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png'
const SUBDOMAINS = ['a', 'b', 'c', 'd']
/**
* Must stay identical to Leaflet's `subdomains` default ('abc'), because the
* index is taken modulo the list length: a fourth entry here shifts the host
* for most tiles away from the one the TileLayer will ask for, so the prefetch
* fills the cache under URLs the map never requests. It also produced the dead
* d.tile.openstreetmap.org lookups in #1733.
*/
const SUBDOMAINS = ['a', 'b', 'c']
/**
* Pick the subdomain from the tile coordinates, the way Leaflet does.
*
* It has to be a pure function of x/y: a rotating counter hands the same tile a
* different host on every run, which both defeats the cache lookup below and
* stores the tile up to four times under four URLs.
* stores the tile once per host.
*/
function subdomainFor(x: number, y: number): string {
return SUBDOMAINS[Math.abs(x + y) % SUBDOMAINS.length]
@@ -145,10 +153,14 @@ export function countTiles(bbox: TileBbox, minZoom: number, maxZoom: number): nu
/**
* Build the concrete tile URL for given z/x/y from a Leaflet template.
* Rotates through subdomains (a–d).
* Rotates through subdomains (a–c).
*
* The template is normalized first: this function is also reached with a raw
* admin default rather than the value from the settings store, so the OSM
* sharding rewrite has to happen here too.
*/
export function buildTileUrl(template: string, z: number, x: number, y: number): string {
return template
return normalizeTileUrl(template)
.replace('{z}', String(z))
.replace('{x}', String(x))
.replace('{y}', String(y))
+58
View File
@@ -0,0 +1,58 @@
import { describe, it, expect } from 'vitest'
import { normalizeTileUrl } from './tileUrl'
describe('normalizeTileUrl', () => {
it('drops the {s} placeholder from an OSM template', () => {
expect(normalizeTileUrl('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'))
.toBe('https://tile.openstreetmap.org/{z}/{x}/{y}.png')
})
it('rewrites a hard-coded shard host', () => {
for (const shard of ['a', 'b', 'c', 'd']) {
expect(normalizeTileUrl(`https://${shard}.tile.openstreetmap.org/{z}/{x}/{y}.png`))
.toBe('https://tile.openstreetmap.org/{z}/{x}/{y}.png')
}
})
it('rewrites a protocol-relative template', () => {
// Older templates were often stored without a scheme so they'd follow the
// page. Those reach the network just like the https ones, so the shard
// rewrite has to see them too.
expect(normalizeTileUrl('//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'))
.toBe('//tile.openstreetmap.org/{z}/{x}/{y}.png')
expect(normalizeTileUrl('//d.tile.openstreetmap.org/{z}/{x}/{y}.png'))
.toBe('//tile.openstreetmap.org/{z}/{x}/{y}.png')
})
it('keeps http and an explicit port', () => {
expect(normalizeTileUrl('http://{s}.tile.openstreetmap.org:8080/{z}/{x}/{y}.png'))
.toBe('http://tile.openstreetmap.org:8080/{z}/{x}/{y}.png')
})
it('leaves the already-correct host alone', () => {
const url = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png'
expect(normalizeTileUrl(url)).toBe(url)
})
it('leaves other providers untouched', () => {
const carto = 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png'
expect(normalizeTileUrl(carto)).toBe(carto)
const osmDe = 'https://tile.openstreetmap.de/{z}/{x}/{y}.png'
expect(normalizeTileUrl(osmDe)).toBe(osmDe)
})
it('does not touch a look-alike host', () => {
// Only the {s} placeholder and single shard letters are rewritten — a
// self-hosted mirror keeps its own hostname.
const mirror = 'https://mirror.tile.openstreetmap.org.example.com/{z}/{x}/{y}.png'
expect(normalizeTileUrl(mirror)).toBe(mirror)
const proxy = 'https://tiles.example.com/https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
expect(normalizeTileUrl(proxy)).toBe(proxy)
})
it('passes an empty template through', () => {
expect(normalizeTileUrl('')).toBe('')
})
})
+24
View File
@@ -0,0 +1,24 @@
/**
* OpenStreetMap has not needed the a/b/c.tile.openstreetmap.org subdomains
* since 2022 — tile.openstreetmap.org serves the whole grid on its own — and
* d.tile.openstreetmap.org has meanwhile lost its DNS record entirely. A
* template that still carries the `{s}` placeholder therefore depends on which
* letters the renderer substitutes: everything that lands on `d` fails with
* ERR_NAME_NOT_RESOLVED, which is console noise plus holes in the offline tile
* cache (#1733).
*
* The presets ship the single-host form now, but a template the user (or an
* admin default) saved earlier is still in the database. Rewriting it on read
* fixes those instances without a migration; the settings store rewrites it on
* save as well, so a legacy URL typed by hand converges on the same host
* instead of coming back on the next load. Other providers are left untouched.
*/
/** `{s}.` or a bare shard letter in front of tile.openstreetmap.org. */
const OSM_SHARD = /^((?:https?:)?\/\/)(?:\{s\}|[a-d])\.tile\.openstreetmap\.org(?=[/:]|$)/i
/** Collapse a sharded OSM tile template onto the single supported host. */
export function normalizeTileUrl(url: string): string {
if (!url) return url
return url.replace(OSM_SHARD, '$1tile.openstreetmap.org')
}