Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Refactor AppContext usages to AuthContext (#2413)

Leendert de Borst938d5dd935ad
diff --git a/apps/web/src/components/auth/setup/SetupSteps.tsx b/apps/web/src/components/auth/setup/SetupSteps.tsx
index 9c6d5a02a..de6a70152 100644
--- a/apps/web/src/components/auth/setup/SetupSteps.tsx
+++ b/apps/web/src/components/auth/setup/SetupSteps.tsx
@@ -7,7 +7,7 @@ import GlobalNotificationDisplay from '@/components/alerts/GlobalNotificationDis
import PasswordInputField from '@/components/auth/PasswordInputField';
import EditFormRow from '@/components/forms/EditFormRow';
import PasswordStrengthIndicator from '@/components/shared/PasswordStrengthIndicator';
-import { useApp } from '@/context/AppContext';
+import { useAuth } from '@/context/AuthContext';
import { useNotifications } from '@/context/NotificationContext';
import { useWebApi } from '@/context/WebApiContext';
import { RegistrationService } from '@/services/RegistrationService';
@@ -272,7 +272,7 @@ export const PasswordStep: React.FC<{ onPasswordChange: (password: string) => vo
*/
export const CreatingStep: React.FC<{ username: string; password: string; onDone: () => void }> = ({ username, password, onDone }) => {
const { t } = useTranslation();
- const app = useApp();
+ const auth = useAuth();
const webApi = useWebApi();
const notifications = useNotifications();
const [isLoading, setIsLoading] = useState(true);
@@ -289,7 +289,7 @@ export const CreatingStep: React.FC<{ username: string; password: string; onDone
*/
const completeSetup = async (): Promise<void> => {
try {
- await RegistrationService.register(webApi, username, password, app.setAuthTokens);
+ await RegistrationService.register(webApi, username, password, auth.setAuthTokens);
onDone();
} catch (error) {
console.error('Registration failed:', error);
@@ -298,7 +298,7 @@ export const CreatingStep: React.FC<{ username: string; password: string; onDone
}
};
void completeSetup();
- }, [app.setAuthTokens, notifications, onDone, password, t, username, webApi]);
+ }, [auth.setAuthTokens, notifications, onDone, password, t, username, webApi]);
return (
<div className="w-full mx-auto">
diff --git a/apps/web/src/components/forms/EmailDomainField.tsx b/apps/web/src/components/forms/EmailDomainField.tsx
index 1b972f385..8e9549624 100644
--- a/apps/web/src/components/forms/EmailDomainField.tsx
+++ b/apps/web/src/components/forms/EmailDomainField.tsx
@@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next';
import { getAppConfig } from '@/config/AppConfig';
import { useDb } from '@/context/DbContext';
+import { vaultStore } from '@/vault/VaultStore';
type EmailDomainFieldProps = {
id: string;
@@ -21,7 +22,7 @@ type EmailDomainFieldProps = {
*/
const EmailDomainField: React.FC<EmailDomainFieldProps> = ({ id, value, onChange, error = null, required = false, onRemove, defaultToEmailMode = false, onGenerateAlias }) => {
const { t } = useTranslation();
- const dbContext = useDb();
+ const { sqliteClient } = useDb();
const [privateDomains, setPrivateDomains] = useState<string[]>([]);
const [publicDomains, setPublicDomains] = useState<string[]>([]);
const [hiddenPrivateDomains, setHiddenPrivateDomains] = useState<string[]>([]);
@@ -37,7 +38,7 @@ const EmailDomainField: React.FC<EmailDomainFieldProps> = ({ id, value, onChange
useEffect(() => {
let cancelled = false;
- void dbContext.getVaultMetadata().then((metadata) => {
+ void vaultStore.getVaultMetadata().then((metadata) => {
if (cancelled) {
return;
}
@@ -49,7 +50,7 @@ const EmailDomainField: React.FC<EmailDomainFieldProps> = ({ id, value, onChange
return (): void => {
cancelled = true;
};
- }, [dbContext]);
+ }, [sqliteClient]);
/*
* Derive the local part, domain and mode from the value. After a toggle the user's mode choice is kept; on load
diff --git a/apps/web/src/components/layout/CreateNewIdentityWidget.tsx b/apps/web/src/components/layout/CreateNewIdentityWidget.tsx
index ebed7c7c5..4079876da 100644
--- a/apps/web/src/components/layout/CreateNewIdentityWidget.tsx
+++ b/apps/web/src/components/layout/CreateNewIdentityWidget.tsx
@@ -6,11 +6,12 @@ import { useLocation, useNavigate } from 'react-router-dom';
import { useDb } from '@/context/DbContext';
import { useLoading } from '@/context/LoadingContext';
import { useNotifications } from '@/context/NotificationContext';
+import { useWebApi } from '@/context/WebApiContext';
import { useClickOutside } from '@/hooks/useClickOutside';
-import { useIdentityGenerator } from '@/hooks/useIdentityGenerator';
import { useKeyboardShortcut } from '@/hooks/useKeyboardShortcut';
import { useSaveItem } from '@/hooks/useSaveItem';
import { createNewItemEdit, type ItemEdit, setFieldValue } from '@/models/ItemEdit';
+import { generateIdentity } from '@/utils/IdentityGenerator';
import { itemRoute } from '@/utils/ItemRoute';
import type { FolderRef } from '@aliasvault/client/database/repositories/FolderRepository';
@@ -39,7 +40,7 @@ const CreateNewIdentityWidget: React.FC = () => {
const dbContext = useDb();
const { showLoading, hideLoading } = useLoading();
const notifications = useNotifications();
- const { generateIdentity } = useIdentityGenerator();
+ const webApi = useWebApi();
const { saveItem } = useSaveItem();
const [isCreating, setIsCreating] = useState(false);
const [isPopupVisible, setIsPopupVisible] = useState(false);
@@ -97,7 +98,7 @@ const CreateNewIdentityWidget: React.FC = () => {
if (serviceUrl !== DEFAULT_SERVICE_URL) {
edit = setFieldValue(edit, 'login.url', serviceUrl);
}
- const identity = await generateIdentity();
+ const identity = dbContext.sqliteClient ? await generateIdentity(dbContext.sqliteClient, webApi) : null;
if (identity) {
edit = setFieldValue(edit, 'login.username', identity.username);
edit = setFieldValue(edit, 'login.password', identity.password);
diff --git a/apps/web/src/components/layout/TopMenu.tsx b/apps/web/src/components/layout/TopMenu.tsx
index d6c8b4242..fe74ddb49 100644
--- a/apps/web/src/components/layout/TopMenu.tsx
+++ b/apps/web/src/components/layout/TopMenu.tsx
@@ -6,7 +6,7 @@ import CreateNewIdentityWidget from '@/components/layout/CreateNewIdentityWidget
import DbLockButton from '@/components/layout/DbLockButton';
import DbStatusIndicator from '@/components/layout/DbStatusIndicator';
import SearchWidget from '@/components/layout/SearchWidget';
-import { useApp } from '@/context/AppContext';
+import { useAuth } from '@/context/AuthContext';
import { useTheme } from '@/context/ThemeContext';
import { useClickOutside } from '@/hooks/useClickOutside';
@@ -26,7 +26,7 @@ const DROPDOWN_LINK = 'block py-2 px-4 text-sm hover:bg-gray-100 dark:hover:bg-g
const TopMenu: React.FC = () => {
const { t } = useTranslation();
const location = useLocation();
- const { username } = useApp();
+ const { username } = useAuth();
const { isDarkMode, toggleTheme } = useTheme();
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
const menuRef = useRef<HTMLDivElement>(null);
diff --git a/apps/web/src/components/settings/security/QuickVaultUnlockSection.tsx b/apps/web/src/components/settings/security/QuickVaultUnlockSection.tsx
index 7399afd58..ea940b4b3 100644
--- a/apps/web/src/components/settings/security/QuickVaultUnlockSection.tsx
+++ b/apps/web/src/components/settings/security/QuickVaultUnlockSection.tsx
@@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next';
import LoadingIndicator from '@/components/loading/LoadingIndicator';
import SecuritySection, { type SectionHandle } from '@/components/settings/security/SecuritySection';
import Button from '@/components/shared/Button';
-import { useApp } from '@/context/AppContext';
+import { useAuth } from '@/context/AuthContext';
import { useNotifications } from '@/context/NotificationContext';
import { WebAuthnNotSupportedError, WebAuthnService } from '@/utils/WebAuthnService';
@@ -14,7 +14,7 @@ import { WebAuthnNotSupportedError, WebAuthnService } from '@/utils/WebAuthnServ
*/
const QuickVaultUnlockSection = forwardRef<SectionHandle>((_, ref) => {
const { t } = useTranslation();
- const app = useApp();
+ const auth = useAuth();
const notifications = useNotifications();
const [isLoading, setIsLoading] = useState(true);
const [enabled, setEnabled] = useState(false);
@@ -33,7 +33,7 @@ const QuickVaultUnlockSection = forwardRef<SectionHandle>((_, ref) => {
*/
const enable = async (): Promise<void> => {
try {
- await WebAuthnService.enable(app.username ?? '');
+ await WebAuthnService.enable(auth.username ?? '');
notifications.addSuccessMessage(t(`${tk}.SuccessEnabledMessage`), true);
} catch (error) {
if (error instanceof WebAuthnNotSupportedError) {
diff --git a/apps/web/src/components/shared/ConfirmModal.tsx b/apps/web/src/components/shared/ConfirmModal.tsx
index e583eae59..a3a367c49 100644
--- a/apps/web/src/components/shared/ConfirmModal.tsx
+++ b/apps/web/src/components/shared/ConfirmModal.tsx
@@ -4,7 +4,8 @@ type ConfirmModalProps = {
title: string;
message: string;
confirmText: string;
- cancelText: string;
+ /** Omit for a dialog that only informs. */
+ cancelText?: string;
onClose: (confirmed: boolean) => void;
};
@@ -30,9 +31,11 @@ const ConfirmModal: React.FC<ConfirmModalProps> = ({ title, message, confirmText
<button id="confirmButton" className="px-4 py-2 bg-primary-500 text-white text-base font-medium rounded-md w-full shadow-sm hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-primary-300" onClick={() => onClose(true)}>
{confirmText}
</button>
- <button id="cancelButton" className="mt-3 px-4 py-2 bg-gray-300 text-gray-800 text-base font-medium rounded-md w-full shadow-sm hover:bg-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-300" onClick={() => onClose(false)}>
- {cancelText}
- </button>
+ {cancelText && (
+ <button id="cancelButton" className="mt-3 px-4 py-2 bg-gray-300 text-gray-800 text-base font-medium rounded-md w-full shadow-sm hover:bg-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-300" onClick={() => onClose(false)}>
+ {cancelText}
+ </button>
+ )}
</div>
</div>
</div>
diff --git a/apps/web/src/context/AppContext.tsx b/apps/web/src/context/AppContext.tsx
deleted file mode 100644
index 48460cc65..000000000
--- a/apps/web/src/context/AppContext.tsx
+++ /dev/null
@@ -1,127 +0,0 @@
-import { logoutEventEmitter } from '@aliasvault/client/api/LogoutEventEmitter';
-import React, { createContext, useContext, useMemo, useCallback, useEffect, useState, useRef } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { useAuth } from '@/context/AuthContext';
-import { useDb } from '@/context/DbContext';
-import { useWebApi } from '@/context/WebApiContext';
-import { vaultStateEvents } from '@/events/VaultStateEvents';
-import { vaultStore } from '@/vault/VaultStore';
-
-type AppContextType = {
- isLoggedIn: boolean;
- isInitialized: boolean;
- username: string | null;
- logout: (errorMessage?: string) => Promise<void>;
- initializeAuth: () => Promise<boolean>;
- setAuthTokens: (username: string, accessToken: string, refreshToken: string) => Promise<void>;
- globalMessage: string | null;
- clearGlobalMessage: () => void;
-}
-
-const AppContext = createContext<AppContextType | undefined>(undefined);
-
-/**
- * AppProvider that coordinates between the auth, db and webApi contexts.
- */
-export const AppProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
- const auth = useAuth();
- const webApi = useWebApi();
- const { clearDatabase } = useDb();
- const [isLoggedIn, setIsLoggedIn] = useState(false);
- const isLoggingOutRef = useRef(false);
- const { t } = useTranslation();
-
- /**
- * Forced logout: revoke the tokens and clear the session. User-initiated logout goes through the logout page.
- */
- const logout = useCallback(async (errorMessage?: string): Promise<void> => {
- if (isLoggingOutRef.current) {
- return;
- }
-
- try {
- isLoggingOutRef.current = true;
- await webApi.revokeTokens();
- await auth.clearAuthForced(errorMessage);
- } catch (error) {
- console.error('Error during logout:', error);
- } finally {
- isLoggingOutRef.current = false;
- setIsLoggedIn(false);
- }
- }, [auth, webApi]);
-
- /**
- * Initialize the authentication state.
- * @returns Whether the user is logged in.
- */
- const initializeAuth = useCallback(async (): Promise<boolean> => {
- const loggedIn = await auth.initializeAuth();
- setIsLoggedIn(loggedIn);
- return loggedIn;
- }, [auth]);
-
- /**
- * Set auth tokens and update the logged in state.
- */
- const setAuthTokens = useCallback(async (username: string, accessToken: string, refreshToken: string): Promise<void> => {
- await auth.setAuthTokens(username, accessToken, refreshToken);
- setIsLoggedIn(true);
- }, [auth]);
-
- /**
- * Subscribe to logout events from the WebApiService.
- */
- useEffect(() => {
- return logoutEventEmitter.subscribe(async (errorKey: string) => {
- await logout(t(errorKey));
- });
- }, [logout, t]);
-
- /**
- * Check for tokens in storage on initial load.
- */
- useEffect(() => {
- initializeAuth();
- }, [initializeAuth]);
-
- /*
- * Reflect a logout from this tab or another one.
- */
- useEffect(() => {
- return vaultStateEvents.onLoggedOut(() => {
- clearDatabase();
- void vaultStore.lockVault();
- setIsLoggedIn(false);
- });
- }, [clearDatabase]);
-
- const contextValue = useMemo(() => ({
- isInitialized: auth.isInitialized,
- username: auth.username,
- globalMessage: auth.globalMessage,
- logout,
- initializeAuth,
- setAuthTokens,
- clearGlobalMessage: auth.clearGlobalMessage,
- isLoggedIn,
- }), [auth.isInitialized, auth.username, auth.globalMessage, auth.clearGlobalMessage, logout, initializeAuth, setAuthTokens, isLoggedIn]);
-
- return (
- <AppContext.Provider value={contextValue}>
- {children}
- </AppContext.Provider>
- );
-};
-
-/**
- * Hook to use the AppContext.
- */
-export const useApp = (): AppContextType => {
- const context = useContext(AppContext);
- if (context === undefined) {
- throw new Error('useApp must be used within an AppProvider');
- }
- return context;
-};
diff --git a/apps/web/src/context/AuthContext.tsx b/apps/web/src/context/AuthContext.tsx
new file mode 100644
index 000000000..ceca2bbd2
--- /dev/null
+++ b/apps/web/src/context/AuthContext.tsx
@@ -0,0 +1,181 @@
+import { logoutEventEmitter } from '@aliasvault/client/api/LogoutEventEmitter';
+import { getPlatform } from '@aliasvault/client/platform';
+import React, { createContext, useContext, useState, useMemo, useCallback, useEffect, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useDb } from '@/context/DbContext';
+import { useWebApi } from '@/context/WebApiContext';
+import { StorageKeys } from '@/utils/StorageKeys';
+import { vaultStore } from '@/vault/VaultStore';
+
+/**
+ * How a logout ends the session.
+ */
+type LogoutOptions = {
+ userInitiated?: boolean;
+ errorMessage?: string;
+};
+
+type AuthContextType = {
+ isInitialized: boolean;
+ isLoggedIn: boolean;
+ username: string | null;
+ initializeAuth: () => Promise<boolean>;
+ setAuthTokens: (username: string, accessToken: string, refreshToken: string) => Promise<void>;
+ logout: (options?: LogoutOptions) => Promise<void>;
+ globalMessage: string | null;
+ clearGlobalMessage: () => void;
+}
+
+const AuthContext = createContext<AuthContextType | undefined>(undefined);
+
+/**
+ * AuthProvider: the login state, the auth tokens and logout.
+ */
+export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
+ const { t } = useTranslation();
+ const webApi = useWebApi();
+ const { clearDatabase } = useDb();
+ const [isInitialized, setIsInitialized] = useState(false);
+ const [isLoggedIn, setIsLoggedIn] = useState(false);
+ const [username, setUsername] = useState<string | null>(null);
+ const [globalMessage, setGlobalMessage] = useState<string | null>(null);
+ const isLoggingOutRef = useRef(false);
+
+ /**
+ * Initialize the authentication state from the stored tokens.
+ * @returns Whether the user is logged in.
+ */
+ const initializeAuth = useCallback(async (): Promise<boolean> => {
+ const storage = getPlatform().storage;
+ const [accessToken, refreshToken, storedUsername] = await Promise.all([
+ storage.get<string>(StorageKeys.ACCESS_TOKEN),
+ storage.get<string>(StorageKeys.REFRESH_TOKEN),
+ storage.get<string>(StorageKeys.USERNAME),
+ ]);
+ const loggedIn = Boolean(accessToken && refreshToken && storedUsername);
+ if (loggedIn) {
+ setUsername(storedUsername);
+ }
+ setIsLoggedIn(loggedIn);
+ setIsInitialized(true);
+ return loggedIn;
+ }, []);
+
+ /**
+ * Store the auth tokens as part of the login process.
+ */
+ const setAuthTokens = useCallback(async (newUsername: string, accessToken: string, refreshToken: string): Promise<void> => {
+ await getPlatform().storage.setMany([
+ { key: StorageKeys.USERNAME, value: newUsername },
+ { key: StorageKeys.ACCESS_TOKEN, value: accessToken },
+ { key: StorageKeys.REFRESH_TOKEN, value: refreshToken },
+ ]);
+ setUsername(newUsername);
+ setIsLoggedIn(true);
+ }, []);
+
+ /**
+ * Drop this tab's in-memory session: the decrypted vault and the logged-in state.
+ */
+ const endSession = useCallback((): void => {
+ clearDatabase();
+ setIsLoggedIn(false);
+ }, [clearDatabase]);
+
+ /**
+ * Revoke the tokens and clear the tokens, session keys and vault. A forced logout (401, token revocation, password
+ * change) keeps the username so the login page can prefill it.
+ */
+ const logout = useCallback(async (options: LogoutOptions = {}): Promise<void> => {
+ if (isLoggingOutRef.current) {
+ return;
+ }
+
+ try {
+ isLoggingOutRef.current = true;
+ try {
+ await webApi.revokeTokens();
+ } catch (error) {
+ console.error('Error revoking tokens during logout:', error);
+ }
+ if (options.userInitiated) {
+ await vaultStore.clearVaultData();
+ setUsername(null);
+ }
+ await vaultStore.clearSession();
+ if (options.errorMessage) {
+ setGlobalMessage(options.errorMessage);
+ }
+ } catch (error) {
+ console.error('Error during logout:', error);
+ } finally {
+ endSession();
+ isLoggingOutRef.current = false;
+ }
+ }, [webApi, endSession]);
+
+ /**
+ * Clear the global message (called after displaying it).
+ */
+ const clearGlobalMessage = useCallback((): void => {
+ setGlobalMessage(null);
+ }, []);
+
+ /**
+ * Log out when the API reports the session is gone.
+ */
+ useEffect(() => {
+ return logoutEventEmitter.subscribe(async (errorKey: string) => {
+ await logout({ errorMessage: t(errorKey) });
+ });
+ }, [logout, t]);
+
+ /**
+ * Check for tokens in storage on initial load.
+ */
+ useEffect(() => {
+ void initializeAuth();
+ }, [initializeAuth]);
+
+ /*
+ * Reflect a logout from any tab: the access token is shared by every tab, but another tab cannot clear this tab's
+ * in-memory unlock key and decrypted vault, so drop them here too.
+ */
+ useEffect(() => {
+ return getPlatform().storage.watch<string | null>(StorageKeys.ACCESS_TOKEN, (newValue) => {
+ if (!newValue) {
+ endSession();
+ void vaultStore.lockVault();
+ }
+ });
+ }, [endSession]);
+
+ const contextValue = useMemo(() => ({
+ isInitialized,
+ isLoggedIn,
+ username,
+ initializeAuth,
+ setAuthTokens,
+ logout,
+ globalMessage,
+ clearGlobalMessage,
+ }), [isInitialized, isLoggedIn, username, initializeAuth, setAuthTokens, logout, globalMessage, clearGlobalMessage]);
+
+ return (
+ <AuthContext.Provider value={contextValue}>
+ {children}
+ </AuthContext.Provider>
+ );
+};
+
+/**
+ * Hook to use the AuthContext.
+ */
+export const useAuth = (): AuthContextType => {
+ const context = useContext(AuthContext);
+ if (context === undefined) {
+ throw new Error('useAuth must be used within an AuthProvider');
+ }
+ return context;
+};
diff --git a/apps/web/src/context/DbContext.tsx b/apps/web/src/context/DbContext.tsx
new file mode 100644
index 000000000..7d7b295eb
--- /dev/null
+++ b/apps/web/src/context/DbContext.tsx
@@ -0,0 +1,191 @@
+import { AppErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';
+import EncryptionUtility from '@aliasvault/client/crypto/EncryptionUtility';
+import SqliteClient from '@aliasvault/client/database/SqliteClient';
+import { getPlatform } from '@aliasvault/client/platform';
+import { syncErrorMessage, toSyncErrorDetail } from '@aliasvault/client/sync/SyncErrorMessage';
+import React, { createContext, useContext, useState, useEffect, useCallback, useMemo, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { StorageKeys } from '@/utils/StorageKeys';
+import { vaultStore } from '@/vault/VaultStore';
+
+import type { SyncErrorDetail } from '@aliasvault/client/sync/VaultSync';
+
+type DbContextType = {
+ sqliteClient: SqliteClient | null;
+ dbInitialized: boolean;
+ dbAvailable: boolean;
+ isOffline: boolean;
+ getIsOffline: () => boolean;
+ setIsOffline: (offline: boolean) => Promise<void>;
+ isSyncing: boolean;
+ isUploading: boolean;
+ loadStoredDatabase: () => Promise<SqliteClient | null>;
+ clearDatabase: () => void;
+ /** Last background sync error, translated in the current display language. Null when no error is pending. */
+ syncError: string | null;
+ /** Dismiss the current sync error. */
+ clearSyncError: () => Promise<void>;
+}
+
+const DbContext = createContext<DbContextType | undefined>(undefined);
+
+/**
+ * DbProvider: the decrypted vault and the sync state the UI shows.
+ */
+export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
+ const { t } = useTranslation();
+ const [sqliteClient, setSqliteClient] = useState<SqliteClient | null>(null);
+ const [dbInitialized, setDbInitialized] = useState(false);
+ const [dbAvailable, setDbAvailable] = useState(false);
+ const [isOffline, setIsOfflineState] = useState(false);
+ const isOfflineRef = useRef(false);
+ const [isSyncing, setIsSyncing] = useState(false);
+ const [isUploading, setIsUploading] = useState(false);
+ const [syncErrorDetail, setSyncErrorDetail] = useState<SyncErrorDetail | null>(null);
+
+ const syncError = useMemo(() => syncErrorDetail ? syncErrorMessage(syncErrorDetail, t) ?? null : null, [syncErrorDetail, t]);
+
+ /**
+ * Set the offline mode state and persist it.
+ */
+ const setIsOffline = useCallback(async (offline: boolean) => {
+ isOfflineRef.current = offline;
+ setIsOfflineState(offline);
+ await getPlatform().storage.set(StorageKeys.IS_OFFLINE_MODE, offline);
+ }, []);
+
+ /**
+ * Load the offline mode and the last sync error from storage.
+ */
+ useEffect(() => {
+ /**
+ * Load the persisted state.
+ */
+ const loadSyncState = async (): Promise<void> => {
+ const storage = getPlatform().storage;
+ const [offlineMode, lastError] = await Promise.all([storage.get<boolean>(StorageKeys.IS_OFFLINE_MODE), storage.get(StorageKeys.LAST_SYNC_ERROR)]);
+ isOfflineRef.current = offlineMode ?? false;
+ setIsOfflineState(offlineMode ?? false);
+ setSyncErrorDetail(toSyncErrorDetail(lastError));
+ };
+ void loadSyncState();
+ }, []);
+
+ /**
+ * Reflect the sync error every sync persists (see VaultStore.fullVaultSync), whoever started it.
+ */
+ useEffect(() => {
+ return getPlatform().storage.watch(StorageKeys.LAST_SYNC_ERROR, (newValue) => {
+ setSyncErrorDetail(toSyncErrorDetail(newValue));
+ });
+ }, []);
+
+ /**
+ * Drive the sync/upload indicators from the sync itself.
+ */
+ useEffect(() => {
+ return vaultStore.onSyncPhase((phase) => {
+ setIsSyncing(phase === 'pull');
+ setIsUploading(phase === 'push');
+ });
+ }, []);
+
+ /**
+ * Dismiss the current sync error.
+ */
+ const clearSyncError = useCallback(async (): Promise<void> => {
+ setSyncErrorDetail(null);
+ await getPlatform().storage.remove(StorageKeys.LAST_SYNC_ERROR);
+ }, []);
+
+ /**
+ * Load the stored (encrypted) vault into memory.
+ * @throws When the vault cannot be opened (all errors carry an E-XXX code).
+ */
+ const loadStoredDatabase = useCallback(async (): Promise<SqliteClient | null> => {
+ try {
+ const response = await vaultStore.getVault();
+ if (!response.success && response.error) {
+ throw new Error(response.error);
+ }
+
+ if (response.vault) {
+ const client = new SqliteClient();
+ await client.initializeFromBytes(response.vault);
+ setSqliteClient(client);
+ setDbInitialized(true);
+ setDbAvailable(true);
+ return client;
+ }
+
+ setDbInitialized(true);
+ setDbAvailable(false);
+ return null;
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ if (!message.includes(AppErrorCode.VAULT_LOCKED) && !message.includes(AppErrorCode.VAULT_NOT_FOUND)) {
+ console.error('Error opening the stored vault:', error);
+ }
+ setDbInitialized(true);
+ setDbAvailable(false);
+ throw error;
+ }
+ }, []);
+
+ /**
+ * Try to open the stored vault once on mount.
+ */
+ useEffect((): void => {
+ if (!dbInitialized) {
+ loadStoredDatabase().catch(() => { });
+ }
+ }, [dbInitialized, loadStoredDatabase]);
+
+ /**
+ * Drop the in-memory database, called when logging out or locking.
+ */
+ const clearDatabase = useCallback((): void => {
+ EncryptionUtility.clearRsaPrivateKeyCache();
+ setSqliteClient(null);
+ setDbInitialized(false);
+ setDbAvailable(false);
+ }, []);
+
+ /**
+ * Get offline state.
+ */
+ const getIsOffline = useCallback(() => isOfflineRef.current, []);
+
+ const contextValue = useMemo(() => ({
+ sqliteClient,
+ dbInitialized,
+ dbAvailable,
+ isOffline,
+ getIsOffline,
+ setIsOffline,
+ isSyncing,
+ isUploading,
+ loadStoredDatabase,
+ clearDatabase,
+ syncError,
+ clearSyncError,
+ }), [sqliteClient, dbInitialized, dbAvailable, isOffline, getIsOffline, setIsOffline, isSyncing, isUploading, loadStoredDatabase, clearDatabase, syncError, clearSyncError]);
+
+ return (
+ <DbContext.Provider value={contextValue}>
+ {children}
+ </DbContext.Provider>
+ );
+};
+
+/**
+ * Hook to use the DbContext.
+ */
+export const useDb = (): DbContextType => {
+ const context = useContext(DbContext);
+ if (context === undefined) {
+ throw new Error('useDb must be used within a DbProvider');
+ }
+ return context;
+};
diff --git a/apps/web/src/events/VaultStateEvents.ts b/apps/web/src/events/VaultStateEvents.ts
deleted file mode 100644
index 95d4e936d..000000000
--- a/apps/web/src/events/VaultStateEvents.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { getPlatform } from '@aliasvault/client/platform';
-
-import { StorageKeys } from '@/utils/StorageKeys';
-
-type Unsubscribe = () => void;
-type Listener = () => void;
-
-/**
- * Vault state events. The access token is stored for every tab, so a logout reaches all open tabs.
- */
-export const vaultStateEvents = {
- /** Fires when the user is logged out in any tab. */
- onLoggedOut(listener: Listener): Unsubscribe {
- return getPlatform().storage.watch<string | null>(StorageKeys.ACCESS_TOKEN, (newValue) => {
- if (!newValue) {
- listener();
- }
- });
- },
-};
diff --git a/apps/web/src/hooks/useEmailDomains.ts b/apps/web/src/hooks/useEmailDomains.ts
index e23f4e59c..6fdd6348b 100644
--- a/apps/web/src/hooks/useEmailDomains.ts
+++ b/apps/web/src/hooks/useEmailDomains.ts
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useDb } from '@/context/DbContext';
+import { vaultStore } from '@/vault/VaultStore';
/**
* Domain checks: which addresses AliasVault or SpamOK can receive mail for.
@@ -25,14 +26,14 @@ const endsWithDomain = (email: string, domains: string[]): boolean => {
* The email domains this instance serves, from the vault metadata the sync recorded.
*/
export function useEmailDomains(): EmailDomainChecks {
- const dbContext = useDb();
+ const { sqliteClient } = useDb();
const [publicDomains, setPublicDomains] = useState<string[]>([]);
const [privateDomains, setPrivateDomains] = useState<string[]>([]);
const [isLoaded, setIsLoaded] = useState(false);
useEffect(() => {
let cancelled = false;
- void dbContext.getVaultMetadata().then((metadata) => {
+ void vaultStore.getVaultMetadata().then((metadata) => {
if (cancelled) {
return;
}
@@ -43,7 +44,7 @@ export function useEmailDomains(): EmailDomainChecks {
return (): void => {
cancelled = true;
};
- }, [dbContext]);
+ }, [sqliteClient]);
const isSpamOkDomain = useCallback((email: string): boolean => endsWithDomain(email, publicDomains), [publicDomains]);
const isAliasVaultDomain = useCallback((email: string): boolean => endsWithDomain(email, privateDomains), [privateDomains]);
diff --git a/apps/web/src/hooks/useVaultMutate.ts b/apps/web/src/hooks/useVaultMutate.ts
new file mode 100644
index 000000000..4e14c148d
--- /dev/null
+++ b/apps/web/src/hooks/useVaultMutate.ts
@@ -0,0 +1,71 @@
+import { encryptVaultBlob } from '@aliasvault/client/crypto/VaultBlob';
+import { hasSyncError } from '@aliasvault/client/sync/VaultSync';
+import { useCallback } from 'react';
+
+import { useDb } from '@/context/DbContext';
+import { devLog } from '@/utils/DevLogger';
+import { vaultStore } from '@/vault/VaultStore';
+
+/**
+ * Hook to execute a vault mutation.
+ *
+ * Flow:
+ * 1. Execute the mutation on the in-memory database
+ * 2. Save the encrypted vault locally and mark it dirty (bumps the mutation sequence)
+ * 3. Trigger a sync which handles upload, merge if needed and offline mode; the sync drives the upload indicator
+ */
+export function useVaultMutate(): { executeVaultMutationAsync: (operation: () => Promise<void>) => Promise<void>; } {
+ const dbContext = useDb();
+
+ /**
+ * Execute the operation and save the result locally, marking the vault dirty with the scopes it wrote into.
+ */
+ const saveLocally = useCallback(async (operation: () => Promise<void>): Promise<void> => {
+ await operation();
+
+ const sqliteClient = dbContext.sqliteClient;
+ if (!sqliteClient) {
+ throw new Error('Vault is locked');
+ }
+ const scopes = sqliteClient.takeMutationScopes();
+
+ try {
+ const encryptionKey = await vaultStore.getEncryptionKey();
+ if (!encryptionKey) {
+ throw new Error('Vault is locked');
+ }
+ const encryptedVaultBlob = await encryptVaultBlob(sqliteClient.exportToBytes(), encryptionKey);
+ await vaultStore.storeEncryptedVault({ vaultBlob: encryptedVaultBlob, markDirty: true, scopes });
+ } catch (error) {
+ // The write is still in the local database, so put the scopes back for whichever store carries it next.
+ scopes.forEach(scope => sqliteClient.recordMutationScope(scope));
+ throw error;
+ }
+ }, [dbContext]);
+
+ /**
+ * Trigger the sync that pushes the mutation.
+ */
+ const triggerSync = useCallback((): void => {
+ vaultStore.fullVaultSync().then(async (result) => {
+ if (hasSyncError(result)) {
+ devLog('[VaultMutate] Sync after mutation reported an error', result);
+ }
+ if (result.hasNewVault) {
+ await dbContext.loadStoredDatabase();
+ }
+ }).catch((error) => {
+ console.error('[VaultMutate] Sync after mutation failed:', error);
+ });
+ }, [dbContext]);
+
+ /**
+ * Execute a vault mutation: apply it locally, persist it, and sync it to the server.
+ */
+ const executeVaultMutationAsync = useCallback(async (operation: () => Promise<void>): Promise<void> => {
+ await saveLocally(operation);
+ triggerSync();
+ }, [saveLocally, triggerSync]);
+
+ return { executeVaultMutationAsync };
+}
diff --git a/apps/web/src/hooks/useVaultSync.ts b/apps/web/src/hooks/useVaultSync.ts
new file mode 100644
index 000000000..5bf9c21ba
--- /dev/null
+++ b/apps/web/src/hooks/useVaultSync.ts
@@ -0,0 +1,88 @@
+import { syncErrorMessage } from '@aliasvault/client/sync/SyncErrorMessage';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useAuth } from '@/context/AuthContext';
+import { useDb } from '@/context/DbContext';
+import { vaultStore } from '@/vault/VaultStore';
+
+type VaultSyncOptions = {
+ onSuccess?: (hasNewVault: boolean) => void;
+ onError?: (error: string) => void;
+ onOffline?: () => void;
+ onLegacySqliteBlobUpgradeRequired?: () => void;
+ onManifestMigrationRequired?: () => void;
+}
+
+/**
+ * Hook to sync the vault with the server.
+ *
+ * Sync logic (handled by the Rust sync engine):
+ * - If server has newer vault AND we have local changes (isDirty): merge then upload
+ * - If server has newer vault AND no local changes: just download
+ * - If server has same revision AND we have local changes: upload
+ * - If offline: keep local changes, sync later
+ */
+export const useVaultSync = (): { syncVault: (options?: VaultSyncOptions) => Promise<boolean>; } => {
+ const { t } = useTranslation();
+ const auth = useAuth();
+ const dbContext = useDb();
+
+ const syncVault = useCallback(async (options: VaultSyncOptions = {}) => {
+ const { onSuccess, onError, onOffline, onLegacySqliteBlobUpgradeRequired, onManifestMigrationRequired } = options;
+
+ try {
+ const isLoggedIn = await auth.initializeAuth();
+ if (!isLoggedIn) {
+ return false;
+ }
+
+ const result = await vaultStore.fullVaultSync({});
+
+ if (result.requiresLogout) {
+ await auth.logout({ errorMessage: syncErrorMessage(result, t) });
+ return false;
+ }
+
+ if (result.wasOffline) {
+ await dbContext.setIsOffline(true);
+ onOffline?.();
+ onSuccess?.(false);
+ return true;
+ }
+
+ if (dbContext.isOffline) {
+ await dbContext.setIsOffline(false);
+ }
+
+ if (result.sqliteBlobUpgradeRequired) {
+ onLegacySqliteBlobUpgradeRequired?.();
+ return false;
+ }
+
+ if (result.manifestMigrationRequired) {
+ onManifestMigrationRequired?.();
+ return false;
+ }
+
+ if (!result.success) {
+ onError?.(syncErrorMessage(result, t) ?? t('common.errors.unknownError'));
+ return false;
+ }
+
+ if (result.hasNewVault) {
+ await dbContext.loadStoredDatabase();
+ }
+
+ onSuccess?.(result.hasNewVault);
+ return true;
+ } catch (err) {
+ const errorMessage = err instanceof Error ? err.message : 'Unknown error during vault sync';
+ console.error('Vault sync error:', err);
+ onError?.(errorMessage);
+ return false;
+ }
+ }, [auth, dbContext, t]);
+
+ return { syncVault };
+};
diff --git a/apps/web/src/layouts/MainLayout.tsx b/apps/web/src/layouts/MainLayout.tsx
index d3ee3706b..30b24171d 100644
--- a/apps/web/src/layouts/MainLayout.tsx
+++ b/apps/web/src/layouts/MainLayout.tsx
@@ -1,11 +1,13 @@
import React, { useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import GlobalNotificationDisplay from '@/components/alerts/GlobalNotificationDisplay';
import ClipboardCountdownBar from '@/components/layout/ClipboardCountdownBar';
import Footer from '@/components/layout/Footer';
import TopMenu from '@/components/layout/TopMenu';
-import { useApp } from '@/context/AppContext';
+import ConfirmModal from '@/components/shared/ConfirmModal';
+import { useAuth } from '@/context/AuthContext';
import { useDb } from '@/context/DbContext';
import { useVaultSync } from '@/hooks/useVaultSync';
import { setLocalPreference } from '@/utils/LocalPreferences';
@@ -19,8 +21,9 @@ import { vaultStore } from '@/vault/VaultStore';
const MainLayout: React.FC = () => {
const navigate = useNavigate();
const location = useLocation();
- const { isInitialized, isLoggedIn } = useApp();
- const { dbInitialized, dbAvailable } = useDb();
+ const { isInitialized, isLoggedIn } = useAuth();
+ const { t } = useTranslation();
+ const { dbInitialized, dbAvailable, syncError, clearSyncError } = useDb();
const { syncVault } = useVaultSync();
const [isReady, setIsReady] = useState(false);
const hasSynced = useRef(false);
@@ -71,7 +74,7 @@ const MainLayout: React.FC = () => {
*/
onManifestMigrationRequired: () => navigate('/sync', { replace: true }),
/**
- * A failed background sync is not fatal; the local vault stays usable.
+ * A failed background sync is not fatal; the local vault stays usable and the sync error dialog shows why.
*/
onError: (error) => console.error('Background vault sync error:', error),
});
@@ -94,6 +97,9 @@ const MainLayout: React.FC = () => {
</div>
</div>
<Footer />
+ {syncError && (
+ <ConfirmModal title={t('sharedResources.Error')} message={syncError} confirmText={t('sharedResources.Close')} onClose={() => void clearSyncError()} />
+ )}
</>
);
};
diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx
index 3b362d3d8..475ccf61b 100644
--- a/apps/web/src/main.tsx
+++ b/apps/web/src/main.tsx
@@ -4,7 +4,6 @@ import ReactDOM from 'react-dom/client';
import App from '@/App';
import { loadAppConfig } from '@/config/AppConfig';
-import { AppProvider } from '@/context/AppContext';
import { AuthProvider } from '@/context/AuthContext';
import { CapabilityProvider } from '@/context/CapabilityContext';
import { ConfirmModalProvider } from '@/context/ConfirmModalContext';
@@ -26,15 +25,13 @@ const renderApp = (): void => {
<DbProvider>
<WebApiProvider>
<AuthProvider>
- <AppProvider>
- <LoadingProvider>
- <ConfirmModalProvider>
- <CapabilityProvider>
- <App />
- </CapabilityProvider>
- </ConfirmModalProvider>
- </LoadingProvider>
- </AppProvider>
+ <LoadingProvider>
+ <ConfirmModalProvider>
+ <CapabilityProvider>
+ <App />
+ </CapabilityProvider>
+ </ConfirmModalProvider>
+ </LoadingProvider>
</AuthProvider>
</WebApiProvider>
</DbProvider>
diff --git a/apps/web/src/vault/VaultStore.ts b/apps/web/src/vault/VaultStore.ts
new file mode 100644
index 000000000..0d9551674
--- /dev/null
+++ b/apps/web/src/vault/VaultStore.ts
@@ -0,0 +1,435 @@
+/**
+ * The web app's vault store: the at-rest (encrypted) vault, the session key, and the interface with the Rust sync engine.
+ */
+
+import { AppErrorCode, formatErrorWithCode } from '@aliasvault/client/api/errors/AppErrorCodes';
+import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';
+import { decryptVaultBlob } from '@aliasvault/client/crypto/VaultBlob';
+import { SqliteClient } from '@aliasvault/client/database/SqliteClient';
+import { getPlatform } from '@aliasvault/client/platform';
+import { clearDirtyScopes, getDirtyScopes } from '@aliasvault/client/sync/VaultDirtyState';
+import { vaultRequiresManifestMigration, VaultMigrationKind } from '@aliasvault/client/sync/VaultManifestMigration';
+import { DEFAULT_VAULT_MUTATION_SCOPE, hasUserVisibleScope, type VaultMutationScope } from '@aliasvault/client/sync/VaultMutationScope';
+import { hasSyncError, syncResult, VaultSync, type FullVaultSyncResult, type VaultManifestMigrationResult } from '@aliasvault/client/sync/VaultSync';
+import { type IVaultSyncEngineHost, type VaultSyncOptions, type VaultSyncPhase as EngineSyncPhase, type VaultSyncStoreOutcome, type VaultSyncStoreRequest } from '@aliasvault/client/sync/VaultSyncEngine';
+import { getVaultSyncHoldReason } from '@aliasvault/client/sync/VaultSyncHold';
+
+import i18n from '@/i18n/i18n';
+import { devLog } from '@/utils/DevLogger';
+import { AUTH_STORAGE_KEYS, dirtyScopeStorageKey, SESSION_STORAGE_KEYS, StorageKeys, vaultDataStorageKeys, VAULT_LOCK_STORAGE_KEYS } from '@/utils/StorageKeys';
+
+import type { ISqliteDatabase, SqliteValue } from '@aliasvault/client/platform';
+import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';
+
+/** What a running sync is doing, or idle. */
+export type VaultSyncPhase = 'pull' | 'push' | 'idle';
+
+/** The decrypted vault, or why it could not be opened. */
+export type VaultResponse = {
+ success: boolean;
+ error?: string;
+ vault?: Uint8Array;
+};
+
+/** The email domain lists the server published on the last sync. */
+export type VaultMetadata = {
+ publicEmailDomains: string[];
+ privateEmailDomains: string[];
+ hiddenPrivateEmailDomains: string[];
+};
+
+/** What a full sync may be asked beyond what the revisions decide. */
+export type FullVaultSyncRequest = VaultSyncOptions & {
+ /** Persist a failure so the UI shows it (default true). A login-time pull reports its own errors. */
+ reportErrorToPopup?: boolean;
+};
+
+let cachedSqliteClient: SqliteClient | null = null;
+let cachedVaultBlob: string | null = null;
+let isSyncInProgress = false;
+let hasPendingSync = false;
+
+const phaseListeners = new Set<(phase: VaultSyncPhase) => void>();
+
+/**
+ * Tell the UI what the sync is doing.
+ * @param phase - the phase
+ */
+function broadcastSyncPhase(phase: VaultSyncPhase): void {
+ phaseListeners.forEach(listener => listener(phase));
+}
+
+/**
+ * Drop the cached decrypted vault.
+ */
+function cleanupCachedSqliteClient(): void {
+ cachedSqliteClient?.close();
+ cachedSqliteClient = null;
+ cachedVaultBlob = null;
+}
+
+/**
+ * The session vault key, derived from the session unlock key and the cached key chain, or null while locked.
+ */
+async function getEncryptionKey(): Promise<string | null> {
+ return VaultKeyService.getSessionVaultEncryptionKey();
+}
+
+/**
+ * The stored encrypted vault blob.
+ */
+async function getEncryptedVault(): Promise<string | null> {
+ return getPlatform().storage.get<string>(StorageKeys.ENCRYPTED_VAULT);
+}
+
+/**
+ * Open the stored vault for the sync engine.
+ * @throws When the vault is missing or locked.
+ */
+async function createVaultSqliteClient(): Promise<SqliteClient> {
+ const encryptedVault = await getEncryptedVault();
+ const encryptionKey = await getEncryptionKey();
+ if (!encryptedVault) {
+ throw new Error(formatErrorWithCode(i18n.t('common.errors.vaultNotAvailable'), AppErrorCode.VAULT_NOT_FOUND));
+ }
+ if (!encryptionKey) {
+ throw new Error(formatErrorWithCode(i18n.t('common.errors.vaultIsLocked'), AppErrorCode.VAULT_LOCKED));
+ }
+
+ if (cachedSqliteClient && cachedVaultBlob === encryptedVault) {
+ return cachedSqliteClient;
+ }
+
+ const decryptedVault = await decryptVaultBlob(encryptedVault, encryptionKey);
+ const sqliteClient = new SqliteClient();
+ await sqliteClient.initializeFromBytes(decryptedVault);
+
+ cachedSqliteClient = sqliteClient;
+ cachedVaultBlob = encryptedVault;
+ return sqliteClient;
+}
+
+/**
+ * Store the encrypted vault blob.
+ *
+ * Two modes: a local mutation (markDirty) always succeeds and bumps the mutation sequence; a sync store
+ * (expectedMutationSeq) only succeeds when no mutation happened since the sync started, so a sync never
+ * overwrites concurrent local changes.
+ * @param request - the blob and how to record it
+ */
+async function storeEncryptedVault(request: { vaultBlob: string; markDirty?: boolean; expectedMutationSeq?: number; scopes?: VaultMutationScope[] }): Promise<{ success: boolean; mutationSequence: number }> {
+ const storage = getPlatform().storage;
+ let mutationSequence = await storage.get<number>(StorageKeys.MUTATION_SEQUENCE) ?? 0;
+
+ if (request.expectedMutationSeq !== undefined && request.expectedMutationSeq !== mutationSequence) {
+ return { success: false, mutationSequence };
+ }
+
+ if (request.markDirty) {
+ mutationSequence++;
+ // A store that names no scope changed something the repositories do not account for, so it pushes the full manifest.
+ const dirtyScopes = request.scopes?.length ? request.scopes : [DEFAULT_VAULT_MUTATION_SCOPE];
+ await storage.setMany([
+ { key: StorageKeys.ENCRYPTED_VAULT, value: request.vaultBlob },
+ { key: StorageKeys.MUTATION_SEQUENCE, value: mutationSequence },
+ { key: StorageKeys.IS_DIRTY, value: true },
+ ...dirtyScopes.map(scope => ({ key: dirtyScopeStorageKey(scope), value: true })),
+ ]);
+ } else {
+ await storage.set(StorageKeys.ENCRYPTED_VAULT, request.vaultBlob);
+ }
+
+ // The blob changed, so the cached client no longer matches it.
+ cachedSqliteClient = null;
+ cachedVaultBlob = null;
+
+ return { success: true, mutationSequence };
+}
+
+/**
+ * Clear the dirty flag unless a mutation raced the sync.
+ * @param mutationSeqAtStart - the mutation sequence when the sync started
+ */
+async function markVaultClean(mutationSeqAtStart: number): Promise<boolean> {
+ const storage = getPlatform().storage;
+ const currentMutationSeq = await storage.get<number>(StorageKeys.MUTATION_SEQUENCE) ?? 0;
+ if (currentMutationSeq === mutationSeqAtStart) {
+ await storage.set(StorageKeys.IS_DIRTY, false);
+ await clearDirtyScopes();
+ return true;
+ }
+ return false;
+}
+
+/**
+ * The Rust sync engine's host: how it reaches the local vault and the at-rest blob.
+ */
+const syncEngineHost: IVaultSyncEngineHost = {
+ /**
+ * The open vault. A store clears the cache, so the next call re-opens the blob just stored.
+ */
+ localDatabase: async (): Promise<ISqliteDatabase> => {
+ const sqliteClient = await createVaultSqliteClient();
+ const db = sqliteClient.getDb();
+ if (!db) {
+ throw new Error('Vault database not initialized');
+ }
+ return {
+ /** Run a statement. */
+ run: (sql: string, params?: SqliteValue[]): number => db.run(sql, params),
+ /** Run a query. */
+ query: <T,>(sql: string, params?: SqliteValue[]): T[] => db.query<T>(sql, params),
+ /** Run raw SQL. */
+ exec: (sql: string): void => db.exec(sql),
+ /** Export through the client so it can compact the file first. */
+ export: (): Uint8Array => sqliteClient.exportToBytes(),
+ /** The cached client owns the database's lifetime. */
+ close: (): void => {},
+ };
+ },
+ /**
+ * The stored vault blob.
+ */
+ loadVault: (): Promise<string | null> => getEncryptedVault(),
+ /**
+ * Persist a vault blob the engine produced.
+ */
+ storeVault: (request: VaultSyncStoreRequest): Promise<VaultSyncStoreOutcome> =>
+ storeEncryptedVault({ vaultBlob: request.encryptedBlob, markDirty: request.markDirty, expectedMutationSeq: request.expectedMutationSeq }),
+ /**
+ * Clear the dirty flag unless a mutation raced the sync.
+ */
+ markClean: (mutationSeqAtStart: number): Promise<boolean> => markVaultClean(mutationSeqAtStart),
+ /**
+ * Drop an in-memory vault holding changes no store persisted; the next reader reopens the stored blob.
+ */
+ discardLocalDatabase: (): void => {
+ cachedSqliteClient = null;
+ cachedVaultBlob = null;
+ },
+ /**
+ * Show the UI what the sync is doing.
+ */
+ onPhase: (phase: EngineSyncPhase): void => {
+ if (phase === 'pull') {
+ broadcastSyncPhase('pull');
+ return;
+ }
+ void getDirtyScopes().then(scopes => {
+ if (hasUserVisibleScope(scopes)) {
+ broadcastSyncPhase('push');
+ }
+ });
+ },
+};
+
+/**
+ * The sync operations on the stored vault.
+ */
+const vaultSync = new VaultSync(syncEngineHost, createVaultSqliteClient);
+
+/**
+ * Persist a sync failure so the UI can surface it; any other outcome clears the stored failure.
+ * @param result - the sync outcome
+ */
+async function persistSyncErrorState(result: FullVaultSyncResult): Promise<void> {
+ const storage = getPlatform().storage;
+ const dedicatedError = result.requiresLogout || result.wasOffline;
+ if (hasSyncError(result) && !dedicatedError) {
+ await storage.set(StorageKeys.LAST_SYNC_ERROR, { errorKey: result.errorKey, errorCode: result.errorCode, error: result.error });
+ } else {
+ await storage.remove(StorageKeys.LAST_SYNC_ERROR);
+ }
+}
+
+/**
+ * Whether a sync has to yield to a sync hold (see VaultSyncHold).
+ */
+async function syncIsOnHold(): Promise<boolean> {
+ const reason = await getVaultSyncHoldReason();
+ if (reason) {
+ devLog(`[VaultSync] Sync refused: on hold for ${reason}.`);
+ }
+ return reason !== null;
+}
+
+/**
+ * Full vault sync (push and pull based on revision counters), one at a time.
+ * @param options - what the caller asks beyond what the revisions decide
+ */
+async function fullVaultSyncInternal(options?: VaultSyncOptions): Promise<FullVaultSyncResult> {
+ if (await syncIsOnHold()) {
+ return syncResult({ success: false });
+ }
+
+ if (isSyncInProgress) {
+ hasPendingSync = true;
+ devLog('[VaultSync] Sync already in progress, queued for retry after completion');
+ return syncResult();
+ }
+
+ isSyncInProgress = true;
+ hasPendingSync = false;
+
+ try {
+ return await vaultSync.syncVaultWithServer(options);
+ } finally {
+ isSyncInProgress = false;
+ broadcastSyncPhase('idle');
+
+ if (hasPendingSync) {
+ devLog('[VaultSync] Pending mutations detected, triggering follow-up sync');
+ hasPendingSync = false;
+ vaultStore.fullVaultSync().catch(err => {
+ console.error('[VaultSync] Follow-up sync failed:', err);
+ });
+ }
+ }
+}
+
+/**
+ * The vault store.
+ */
+export const vaultStore = {
+ /**
+ * Subscribe to sync phase changes.
+ * @param listener - called with the phase
+ */
+ onSyncPhase(listener: (phase: VaultSyncPhase) => void): () => void {
+ phaseListeners.add(listener);
+ return (): void => {
+ phaseListeners.delete(listener);
+ };
+ },
+
+ getEncryptionKey,
+ getEncryptedVault,
+ storeEncryptedVault,
+ createVaultSqliteClient,
+
+ /**
+ * Store the session unlock key.
+ * @param unlockKey - the unlock key
+ */
+ async storeUnlockKey(unlockKey: string): Promise<void> {
+ await getPlatform().storage.set(StorageKeys.UNLOCK_KEY, unlockKey);
+ },
+
+ /**
+ * Store the unlock key derivation parameters, which enable an offline unlock.
+ * @param params - the parameters
+ */
+ async storeUnlockKeyDerivationParams(params: UnlockKeyDerivationParams): Promise<void> {
+ await getPlatform().storage.set(StorageKeys.UNLOCK_KEY_DERIVATION_PARAMS, params);
+ },
+
+ /**
+ * Decrypt the stored vault.
+ */
+ async getVault(): Promise<VaultResponse> {
+ try {
+ const [encryptionKey, encryptedVault] = await Promise.all([getEncryptionKey(), getEncryptedVault()]);
+ if (!encryptedVault) {
+ return { success: false, error: formatErrorWithCode(i18n.t('common.errors.vaultNotAvailable'), AppErrorCode.VAULT_NOT_FOUND) };
+ }
+ if (!encryptionKey) {
+ return { success: false, error: formatErrorWithCode(i18n.t('common.errors.vaultIsLocked'), AppErrorCode.VAULT_LOCKED) };
+ }
+ return { success: true, vault: await decryptVaultBlob(encryptedVault, encryptionKey) };
+ } catch (error) {
+ console.error('Failed to get vault:', error);
+ return { success: false, error: formatErrorWithCode(i18n.t('common.errors.unknownError'), AppErrorCode.VAULT_DECRYPT_FAILED) };
+ }
+ },
+
+ /**
+ * The email domain lists from the last sync, or null when no sync recorded them yet.
+ */
+ async getVaultMetadata(): Promise<VaultMetadata | null> {
+ try {
+ const storage = getPlatform().storage;
+ const [publicEmailDomains, privateEmailDomains, hiddenPrivateEmailDomains] = await Promise.all([
+ storage.get<string[]>(StorageKeys.PUBLIC_EMAIL_DOMAINS),
+ storage.get<string[]>(StorageKeys.PRIVATE_EMAIL_DOMAINS),
+ storage.get<string[]>(StorageKeys.HIDDEN_PRIVATE_EMAIL_DOMAINS),
+ ]);
+ if (!publicEmailDomains && !privateEmailDomains) {
+ return null;
+ }
+ return { publicEmailDomains: publicEmailDomains ?? [], privateEmailDomains: privateEmailDomains ?? [], hiddenPrivateEmailDomains: hiddenPrivateEmailDomains ?? [] };
+ } catch (error) {
+ console.error('Error getting vault metadata from storage:', error);
+ return null;
+ }
+ },
+
+ /**
+ * Whether the user is logged in and whether the vault can be opened right now.
+ */
+ async checkAuthStatus(): Promise<{ isLoggedIn: boolean; isVaultLocked: boolean; hasStoredVault: boolean }> {
+ const storage = getPlatform().storage;
+ const [username, accessToken, vaultData, unlockKey] = await Promise.all([storage.get<string>(StorageKeys.USERNAME), storage.get<string>(StorageKeys.ACCESS_TOKEN), getEncryptedVault(), VaultKeyService.getSessionUnlockKey()]);
+ const isLoggedIn = username !== null && accessToken !== null;
+ return { isLoggedIn, isVaultLocked: isLoggedIn && unlockKey === null, hasStoredVault: vaultData !== null };
+ },
+
+ /**
+ * Lock the vault: clear the session keys, keep the encrypted vault so the user can unlock without the server.
+ */
+ async lockVault(): Promise<void> {
+ await getPlatform().storage.removeMany([...VAULT_LOCK_STORAGE_KEYS]);
+ cleanupCachedSqliteClient();
+ },
+
+ /**
+ * Clear the session: tokens, session keys and the vault itself (forced logout, keeps the username for prefill).
+ */
+ async clearSession(): Promise<void> {
+ const storage = getPlatform().storage;
+ await storage.removeMany([...AUTH_STORAGE_KEYS]);
+ await storage.removeMany([...SESSION_STORAGE_KEYS]);
+ await storage.removeMany(vaultDataStorageKeys());
+ cleanupCachedSqliteClient();
+ },
+
+ /**
+ * Clear the vault data and the username (user-initiated logout).
+ */
+ async clearVaultData(): Promise<void> {
+ await getPlatform().storage.removeMany([...vaultDataStorageKeys(), StorageKeys.USERNAME]);
+ cleanupCachedSqliteClient();
+ },
+
+ /**
+ * Full vault sync, persisting a failure for the UI unless the caller reports it itself.
+ * @param options - what the caller asks of the sync beyond what the revisions decide
+ */
+ async fullVaultSync(options?: FullVaultSyncRequest): Promise<FullVaultSyncResult> {
+ const result = await fullVaultSyncInternal(options);
+ if (options?.reportErrorToPopup !== false) {
+ await persistSyncErrorState(result);
+ }
+ return result;
+ },
+
+ /**
+ * Whether the stored vault still needs a migration before it can be used.
+ */
+ async requiresManifestMigration(): Promise<boolean> {
+ return vaultRequiresManifestMigration(await createVaultSqliteClient());
+ },
+
+ /**
+ * Classify the pending migration.
+ */
+ getVaultMigrationStatus(): Promise<VaultMigrationKind> {
+ return vaultSync.getVaultMigrationStatus();
+ },
+
+ /**
+ * Upgrade the local vault to the current storage model and push it.
+ */
+ migrateVaultManifest(): Promise<VaultManifestMigrationResult> {
+ return vaultSync.migrateVaultManifest();
+ },
+};