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
+2
View File
@@ -173,6 +173,8 @@ export interface Settings {
map_always_show_routes?: boolean
optimize_from_accommodation?: boolean
map_provider?: 'leaflet' | 'mapbox-gl' | 'maplibre-gl'
/** Set by the server once the user picks a provider themselves; read-only here, the server drops a client's value. */
map_provider_chosen?: boolean
/** Leaflet base layer: default street tiles or a satellite/aerial view. */
map_base_layer?: 'default' | 'satellite'
/**
@@ -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++;
@@ -0,0 +1,201 @@
/**
* The map provider a managed install shows, on the whole app (both engines: the
* Postgres lane runs this suite too). A managed install with the operator's
* Mapbox token shows Mapbox in place of an empty provider and in place of a
* Leaflet nobody chose, as it always has; a Leaflet the user or the admin picked
* stays Leaflet. Whether it was picked is a mark only the server sets: on a
* write that changes the provider shown, or when the admin sets the default. No
* stored row is rewritten, and no client can set or clear a mark.
*/
import { buildApp } from '../../src/bootstrap';
import { AppSettings } from '../../src/db/entities/AppSettings.entity';
import { MAP_PROVIDER_CHOSEN_KEY } from '../../src/nest/settings/settings.service';
import { deleteRows } from '../helpers/factories/rows';
import { readAppSetting, readUserSetting, setAppSetting, setUserSetting } from '../helpers/factories/settings';
import { makeAdmin, makeUser } from '../helpers/factories/users';
import { sessionCookie } from './harness';
import { MikroORM } from '@mikro-orm/core';
import type { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
let app: INestApplication;
let orm: MikroORM;
let adminId: number;
const ADMIN_DEFAULT = 'default_user_setting_map_provider';
const ADMIN_MARK = 'map_provider_default_chosen';
beforeAll(async () => {
app = await buildApp();
orm = app.get(MikroORM);
adminId = (await makeAdmin(orm)).user.id;
}, 60_000);
beforeEach(async () => {
vi.stubEnv('TREK_MANAGED', 'true');
vi.stubEnv('MAPBOX_ACCESS_TOKEN', 'pk.operator');
await deleteRows(orm, AppSettings, { key: { $in: [ADMIN_DEFAULT, ADMIN_MARK] } });
});
afterAll(async () => {
vi.unstubAllEnvs();
await app?.close();
});
async function newUser(): Promise<number> {
return (await makeUser(orm)).user.id;
}
async function shownProvider(userId: number): Promise<unknown> {
const res = await request(app.getHttpServer()).get('/api/settings').set('Cookie', sessionCookie(userId));
expect(res.status).toBe(200);
return (res.body as { settings: Record<string, unknown> }).settings.map_provider;
}
function saveOne(userId: number, key: string, value: unknown) {
return request(app.getHttpServer()).put('/api/settings').set('Cookie', sessionCookie(userId)).send({ key, value });
}
function saveAll(userId: number, settings: Record<string, unknown>) {
return request(app.getHttpServer())
.post('/api/settings/bulk')
.set('Cookie', sessionCookie(userId))
.send({ settings });
}
function setAdminDefault(value: string | null) {
return request(app.getHttpServer())
.put('/api/admin/default-user-settings')
.set('Cookie', sessionCookie(adminId))
.send({ map_provider: value });
}
describe('the provider a managed install shows', () => {
it('MAPPROV-E2E-001: no provider anywhere reads as Mapbox', async () => {
expect(await shownProvider(await newUser())).toBe('mapbox-gl');
});
it('MAPPROV-E2E-002: a Leaflet row without the mark reads as Mapbox, as it did before the mark existed', async () => {
const userId = await newUser();
await setUserSetting(orm, userId, 'map_provider', 'leaflet');
expect(await shownProvider(userId)).toBe('mapbox-gl');
expect(await readUserSetting(orm, userId, 'map_provider')).toBe('leaflet');
});
it('MAPPROV-E2E-003: a Leaflet row with the mark stays Leaflet', async () => {
const userId = await newUser();
await setUserSetting(orm, userId, 'map_provider', 'leaflet');
await setUserSetting(orm, userId, MAP_PROVIDER_CHOSEN_KEY, 'true');
expect(await shownProvider(userId)).toBe('leaflet');
});
it('MAPPROV-E2E-004: a MapLibre row stays MapLibre without any mark', async () => {
const userId = await newUser();
await setUserSetting(orm, userId, 'map_provider', 'maplibre-gl');
expect(await shownProvider(userId)).toBe('maplibre-gl');
});
it('MAPPROV-E2E-005: a Leaflet admin default stored before the mark existed reads as Mapbox', async () => {
await setAppSetting(orm, ADMIN_DEFAULT, JSON.stringify('leaflet'));
expect(await shownProvider(await newUser())).toBe('mapbox-gl');
});
it('MAPPROV-E2E-006: a Leaflet default the admin sets is kept, and resetting it takes the mark away', async () => {
const userId = await newUser();
expect((await setAdminDefault('leaflet')).status).toBe(200);
expect(await readAppSetting(orm, ADMIN_MARK)).toBe('true');
expect(await shownProvider(userId)).toBe('leaflet');
// An empty personal row still defers to that default.
await setUserSetting(orm, userId, 'map_provider', '');
expect(await shownProvider(userId)).toBe('leaflet');
expect((await setAdminDefault(null)).status).toBe(200);
expect(await readAppSetting(orm, ADMIN_MARK)).toBeNull();
expect(await readAppSetting(orm, ADMIN_DEFAULT)).toBeNull();
expect(await shownProvider(userId)).toBe('mapbox-gl');
});
it("MAPPROV-E2E-007: the admin's mark does not reach a user's own unmarked Leaflet row", async () => {
expect((await setAdminDefault('leaflet')).status).toBe(200);
const userId = await newUser();
await setUserSetting(orm, userId, 'map_provider', 'leaflet');
expect(await shownProvider(userId)).toBe('mapbox-gl');
});
});
describe('the mark a write sets', () => {
it('MAPPROV-E2E-008: switching from the Mapbox shown to Leaflet is a choice and is kept', async () => {
const userId = await newUser();
await setUserSetting(orm, userId, 'map_provider', 'leaflet');
expect((await saveOne(userId, 'map_provider', 'leaflet')).status).toBe(200);
expect(await readUserSetting(orm, userId, MAP_PROVIDER_CHOSEN_KEY)).toBe('true');
expect(await shownProvider(userId)).toBe('leaflet');
// Saving the whole form again later keeps it.
expect((await saveAll(userId, { map_provider: 'leaflet', map_tile_url: '' })).status).toBe(200);
expect(await shownProvider(userId)).toBe('leaflet');
});
it('MAPPROV-E2E-009: saving every field with the provider shown sets no mark', async () => {
const userId = await newUser();
await setUserSetting(orm, userId, 'map_provider', 'leaflet');
const res = await saveAll(userId, { map_provider: 'mapbox-gl', map_tile_url: '', mapbox_style: '' });
expect(res.status).toBe(200);
expect(await readUserSetting(orm, userId, MAP_PROVIDER_CHOSEN_KEY)).toBeNull();
expect(await shownProvider(userId)).toBe('mapbox-gl');
});
it('MAPPROV-E2E-010: a switch through the bulk save is a choice too', async () => {
const userId = await newUser();
expect((await saveAll(userId, { map_provider: 'leaflet' })).status).toBe(200);
expect(await readUserSetting(orm, userId, MAP_PROVIDER_CHOSEN_KEY)).toBe('true');
expect(await shownProvider(userId)).toBe('leaflet');
});
it('MAPPROV-E2E-011: a value that names no provider sets no mark', async () => {
const userId = await newUser();
expect((await saveOne(userId, 'map_provider', '')).status).toBe(200);
expect(await readUserSetting(orm, userId, MAP_PROVIDER_CHOSEN_KEY)).toBeNull();
});
it('MAPPROV-E2E-012: outside a managed install the mark changes nothing about what is shown', async () => {
vi.stubEnv('TREK_MANAGED', 'false');
const userId = await newUser();
await setUserSetting(orm, userId, 'map_provider', 'leaflet');
expect(await shownProvider(userId)).toBe('leaflet');
expect((await saveOne(userId, 'map_provider', 'maplibre-gl')).status).toBe(200);
expect(await readUserSetting(orm, userId, MAP_PROVIDER_CHOSEN_KEY)).toBe('true');
expect(await shownProvider(userId)).toBe('maplibre-gl');
});
});
describe("the mark is the server's alone", () => {
it('MAPPROV-E2E-013: a client cannot clear it, through either route', async () => {
const userId = await newUser();
await setUserSetting(orm, userId, 'map_provider', 'leaflet');
await setUserSetting(orm, userId, MAP_PROVIDER_CHOSEN_KEY, 'true');
const single = await saveOne(userId, MAP_PROVIDER_CHOSEN_KEY, false);
expect(single.status).toBe(200);
expect(single.body).toEqual({ success: true, key: MAP_PROVIDER_CHOSEN_KEY, unchanged: true });
const bulk = await saveAll(userId, { [MAP_PROVIDER_CHOSEN_KEY]: false, map_provider: 'leaflet' });
expect(bulk.status).toBe(200);
expect(bulk.body).toMatchObject({ success: true, updated: 1 });
expect(await readUserSetting(orm, userId, MAP_PROVIDER_CHOSEN_KEY)).toBe('true');
expect(await shownProvider(userId)).toBe('leaflet');
});
it('MAPPROV-E2E-014: a client cannot set it either', async () => {
const userId = await newUser();
await setUserSetting(orm, userId, 'map_provider', 'leaflet');
expect((await saveOne(userId, MAP_PROVIDER_CHOSEN_KEY, true)).status).toBe(200);
expect((await saveAll(userId, { [MAP_PROVIDER_CHOSEN_KEY]: true })).body).toMatchObject({ updated: 0 });
expect(await readUserSetting(orm, userId, MAP_PROVIDER_CHOSEN_KEY)).toBeNull();
expect(await shownProvider(userId)).toBe('mapbox-gl');
});
});