Skip to content

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

Tweak RPO recovery for browser extension and mobile app to prevent login errors with stale data (#1719)

Leendert de Borst03b91ababac1
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
index 5c3aa3d82..8ee616c11 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
@@ -63,49 +63,59 @@ const Login: React.FC = () => {
/**
* Helper to persist and load vault after successful authentication.
* Checks if local vault exists from forced logout and preserves it if more advanced.
+ * Also checks if the vault belongs to the same user - if different user, uses server vault.
*/
- const persistAndLoadVault = async (vaultResponse: VaultResponse, encryptionKey: string): Promise<void> => {
+ const persistAndLoadVault = async (vaultResponse: VaultResponse, encryptionKey: string, loginUsername: string): Promise<void> => {
// Check if there's existing vault data (from forced logout)
const existingVault = await storage.getItem('local:encryptedVault') as string | null;
const existingRevision = await storage.getItem('local:serverRevision') as number | null;
+ const storedUsername = await storage.getItem('local:username') as string | null;
let vaultToLoad = vaultResponse.vault.blob;
if (existingVault && existingRevision !== null) {
- // Try to decrypt existing vault to verify it's valid
- try {
- const decryptedExisting = await EncryptionUtility.symmetricDecrypt(existingVault, encryptionKey);
+ // Check if the existing vault belongs to a different user
+ const normalizedLoginUsername = loginUsername.toLowerCase().trim();
+ const normalizedStoredUsername = storedUsername?.toLowerCase().trim();
- // Check if existing vault is more advanced than server
- if (existingRevision >= vaultResponse.vault.currentRevisionNumber) {
+ if (storedUsername && normalizedStoredUsername !== normalizedLoginUsername) {
+ // Different user
+ console.info(
+ `Existing vault belongs to different user (${storedUsername}), using server vault for ${loginUsername}`
+ );
+ } else {
+ // Same user (or no stored username)
+ try {
+ const decryptedExisting = await EncryptionUtility.symmetricDecrypt(existingVault, encryptionKey);
+
+ // Check if existing vault is more advanced than server
+ if (existingRevision >= vaultResponse.vault.currentRevisionNumber) {
+ console.info(
+ `Existing vault is more advanced (rev ${existingRevision} >= ${vaultResponse.vault.currentRevisionNumber}), ` +
+ `preserving local vault and will upload to server`
+ );
+
+ // Update metadata and load existing vault
+ vaultToLoad = existingVault;
+ await sendMessage('STORE_VAULT_METADATA', {
+ publicEmailDomainList: vaultResponse.vault.publicEmailDomainList,
+ privateEmailDomainList: vaultResponse.vault.privateEmailDomainList,
+ hiddenPrivateEmailDomainList: vaultResponse.vault.hiddenPrivateEmailDomainList,
+ }, 'background');
+
+ await dbContext.loadDatabase(decryptedExisting);
+ return;
+ }
+
+ // Server is more advanced, fetch server vault
console.info(
- `Existing vault is more advanced (rev ${existingRevision} >= ${vaultResponse.vault.currentRevisionNumber}), ` +
- `preserving local vault and will upload to server`
+ `Server vault is more advanced (rev ${vaultResponse.vault.currentRevisionNumber} > ${existingRevision}), ` +
+ `using server vault`
);
-
- /*
- * Don't overwrite the vault - it will be uploaded via sync flow
- * Just update metadata and load existing vault
- */
- vaultToLoad = existingVault;
- await sendMessage('STORE_VAULT_METADATA', {
- publicEmailDomainList: vaultResponse.vault.publicEmailDomainList,
- privateEmailDomainList: vaultResponse.vault.privateEmailDomainList,
- hiddenPrivateEmailDomainList: vaultResponse.vault.hiddenPrivateEmailDomainList,
- }, 'background');
-
- await dbContext.loadDatabase(decryptedExisting);
- return;
+ } catch {
+ // Decryption failed, password changed or corrupt vault
+ console.info('Existing vault could not be decrypted (password changed), using server vault');
}
-
- // Server is more advanced - will overwrite local
- console.info(
- `Server vault is more advanced (rev ${vaultResponse.vault.currentRevisionNumber} > ${existingRevision}), ` +
- `using server vault`
- );
- } catch {
- // Decryption failed - password changed or corrupt vault
- console.info('Existing vault could not be decrypted (password changed), using server vault');
}
}
@@ -155,11 +165,12 @@ const Login: React.FC = () => {
/*
* Persist and load the vault.
* If there was a forced logout, persistAndLoadVault checks existing vault data:
+ * - If different user → uses server vault
* - If local vault is more advanced → preserves it (will upload via sync in /reinitialize)
* - If server is more advanced → uses server vault
* - If password changed (can't decrypt) → uses server vault
*/
- await persistAndLoadVault(vaultResponseJson, passwordHashBase64);
+ await persistAndLoadVault(vaultResponseJson, passwordHashBase64, username);
// Reset prefill flag so next logout will prefill again
usernamePrefillAttempted = false;
@@ -429,7 +440,7 @@ const Login: React.FC = () => {
});
// Persist and load the vault
- await persistAndLoadVault(vaultResponse, result.decryptionKey);
+ await persistAndLoadVault(vaultResponse, result.decryptionKey, result.username);
/*
* Navigate to reinitialize page which will:
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
index 7d7037ef5..fc26c7023 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
@@ -1477,18 +1477,32 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
}
/**
- * Reset sync state to force a fresh download on next sync.
- * Clears isDirty flag so sync will download instead of trying to merge.
+ * Clear encrypted vault and reset sync state to force a fresh download on next sync.
+ * Deletes the corrupted vault and resets sync state so sync will download fresh.
+ * Called when existing vault cannot be decrypted (e.g. password changed).
* @param promise The promise to resolve when complete.
*/
@ReactMethod
- override fun resetSyncStateForFreshDownload(promise: Promise) {
+ override fun clearEncryptedVaultForFreshDownload(promise: Promise) {
try {
+ // Delete only the encrypted database file (not all storage)
+ val encryptedDbFile = java.io.File(reactApplicationContext.filesDir, "encrypted_database.db")
+ if (encryptedDbFile.exists()) {
+ encryptedDbFile.delete()
+ Log.d(TAG, "Deleted corrupted encrypted database for fresh download")
+ }
+
+ // Close in-memory database connection if open
+ vaultStore.clearCache()
+
+ // Reset sync state - set isDirty=false and revision=0 so sync sees server as newer
vaultStore.metadata.setIsDirty(false)
+ vaultStore.setVaultRevisionNumber(0)
+
promise.resolve(null)
} catch (e: Exception) {
- Log.e(TAG, "Error resetting sync state", e)
- promise.reject("ERR_RESET_SYNC_STATE", "Failed to reset sync state: ${e.message}", e)
+ Log.e(TAG, "Error clearing encrypted vault for fresh download", e)
+ promise.reject("ERR_CLEAR_VAULT_FOR_DOWNLOAD", "Failed to clear vault for fresh download: ${e.message}", e)
}
}
diff --git a/apps/mobile-app/app/login.tsx b/apps/mobile-app/app/login.tsx
index 87d8ec133..ce7d18f57 100644
--- a/apps/mobile-app/app/login.tsx
+++ b/apps/mobile-app/app/login.tsx
@@ -253,26 +253,29 @@ export default function LoginScreen() : React.ReactNode {
/*
* Forced logout recovery check:
* If there's an existing local vault (from forced logout), try to unlock it.
+ * First check if it belongs to the same user - if different user, clear and download fresh.
* If decryption fails (password changed or corrupted), reset sync state so
* sync will do a clean download instead of trying to merge.
*/
const hasExistingVault = await NativeVaultManager.hasEncryptedDatabase();
if (hasExistingVault) {
- try {
- await NativeVaultManager.unlockVault();
- /*
- * Decryption succeeded - local vault is valid, sync will handle it.
- * The sync will compare revisions and decide whether to keep local or download.
- */
- console.info('Existing local vault (after forced logout) decrypted successfully, syncing with server');
- } catch {
- /*
- * Decryption failed (password changed or corrupted).
- * Reset sync state so sync will do a clean download instead of trying to merge.
- * This matches the browser extension behavior in persistAndLoadVault().
- */
- console.info('Existing vault could not be decrypted (password changed or corrupted), resetting for fresh download');
- await NativeVaultManager.resetSyncStateForFreshDownload();
+ const storedUsername = await NativeVaultManager.getUsername();
+ const normalizedLoginUsername = ConversionUtility.normalizeUsername(credentials.username);
+
+ if (storedUsername && storedUsername !== normalizedLoginUsername) {
+ // Different user: clear vault and download fresh
+ console.info(`Existing vault belongs to different user (${storedUsername}), clearing for fresh download`);
+ await NativeVaultManager.clearEncryptedVaultForFreshDownload();
+ } else {
+ try {
+ await NativeVaultManager.unlockVault();
+ // Decryption succeeded, local vault is valid, sync will handle it
+ console.info('Existing local vault (after forced logout) decrypted successfully, syncing with server');
+ } catch {
+ // Decryption failed (password changed or corrupted), clear vault and download fresh
+ console.info('Existing vault could not be decrypted (password changed or corrupted), clearing for fresh download');
+ await NativeVaultManager.clearEncryptedVaultForFreshDownload();
+ }
}
}
diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
index 1fe241305..1304f4574 100644
--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
@@ -255,8 +255,8 @@
[vaultManager markVaultClean:(NSInteger)mutationSeqAtStart newServerRevision:(NSInteger)newServerRevision resolver:resolve rejecter:reject];
}
-- (void)resetSyncStateForFreshDownload:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
- [vaultManager resetSyncStateForFreshDownload:resolve rejecter:reject];
+- (void)clearEncryptedVaultForFreshDownload:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager clearEncryptedVaultForFreshDownload:resolve rejecter:reject];
}
// MARK: - PIN Unlock
diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
index 270bf2320..995c4bc31 100644
--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
@@ -937,9 +937,22 @@ public class VaultManager: NSObject {
}
@objc
- func resetSyncStateForFreshDownload(_ resolve: @escaping RCTPromiseResolveBlock,
- rejecter reject: @escaping RCTPromiseRejectBlock) {
+ func clearEncryptedVaultForFreshDownload(_ resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ do {
+ try vaultStore.removeEncryptedDatabase()
+ print("Deleted corrupted encrypted database for fresh download")
+ } catch {
+ print("Could not delete encrypted database (may not exist): \(error)")
+ }
+
+ // Close in-memory database connection if open
+ vaultStore.clearCache()
+
+ // Reset sync state - set isDirty=false and revision=0 so sync sees server as newer
vaultStore.setIsDirty(false)
+ vaultStore.setCurrentVaultRevisionNumber(0)
+
resolve(nil)
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift
index 0fca3647b..1fbefe588 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift
@@ -45,7 +45,7 @@ extension VaultStore {
}
/// Remove the encrypted database from the local filesystem
- internal func removeEncryptedDatabase() throws {
+ public func removeEncryptedDatabase() throws {
try FileManager.default.removeItem(at: getEncryptedDbPath())
}
diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.ts
index e1bc92bba..293433c3c 100644
--- a/apps/mobile-app/specs/NativeVaultManager.ts
+++ b/apps/mobile-app/specs/NativeVaultManager.ts
@@ -29,7 +29,7 @@ export interface Spec extends TurboModule {
// Sync state management (kept for local mutation tracking)
getSyncState(): Promise<{isDirty: boolean; mutationSequence: number; serverRevision: number; isSyncing: boolean}>;
markVaultClean(mutationSeqAtStart: number, newServerRevision: number): Promise<boolean>;
- resetSyncStateForFreshDownload(): Promise<void>; // Clears isDirty to force clean download on next sync
+ clearEncryptedVaultForFreshDownload(): Promise<void>; // Deletes corrupted vault and resets sync state to force fresh download
// Vault SQL operations
executeQuery(query: string, params: (string | number | null)[]): Promise<string[]>;