Skip to content

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

Add browser extension offline mode scaffolding (#1404)

Leendert de Borst6aa731bb9620
diff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.ts
index 0cde44cf7..237057e97 100644
--- a/apps/browser-extension/src/entrypoints/background.ts
+++ b/apps/browser-extension/src/entrypoints/background.ts
@@ -9,7 +9,7 @@ import { handleClipboardCopied, handleCancelClipboardClear, handleGetClipboardCl
import { setupContextMenus } from '@/entrypoints/background/ContextMenu';
import { handleGetWebAuthnSettings, handleWebAuthnCreate, handleWebAuthnGet, handlePasskeyPopupResponse, handleGetRequestData } from '@/entrypoints/background/PasskeyHandler';
import { handleOpenPopup, handlePopupWithCredential, handleOpenPopupCreateCredential, handleToggleContextMenu } from '@/entrypoints/background/PopupMessageHandler';
-import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearVault, handleCreateIdentity, handleGetCredentials, handleGetDefaultEmailDomain, handleGetDefaultIdentitySettings, handleGetEncryptionKey, handleGetEncryptionKeyDerivationParams, handleGetPasswordSettings, handleGetPersistedFormValues, handleGetVault, handlePersistFormValues, handleStoreEncryptionKey, handleStoreEncryptionKeyDerivationParams, handleStoreVault, handleSyncVault, handleUploadVault } from '@/entrypoints/background/VaultMessageHandler';
+import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearVault, handleCreateIdentity, handleGetCredentials, handleGetDefaultEmailDomain, handleGetDefaultIdentitySettings, handleGetEncryptionKey, handleGetEncryptionKeyDerivationParams, handleGetPasswordSettings, handleGetPersistedFormValues, handleGetVault, handlePersistFormValues, handleStoreEncryptionKey, handleStoreEncryptionKeyDerivationParams, handleStoreVault, handleSyncVault, handleUploadVault, handleGetOfflineMode, handleSetOfflineMode, handleGetEncryptedVault, handleStoreEncryptedVault } from '@/entrypoints/background/VaultMessageHandler';
import { GLOBAL_CONTEXT_MENU_ENABLED_KEY } from '@/utils/Constants';
import { EncryptionKeyDerivationParams } from "@/utils/dist/shared/models/metadata";
@@ -42,6 +42,12 @@ export default defineBackground({
onMessage('SYNC_VAULT', () => handleSyncVault());
onMessage('CLEAR_VAULT', () => handleClearVault());
+ // Offline mode management messages
+ onMessage('GET_OFFLINE_MODE', () => handleGetOfflineMode());
+ onMessage('SET_OFFLINE_MODE', ({ data }) => handleSetOfflineMode(data as boolean));
+ onMessage('GET_ENCRYPTED_VAULT', () => handleGetEncryptedVault());
+ onMessage('STORE_ENCRYPTED_VAULT', ({ data }) => handleStoreEncryptedVault(data as string));
+
onMessage('OPEN_POPUP', () => handleOpenPopup());
onMessage('OPEN_POPUP_WITH_CREDENTIAL', ({ data }) => handlePopupWithCredential(data));
onMessage('OPEN_POPUP_CREATE_CREDENTIAL', ({ data }) => handleOpenPopupCreateCredential(data));
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
index 5a081be45..3c7cd062a 100644
--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
@@ -24,7 +24,8 @@ import { t } from '@/i18n/StandaloneI18n';
export async function handleCheckAuthStatus() : Promise<{ isLoggedIn: boolean, isVaultLocked: boolean, hasPendingMigrations: boolean, error?: string }> {
const username = await storage.getItem('local:username');
const accessToken = await storage.getItem('local:accessToken');
- const vaultData = await storage.getItem('session:encryptedVault');
+ // Check local: storage for persistent vault (survives browser close)
+ const vaultData = await storage.getItem('local:encryptedVault');
const encryptionKey = await handleGetEncryptionKey();
const isLoggedIn = username !== null && accessToken !== null;
@@ -82,6 +83,8 @@ export async function handleCheckAuthStatus() : Promise<{ isLoggedIn: boolean, i
/**
* Store the vault in browser storage.
+ * The encrypted vault is stored in local: storage (persistent) while metadata is in local:.
+ * The encryption key remains in session: storage for security.
*/
export async function handleStoreVault(
message: any,
@@ -89,28 +92,32 @@ export async function handleStoreVault(
try {
const vaultRequest = message as StoreVaultRequest;
- // Store new encrypted vault in session storage.
- await storage.setItem('session:encryptedVault', vaultRequest.vaultBlob);
+ /*
+ * Store encrypted vault in local: storage (persistent across browser sessions).
+ * This allows offline access after browser restart (user must re-enter password to unlock).
+ */
+ await storage.setItem('local:encryptedVault', vaultRequest.vaultBlob);
/*
- * For all other values, check if they have a value and store them in session storage if they do.
+ * For all other values, check if they have a value and store them in local: storage if they do.
+ * These are also persisted to enable offline mode.
* Some updates, e.g. when mutating local database, these values will not be set.
*/
if (vaultRequest.publicEmailDomainList) {
- await storage.setItem('session:publicEmailDomains', vaultRequest.publicEmailDomainList);
+ await storage.setItem('local:publicEmailDomains', vaultRequest.publicEmailDomainList);
}
if (vaultRequest.privateEmailDomainList) {
- await storage.setItem('session:privateEmailDomains', vaultRequest.privateEmailDomainList);
+ await storage.setItem('local:privateEmailDomains', vaultRequest.privateEmailDomainList);
}
if (vaultRequest.hiddenPrivateEmailDomainList) {
- await storage.setItem('session:hiddenPrivateEmailDomains', vaultRequest.hiddenPrivateEmailDomainList);
+ await storage.setItem('local:hiddenPrivateEmailDomains', vaultRequest.hiddenPrivateEmailDomainList);
}
if (vaultRequest.vaultRevisionNumber) {
- await storage.setItem('session:vaultRevisionNumber', vaultRequest.vaultRevisionNumber);
+ await storage.setItem('local:vaultRevisionNumber', vaultRequest.vaultRevisionNumber);
}
return { success: true };
@@ -137,12 +144,13 @@ export async function handleStoreEncryptionKey(
/**
* Store the encryption key derivation parameters in browser storage.
+ * These are stored in local: storage to enable offline unlock after browser restart.
*/
export async function handleStoreEncryptionKeyDerivationParams(
params: EncryptionKeyDerivationParams,
) : Promise<messageBoolResponse> {
try {
- await storage.setItem('session:encryptionKeyDerivationParams', params);
+ await storage.setItem('local:encryptionKeyDerivationParams', params);
return { success: true };
} catch (error) {
console.error('Failed to store encryption key derivation params:', error);
@@ -155,25 +163,26 @@ export async function handleStoreEncryptionKeyDerivationParams(
*/
export async function handleSyncVault(
) : Promise<messageBoolResponse> {
- const webApi = new WebApiService(() => {});
+ const webApi = new WebApiService();
const statusResponse = await webApi.getStatus();
const statusError = webApi.validateStatusResponse(statusResponse);
if (statusError !== null) {
return { success: false, error: await t('common.errors.' + statusError) };
}
- const vaultRevisionNumber = await storage.getItem('session:vaultRevisionNumber') as number;
+ const vaultRevisionNumber = await storage.getItem('local:vaultRevisionNumber') as number;
if (statusResponse.vaultRevision > vaultRevisionNumber) {
// Retrieve the latest vault from the server.
const vaultResponse = await webApi.get<VaultResponse>('Vault');
+ // Store in local: storage for persistence
await storage.setItems([
- { key: 'session:encryptedVault', value: vaultResponse.vault.blob },
- { key: 'session:publicEmailDomains', value: vaultResponse.vault.publicEmailDomainList },
- { key: 'session:privateEmailDomains', value: vaultResponse.vault.privateEmailDomainList },
- { key: 'session:hiddenPrivateEmailDomains', value: vaultResponse.vault.hiddenPrivateEmailDomainList },
- { key: 'session:vaultRevisionNumber', value: vaultResponse.vault.currentRevisionNumber }
+ { key: 'local:encryptedVault', value: vaultResponse.vault.blob },
+ { key: 'local:publicEmailDomains', value: vaultResponse.vault.publicEmailDomainList },
+ { key: 'local:privateEmailDomains', value: vaultResponse.vault.privateEmailDomainList },
+ { key: 'local:hiddenPrivateEmailDomains', value: vaultResponse.vault.hiddenPrivateEmailDomainList },
+ { key: 'local:vaultRevisionNumber', value: vaultResponse.vault.currentRevisionNumber }
]);
}
@@ -181,18 +190,19 @@ export async function handleSyncVault(
}
/**
- * Get the vault from browser storage.
+ * Get the vault from browser storage (local: for persistence).
*/
export async function handleGetVault(
) : Promise<messageVaultResponse> {
try {
const encryptionKey = await handleGetEncryptionKey();
- const encryptedVault = await storage.getItem('session:encryptedVault') as string;
- const publicEmailDomains = await storage.getItem('session:publicEmailDomains') as string[];
- const privateEmailDomains = await storage.getItem('session:privateEmailDomains') as string[];
- const hiddenPrivateEmailDomains = await storage.getItem('session:hiddenPrivateEmailDomains') as string[] ?? [];
- const vaultRevisionNumber = await storage.getItem('session:vaultRevisionNumber') as number;
+ // Read from local: storage for persistent vault access
+ const encryptedVault = await storage.getItem('local:encryptedVault') as string;
+ const publicEmailDomains = await storage.getItem('local:publicEmailDomains') as string[];
+ const privateEmailDomains = await storage.getItem('local:privateEmailDomains') as string[];
+ const hiddenPrivateEmailDomains = await storage.getItem('local:hiddenPrivateEmailDomains') as string[] ?? [];
+ const vaultRevisionNumber = await storage.getItem('local:vaultRevisionNumber') as number;
if (!encryptedVault) {
console.error('Vault not available');
@@ -224,20 +234,28 @@ export async function handleGetVault(
}
/**
- * Clear the vault from browser storage.
+ * Clear the vault from browser storage (both local: and session:).
*/
export function handleClearVault(
) : messageBoolResponse {
+ // Clear persistent vault data from local: storage
+ storage.removeItems([
+ 'local:encryptedVault',
+ 'local:publicEmailDomains',
+ 'local:privateEmailDomains',
+ 'local:hiddenPrivateEmailDomains',
+ 'local:vaultRevisionNumber',
+ 'local:isOfflineMode',
+ 'local:encryptionKeyDerivationParams'
+ ]);
+
+ // Clear session-only data
storage.removeItems([
- 'session:encryptedVault',
'session:encryptionKey',
// TODO: the derivedKey clear can be removed some period of time after 0.22.0 is released.
'session:derivedKey',
- 'session:encryptionKeyDerivationParams',
- 'session:publicEmailDomains',
- 'session:privateEmailDomains',
- 'session:hiddenPrivateEmailDomains',
- 'session:vaultRevisionNumber'
+ // TODO: the session encryptionKeyDerivationParams clear can be removed after users have migrated to local: storage.
+ 'session:encryptionKeyDerivationParams'
]);
return { success: true };
@@ -301,8 +319,8 @@ export async function getEmailAddressesForVault(
// TODO: create separate query to only get email addresses to avoid loading all credentials.
const credentials = sqliteClient.getAllCredentials();
- // Get metadata from storage
- const privateEmailDomains = await storage.getItem('session:privateEmailDomains') as string[];
+ // Get metadata from local: storage
+ const privateEmailDomains = await storage.getItem('local:privateEmailDomains') as string[];
const emailAddresses = credentials
.filter(cred => cred.Alias?.Email != null)
@@ -391,10 +409,18 @@ export async function handleGetEncryptionKey(
/**
* Get the encryption key derivation parameters for password change detection and offline mode.
+ * These are stored in local: storage to enable offline unlock after browser restart.
*/
export async function handleGetEncryptionKeyDerivationParams(
) : Promise<EncryptionKeyDerivationParams | null> {
- const params = await storage.getItem('session:encryptionKeyDerivationParams') as EncryptionKeyDerivationParams | null;
+ // Try local: storage first (current location since offline support)
+ let params = await storage.getItem('local:encryptionKeyDerivationParams') as EncryptionKeyDerivationParams | null;
+
+ // Fall back to session: storage for backwards compatibility
+ if (!params) {
+ params = await storage.getItem('session:encryptionKeyDerivationParams') as EncryptionKeyDerivationParams | null;
+ }
+
return params;
}
@@ -405,8 +431,8 @@ export async function handleUploadVault(
message: any
) : Promise<messageVaultUploadResponse> {
try {
- // Store the new vault blob in session storage.
- await storage.setItem('session:encryptedVault', message.vaultBlob);
+ // Store the new vault blob in local: storage (persistent).
+ await storage.setItem('local:encryptedVault', message.vaultBlob);
// Create new sqlite client which will use the new vault blob.
const sqliteClient = await createVaultSqliteClient();
@@ -486,12 +512,13 @@ async function uploadNewVaultToServer(sqliteClient: SqliteClient) : Promise<Vaul
encryptionKey
);
+ // Store in local: storage for persistence
await storage.setItems([
- { key: 'session:encryptedVault', value: encryptedVault }
+ { key: 'local:encryptedVault', value: encryptedVault }
]);
- // Get metadata from storage
- const vaultRevisionNumber = await storage.getItem('session:vaultRevisionNumber') as number;
+ // Get metadata from local: storage
+ const vaultRevisionNumber = await storage.getItem('local:vaultRevisionNumber') as number;
// Upload new encrypted vault to server.
const username = await storage.getItem('local:username') as string;
@@ -510,12 +537,12 @@ async function uploadNewVaultToServer(sqliteClient: SqliteClient) : Promise<Vaul
encryptionPublicKey: '',
};
- const webApi = new WebApiService(() => {});
+ const webApi = new WebApiService();
const response = await webApi.post<Vault, VaultPostResponse>('Vault', newVault);
// Check if response is successful (.status === 0)
if (response.status === 0) {
- await storage.setItem('session:vaultRevisionNumber', response.newRevisionNumber);
+ await storage.setItem('local:vaultRevisionNumber', response.newRevisionNumber);
} else {
throw new Error(await t('common.errors.unknownError'));
}
@@ -527,7 +554,8 @@ async function uploadNewVaultToServer(sqliteClient: SqliteClient) : Promise<Vaul
* Create a new sqlite client for the stored vault.
*/
async function createVaultSqliteClient() : Promise<SqliteClient> {
- const encryptedVault = await storage.getItem('session:encryptedVault') as string;
+ // Read from local: storage for persistent vault access
+ const encryptedVault = await storage.getItem('local:encryptedVault') as string;
const encryptionKey = await handleGetEncryptionKey();
if (!encryptedVault || !encryptionKey) {
throw new Error(await t('common.errors.unknownError'));
@@ -545,3 +573,32 @@ async function createVaultSqliteClient() : Promise<SqliteClient> {
return sqliteClient;
}
+
+/**
+ * Get offline mode status.
+ */
+export async function handleGetOfflineMode(): Promise<boolean> {
+ const isOffline = await storage.getItem('local:isOfflineMode') as boolean;
+ return isOffline ?? false;
+}
+
+/**
+ * Set offline mode status.
+ */
+export async function handleSetOfflineMode(isOffline: boolean): Promise<void> {
+ await storage.setItem('local:isOfflineMode', isOffline);
+}
+
+/**
+ * Get the encrypted vault blob directly (for merge operations).
+ */
+export async function handleGetEncryptedVault(): Promise<string | null> {
+ return await storage.getItem('local:encryptedVault') as string | null;
+}
+
+/**
+ * Store the encrypted vault blob directly (for merge operations).
+ */
+export async function handleStoreEncryptedVault(encryptedVault: string): Promise<void> {
+ await storage.setItem('local:encryptedVault', encryptedVault);
+}
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Layout/Header.tsx b/apps/browser-extension/src/entrypoints/popup/components/Layout/Header.tsx
index b7a3d0c57..2aed5ecde 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Layout/Header.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Layout/Header.tsx
@@ -5,6 +5,8 @@ import { useNavigate, useLocation } from 'react-router-dom';
import Logo from '@/entrypoints/popup/components/Logo';
import { useApp } from '@/entrypoints/popup/context/AppContext';
+import OfflineIndicator from './OfflineIndicator';
+
/**
* Header props.
*/
@@ -104,6 +106,9 @@ const Header: React.FC<HeaderProps> = ({
<div className="flex-grow" />
+ {/* Offline mode indicator */}
+ <OfflineIndicator />
+
<div className="flex items-center gap-2">
{!app.isLoggedIn ? (
<>
@@ -128,4 +133,4 @@ const Header: React.FC<HeaderProps> = ({
);
};
-export default Header;
\ No newline at end of file
+export default Header;
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Layout/OfflineIndicator.tsx b/apps/browser-extension/src/entrypoints/popup/components/Layout/OfflineIndicator.tsx
new file mode 100644
index 000000000..2339a559d
--- /dev/null
+++ b/apps/browser-extension/src/entrypoints/popup/components/Layout/OfflineIndicator.tsx
@@ -0,0 +1,36 @@
+import React from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useApp } from '@/entrypoints/popup/context/AppContext';
+import { useDb } from '@/entrypoints/popup/context/DbContext';
+
+/**
+ * Offline mode indicator component.
+ * Displays an amber badge when the extension is operating in offline mode.
+ */
+const OfflineIndicator: React.FC = () => {
+ const { t } = useTranslation();
+ const app = useApp();
+ const dbContext = useDb();
+
+ // Only show when logged in and offline
+ if (!dbContext.isOffline || !app.isLoggedIn) {
+ return null;
+ }
+
+ return (
+ <div className="flex items-center gap-1.5 px-2 py-1 bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400 rounded-md text-xs font-medium">
+ <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M18.364 5.636a9 9 0 010 12.728m0 0l-2.829-2.829m2.829 2.829L21 21M15.536 8.464a5 5 0 010 7.072m0 0l-2.829-2.829m-4.243 2.829a4.978 4.978 0 01-1.414-2.83m-1.414 5.658a9 9 0 01-2.167-9.238m7.824 2.167a1 1 0 111.414 1.414m-1.414-1.414L3 3m8.293 8.293l1.414 1.414"
+ />
+ </svg>
+ <span>{t('common.offline')}</span>
+ </div>
+ );
+};
+
+export default OfflineIndicator;
diff --git a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
index f702b2a86..914254a29 100644
--- a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
@@ -14,7 +14,10 @@ type DbContextType = {
sqliteClient: SqliteClient | null;
dbInitialized: boolean;
dbAvailable: boolean;
+ isOffline: boolean;
+ setIsOffline: (offline: boolean) => Promise<void>;
initializeDatabase: (vaultResponse: VaultResponse, derivedKey: string) => Promise<SqliteClient>;
+ initializeDatabaseFromDecryptedVault: (decryptedVaultBase64: string) => Promise<SqliteClient>;
storeEncryptionKey: (derivedKey: string) => Promise<void>;
storeEncryptionKeyDerivationParams: (params: EncryptionKeyDerivationParams) => Promise<void>;
clearDatabase: () => void;
@@ -44,6 +47,33 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
*/
const [dbAvailable, setDbAvailable] = useState(false);
+ /**
+ * Offline mode state. If true, the extension is operating offline.
+ */
+ const [isOffline, setIsOfflineState] = useState(false);
+
+ /**
+ * Set the offline mode state and persist it.
+ */
+ const setIsOffline = useCallback(async (offline: boolean) => {
+ setIsOfflineState(offline);
+ await sendMessage('SET_OFFLINE_MODE', offline, 'background');
+ }, []);
+
+ /**
+ * Load initial offline state from storage.
+ */
+ useEffect(() => {
+ /**
+ * Load the offline mode state from background storage.
+ */
+ const loadOfflineState = async () : Promise<void> => {
+ const offlineMode = await sendMessage('GET_OFFLINE_MODE', {}, 'background') as boolean;
+ setIsOfflineState(offlineMode);
+ };
+ loadOfflineState();
+ }, []);
+
const initializeDatabase = useCallback(async (vaultResponse: VaultResponse, derivedKey: string) => {
// Attempt to decrypt the blob.
const decryptedBlob = await EncryptionUtility.symmetricDecrypt(
@@ -75,6 +105,22 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
return client;
}, []);
+ /**
+ * Initialize the database from an already-decrypted vault (for offline mode).
+ * This is used when we have the decryption key but the server is unavailable.
+ */
+ const initializeDatabaseFromDecryptedVault = useCallback(async (decryptedVaultBase64: string) => {
+ // Initialize the SQLite client.
+ const client = new SqliteClient();
+ await client.initializeFromBase64(decryptedVaultBase64);
+
+ setSqliteClient(client);
+ setDbInitialized(true);
+ setDbAvailable(true);
+
+ return client;
+ }, []);
+
const checkStoredVault = useCallback(async () => {
try {
const response = await sendMessage('GET_VAULT', {}, 'background') as messageVaultResponse;
@@ -98,14 +144,14 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
}, []);
/**
- * Get the vault metadata from session storage.
+ * Get the vault metadata from local storage (persistent).
*/
const getVaultMetadata = useCallback(async () : Promise<VaultMetadata | null> => {
try {
- const publicEmailDomains = await storage.getItem('session:publicEmailDomains') as string[] | null;
- const privateEmailDomains = await storage.getItem('session:privateEmailDomains') as string[] | null;
- const hiddenPrivateEmailDomains = await storage.getItem('session:hiddenPrivateEmailDomains') as string[] | null;
- const vaultRevisionNumber = await storage.getItem('session:vaultRevisionNumber') as number | null;
+ const publicEmailDomains = await storage.getItem('local:publicEmailDomains') as string[] | null;
+ const privateEmailDomains = await storage.getItem('local:privateEmailDomains') as string[] | null;
+ const hiddenPrivateEmailDomains = await storage.getItem('local:hiddenPrivateEmailDomains') as string[] | null;
+ const vaultRevisionNumber = await storage.getItem('local:vaultRevisionNumber') as number | null;
if (!publicEmailDomains && !privateEmailDomains) {
return null;
@@ -118,16 +164,16 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
vaultRevisionNumber: vaultRevisionNumber ?? 0,
};
} catch (error) {
- console.error('Error getting vault metadata from session storage:', error);
+ console.error('Error getting vault metadata from local storage:', error);
return null;
}
}, []);
/**
- * Set the current vault revision number in session storage.
+ * Set the current vault revision number in local storage (persistent).
*/
const setCurrentVaultRevisionNumber = useCallback(async (revisionNumber: number) => {
- await storage.setItem('session:vaultRevisionNumber', revisionNumber);
+ await storage.setItem('local:vaultRevisionNumber', revisionNumber);
}, []);
/**
@@ -177,14 +223,17 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
sqliteClient,
dbInitialized,
dbAvailable,
+ isOffline,
+ setIsOffline,
initializeDatabase,
+ initializeDatabaseFromDecryptedVault,
storeEncryptionKey,
storeEncryptionKeyDerivationParams,
clearDatabase,
getVaultMetadata,
setCurrentVaultRevisionNumber,
hasPendingMigrations,
- }), [sqliteClient, dbInitialized, dbAvailable, initializeDatabase, storeEncryptionKey, storeEncryptionKeyDerivationParams, clearDatabase, getVaultMetadata, setCurrentVaultRevisionNumber, hasPendingMigrations]);
+ }), [sqliteClient, dbInitialized, dbAvailable, isOffline, setIsOffline, initializeDatabase, initializeDatabaseFromDecryptedVault, storeEncryptionKey, storeEncryptionKeyDerivationParams, clearDatabase, getVaultMetadata, setCurrentVaultRevisionNumber, hasPendingMigrations]);
return (
<DbContext.Provider value={contextValue}>
diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
index 25316ed21..40419dafa 100644
--- a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
+++ b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
@@ -3,11 +3,15 @@ import { useTranslation } from 'react-i18next';
import { sendMessage } from 'webext-bridge/popup';
import { useDb } from '@/entrypoints/popup/context/DbContext';
-import { useVaultSync } from '@/entrypoints/popup/hooks/useVaultSync';
+import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
+import type { VaultResponse } from '@/utils/dist/shared/models/webapi';
import { EncryptionUtility } from '@/utils/EncryptionUtility';
import { UploadVaultRequest } from '@/utils/types/messaging/UploadVaultRequest';
import { VaultUploadResponse as messageVaultUploadResponse } from '@/utils/types/messaging/VaultUploadResponse';
+import { vaultMergeService } from '@/utils/VaultMergeService';
+
+import { useVaultSync } from './useVaultSync';
type VaultMutationOptions = {
onSuccess?: () => void;
@@ -17,6 +21,7 @@ type VaultMutationOptions = {
/**
* Hook to execute a vault mutation.
+ * Supports offline mode with LWW merge when coming back online.
*/
export function useVaultMutate() : {
executeVaultMutation: (operation: () => Promise<void>, options?: VaultMutationOptions) => Promise<void>;
@@ -27,29 +32,50 @@ export function useVaultMutate() : {
const [isLoading, setIsLoading] = useState(false);
const [syncStatus, setSyncStatus] = useState(t('common.syncingVault'));
const dbContext = useDb();
+ const webApi = useWebApi();
const { syncVault } = useVaultSync();
/**
- * Execute the provided operation (e.g. create/update/delete credential)
+ * Execute the provided operation and save locally (for offline mode)
*/
- const executeMutateOperation = useCallback(async (
+ const executeMutateOperationLocal = useCallback(async (
operation: () => Promise<void>,
- options: VaultMutationOptions
) : Promise<void> => {
setSyncStatus(t('common.savingChangesToVault'));
// Execute the provided operation (e.g. create/update/delete credential)
await operation();
+ // Export and encrypt the updated vault
+ const base64Vault = dbContext.sqliteClient!.exportToBase64();
+ const encryptionKey = await sendMessage('GET_ENCRYPTION_KEY', {}, 'background') as string;
+ const encryptedVaultBlob = await EncryptionUtility.symmetricEncrypt(
+ base64Vault,
+ encryptionKey
+ );
+
+ // Store the updated vault locally (persistent storage)
+ await sendMessage('STORE_ENCRYPTED_VAULT', encryptedVaultBlob, 'background');
+ }, [dbContext, t]);
+
+ /**
+ * Upload the vault to the server, handling conflicts with LWW merge
+ */
+ const uploadVaultWithMerge = useCallback(async (
+ options: VaultMutationOptions,
+ retryCount: number = 0
+ ) : Promise<void> => {
+ const MAX_RETRIES = 3;
+
+ if (retryCount >= MAX_RETRIES) {
+ throw new Error(t('common.errors.syncConflictMaxRetries'));
+ }
+
setSyncStatus(t('common.uploadingVaultToServer'));
- // Upload the updated vault to the server.
+ // Get the current local vault
const base64Vault = dbContext.sqliteClient!.exportToBase64();
-
- // Get encryption key from background worker
const encryptionKey = await sendMessage('GET_ENCRYPTION_KEY', {}, 'background') as string;
-
- // Encrypt the vault.
const encryptedVaultBlob = await EncryptionUtility.symmetricEncrypt(
base64Vault,
encryptionKey
@@ -59,37 +85,88 @@ export function useVaultMutate() : {
vaultBlob: encryptedVaultBlob,
};
- const response = await sendMessage('UPLOAD_VAULT', request, 'background') as messageVaultUploadResponse;
+ try {
+ const response = await sendMessage('UPLOAD_VAULT', request, 'background') as messageVaultUploadResponse;
+
+ if (response.status === 0 && response.newRevisionNumber) {
+ // Success - update local revision number and exit offline mode
+ await dbContext.setCurrentVaultRevisionNumber(response.newRevisionNumber);
+ if (dbContext.isOffline) {
+ await dbContext.setIsOffline(false);
+ }
+ options.onSuccess?.();
+ } else if (response.status === 2) {
+ // Vault is outdated - need to merge with server vault
+ setSyncStatus(t('common.mergingVaultChanges'));
+
+ // Fetch the latest vault from server
+ const serverVaultResponse = await webApi.get<VaultResponse>('Vault');
+ const serverEncryptedBlob = serverVaultResponse.vault.blob;
+
+ // Decrypt both vaults for merge
+ const localDecrypted = base64Vault; // Already decrypted
+ const serverDecrypted = await EncryptionUtility.symmetricDecrypt(
+ serverEncryptedBlob,
+ encryptionKey
+ );
+
+ // Perform LWW merge
+ const mergeResult = await vaultMergeService.merge(localDecrypted, serverDecrypted);
+
+ if (!mergeResult.success) {
+ throw new Error(t('common.errors.mergeFailed'));
+ }
+
+ console.info('Vault merge completed:', mergeResult.stats);
- /*
- * If we get here, it means we have a valid connection to the server.
- * TODO: offline mode is not implemented for browser extension yet.
- * authContext.setOfflineMode(false);
- */
+ // Re-initialize the database with merged vault
+ await dbContext.sqliteClient!.initializeFromBase64(mergeResult.mergedVaultBase64);
- if (response.status === 0 && response.newRevisionNumber) {
- await dbContext.setCurrentVaultRevisionNumber(response.newRevisionNumber);
+ // Update local revision to server's revision before retrying
+ await dbContext.setCurrentVaultRevisionNumber(serverVaultResponse.vault.currentRevisionNumber);
+
+ // Retry upload with merged vault
+ await uploadVaultWithMerge(options, retryCount + 1);
+ } else if (response.status === 1) {
+ // Legacy merge status - should not happen with API >= 0.20.0
+ throw new Error(t('common.errors.legacyMergeRequired'));
+ } else {
+ throw new Error(t('common.errors.unknownError'));
+ }
+ } catch (error) {
+ // Check if it's a network error - enter offline mode
+ const errorMessage = error instanceof Error ? error.message : '';
+ if (errorMessage.includes('network') || errorMessage.includes('timeout') || errorMessage.includes('fetch') || errorMessage.includes('Failed to fetch')) {
+ await dbContext.setIsOffline(true);
+ setSyncStatus(t('common.offlineModeSaved'));
+ // Changes are saved locally, success from user perspective
+ options.onSuccess?.();
+ return;
+ }
+ throw error;
+ }
+ }, [dbContext, webApi, t]);
+
+ /**
+ * Execute the provided operation (e.g. create/update/delete credential)
+ */
+ const executeMutateOperation = useCallback(async (
+ operation: () => Promise<void>,
+ options: VaultMutationOptions
+ ) : Promise<void> => {
+ // First, execute the operation and save locally
+ await executeMutateOperationLocal(operation);
+
+ // If we're offline, we're done - changes are saved locally
+ if (dbContext.isOffline) {
+ setSyncStatus(t('common.offlineModeSaved'));
options.onSuccess?.();
- } else if (response.status === 1) {
- // Note: vault merge is no longer allowed by the API as of 0.20.0, updates with the same revision number are rejected. So this check can be removed later.
- throw new Error('Vault merge required. Please login via the web app to merge the multiple pending updates to your vault.');
- } else if (response.status === 2) {
- throw new Error(t('common.errors.unknownError'));
- } else {
- throw new Error(t('common.errors.unknownError'));
+ return;
}
- // Check if it's a network error
- /*
- * if (error instanceof Error && (error.message.includes('network') || error.message.includes('timeout'))) {
- *
- * // Network error, mark as offline and track pending changes - TODO: offline mode is not implemented for browser extension yet.
- * // authContext.setOfflineMode(true);
- *options.onError?.(new Error('Network error'));
- *return;
- *}
- */
- }, [dbContext, t]);
+ // Try to upload to server (with merge if needed)
+ await uploadVaultWithMerge(options);
+ }, [dbContext, executeMutateOperationLocal, uploadVaultWithMerge, t]);
/**
* Hook to execute a vault mutation which uploads a new encrypted vault to the server
@@ -109,6 +186,13 @@ export function useVaultMutate() : {
return;
}
+ // If offline, skip sync and just execute the operation locally
+ if (dbContext.isOffline) {
+ setSyncStatus(t('common.executingOperation'));
+ await executeMutateOperation(operation, options);
+ return;
+ }
+
await syncVault({
/**
* Handle the status update.
@@ -123,6 +207,13 @@ export function useVaultMutate() : {
}
await executeMutateOperation(operation, options);
},
+ /**
+ * Handle offline mode - continue with local operation.
+ */
+ onOffline: async () => {
+ // We're now in offline mode, execute operation locally
+ await executeMutateOperation(operation, options);
+ },
/**
* Handle error during vault sync.
*/
@@ -137,11 +228,11 @@ export function useVaultMutate() : {
setIsLoading(false);
setSyncStatus('');
}
- }, [syncVault, executeMutateOperation, t]);
+ }, [syncVault, executeMutateOperation, dbContext.isOffline, t]);
return {
executeVaultMutation,
isLoading,
syncStatus,
};
-}
\ No newline at end of file
+}
diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultSync.ts b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultSync.ts
index be2b67e3d..642a78847 100644
--- a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultSync.ts
+++ b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultSync.ts
@@ -39,12 +39,13 @@ type VaultSyncOptions = {
onSuccess?: (hasNewVault: boolean) => void;
onError?: (error: string) => void;
onStatus?: (message: string) => void;
- _onOffline?: () => void;
+ onOffline?: () => void;
onUpgradeRequired?: () => void;
}
/**
* Hook to sync the vault with the server.
+ * Supports offline mode: if server is unavailable, continues with local vault.
*/
export const useVaultSync = () : {
syncVault: (options?: VaultSyncOptions) => Promise<boolean>;
@@ -55,7 +56,7 @@ export const useVaultSync = () : {
const webApi = useWebApi();
const syncVault = useCallback(async (options: VaultSyncOptions = {}) => {
- const { initialSync = false, onSuccess, onError, onStatus, _onOffline, onUpgradeRequired } = options;
+ const { initialSync = false, onSuccess, onError, onStatus, onOffline, onUpgradeRequired } = options;
// For the initial sync, we add an artifical delay to various steps which makes it feel more fluid.
const enableDelay = initialSync;
@@ -74,9 +75,19 @@ export const useVaultSync = () : {
// Check if server is actually available, 0.0.0 indicates connection error which triggers offline mode.
if (statusResponse.serverVersion === '0.0.0') {
- // Offline mode is not implemented for browser extension yet, so logout the user.
- onError?.(t('common.errors.serverNotAvailable'));
- return false;
+ // Server is unavailable - enter offline mode if we have a local vault
+ if (dbContext.dbAvailable) {
+ // We have a local vault, continue in offline mode
+ await dbContext.setIsOffline(true);
+ onStatus?.(t('common.offlineMode'));
+ onOffline?.();
+ onSuccess?.(false);
+ return true;
+ } else {
+ // No local vault available, can't operate offline
+ onError?.(t('common.errors.serverNotAvailable'));
+ return false;
+ }
}
const statusError = webApi.validateStatusResponse(statusResponse);
@@ -98,11 +109,10 @@ export const useVaultSync = () : {
return false;
}
- /*
- * If we get here, it means we have a valid connection to the server.
- * TODO: browser extension does not support offline mode yet.
- * authContext.setOfflineMode(false);
- */
+ // We have a valid connection to the server - exit offline mode if we were in it
+ if (dbContext.isOffline) {
+ await dbContext.setIsOffline(false);
+ }
// Compare vault revisions
const vaultMetadata = await dbContext.getVaultMetadata();
@@ -154,16 +164,17 @@ export const useVaultSync = () : {
return false;
}
- /*
- * Check if it's a network error
- * TODO: browser extension does not support offline mode yet.
- */
- /*
- * if (errorMessage.includes('network') || errorMessage.includes('timeout')) {
- *authContext.setOfflineMode(true);
- *return true;
- *}
- */
+ // Check if it's a network error - enter offline mode if we have a local vault
+ if (errorMessage.includes('network') || errorMessage.includes('timeout') || errorMessage.includes('fetch') || errorMessage.includes('Failed to fetch')) {
+ if (dbContext.dbAvailable) {
+ // We have a local vault, continue in offline mode
+ await dbContext.setIsOffline(true);
+ onStatus?.(t('common.offlineMode'));
+ onOffline?.();
+ onSuccess?.(false);
+ return true;
+ }
+ }
onError?.(errorMessage);
return false;
@@ -171,4 +182,4 @@ export const useVaultSync = () : {
}, [app, dbContext, webApi, t]);
return { syncVault };
-};
\ No newline at end of file
+};
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
index 6b1f0beff..d03e4cf54 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
@@ -3,6 +3,7 @@ import { Buffer } from 'buffer';
import React, { useEffect, useState, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
+import { sendMessage } from 'webext-bridge/popup';
import AlertMessage from '@/entrypoints/popup/components/AlertMessage';
import Button from '@/entrypoints/popup/components/Button';
@@ -20,6 +21,7 @@ import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';
import SrpUtility from '@/entrypoints/popup/utils/SrpUtility';
import { VAULT_LOCKED_DISMISS_UNTIL_KEY } from '@/utils/Constants';
+import type { EncryptionKeyDerivationParams } from '@/utils/dist/shared/models/metadata';
import type { VaultResponse } from '@/utils/dist/shared/models/webapi';
import EncryptionUtility from '@/utils/EncryptionUtility';
import {
@@ -76,26 +78,34 @@ const Unlock: React.FC = () => {
// Mobile unlock state
const [showMobileUnlockModal, setShowMobileUnlockModal] = useState(false);
+ // Server connectivity state (for hiding mobile unlock when offline)
+ const [isServerOnline, setIsServerOnline] = useState<boolean | null>(null);
+
/**
* Make status call to API which acts as health check.
* This runs only once during component mount.
+ * Returns { online: boolean, error: string | null }
*/
- const checkStatus = async () : Promise<boolean> => {
+ const checkStatus = async () : Promise<{ online: boolean; error: string | null }> => {
const statusResponse = await webApi.getStatus();
- const statusError = webApi.validateStatusResponse(statusResponse);
+ // Server is offline - this is OK for unlock, we can use local vault
if (statusResponse.serverVersion === '0.0.0') {
- setError(t('common.errors.serverNotAvailable'));
- return false;
+ setIsInitialLoading(false);
+ setIsServerOnline(false);
+ return { online: false, error: null };
}
+ const statusError = webApi.validateStatusResponse(statusResponse);
if (statusError !== null) {
await app.logout(t('common.errors.' + statusError));
- return false;
+ setIsServerOnline(false);
+ return { online: false, error: statusError };
}
setIsInitialLoading(false);
- return true;
+ setIsServerOnline(true);
+ return { online: true, error: null };
};
/**
@@ -195,48 +205,102 @@ const Unlock: React.FC = () => {
}, [unlockMode]);
/**
- * Handle password unlock
+ * Handle password unlock (supports both online and offline mode)
*/
const handlePasswordSubmit = async (e: React.FormEvent) : Promise<void> => {
e.preventDefault();
setError(null);
showLoading();
- const isStatusOk = await checkStatus();
- if (!isStatusOk) {
+ const statusResult = await checkStatus();
+ if (statusResult.error) {
+ // Fatal error (e.g., version mismatch), already handled by checkStatus
hideLoading();
return;
}
try {
- // 1. Initiate login to get salt and server ephemeral
- const loginResponse = await srpUtil.initiateLogin(authContext.username!);
+ let passwordHashBase64: string;
+ let vaultResponseJson: VaultResponse | null = null;
+
+ if (statusResult.online) {
+ // Online mode: get encryption params from server and fetch latest vault
+ const loginResponse = await srpUtil.initiateLogin(authContext.username!);
+
+ // Derive key from password using user's encryption settings
+ const passwordHash = await EncryptionUtility.deriveKeyFromPassword(
+ password,
+ loginResponse.salt,
+ loginResponse.encryptionType,
+ loginResponse.encryptionSettings
+ );
+
+ // Make API call to get latest vault
+ vaultResponseJson = await webApi.get<VaultResponse>('Vault');
+
+ // Get the derived key as base64 string required for decryption.
+ passwordHashBase64 = Buffer.from(passwordHash).toString('base64');
+ } else {
+ // Offline mode: use stored encryption params to derive key, decrypt local vault
+ const storedParams = await sendMessage('GET_ENCRYPTION_KEY_DERIVATION_PARAMS', {}, 'background') as EncryptionKeyDerivationParams | null;
+
+ if (!storedParams) {
+ // No stored params - can't unlock offline without having logged in before
+ setError(t('common.errors.serverNotAvailable'));
+ hideLoading();
+ return;
+ }
- // Derive key from password using user's encryption settings
- const passwordHash = await EncryptionUtility.deriveKeyFromPassword(
- password,
- loginResponse.salt,
- loginResponse.encryptionType,
- loginResponse.encryptionSettings
- );
+ // Derive key from password using stored encryption settings
+ const passwordHash = await EncryptionUtility.deriveKeyFromPassword(
+ password,
+ storedParams.salt,
+ storedParams.encryptionType,
+ storedParams.encryptionSettings
+ );
- // Make API call to get latest vault
- const vaultResponseJson = await webApi.get<VaultResponse>('Vault');
+ passwordHashBase64 = Buffer.from(passwordHash).toString('base64');
- // Get the derived key as base64 string required for decryption.
- const passwordHashBase64 = Buffer.from(passwordHash).toString('base64');
+ // Set offline mode
+ await dbContext.setIsOffline(true);
+ }
// Store the encryption key in session storage.
await dbContext.storeEncryptionKey(passwordHashBase64);
- // Initialize the SQLite context with the new vault data.
- const sqliteClient = await dbContext.initializeDatabase(vaultResponseJson, passwordHashBase64);
+ if (vaultResponseJson) {
+ // Online mode: Initialize the SQLite context with the new vault data from server.
+ const sqliteClient = await dbContext.initializeDatabase(vaultResponseJson, passwordHashBase64);
- // Check if there are pending migrations
- if (await sqliteClient.hasPendingMigrations()) {
- navigate('/upgrade', { replace: true });
- hideLoading();
- return;
+ // Check if there are pending migrations
+ if (await sqliteClient.hasPendingMigrations()) {
+ navigate('/upgrade', { replace: true });
+ hideLoading();
+ return;
+ }
+ } else {
+ /*
+ * Offline mode: Get vault from local storage and decrypt it.
+ * The vault response from background already includes the decrypted vault.
+ */
+ const vaultResponse = await sendMessage('GET_VAULT', {}, 'background') as { success: boolean; vault?: string; error?: string };
+
+ if (!vaultResponse.success || !vaultResponse.vault) {
+ // Decryption failed - likely wrong password
+ setError(t('auth.errors.wrongPassword'));
+ hideLoading();
+ return;
+ }
+
+ // Initialize SQLite client with the decrypted vault and set it in dbContext
+ const sqliteClient = await dbContext.initializeDatabaseFromDecryptedVault(vaultResponse.vault);
+
+ // Check if there are pending migrations
+ if (await sqliteClient.hasPendingMigrations()) {
+ navigate('/upgrade', { replace: true });
+ hideLoading();
+ return;
+ }
}
// Clear dismiss until
@@ -293,7 +357,7 @@ const Unlock: React.FC = () => {
};
/**
- * Handle PIN unlock
+ * Handle PIN unlock (supports both online and offline mode)
*/
const handlePinUnlock = async (pinToUse: string = pin): Promise<void> => {
if (pinToUse.length !== pinLength) {
@@ -304,23 +368,48 @@ const Unlock: React.FC = () => {
showLoading();
try {
- // Unlock with PIN
+ // Unlock with PIN - this derives the encryption key from the PIN
const passwordHashBase64 = await unlockWithPin(pinToUse);
- // Get latest vault from API
- const vaultResponseJson = await webApi.get<VaultResponse>('Vault');
+ // Check if we're online or offline
+ const statusResult = await checkStatus();
// Store the encryption key in session storage
await dbContext.storeEncryptionKey(passwordHashBase64);
- // Initialize the SQLite context with the vault data
- const sqliteClient = await dbContext.initializeDatabase(vaultResponseJson, passwordHashBase64);
+ if (statusResult.online) {
+ // Online mode: Get latest vault from API
+ const vaultResponseJson = await webApi.get<VaultResponse>('Vault');
- // Check if there are pending migrations
- if (await sqliteClient.hasPendingMigrations()) {
- navigate('/upgrade', { replace: true });
- hideLoading();
- return;
+ // Initialize the SQLite context with the vault data
+ const sqliteClient = await dbContext.initializeDatabase(vaultResponseJson, passwordHashBase64);
+
+ // Check if there are pending migrations
+ if (await sqliteClient.hasPendingMigrations()) {
+ navigate('/upgrade', { replace: true });
+ hideLoading();
+ return;
+ }
+ } else {
+ // Offline mode: Get vault from local storage and decrypt it
+ await dbContext.setIsOffline(true);
+
+ const vaultResponse = await sendMessage('GET_VAULT', {}, 'background') as { success: boolean; vault?: string; error?: string };
+
+ if (!vaultResponse.success || !vaultResponse.vault) {
+ // Decryption failed - likely wrong PIN
+ throw new IncorrectPinError(3); // Fallback to show incorrect PIN error
+ }
+
+ // Initialize SQLite client with the decrypted vault and set it in dbContext
+ const sqliteClient = await dbContext.initializeDatabaseFromDecryptedVault(vaultResponse.vault);
+
+ // Check if there are pending migrations
+ if (await sqliteClient.hasPendingMigrations()) {
+ navigate('/upgrade', { replace: true });
+ hideLoading();
+ return;
+ }
}
// Clear dismiss until
@@ -582,17 +671,19 @@ const Unlock: React.FC = () => {
{t('auth.unlockVault')}
</Button>
- {/* Mobile Unlock Button */}
- <button
- type="button"
- onClick={() => setShowMobileUnlockModal(true)}
- className="w-full max-w-md mt-4 px-4 py-2 text-sm font-medium text-center text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-100 focus:ring-4 focus:ring-gray-200 dark:bg-gray-600 dark:text-white dark:border-gray-500 dark:hover:bg-gray-500 dark:focus:ring-gray-700 flex items-center justify-center gap-2"
- >
- <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"></path>
- </svg>
- {t('auth.unlockWithMobile')}
- </button>
+ {/* Mobile Unlock Button - only show when server is online */}
+ {isServerOnline && (
+ <button
+ type="button"
+ onClick={() => setShowMobileUnlockModal(true)}
+ className="w-full max-w-md mt-4 px-4 py-2 text-sm font-medium text-center text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-100 focus:ring-4 focus:ring-gray-200 dark:bg-gray-600 dark:text-white dark:border-gray-500 dark:hover:bg-gray-500 dark:focus:ring-gray-700 flex items-center justify-center gap-2"
+ >
+ <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"></path>
+ </svg>
+ {t('auth.unlockWithMobile')}
+ </button>
+ )}
<div className="text-center text-sm text-gray-500 dark:text-gray-400 mt-6">
{t('auth.switchAccounts')} <button type="button" onClick={handleLogout} className="text-primary-600 hover:text-primary-700 dark:text-primary-500 dark:hover:text-primary-400 hover:underline font-medium">{t('auth.logout')}</button>
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/credentials/CredentialsList.tsx b/apps/browser-extension/src/entrypoints/popup/pages/credentials/CredentialsList.tsx
index e657a5bdd..4d95b625b 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/credentials/CredentialsList.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/credentials/CredentialsList.tsx
@@ -111,8 +111,8 @@ const CredentialsList: React.FC = () => {
/**
* On offline.
*/
- _onOffline: () => {
- // Not implemented for browser extension yet.
+ onOffline: () => {
+ // Continue with local vault in offline mode.
},
/**
* On error.
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemsList.tsx b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemsList.tsx
index 9b01de687..fbe5ddafb 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemsList.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemsList.tsx
@@ -172,8 +172,8 @@ const ItemsList: React.FC = () => {
/**
* On offline.
*/
- _onOffline: () => {
- // Not implemented for browser extension yet.
+ onOffline: () => {
+ // Continue with local vault in offline mode.
},
/**
* On error.
diff --git a/apps/browser-extension/src/i18n/locales/en.json b/apps/browser-extension/src/i18n/locales/en.json
index fe3b62ddd..c4261bd71 100644
--- a/apps/browser-extension/src/i18n/locales/en.json
+++ b/apps/browser-extension/src/i18n/locales/en.json
@@ -99,6 +99,10 @@
"syncingUpdatedVault": "Syncing updated vault",
"executingOperation": "Executing operation...",
"loadMore": "Load more",
+ "offline": "Offline",
+ "offlineMode": "Operating in offline mode",
+ "offlineModeSaved": "Changes saved locally (offline)",
+ "mergingVaultChanges": "Merging vault changes...",
"errors": {
"serverNotAvailable": "The AliasVault server is not available. Please try again later or contact support if the problem persists.",
"clientVersionNotSupported": "This version of the AliasVault browser extension is not supported by the server anymore. Please update your browser extension to the latest version.",
@@ -109,7 +113,10 @@
"unknownErrorTryAgain": "An unknown error occurred. Please try again.",
"vaultNotAvailable": "Vault not available",
"vaultIsLocked": "Vault is locked",
- "passwordChanged": "Your password has changed since the last time you logged in. Please login again for security reasons."
+ "passwordChanged": "Your password has changed since the last time you logged in. Please login again for security reasons.",
+ "syncConflictMaxRetries": "Could not sync vault after multiple attempts. Please try again later.",
+ "mergeFailed": "Failed to merge vault changes. Please try again.",
+ "legacyMergeRequired": "Vault merge required. Please login via the web app to merge the pending updates to your vault."
},
"apiErrors": {
"UNKNOWN_ERROR": "An unknown error occurred. Please try again.",
diff --git a/apps/browser-extension/src/utils/VaultMergeService.ts b/apps/browser-extension/src/utils/VaultMergeService.ts
new file mode 100644
index 000000000..23cbe123a
--- /dev/null
+++ b/apps/browser-extension/src/utils/VaultMergeService.ts
@@ -0,0 +1,402 @@
+import initSqlJs, { Database } from 'sql.js';
+
+/**
+ * Entity record from a SyncableEntity table.
+ * All entities extending SyncableEntity have these fields.
+ */
+interface ISyncableRecord {
+ Id: string;
+ CreatedAt: string;
+ UpdatedAt: string;
+ IsDeleted: number; // SQLite stores booleans as 0/1
+}
+
+/**
+ * Item record with additional deletion tracking fields.
+ */
+interface IItemRecord extends ISyncableRecord {
+ DeletedAt: string | null;
+}
+
+/**
+ * Result of a merge operation.
+ */
+export interface IMergeResult {
+ success: boolean;
+ mergedVaultBase64: string;
+ stats: IMergeStats;
+}
+
+/**
+ * Statistics about what was merged.
+ */
+export interface IMergeStats {
+ tablesProcessed: number;
+ recordsFromLocal: number;
+ recordsFromServer: number;
+ recordsCreatedLocally: number;
+ conflicts: number;
+}
+
+/**
+ * Configuration for a syncable table.
+ */
+interface ITableConfig {
+ name: string;
+ primaryKey: string;
+ isItemTable?: boolean; // Special handling for Item.DeletedAt
+}
+
+/**
+ * All tables that extend SyncableEntity and need LWW merge.
+ */
+const SYNCABLE_TABLES: ITableConfig[] = [
+ { name: 'Items', primaryKey: 'Id', isItemTable: true },
+ { name: 'FieldValues', primaryKey: 'Id' },
+ { name: 'Folders', primaryKey: 'Id' },
+ { name: 'Tags', primaryKey: 'Id' },
+ { name: 'ItemTags', primaryKey: 'Id' },
+ { name: 'Attachments', primaryKey: 'Id' },
+ { name: 'TotpCodes', primaryKey: 'Id' },
+ { name: 'Passkeys', primaryKey: 'Id' },
+ { name: 'FieldDefinitions', primaryKey: 'Id' },
+ { name: 'FieldHistories', primaryKey: 'Id' },
+ { name: 'Logos', primaryKey: 'Id' },
+];
+
+/**
+ * Service for merging two vault SQLite databases using Last-Write-Wins (LWW) strategy.
+ *
+ * The merge uses UpdatedAt timestamps on all SyncableEntity records to determine
+ * which version of a record wins in case of conflict.
+ */
+export class VaultMergeService {
+ /**
+ * Merge local vault changes with server vault using LWW strategy.
+ *
+ * @param localVaultBase64 - The local vault (with offline changes) as base64 SQLite
+ * @param serverVaultBase64 - The server vault (latest version) as base64 SQLite
+ * @returns MergeResult with the merged vault as base64
+ */
+ public async merge(localVaultBase64: string, serverVaultBase64: string): Promise<IMergeResult> {
+ const stats: IMergeStats = {
+ tablesProcessed: 0,
+ recordsFromLocal: 0,
+ recordsFromServer: 0,
+ recordsCreatedLocally: 0,
+ conflicts: 0,
+ };
+
+ try {
+ // Initialize SQL.js
+ const SQL = await initSqlJs({
+ /**
+ * Locate the SQL.js WASM file.
+ * @param file - The file name to locate
+ * @returns The path to the file
+ */
+ locateFile: (file: string) => `src/${file}`
+ });
+
+ // Load both databases
+ const localDb = this.loadDatabase(SQL, localVaultBase64);
+ const serverDb = this.loadDatabase(SQL, serverVaultBase64);
+
+ /*
+ * We'll merge INTO the local database (which has our changes)
+ * by comparing with server and updating where server wins.
+ */
+ for (const tableConfig of SYNCABLE_TABLES) {
+ try {
+ await this.mergeTable(localDb, serverDb, tableConfig, stats);
+ stats.tablesProcessed++;
+ } catch (error) {
+ // Table might not exist in one of the databases (schema mismatch)
+ console.warn(`Skipping table ${tableConfig.name} during merge:`, error);
+ }
+ }
+
+ // Export the merged database
+ const mergedVaultBase64 = this.exportDatabase(localDb);
+
+ // Clean up
+ localDb.close();
+ serverDb.close();
+
+ return {
+ success: true,
+ mergedVaultBase64,
+ stats,
+ };
+ } catch (error) {
+ console.error('Vault merge failed:', error);
+ throw error;
+ }
+ }
+
+ /**
+ * Load a SQLite database from base64 string.
+ * @param SQL - The SQL.js instance
+ * @param base64String - The base64 encoded database
+ * @returns The loaded Database instance
+ */
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ private loadDatabase(SQL: any, base64String: string): Database {
+ const binaryString = atob(base64String);
+ const bytes = new Uint8Array(binaryString.length);
+ for (let i = 0; i < binaryString.length; i++) {
+ bytes[i] = binaryString.charCodeAt(i);
+ }
+ return new SQL.Database(bytes);
+ }
+
+ /**
+ * Export a SQLite database to base64 string.
+ * @param db - The database to export
+ * @returns The base64 encoded database
+ */
+ private exportDatabase(db: Database): string {
+ db.run('VACUUM');
+ const binaryArray = db.export();
+ let binaryString = '';
+ for (let i = 0; i < binaryArray.length; i++) {
+ binaryString += String.fromCharCode(binaryArray[i]);
+ }
+ return btoa(binaryString);
+ }
+
+ /**
+ * Merge a single table using LWW strategy.
+ * @param localDb - The local database
+ * @param serverDb - The server database
+ * @param tableConfig - Configuration for the table
+ * @param stats - Statistics to update
+ */
+ private async mergeTable(
+ localDb: Database,
+ serverDb: Database,
+ tableConfig: ITableConfig,
+ stats: IMergeStats
+ ): Promise<void> {
+ const { name: tableName, primaryKey: _primaryKey, isItemTable } = tableConfig;
+
+ // Get all records from both databases
+ const localRecords = this.getTableRecords(localDb, tableName);
+ const serverRecords = this.getTableRecords(serverDb, tableName);
+
+ // Create a map of server records by primary key for quick lookup
+ const serverMap = new Map<string, ISyncableRecord>();
+ for (const record of serverRecords) {
+ serverMap.set(record.Id, record);
+ }
+
+ // Process local records
+ for (const localRecord of localRecords) {
+ const serverRecord = serverMap.get(localRecord.Id);
+
+ if (!serverRecord) {
+ // Record only exists locally (created offline) - keep it
+ stats.recordsCreatedLocally++;
+ continue;
+ }
+
+ // Record exists in both - compare UpdatedAt for LWW
+ const localUpdated = new Date(localRecord.UpdatedAt).getTime();
+ const serverUpdated = new Date(serverRecord.UpdatedAt).getTime();
+
+ if (serverUpdated > localUpdated) {
+ // Server wins - update local with server data
+ stats.conflicts++;
+ stats.recordsFromServer++;
+
+ if (isItemTable) {
+ this.updateItemRecord(localDb, tableName, serverRecord as IItemRecord, serverDb);
+ } else {
+ this.updateRecord(localDb, tableName, serverRecord, serverDb);
+ }
+ } else {
+ // Local wins - keep local (already there)
+ stats.recordsFromLocal++;
+ }
+
+ // Remove from server map to track what's been processed
+ serverMap.delete(localRecord.Id);
+ }
+
+ // Insert server-only records into local (new records from other devices)
+ for (const serverRecord of serverMap.values()) {
+ stats.recordsFromServer++;
+ if (isItemTable) {
+ this.insertItemRecord(localDb, tableName, serverRecord as IItemRecord, serverDb);
+ } else {
+ this.insertRecord(localDb, tableName, serverRecord, serverDb);
+ }
+ }
+ }
+
+ /**
+ * Get all records from a table.
+ * @param db - The database to query
+ * @param tableName - The name of the table
+ * @returns Array of records from the table
+ */
+ private getTableRecords(db: Database, tableName: string): ISyncableRecord[] {
+ const stmt = db.prepare(`SELECT * FROM ${tableName}`);
+ const records: ISyncableRecord[] = [];
+
+ while (stmt.step()) {
+ records.push(stmt.getAsObject() as unknown as ISyncableRecord);
+ }
+ stmt.free();
+
+ return records;
+ }
+
+ /**
+ * Get column names for a table (excluding computed columns).
+ * @param db - The database to query
+ * @param tableName - The name of the table
+ * @returns Array of column names
+ */
+ private getTableColumns(db: Database, tableName: string): string[] {
+ const stmt = db.prepare(`PRAGMA table_info(${tableName})`);
+ const columns: string[] = [];
+
+ while (stmt.step()) {
+ const col = stmt.getAsObject() as { name: string };
+ columns.push(col.name);
+ }
+ stmt.free();
+
+ return columns;
+ }
+
+ /**
+ * Update a record in local database with data from server.
+ * @param localDb - The local database
+ * @param tableName - The name of the table
+ * @param serverRecord - The record from server
+ * @param serverDb - The server database (for schema info)
+ */
+ private updateRecord(
+ localDb: Database,
+ tableName: string,
+ serverRecord: ISyncableRecord,
+ serverDb: Database
+ ): void {
+ const columns = this.getTableColumns(serverDb, tableName);
+
+ // Build UPDATE statement
+ const setClause = columns
+ .filter(col => col !== 'Id')
+ .map(col => `${col} = ?`)
+ .join(', ');
+
+ const values = columns
+ .filter(col => col !== 'Id')
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ .map(col => (serverRecord as any)[col]);
+
+ values.push(serverRecord.Id); // For WHERE clause
+
+ const sql = `UPDATE ${tableName} SET ${setClause} WHERE Id = ?`;
+ localDb.run(sql, values);
+ }
+
+ /**
+ * Update an Item record with special handling for DeletedAt.
+ * @param localDb - The local database
+ * @param tableName - The name of the table
+ * @param serverRecord - The record from server
+ * @param serverDb - The server database (for schema info)
+ */
+ private updateItemRecord(
+ localDb: Database,
+ tableName: string,
+ serverRecord: IItemRecord,
+ serverDb: Database
+ ): void {
+ // For Item table, use same update logic but server record includes DeletedAt
+ this.updateRecord(localDb, tableName, serverRecord, serverDb);
+ }
+
+ /**
+ * Insert a new record from server into local database.
+ * @param localDb - The local database
+ * @param tableName - The name of the table
+ * @param serverRecord - The record from server
+ * @param serverDb - The server database (for schema info)
+ */
+ private insertRecord(
+ localDb: Database,
+ tableName: string,
+ serverRecord: ISyncableRecord,
+ serverDb: Database
+ ): void {
+ const columns = this.getTableColumns(serverDb, tableName);
+
+ const columnList = columns.join(', ');
+ const placeholders = columns.map(() => '?').join(', ');
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const values = columns.map(col => (serverRecord as any)[col]);
+
+ const sql = `INSERT OR REPLACE INTO ${tableName} (${columnList}) VALUES (${placeholders})`;
+ localDb.run(sql, values);
+ }
+
+ /**
+ * Insert an Item record with special handling for DeletedAt.
+ * @param localDb - The local database
+ * @param tableName - The name of the table
+ * @param serverRecord - The record from server
+ * @param serverDb - The server database (for schema info)
+ */
+ private insertItemRecord(
+ localDb: Database,
+ tableName: string,
+ serverRecord: IItemRecord,
+ serverDb: Database
+ ): void {
+ // For Item table, use same insert logic
+ this.insertRecord(localDb, tableName, serverRecord, serverDb);
+ }
+
+ /**
+ * Resolve deletion conflicts for Item records.
+ *
+ * Rules:
+ * - IsDeleted=true (permanent delete) is "sticky" unless restored with later UpdatedAt
+ * - DeletedAt (moved to trash) follows LWW
+ * @param local - The local record
+ * @param server - The server record
+ * @returns The resolved record
+ */
+ public resolveItemDeletionConflict(local: IItemRecord, server: IItemRecord): IItemRecord {
+ const localUpdated = new Date(local.UpdatedAt).getTime();
+ const serverUpdated = new Date(server.UpdatedAt).getTime();
+
+ // Standard LWW for the base winner
+ const winner = serverUpdated > localUpdated ? { ...server } : { ...local };
+
+ /*
+ * Special handling for IsDeleted (permanent delete)
+ * If both are deleted, stay deleted
+ */
+ if (local.IsDeleted && server.IsDeleted) {
+ winner.IsDeleted = 1;
+ } else if (local.IsDeleted && localUpdated > serverUpdated) {
+ // If only one is deleted, the delete wins if it's newer
+ winner.IsDeleted = 1;
+ } else if (server.IsDeleted && serverUpdated > localUpdated) {
+ winner.IsDeleted = 1;
+ }
+ // Otherwise, the non-deleted (restore) wins if it's newer
+
+ return winner;
+ }
+}
+
+/**
+ * Singleton instance for the vault merge service.
+ */
+export const vaultMergeService = new VaultMergeService();