fix(settings): a managed install keeps a map provider somebody chose

With the operator's Mapbox token a managed install replaced every empty or
Leaflet provider with Mapbox, including a Leaflet the user picked and a
Leaflet default the admin set. A plain "only when empty" would switch
everyone whose Leaflet row only exists because the settings form writes
every field (#1634), so the choice is recorded instead, by the server alone:

- map_provider_chosen on the user's settings, set when a write changes the
  provider the user is shown (so saving the form unchanged is no choice,
  and leaving the Mapbox a managed install shows is one). A client patch
  naming the key is dropped on both routes, false included, so no client
  can set or clear it.
- map_provider_default_chosen in app_settings, set when the admin saves a
  map_provider default and removed when it is reset.

Mapbox now replaces an empty provider, or a Leaflet without the mark of
where it came from. No stored row is rewritten: rows without a mark read
exactly as before. The client Settings type gains the read-only field.
This commit is contained in:
Maurice
2026-11-30 14:24:02 +01:00
parent 51dc0e6a82
commit fdfc034a68
6 changed files with 295 additions and 16 deletions
@@ -139,6 +139,12 @@ export const APP_SETTINGS = {
airtrail_sync_enabled: { schema: flag, default: 'true' },
airtrail_poll_interval_minutes: { schema: intText, default: null },
dawarich_poll_interval_minutes: { schema: intText, default: null },
/**
* Set by the server when an admin picks the default map provider, removed when
* the default is reset: a managed install shows its Mapbox in place of a
* Leaflet default only while this is missing (SettingsService).
*/
map_provider_default_chosen: { schema: flag, default: null },
/** The release the admins were last notified about (the version-check job's memory). */
last_notified_version: { schema: text, default: null },
/** When the one pass that carried every person's place votes onto their other copies of the place finished. */
@@ -1,5 +1,5 @@
import { RealtimeService } from '../realtime/realtime.service';
import { SettingsService } from './settings.service';
import { SettingsService, isServerOwnedSetting } from './settings.service';
import { Injectable } from '@nestjs/common';
import { MASKED_SETTING_VALUE } from '@trek/shared';
@@ -24,12 +24,15 @@ export class SettingsWritesService {
this.announce(userId, [key], socketId);
}
/** Answers how many rows were written. A masked secret echoed back is skipped, and named in no event. */
/**
* Answers how many rows were written. A masked secret echoed back, and a key
* only the server writes, are skipped and named in no event.
*/
async saveMany(userId: number, values: Record<string, unknown>, socketId: string | undefined): Promise<number> {
const written = await this.settings.bulkUpsertSettings(userId, values);
this.announce(
userId,
Object.keys(values).filter((key) => values[key] !== MASKED_SETTING_VALUE),
Object.keys(values).filter((key) => values[key] !== MASKED_SETTING_VALUE && !isServerOwnedSetting(key)),
socketId,
);
return written;
@@ -10,7 +10,7 @@ import { isManagedLockedKey, splitManagedKeys } from '../common/managed';
import { ResponseContract } from '../common/response-contract';
import { SettingsWritesService } from './settings-writes.service';
import { AdminDefaultUserSettingsDto, SettingUpsertDto, SettingsBulkDto } from './settings.dto';
import { SettingsService, isAdminOnlyEndpointSetting } from './settings.service';
import { SettingsService, isAdminOnlyEndpointSetting, isServerOwnedSetting } from './settings.service';
import { Body, Controller, Get, Headers, HttpCode, HttpException, Post, Put, Req, UseGuards } from '@nestjs/common';
import {
MASKED_SETTING_VALUE,
@@ -104,8 +104,9 @@ export class SettingsController {
if (isDemoLockedSetting(user, body.key)) {
return { success: true, key: body.key, unchanged: true };
}
// The client echoes a redacted secret back unchanged — treat as a no-op.
if (body.value === MASKED_SETTING_VALUE) {
// The client echoes a redacted secret back unchanged — treat as a no-op. A key
// only the server writes (the map provider choice mark) stays as it is too.
if (body.value === MASKED_SETTING_VALUE || isServerOwnedSetting(body.key)) {
return { success: true, key: body.key, unchanged: true };
}
await this.writes.saveOne(user.id, body.key, body.value, socketId);
+76 -10
View File
@@ -120,6 +120,34 @@ const VALID_VALUES: Partial<Record<DefaultableKey, unknown[]>> = {
routing_valhalla_provider: [...valhallaProviderSchema.options],
};
/**
* Set on a user's settings when they pick a map provider themselves, and only by
* this service: a client patch naming it is dropped, `false` included, so no
* client can take a choice back. A managed install puts Mapbox in place of a
* Leaflet row that carries no such mark (see `managedMapboxReplaces`).
*/
export const MAP_PROVIDER_CHOSEN_KEY = 'map_provider_chosen';
/** The admin default's counterpart of {@link MAP_PROVIDER_CHOSEN_KEY}, in app_settings. */
const MAP_PROVIDER_DEFAULT_CHOSEN_KEY: AppSettingKey = 'map_provider_default_chosen';
/** User settings only the server writes. */
const SERVER_OWNED_SETTING_KEYS = new Set<string>([MAP_PROVIDER_CHOSEN_KEY]);
/** Whether `key` is written by the server alone, never from a client's patch. */
export function isServerOwnedSetting(key: string): boolean {
return SERVER_OWNED_SETTING_KEYS.has(key);
}
function isMapProvider(value: unknown): boolean {
return VALID_VALUES.map_provider?.includes(value) === true;
}
/** An empty user value defers to the admin default (#1634). */
function isEmptySetting(value: unknown): boolean {
return value === '' || value === null || value === undefined;
}
const BOOLEAN_KEYS = new Set<DefaultableKey>([
'blur_booking_codes',
'mapbox_3d_enabled',
@@ -254,6 +282,7 @@ export class SettingsService {
// null/undefined means "reset to built-in default" — delete the row
if (value === null || value === undefined) {
await this.appSettings.deleteValue(appKey);
if (key === 'map_provider') await this.appSettings.deleteValue(MAP_PROVIDER_DEFAULT_CHOSEN_KEY);
continue;
}
@@ -271,6 +300,9 @@ export class SettingsService {
? (maybe_encrypt_api_key(String(value)) ?? String(value))
: JSON.stringify(value);
await this.appSettings.setValue(appKey, stored);
// The admin page saves a field only when the admin sets it, so a stored
// provider default is always a choice a managed install has to keep.
if (key === 'map_provider') await this.appSettings.setValue(MAP_PROVIDER_DEFAULT_CHOSEN_KEY, 'true');
}
});
}
@@ -314,11 +346,7 @@ export class SettingsService {
merged[key] = MASKED_SETTING_KEYS.has(key) ? (value ? MASKED_SETTING_VALUE : '') : value;
}
for (const [key, value] of Object.entries(userSettings)) {
if (
DEFAULTABLE_USER_SETTING_KEY_SET.has(key) &&
(value === '' || value === null || value === undefined) &&
key in adminDefaults
) {
if (DEFAULTABLE_USER_SETTING_KEY_SET.has(key) && isEmptySetting(value) && key in adminDefaults) {
continue; // empty user value → keep the admin default
}
merged[key] = value;
@@ -328,11 +356,12 @@ export class SettingsService {
// instance, so it is injected here rather than stored per user: the token is
// the operator's, it is a public pk.* that has to reach the browser anyway,
// and nobody should be able to save a different one over it. GL is the
// default there too, since a token is always present.
// default there too, since a token is always present, but never over a
// provider somebody picked.
const managedMaps = readEnv().maps;
if (readEnv().managed.enabled && managedMaps.mapboxToken) {
merged.mapbox_access_token = managedMaps.mapboxToken;
if (!merged.map_provider || merged.map_provider === 'leaflet') {
if (await this.managedMapboxReplaces(merged.map_provider, userSettings)) {
merged.map_provider = 'mapbox-gl';
}
}
@@ -346,9 +375,42 @@ export class SettingsService {
return merged;
}
/**
* Whether a managed install shows Mapbox in place of `provider`, the merged
* value: when there is none, or when it is a Leaflet nobody chose. Before the
* choice marks existed every save wrote all fields (#1634), so a Leaflet row
* without its mark is most likely that and keeps reading as Mapbox, as it
* always has. A Leaflet the user or the admin picked stays Leaflet.
*/
private async managedMapboxReplaces(provider: unknown, userSettings: Record<string, unknown>): Promise<boolean> {
if (!provider) return true;
if (provider !== 'leaflet') return false;
if (!isEmptySetting(userSettings.map_provider)) return userSettings[MAP_PROVIDER_CHOSEN_KEY] !== true;
return (await readAppSetting(this.appSettings, MAP_PROVIDER_DEFAULT_CHOSEN_KEY)) !== 'true';
}
/**
* Marks the user's map provider as their own choice when this write changes
* what they see. Saving the form unchanged writes the provider shown (#1634)
* and is no choice; a switch is one, on a managed install too, where the
* provider shown may be the Mapbox put in place of an unmarked Leaflet row.
* The mark is only ever set, so a later save cannot take it away.
*/
private async recordMapProviderChoice(userId: number, entries: [string, unknown][]): Promise<void> {
const provider = entries.find(([key]) => key === 'map_provider')?.[1];
if (!isMapProvider(provider)) return;
if ((await this.getUserSettings(userId)).map_provider === provider) return;
await this.settings.upsertForUser(userId, MAP_PROVIDER_CHOSEN_KEY, serializeValue(MAP_PROVIDER_CHOSEN_KEY, true));
}
/** Writes one of the user's settings; a key only the server writes is left as it is. */
async upsertSetting(userId: number, key: string, value: unknown) {
if (isServerOwnedSetting(key)) return;
const prepared = await this.prepareValue(userId, key, value);
await this.settings.upsertForUser(userId, key, serializeValue(key, prepared));
await this.uow.transactional(async () => {
await this.recordMapProviderChoice(userId, [[key, prepared]]);
await this.settings.upsertForUser(userId, key, serializeValue(key, prepared));
});
}
async bulkUpsertSettings(userId: number, settings: Record<string, unknown>) {
@@ -356,8 +418,12 @@ export class SettingsService {
await this.uow.transactional(async () => {
// The client echoes redacted secrets back unchanged — skip them so a
// bulk save can never overwrite a stored secret with the mask (the
// single-upsert route has the same no-op in the controller).
const entries = Object.entries(settings).filter(([, value]) => value !== MASKED_SETTING_VALUE);
// single-upsert route has the same no-op in the controller). A key only
// the server writes is skipped the same way.
const entries = Object.entries(settings).filter(
([key, value]) => value !== MASKED_SETTING_VALUE && !isServerOwnedSetting(key),
);
await this.recordMapProviderChoice(userId, entries);
for (const [key, prepared] of await this.prepareValues(userId, entries)) {
await this.settings.upsertForUser(userId, key, serializeValue(key, prepared));
written++;