From 36bf9fb2238e4f0659948bcf4ed6ce792c05fc01 Mon Sep 17 00:00:00 2001 From: Maurice Date: Sun, 6 Dec 2026 16:04:24 +0100 Subject: [PATCH] fix(offline): keep account credentials out of the settings cache Keep only offline presentation and map preferences and scrub old cached settings on access. Update the cache from successful writes without retaining preferences the server declined. --- client/src/db/cacheAccountSettings.test.ts | 66 ++++++++++++++ client/src/db/cacheAccountSettings.ts | 91 +++++++++++++++++-- .../src/store/settingsStore.offline.test.ts | 45 ++++++++- client/src/store/settingsStore.ts | 21 ++++- 4 files changed, 207 insertions(+), 16 deletions(-) diff --git a/client/src/db/cacheAccountSettings.test.ts b/client/src/db/cacheAccountSettings.test.ts index 6db8052ca..7bd73a1fc 100644 --- a/client/src/db/cacheAccountSettings.test.ts +++ b/client/src/db/cacheAccountSettings.test.ts @@ -12,6 +12,13 @@ import { deleteCurrentUserDb, offlineDb, reopenAnonymous, reopenForUser } from ' const LIBERTY = 'https://tiles.openfreemap.org/styles/liberty'; const OSM = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png'; +const PRIVATE_SETTINGS = { + llm_api_key: 'test-llm-key', + webhook_url: 'https://example.test/test-webhook', + ntfy_token: 'test-ntfy-token', + assistant_memory: { '1': 'test-assistant-memory' }, + future_server_preference: 'test-unknown-value', +}; afterEach(async () => { vi.restoreAllMocks(); @@ -91,4 +98,63 @@ describe('account settings kept offline', () => { await expect(cacheAccountSettings({ map_provider: 'maplibre-gl' })).resolves.toBeUndefined(); await expect(cacheAccountSettingsPatch({ map_provider: 'maplibre-gl' })).resolves.toBeUndefined(); }); + + it('FE-DB-ACCOUNTSETTINGS-008: writes only the offline preferences from a server answer', async () => { + await reopenForUser(701); + const preferences = { + language: 'de', + start_page: 'active_trip', + temperature_unit: 'celsius', + mapbox_access_token: 'pk.test-public-map-token', + carto_api_key: 'test-public-tile-key', + } as const; + + await cacheAccountSettings({ ...PRIVATE_SETTINGS, ...preferences }); + + expect(await offlineDb.accountSettings.get('account')).toEqual({ key: 'account', settings: preferences }); + }); + + it('FE-DB-ACCOUNTSETTINGS-009: filters old cached values and the new patch before writing', async () => { + await reopenForUser(701); + await offlineDb.accountSettings.put({ + key: 'account', + settings: { ...PRIVATE_SETTINGS, map_provider: 'leaflet', mapbox_access_token: 'pk.test-old-map-token' }, + }); + + await cacheAccountSettingsPatch({ + ...PRIVATE_SETTINGS, + mapbox_access_token: 'sk.test-private-map-token', + distance_unit: 'imperial', + }); + + expect(await offlineDb.accountSettings.get('account')).toEqual({ + key: 'account', + settings: { map_provider: 'leaflet', distance_unit: 'imperial' }, + }); + }); + + it('FE-DB-ACCOUNTSETTINGS-010: reads and replaces a legacy row with just the offline preferences', async () => { + await reopenForUser(701); + await offlineDb.accountSettings.put({ + key: 'account', + settings: { ...PRIVATE_SETTINGS, map_tile_url: OSM, mapbox_access_token: 'sk.test-private-map-token' }, + }); + + expect(await cachedAccountSettings()).toEqual({ map_tile_url: OSM }); + expect(await offlineDb.accountSettings.get('account')).toEqual({ + key: 'account', + settings: { map_tile_url: OSM }, + }); + }); + + it('FE-DB-ACCOUNTSETTINGS-011: returns only offline preferences even when the scrub cannot write', async () => { + await reopenForUser(701); + await offlineDb.accountSettings.put({ + key: 'account', + settings: { ...PRIVATE_SETTINGS, map_tile_url: OSM }, + }); + vi.spyOn(offlineDb.accountSettings, 'put').mockRejectedValue(new Error('refused')); + + expect(await cachedAccountSettings()).toEqual({ map_tile_url: OSM }); + }); }); diff --git a/client/src/db/cacheAccountSettings.ts b/client/src/db/cacheAccountSettings.ts index ca01f9e3c..3491094fc 100644 --- a/client/src/db/cacheAccountSettings.ts +++ b/client/src/db/cacheAccountSettings.ts @@ -10,30 +10,102 @@ import { isAccountDb, offlineDb } from './offlineDb'; * * The row lives in the signed-in user's own database (offlineDb.ts), so another * account on the device never reads it, and logout deletes it with the database. - * It holds what the server sent this user, the map keys included: the trip data - * beside it is no less private, and without the CARTO key a stored CARTO - * template could not be drawn offline. Secrets the server masks arrive masked. + * Only the preferences needed by the offline UI go into this row. * * Every function here is best effort and never rejects. A device that cannot * keep the row (IndexedDB refused in a private window) behaves as before: it * starts on the defaults until the server answers. */ +const OFFLINE_SETTINGS = new Set([ + 'appearance', + 'dark_mode', + 'language', + 'place_language', + 'start_page', + 'start_trip_tab', + 'default_currency', + 'temperature_unit', + 'distance_unit', + 'time_format', + 'week_start', + 'date_format', + 'dashboard_fx_from', + 'dashboard_fx_to', + 'dashboard_timezones', + 'map_provider', + 'map_tile_url', + 'map_base_layer', + 'maplibre_style', + 'mapbox_style', + 'mapbox_3d_enabled', + 'mapbox_quality_mode', + 'map_hide_basemap_pois', + 'map_compact_unplanned', + 'map_booking_labels', + 'map_place_labels', + 'map_poi_pill_enabled', + 'map_always_show_routes', + 'show_place_description', + 'blur_booking_codes', + 'day_date_first', + 'preferred_nav_app', + 'optimize_from_accommodation', + 'planner_trip_views', + 'roadtrip_vehicle', + 'roadtrip_leg_minutes', + 'roadtrip_day_minutes', + 'roadtrip_day_start', + 'roadtrip_day_end', + 'roadtrip_day_end_mode', + 'roadtrip_range_km', + 'roadtrip_avoid', + 'roadtrip_connect_days', + 'roadtrip_day_colors', + 'roadtrip_fill_percent', + 'roadtrip_tank_litres', + 'roadtrip_litres_per_100', + 'roadtrip_battery_kwh', + 'roadtrip_kwh_per_100', + 'roadtrip_battery_degradation', + // The browser needs this tile key to resolve the same CARTO URL when offline. + 'carto_api_key', +] satisfies (keyof Settings)[]); + +function offlineSettingsOf(settings: Partial): Partial { + const entries = Object.entries(settings).filter(([key]) => OFFLINE_SETTINGS.has(key)); + const kept: Partial = Object.fromEntries(entries); + const token = settings.mapbox_access_token; + // A Mapbox browser token keeps the user's selected engine available offline. + if (typeof token === 'string' && (token === '' || token.startsWith('pk.'))) kept.mapbox_access_token = token; + return kept; +} + /** The settings the server last answered, or null when this device kept none. */ export async function cachedAccountSettings(): Promise | null> { + let settings: Partial | null = null; try { if (!isAccountDb()) return null; - return (await offlineDb.accountSettings.get('account'))?.settings ?? null; + const table = offlineDb.accountSettings; + await offlineDb.transaction('rw', table, async () => { + const row = await table.get('account'); + if (!row) return; + settings = offlineSettingsOf(row.settings); + if (Object.keys(settings).length !== Object.keys(row.settings).length) { + await table.put({ key: 'account', settings }); + } + }); } catch { - return null; + /* If the disk update fails, still use the filtered settings from memory. */ } + return settings; } /** Keeps the server's answer, replacing the one kept before. */ export async function cacheAccountSettings(settings: Partial): Promise { try { if (!isAccountDb()) return; - await offlineDb.accountSettings.put({ key: 'account', settings }); + await offlineDb.accountSettings.put({ key: 'account', settings: offlineSettingsOf(settings) }); } catch { /* Nothing kept: the next start without a connection shows the defaults, as it always did. */ } @@ -46,9 +118,10 @@ export async function cacheAccountSettings(settings: Partial): Promise export async function cacheAccountSettingsPatch(patch: Partial): Promise { try { if (!isAccountDb()) return; - await offlineDb.transaction('rw', offlineDb.accountSettings, async () => { - const kept = (await offlineDb.accountSettings.get('account'))?.settings; - await offlineDb.accountSettings.put({ key: 'account', settings: { ...kept, ...patch } }); + const table = offlineDb.accountSettings; + await offlineDb.transaction('rw', table, async () => { + const kept = (await table.get('account'))?.settings; + await table.put({ key: 'account', settings: offlineSettingsOf({ ...kept, ...patch }) }); }); } catch { /* The kept answer stays as it was; the next server answer replaces it anyway. */ diff --git a/client/src/store/settingsStore.offline.test.ts b/client/src/store/settingsStore.offline.test.ts index 04920224e..0cb2c4a25 100644 --- a/client/src/store/settingsStore.offline.test.ts +++ b/client/src/store/settingsStore.offline.test.ts @@ -10,7 +10,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { settingsApi } from '../api/client'; import { cacheAccountSettings, cachedAccountSettings } from '../db/cacheAccountSettings'; -import { deleteCurrentUserDb, reopenAnonymous, reopenForUser } from '../db/offlineDb'; +import { deleteCurrentUserDb, offlineDb, reopenAnonymous, reopenForUser } from '../db/offlineDb'; import { DEFAULT_SETTINGS, useSettingsStore } from './settingsStore'; vi.mock('../api/client', () => ({ @@ -30,7 +30,9 @@ const settings = () => useSettingsStore.getState().settings; beforeEach(async () => { vi.mocked(settingsApi.get).mockReset(); vi.mocked(settingsApi.set).mockReset().mockResolvedValue(undefined); - vi.mocked(settingsApi.setBulk).mockReset().mockResolvedValue(undefined); + vi.mocked(settingsApi.setBulk) + .mockReset() + .mockImplementation(async (patch) => ({ success: true, updated: Object.keys(patch).length })); vi.spyOn(console, 'error').mockImplementation(() => {}); useSettingsStore.setState(initialState, true); await reopenForUser(801); @@ -119,4 +121,43 @@ describe('settings without a connection', () => { expect(await cachedAccountSettings()).toEqual({ map_provider: 'leaflet' }); }); + + it('FE-STORE-SETTINGS-OFFLINE-008: saving a provider key keeps the offline preference only', async () => { + const patch = { llm_api_key: 'test-llm-key', language: 'de' }; + + await useSettingsStore.getState().updateSettings(patch); + + expect(settingsApi.setBulk).toHaveBeenCalledWith(patch); + await vi.waitFor(async () => + expect(await offlineDb.accountSettings.get('account')).toEqual({ key: 'account', settings: { language: 'de' } }) + ); + }); + + it('FE-STORE-SETTINGS-OFFLINE-009: successful responses only cache values the server wrote', async () => { + await cacheAccountSettings({ map_provider: 'leaflet', map_tile_url: OSM_DE }); + vi.mocked(settingsApi.set).mockResolvedValue({ success: true, key: 'map_provider', unchanged: true }); + vi.mocked(settingsApi.setBulk).mockResolvedValue({ success: true, updated: 1, managed_keys: ['map_tile_url'] }); + + await useSettingsStore.getState().updateSetting('map_provider', 'maplibre-gl'); + await useSettingsStore.getState().updateSettings({ map_tile_url: BRIGHT, distance_unit: 'imperial' }); + + await vi.waitFor(async () => + expect(await cachedAccountSettings()).toEqual({ + map_provider: 'leaflet', + map_tile_url: OSM_DE, + distance_unit: 'imperial', + }) + ); + }); + + it('FE-STORE-SETTINGS-OFFLINE-010: a partial bulk write refreshes the cache from the server', async () => { + vi.mocked(settingsApi.setBulk).mockResolvedValue({ success: true, updated: 1 }); + vi.mocked(settingsApi.get).mockResolvedValue({ settings: { map_provider: 'leaflet', distance_unit: 'imperial' } }); + + await useSettingsStore.getState().updateSettings({ map_provider: 'mapbox-gl', distance_unit: 'imperial' }); + + await vi.waitFor(async () => + expect(await cachedAccountSettings()).toEqual({ map_provider: 'leaflet', distance_unit: 'imperial' }) + ); + }); }); diff --git a/client/src/store/settingsStore.ts b/client/src/store/settingsStore.ts index 5bcffa9b9..538f9999f 100644 --- a/client/src/store/settingsStore.ts +++ b/client/src/store/settingsStore.ts @@ -1,7 +1,13 @@ import { create } from 'zustand' import { settingsApi } from '../api/client' import type { Settings } from '../types' -import { DEFAULT_APPEARANCE, DEFAULT_DATE_FORMAT, DEFAULT_WEEK_START } from '@trek/shared' +import { + DEFAULT_APPEARANCE, + DEFAULT_DATE_FORMAT, + DEFAULT_WEEK_START, + type SettingUpsertResponse, + type SettingsBulkResponse, +} from '@trek/shared' import { getApiErrorMessage } from '../types' import { SUPPORTED_LANGUAGE_CODES } from '../i18n/supportedLanguages' import { detectBrowserLanguage } from '../i18n/detectBrowserLanguage' @@ -214,8 +220,8 @@ export const useSettingsStore = create((set, get) => ({ if (key === 'language') localStorage.setItem('app_language', next as string) rememberStartDestination({ [key]: next } as Partial) try { - await settingsApi.set(key, next) - void cacheAccountSettingsPatch({ [key]: next } as Partial) + const saved: SettingUpsertResponse | undefined = await settingsApi.set(key, next) + if (!saved?.managed && !saved?.unchanged) void cacheAccountSettingsPatch({ [key]: next } as Partial) } catch (err: unknown) { console.error('Failed to save setting:', err) throw new Error(getApiErrorMessage(err, 'Error saving setting')) @@ -248,8 +254,13 @@ export const useSettingsStore = create((set, get) => ({ })) rememberStartDestination(patch) try { - await settingsApi.setBulk(patch) - void cacheAccountSettingsPatch(patch) + const saved: SettingsBulkResponse | undefined = await settingsApi.setBulk(patch) + if (!saved) return + const managed = new Set(saved.managed_keys) + const accepted = Object.entries(patch).filter(([key]) => !managed.has(key)) + // Some no-ops report only a count, so fetch what was actually saved. + if (accepted.length === saved.updated) void cacheAccountSettingsPatch(Object.fromEntries(accepted)) + else void get().loadSettings() } catch (err: unknown) { console.error('Failed to save settings:', err) throw new Error(getApiErrorMessage(err, 'Error saving settings'))