Skip to content

Commit 7ffb14a

Browse files
Merge pull request #795 from bingmokaka/validate-settings-language-allowlist
fix(settings): validate language against supported locales
2 parents 2619389 + e7dc9e1 commit 7ffb14a

2 files changed

Lines changed: 29 additions & 1 deletion

File tree

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { beforeEach, describe, expect, it } from 'vitest';
2+
import { useSettingsStore } from '../store';
3+
4+
beforeEach(() => {
5+
useSettingsStore.getState().resetSettings();
6+
});
7+
8+
describe('useSettingsStore', () => {
9+
it('falls back to the default language for unsupported locales', () => {
10+
useSettingsStore.getState().patchSettings({ language: 'zz-ZZ' });
11+
12+
expect(useSettingsStore.getState().settings.language).toBe('en');
13+
});
14+
15+
it('keeps supported languages when patching settings', () => {
16+
useSettingsStore.getState().patchSettings({ language: 'fr' });
17+
18+
expect(useSettingsStore.getState().settings.language).toBe('fr');
19+
});
20+
});

src/lib/settings/store.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
*/
4242
import { create } from 'zustand';
4343
import { persist, createJSONStorage } from 'zustand/middleware';
44+
import { DEFAULT_LANGUAGE, SUPPORTED_LANGUAGES } from '../../locales/config';
4445
import { SETTINGS_SCHEMA_VERSION, SETTINGS_STORAGE_KEY } from './constants';
4546
import { type AppSettings, appSettingsSchema, createDefaultSettings } from './types';
4647

@@ -88,6 +89,13 @@ const noopStorage = {
8889
removeItem: (): void => undefined,
8990
};
9091

92+
function normalizeLanguage(language: string): AppSettings['language'] {
93+
const trimmed = language.trim();
94+
return Object.prototype.hasOwnProperty.call(SUPPORTED_LANGUAGES, trimmed)
95+
? trimmed
96+
: DEFAULT_LANGUAGE;
97+
}
98+
9199
function localStorageOrNoop() {
92100
if (typeof window === 'undefined') return noopStorage;
93101
try {
@@ -112,7 +120,7 @@ export const useSettingsStore = create<SettingsSlice>()(
112120
version: SETTINGS_SCHEMA_VERSION,
113121
...(partial.language !== undefined
114122
? {
115-
language: partial.language.trim().slice(0, 24) || 'en',
123+
language: normalizeLanguage(partial.language),
116124
}
117125
: {}),
118126
};

0 commit comments

Comments
 (0)