Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Persist configured language in web app and cleanup legacy storage (#2439)
Leendert de Borst8883a5ab243e
diff --git a/apps/server/AliasVault.Api/Program.cs b/apps/server/AliasVault.Api/Program.csindex 06800c841..a28830b48 100644--- a/apps/server/AliasVault.Api/Program.cs+++ b/apps/server/AliasVault.Api/Program.cs@@ -47,13 +47,13 @@ config.PublicRegistrationEnabled = bool.Parse(publicRegistrationEnabled);var privateEmailDomains = Environment.GetEnvironmentVariable("PRIVATE_EMAIL_DOMAINS")?.Split(",", StringSplitOptions.RemoveEmptyEntries)- .Select(d => d.Trim())+ .Select(d => d.Trim().ToLowerInvariant()).Where(d => !string.IsNullOrWhiteSpace(d));config.PrivateEmailDomains = privateEmailDomains?.ToList() ?? new List<string>();var hiddenPrivateEmailDomains = Environment.GetEnvironmentVariable("HIDDEN_PRIVATE_EMAIL_DOMAINS")?.Split(",", StringSplitOptions.RemoveEmptyEntries)- .Select(d => d.Trim())+ .Select(d => d.Trim().ToLowerInvariant()).Where(d => !string.IsNullOrWhiteSpace(d));config.HiddenPrivateEmailDomains = hiddenPrivateEmailDomains?.ToList() ?? new List<string>();diff --git a/apps/web/src/config/AppConfig.ts b/apps/web/src/config/AppConfig.tsindex 71f4407b3..42acdb6e9 100644--- a/apps/web/src/config/AppConfig.ts+++ b/apps/web/src/config/AppConfig.ts@@ -69,8 +69,8 @@ export async function loadAppConfig(): Promise<AppConfig> {current = {apiUrl,- privateEmailDomains: file.PrivateEmailDomains ?? [],- hiddenPrivateEmailDomains: file.HiddenPrivateEmailDomains ?? [],+ privateEmailDomains: (file.PrivateEmailDomains ?? []).map(domain => domain.trim().toLowerCase()),+ hiddenPrivateEmailDomains: (file.HiddenPrivateEmailDomains ?? []).map(domain => domain.trim().toLowerCase()),supportEmail: file.SupportEmail ?? '',publicRegistrationEnabled: String(file.PublicRegistrationEnabled ?? 'true').toLowerCase() === 'true',deploymentMode: file.DeploymentMode ?? '',diff --git a/apps/web/src/hooks/useVaultLanguage.ts b/apps/web/src/hooks/useVaultLanguage.tsnew file mode 100644index 000000000..bde96b210--- /dev/null+++ b/apps/web/src/hooks/useVaultLanguage.ts@@ -0,0 +1,39 @@+import { useEffect } from 'react';++import { useDb } from '@/context/DbContext';+import { useVaultMutate } from '@/hooks/useVaultMutate';+import { LANGUAGE_CODES } from '@/i18n/config';+import i18n, { changeLanguage } from '@/i18n/i18n';++/**+ * Vault setting that holds the UI language, so it follows the user across devices.+ */+const APP_LANGUAGE_SETTING = 'AppLanguage';++/**+ * Set the UI language to the vault's language, or the current language if the vault has none yet.+ * @param enabled - whether the vault is open+ */+export function useVaultLanguage(enabled: boolean): void {+ const { sqliteClient } = useDb();+ const { executeVaultMutationInBackground } = useVaultMutate();++ useEffect(() => {+ if (!enabled || !sqliteClient) {+ return;+ }++ const vaultLanguage = sqliteClient.settings.getSetting(APP_LANGUAGE_SETTING, '');+ if (LANGUAGE_CODES.includes(vaultLanguage)) {+ if (vaultLanguage !== i18n.language) {+ void changeLanguage(vaultLanguage);+ }+ return;+ }++ const currentLanguage = i18n.language;+ executeVaultMutationInBackground(async () => {+ sqliteClient.settings.updateSetting(APP_LANGUAGE_SETTING, currentLanguage);+ }).catch((error) => console.error('Failed to store the app language in the vault:', error));+ }, [enabled, sqliteClient, executeVaultMutationInBackground]);+}diff --git a/apps/web/src/layouts/MainLayout.tsx b/apps/web/src/layouts/MainLayout.tsxindex 2e5be3c84..f83662dee 100644--- a/apps/web/src/layouts/MainLayout.tsx+++ b/apps/web/src/layouts/MainLayout.tsx@@ -9,6 +9,7 @@ import TopMenu from '@/components/layout/TopMenu';import ConfirmModal from '@/components/shared/ConfirmModal';import { useAuth } from '@/context/AuthContext';import { useDb } from '@/context/DbContext';+import { useVaultLanguage } from '@/hooks/useVaultLanguage';import { useVaultSync } from '@/hooks/useVaultSync';import { setLocalPreference } from '@/utils/LocalPreferences';import { LocalPreferenceKeys } from '@/utils/StorageKeys';@@ -21,12 +22,13 @@ import { vaultStore } from '@/vault/VaultStore';const MainLayout: React.FC = () => {const navigate = useNavigate();const location = useLocation();- const { isInitialized, isLoggedIn } = useAuth();+ const { isInitialized, isLoggedIn, globalMessage } = useAuth();const { t } = useTranslation();const { dbInitialized, dbAvailable, syncError, clearSyncError } = useDb();const { syncVault } = useVaultSync();const [isReady, setIsReady] = useState(false);const hasSynced = useRef(false);+ useVaultLanguage(isReady);useEffect(() => {if (!isInitialized || !dbInitialized) {@@ -39,7 +41,8 @@ const MainLayout: React.FC = () => {const gate = async (): Promise<void> => {const status = await vaultStore.checkAuthStatus();if (!status.isLoggedIn || !isLoggedIn) {- navigate('/user/start', { replace: true });+ // A forced logout (session expired, revoked) leaves a message for the login page to show.+ navigate(globalMessage ? '/user/login' : '/user/start', { replace: true });return;}// Unlock continues via the sync page, which returns to this URL.@@ -51,7 +54,7 @@ const MainLayout: React.FC = () => {setIsReady(true);};void gate();- }, [isInitialized, isLoggedIn, dbInitialized, dbAvailable, navigate, location.pathname, location.search]);+ }, [isInitialized, isLoggedIn, globalMessage, dbInitialized, dbAvailable, navigate, location.pathname, location.search]);/*** Once the vault is open, check the server for a newer vault in the background (once per page load).diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsxindex 0374365ed..6ee6ea291 100644--- a/apps/web/src/main.tsx+++ b/apps/web/src/main.tsx@@ -14,6 +14,7 @@ import { NotificationProvider } from '@/context/NotificationContext';import { ThemeProvider } from '@/context/ThemeContext';import { WebApiProvider } from '@/context/WebApiContext';import { initI18n } from '@/i18n/i18n';+import { cleanUpLegacyStorage } from '@/utils/LegacyStorageCleanup';/*** Render the application.@@ -46,6 +47,7 @@ const renderApp = (): void => {* index.html stays up until the app has painted, and shows its error state when any of these fail.*/const bootstrap = async (): Promise<void> => {+ cleanUpLegacyStorage();await Promise.all([getPlatform().rustCore.init(),loadAppConfig().then(initI18n),diff --git a/apps/web/src/pages/auth/Unlock.tsx b/apps/web/src/pages/auth/Unlock.tsxindex f980617be..85cea460f 100644--- a/apps/web/src/pages/auth/Unlock.tsx+++ b/apps/web/src/pages/auth/Unlock.tsx@@ -1,3 +1,4 @@+import { ApiAuthError } from '@aliasvault/client/api/errors/ApiAuthError';import { extractErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';import { ClientUpgradeRequiredError } from '@aliasvault/client/api/errors/ClientUpgradeRequiredError';import { describeAuthError, formatErrorMessage } from '@aliasvault/client/auth/AuthErrorMessage';@@ -114,6 +115,10 @@ const Unlock: React.FC = () => {navigate('/user/login', { replace: true });return;}+ if (err instanceof ApiAuthError) {+ navigate('/user/login', { replace: true });+ return;+ }setErrors([t('auth.unlockPage.connectionFailedError')]);}@@ -177,6 +182,10 @@ const Unlock: React.FC = () => {navigate('/sync', { replace: true });} catch (err) {console.error('Unlock error:', err);+ if (err instanceof ApiAuthError) {+ navigate('/user/login', { replace: true });+ return;+ }const message = await describeAuthError(err, { fallback: 'auth.loginForm.loginErrorMessage' });if (import.meta.env.DEV && err instanceof Error && message.key === 'auth.loginForm.loginErrorMessage') {setErrors([err.message]);diff --git a/apps/web/src/pages/settings/Apps.tsx b/apps/web/src/pages/settings/Apps.tsxindex 24beadd47..ca3cb3cee 100644--- a/apps/web/src/pages/settings/Apps.tsx+++ b/apps/web/src/pages/settings/Apps.tsx@@ -14,7 +14,7 @@ const AppRow: React.FC<{ app: AppInfo; buttonText: string; comingSoonText: strin<div className="p-4 border rounded-lg dark:border-gray-700 flex justify-between items-center"><div className="flex items-center"><img src={app.iconPath} alt={app.name} className="w-8 h-8 mr-3" />- <h4 className="text-lg font-medium text-gray-900 dark:text-white">{app.name}</h4>+ <h4 className="text-base font-medium text-gray-900 dark:text-white">{app.name}</h4></div>{app.isAvailable ? (<a href={app.downloadUrl} target="_blank" rel="noreferrer" className="inline-flex items-center px-4 py-2 text-sm font-medium text-white bg-primary-600 rounded-lg hover:bg-primary-700 focus:ring-4 focus:ring-primary-200 dark:focus:ring-primary-900">@@ -42,7 +42,7 @@ const AppsSettings: React.FC = () => {<Card><div className="mb-6"><h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">{t('settings.apps.browserExtensionsTitle')}</h3>- <p className="text-gray-600 dark:text-gray-400">{t('settings.apps.browserExtensionsDescription')}</p>+ <p className="text-sm text-gray-600 dark:text-gray-400">{t('settings.apps.browserExtensionsDescription')}</p></div><div className="mb-8">@@ -53,7 +53,7 @@ const AppsSettings: React.FC = () => {<div className="mb-6"><h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">{t('settings.apps.mobileAppsTitle')}</h3>- <p className="text-gray-600 dark:text-gray-400 mb-4">{t('settings.apps.mobileAppsDescription')}</p>+ <p className="text-sm text-gray-600 dark:text-gray-400">{t('settings.apps.mobileAppsDescription')}</p></div><div className="grid grid-cols-1 lg:grid-cols-2 gap-4">diff --git a/apps/web/src/utils/LegacyStorageCleanup.ts b/apps/web/src/utils/LegacyStorageCleanup.tsnew file mode 100644index 000000000..c533e0a0b--- /dev/null+++ b/apps/web/src/utils/LegacyStorageCleanup.ts@@ -0,0 +1,62 @@+import { LANGUAGE_CODES } from '@/i18n/config';+import { getLocalPreference, removeLocalPreference, setLocalPreference } from '@/utils/LocalPreferences';+import { LocalPreferenceKeys } from '@/utils/StorageKeys';++/**+ * localStorage keys only the previous (Blazor) web client wrote: its tokens, its cached key chain, debug keys and+ * its own language key. This app keeps its session in IndexedDB, so none of them is read any more.+ */+const LEGACY_ONLY_KEYS = [+ 'token',+ 'refreshToken',+ 'encryptedAccountKey',+ 'encryptedVek',+ 'accountPublicKey',+ 'encryptedAccountPrivateKey',+ 'encryptionKeyDerivationParams',+ 'debugSessionKeys',+ 'encryptionTestString',+ 'webAuthnCredentialDerivedKey',+ 'blazorCulture',+];++/**+ * The value of a key the previous client stored JSON-encoded ('"nl"'), or null when it is not a JSON string.+ */+function jsonStringValue(raw: string | null): string | null {+ if (raw === null || !raw.startsWith('"')) {+ return null;+ }+ try {+ const value: unknown = JSON.parse(raw);+ return typeof value === 'string' ? value : null;+ } catch {+ return null;+ }+}++/**+ * Remove what the previous web client left in localStorage on this origin, keeping the language it had chosen.+ * Safe to run on every start.+ * TODO: this file and calllers can be removed some time after 0.31.0 has been released, together with public/service-worker.js.+ */+export function cleanUpLegacyStorage(): void {+ /*+ * The previous client updated blazorCulture on every language change but its JSON-encoded AppLanguage only before+ * login, so blazorCulture is the more recent of the two.+ */+ const storedLanguage = getLocalPreference(LocalPreferenceKeys.APP_LANGUAGE);+ const legacyLanguage = getLocalPreference('blazorCulture') ?? jsonStringValue(storedLanguage);+ if (legacyLanguage !== null && LANGUAGE_CODES.includes(legacyLanguage)) {+ setLocalPreference(LocalPreferenceKeys.APP_LANGUAGE, legacyLanguage);+ } else if (jsonStringValue(storedLanguage) !== null) {+ removeLocalPreference(LocalPreferenceKeys.APP_LANGUAGE);+ }++ // The previous client stored the return URL JSON-encoded too, which this app would navigate to as a path.+ if (jsonStringValue(getLocalPreference(LocalPreferenceKeys.RETURN_URL)) !== null) {+ removeLocalPreference(LocalPreferenceKeys.RETURN_URL);+ }++ LEGACY_ONLY_KEYS.forEach(removeLocalPreference);+}diff --git a/apps/web/tests/e2e/06-settings.spec.ts b/apps/web/tests/e2e/06-settings.spec.tsnew file mode 100644index 000000000..072bb76ab--- /dev/null+++ b/apps/web/tests/e2e/06-settings.spec.ts@@ -0,0 +1,42 @@+/**+ * Category 6: Settings (requires API)+ */+import { test, expect } from '../fixtures';++import type { Locator } from '@playwright/test';++test.describe('6. Settings', () => {+ test('6.1 should keep the app language in the vault', async ({ app, testUser }) => {+ const { page } = app;+ /**+ * The Emails link of the top menu, by its translated name.+ */+ const emailsLink = (name: string): Locator => page.getByRole('link', { name, exact: true }).first();+ await app.login(testUser.username, testUser.password);++ await test.step('switch to Dutch', async () => {+ await page.locator('#toggleMobileMenuButton').click();+ await page.locator('#mobileMenuDropdown').getByRole('link', { name: 'General settings' }).click();+ await page.locator('#appLanguage').selectOption('nl');+ await expect(emailsLink('E-mails')).toBeVisible();+ });++ await test.step('a reload keeps Dutch', async () => {+ await page.reload();+ await expect(page).toHaveURL(/\/unlock$/);+ await expect(page.getByRole('button', { name: 'Ontgrendelen' })).toBeVisible();+ await page.locator('#password').fill(testUser.password);+ await page.getByRole('button', { name: 'Ontgrendelen' }).click();+ await expect(page).toHaveURL(/\/settings\/general$/);+ await expect(emailsLink('E-mails')).toBeVisible();+ });++ await test.step('a browser without local preferences takes the language from the vault', async () => {+ await page.goto('/user/logout');+ await expect(page).toHaveURL(/\/user\/start$/);+ await page.evaluate(() => localStorage.clear());+ await app.login(testUser.username, testUser.password);+ await expect(emailsLink('E-mails')).toBeVisible();+ });+ });+});diff --git a/core/client/src/items/ItemFilters.ts b/core/client/src/items/ItemFilters.tsindex 6677f8e0b..7f8c76a36 100644--- a/core/client/src/items/ItemFilters.ts+++ b/core/client/src/items/ItemFilters.ts@@ -1,6 +1,6 @@-import { ItemTypes } from '@aliasvault/models/vault';+import { FieldTypes, ItemTypes } from '@aliasvault/models/vault';-import type { Item, ItemType } from '@aliasvault/models/vault';+import type { Item, ItemField, ItemType } from '@aliasvault/models/vault';/*** Filters for the items list: feature filters plus one per item type. The values appear as-is in route params.@@ -74,11 +74,17 @@ export function applyTypeFilter<T extends FilterableItem>(items: T[], filterType});}+/**+ * Whether a field holds a secret (password, card number, CVV, PIN, hidden custom field) whose value search skips.+ */+const isSecretField = (field: ItemField): boolean => field.IsHidden || field.FieldType === FieldTypes.Password || field.FieldType === FieldTypes.Hidden;+/*** Apply the free-text search filter to a list of items.* Splits the term into words and keeps items where every word appears in the name,- * a field value or a field label. Shared with the current-site suggestion so the- * suggested match count always equals what the search field itself returns.+ * a field value or a field label. Secret field values are never searched, so typing part+ * of a password cannot reveal which items hold it. Shared with the current-site suggestion+ * so the suggested match count always equals what the search field itself returns.*/export function applySearchFilter(items: Item[], searchTerm: string): Item[] {const searchWords = searchTerm.toLowerCase().trim().split(/\s+/).filter(word => word.length > 0);@@ -93,8 +99,10 @@ export function applySearchFilter(items: Item[], searchTerm: string): Item[] {];item.Fields?.forEach(field => {- const value = Array.isArray(field.Value) ? field.Value.join(' ') : (field.Value ?? '');- searchableFields.push(value.toLowerCase());+ if (!isSecretField(field)) {+ const value = Array.isArray(field.Value) ? field.Value.join(' ') : (field.Value ?? '');+ searchableFields.push(value.toLowerCase());+ }searchableFields.push(field.Label?.toLowerCase() ?? '');});diff --git a/core/i18n/locales/en.json b/core/i18n/locales/en.jsonindex 300f1c53f..105aab90b 100644--- a/core/i18n/locales/en.json+++ b/core/i18n/locales/en.json@@ -14,6 +14,7 @@"PUBLIC_REGISTRATION_DISABLED": "New account registration is currently disabled on this server. Please contact the administrator.","REFRESH_TOKEN_REQUIRED": "Refresh token is required.","REGISTRATION_FAILED": "Could not create the account. Please try again in a few minutes. If this problem persists, please contact support.",+ "UNKNOWN_ERROR": "An unknown error occurred. Please try again.","USERNAME_ALREADY_IN_USE": "Username is already in use.","USERNAME_AVAILABLE": "Username is available.","USERNAME_EMPTY_OR_WHITESPACE": "Username cannot be empty or whitespace.",diff --git a/core/rust/src/vault_sync/email_routing.rs b/core/rust/src/vault_sync/email_routing.rsindex 8ec4a5a81..aa34f4228 100644--- a/core/rust/src/vault_sync/email_routing.rs+++ b/core/rust/src/vault_sync/email_routing.rs@@ -39,7 +39,7 @@ pub(crate) fn build_email_routing(manifests: &[Manifest], private_email_domains:Some((_, domain)) if !domain.is_empty() => domain.to_string(),_ => continue,};- if !private_email_domains.iter().any(|candidate| *candidate == domain) {+ if !private_email_domains.iter().any(|candidate| candidate.trim().eq_ignore_ascii_case(&domain)) {continue;}