Skip to content

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

Add RPO recovery logic to RN and iOS app (#1404)

Leendert de Borst5d05a7ca073b
diff --git a/apps/mobile-app/app/(tabs)/settings/index.tsx b/apps/mobile-app/app/(tabs)/settings/index.tsx
index ffe591b22..a89d7e237 100644
--- a/apps/mobile-app/app/(tabs)/settings/index.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/index.tsx
@@ -18,6 +18,9 @@ import { InlineSkeletonLoader } from '@/components/ui/InlineSkeletonLoader';
import { TitleContainer } from '@/components/ui/TitleContainer';
import { UsernameDisplay } from '@/components/ui/UsernameDisplay';
import { useApp } from '@/context/AppContext';
+import { useAuth } from '@/context/AuthContext';
+import { useDb } from '@/context/DbContext';
+import { useWebApi } from '@/context/WebApiContext';
/**
* Settings screen.
@@ -26,8 +29,11 @@ export default function SettingsScreen() : React.ReactNode {
const colors = useColors();
const { t } = useTranslation();
const insets = useSafeAreaInsets();
- const { getAuthMethodDisplayKey, shouldShowAutofillReminder, logout } = useApp();
+ const { getAuthMethodDisplayKey, shouldShowAutofillReminder } = useApp();
const { getAutoLockTimeout, getClipboardClearTimeout } = useApp();
+ const { clearAuthUserInitiated } = useAuth();
+ const { isDirty } = useDb();
+ const webApi = useWebApi();
const { loadApiUrl, getDisplayUrl } = useApiUrl();
const scrollY = useRef(new Animated.Value(0)).current;
const scrollViewRef = useRef<ScrollView>(null);
@@ -107,26 +113,53 @@ export default function SettingsScreen() : React.ReactNode {
);
/**
- * Handle the logout.
+ * Perform the actual logout - revokes tokens and clears auth.
+ */
+ const performLogout = async () : Promise<void> => {
+ try {
+ await webApi.revokeTokens();
+ } catch (error) {
+ console.error('Error revoking tokens:', error);
+ // Continue with logout even if revoke fails
+ }
+ await clearAuthUserInitiated();
+ router.replace('/login');
+ };
+
+ /**
+ * Handle the logout button press.
+ * Shows warning if there are unsynced changes, otherwise shows normal confirmation.
*/
const handleLogout = async () : Promise<void> => {
- // Show native confirmation dialog
- Alert.alert(
- t('auth.logout'),
- t('auth.confirmLogout'),
- [
- { text: t('common.cancel'), style: 'cancel' },
- { text: t('auth.logout'), style: 'destructive',
- /**
- * Handle the logout.
- */
- onPress: async () : Promise<void> => {
- await logout();
- router.replace('/login');
- }
- },
- ]
- );
+ if (isDirty) {
+ // Show warning about unsynced changes
+ Alert.alert(
+ t('logout.unsyncedChangesTitle'),
+ t('logout.unsyncedChangesWarning'),
+ [
+ { text: t('common.cancel'), style: 'cancel' },
+ {
+ text: t('logout.logoutAnyway'),
+ style: 'destructive',
+ onPress: performLogout,
+ },
+ ]
+ );
+ } else {
+ // Show normal confirmation dialog
+ Alert.alert(
+ t('auth.logout'),
+ t('auth.confirmLogout'),
+ [
+ { text: t('common.cancel'), style: 'cancel' },
+ {
+ text: t('auth.logout'),
+ style: 'destructive',
+ onPress: performLogout,
+ },
+ ]
+ );
+ }
};
/**
diff --git a/apps/mobile-app/app/login-settings.tsx b/apps/mobile-app/app/login-settings.tsx
index f18278c05..e3d24fd7d 100644
--- a/apps/mobile-app/app/login-settings.tsx
+++ b/apps/mobile-app/app/login-settings.tsx
@@ -192,6 +192,7 @@ export default function SettingsScreen() : React.ReactNode {
selectedOption === option.value && styles.optionButtonSelected
]}
onPress={() => handleOptionChange(option.value)}
+ testID={`api-option-${option.value === 'custom' ? 'custom' : 'default'}`}
>
<Text style={[
styles.optionButtonText,
diff --git a/apps/mobile-app/context/AppContext.tsx b/apps/mobile-app/context/AppContext.tsx
index 3c8493ed3..000fcbd81 100644
--- a/apps/mobile-app/context/AppContext.tsx
+++ b/apps/mobile-app/context/AppContext.tsx
@@ -49,7 +49,8 @@ export const AppProvider: React.FC<{ children: React.ReactNode }> = ({ children
const isLoggingOutRef = useRef(false);
/**
- * Logout the user by revoking tokens and clearing the auth tokens from storage.
+ * Logout the user (forced logout path - e.g., 401, token revocation).
+ * Uses clearAuthForced to preserve vault data for potential RPO recovery.
* Prevents recursive logout calls by tracking logout state.
*/
const logout = useCallback(async (errorMessage?: string): Promise<void> => {
@@ -61,7 +62,8 @@ export const AppProvider: React.FC<{ children: React.ReactNode }> = ({ children
try {
isLoggingOutRef.current = true;
await webApi.revokeTokens();
- await auth.clearAuth(errorMessage);
+ // Use forced logout to preserve vault data for recovery
+ await auth.clearAuthForced(errorMessage);
} catch (error) {
console.error('Error during logout:', error);
} finally {
diff --git a/apps/mobile-app/context/AuthContext.tsx b/apps/mobile-app/context/AuthContext.tsx
index 7a821d821..cb26676fb 100644
--- a/apps/mobile-app/context/AuthContext.tsx
+++ b/apps/mobile-app/context/AuthContext.tsx
@@ -26,7 +26,16 @@ type AuthContextType = {
setAuthTokens: (username: string, accessToken: string, refreshToken: string) => Promise<void>;
initializeAuth: () => Promise<{ isLoggedIn: boolean; enabledAuthMethods: AuthMethod[] }>;
login: () => Promise<void>;
- clearAuth: (errorMessage?: string) => Promise<void>;
+ /**
+ * Clear auth for user-initiated logout (e.g., user clicks logout button).
+ * Clears ALL data including vault - user explicitly chose to logout.
+ */
+ clearAuthUserInitiated: (errorMessage?: string) => Promise<void>;
+ /**
+ * Clear auth for forced logout (e.g., 401 error, token revocation).
+ * Preserves vault data for potential RPO recovery - user didn't choose to logout.
+ */
+ clearAuthForced: (errorMessage?: string) => Promise<void>;
setAuthMethods: (methods: AuthMethod[]) => Promise<void>;
getAuthMethodDisplayKey: () => Promise<string>;
getAutoLockTimeout: () => Promise<number>;
@@ -180,10 +189,10 @@ export const AuthProvider: React.FC<{
}, []);
/**
- * Clear authentication data and tokens from storage.
- * This is called by AppContext after revoking tokens on the server.
+ * Clear authentication data for user-initiated logout (e.g., user clicks logout button).
+ * Clears ALL data including vault - user explicitly chose to logout.
*/
- const clearAuth = useCallback(async (errorMessage?: string): Promise<void> => {
+ const clearAuthUserInitiated = useCallback(async (errorMessage?: string): Promise<void> => {
// Clear credential identity store (password and passkey autofill metadata)
try {
await NativeVaultManager.removeCredentialIdentities();
@@ -211,6 +220,7 @@ export const AuthProvider: React.FC<{
await AsyncStorage.removeItem('refreshToken');
await AsyncStorage.removeItem('authMethods');
+ // Clear ALL vault data - user explicitly chose to logout
dbContext?.clearDatabase();
if (errorMessage) {
@@ -226,6 +236,57 @@ export const AuthProvider: React.FC<{
setIsLoggedIn(false);
}, [dbContext]);
+ /**
+ * Clear authentication data for forced logout (e.g., 401 error, token revocation).
+ * Preserves vault data for potential RPO recovery - user didn't choose to logout.
+ * The vault will be recovered on next login if the password hasn't changed.
+ */
+ const clearAuthForced = useCallback(async (errorMessage?: string): Promise<void> => {
+ // Clear credential identity store (password and passkey autofill metadata)
+ try {
+ await NativeVaultManager.removeCredentialIdentities();
+ } catch (error) {
+ console.error('Failed to remove credential identities:', error);
+ // Non-fatal error - continue with logout
+ }
+
+ // Clear PIN unlock data (if any)
+ try {
+ await NativeVaultManager.removeAndDisablePin();
+ } catch (error) {
+ console.error('Failed to remove PIN data:', error);
+ // Non-fatal error - continue with logout
+ }
+
+ // Clear auth tokens only - preserve vault data for recovery
+ await NativeVaultManager.clearAuthTokens();
+
+ // Clear session in native layer (preserves vault data)
+ await NativeVaultManager.clearSession();
+
+ // Clear from AsyncStorage (for backward compatibility)
+ // TODO: Remove AsyncStorage cleanup in future version 0.25.0+
+ await AsyncStorage.removeItem('accessToken');
+ await AsyncStorage.removeItem('refreshToken');
+ await AsyncStorage.removeItem('authMethods');
+
+ // Note: We do NOT clear:
+ // - Username (preserved for login form prefill)
+ // - Vault data (preserved for potential RPO recovery)
+ // - Encryption key derivation params (needed to decrypt on re-login)
+
+ if (errorMessage) {
+ // Show alert
+ Alert.alert(
+ i18n.t('common.error'),
+ errorMessage,
+ [{ text: i18n.t('common.ok'), style: 'default' }]
+ );
+ }
+
+ setIsLoggedIn(false);
+ }, []);
+
/**
* Set the authentication methods and save them to storage
*/
@@ -441,7 +502,8 @@ export const AuthProvider: React.FC<{
setAuthTokens,
initializeAuth,
login,
- clearAuth,
+ clearAuthUserInitiated,
+ clearAuthForced,
setAuthMethods,
getAuthMethodDisplayKey,
isBiometricsEnabledOnDevice,
@@ -465,7 +527,8 @@ export const AuthProvider: React.FC<{
setAuthTokens,
initializeAuth,
login,
- clearAuth,
+ clearAuthUserInitiated,
+ clearAuthForced,
setAuthMethods,
getAuthMethodDisplayKey,
isBiometricsEnabledOnDevice,
diff --git a/apps/mobile-app/i18n/locales/en.json b/apps/mobile-app/i18n/locales/en.json
index 26b46ad1a..89f608c7a 100644
--- a/apps/mobile-app/i18n/locales/en.json
+++ b/apps/mobile-app/i18n/locales/en.json
@@ -74,6 +74,11 @@
"connectingTo": "Connecting to",
"loggedInAs": "Logged in as"
},
+ "logout": {
+ "unsyncedChangesTitle": "Unsynced Changes",
+ "unsyncedChangesWarning": "You have unsynced changes that will be lost if you log out now. Are you sure you want to continue?",
+ "logoutAnyway": "Log out anyway"
+ },
"vault": {
"syncingVault": "Syncing vault",
"uploadingVaultToServer": "Uploading vault to server",
diff --git a/apps/mobile-app/ios/AliasVault/AppDelegate.swift b/apps/mobile-app/ios/AliasVault/AppDelegate.swift
index b575e9e3a..53931d9d8 100644
--- a/apps/mobile-app/ios/AliasVault/AppDelegate.swift
+++ b/apps/mobile-app/ios/AliasVault/AppDelegate.swift
@@ -15,11 +15,16 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
- // Handle --reset-state launch argument for UI tests
+ // Handle UI test launch arguments
#if DEBUG
if ProcessInfo.processInfo.arguments.contains("--reset-state") {
resetAppState()
}
+ // Disable UIView animations for UI tests to prevent "wait for app to idle" issues
+ // React Native apps have continuous JS bridge activity that prevents XCTest idle detection
+ if ProcessInfo.processInfo.arguments.contains("--uitest") {
+ UIView.setAnimationsEnabled(false)
+ }
#endif
let delegate = ReactNativeDelegate()
diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
index 2f4d375dd..f35b24a6a 100644
--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
@@ -6,6 +6,7 @@ import VaultModels
import SwiftUI
import VaultUI
import AVFoundation
+import RustCoreFramework
/**
* This class is used as a bridge to allow React Native to interact with the VaultStoreKit class.
@@ -168,6 +169,15 @@ public class VaultManager: NSObject {
}
}
+ /// Clear session data only (for forced logout).
+ /// Preserves vault data on disk for recovery on next login.
+ @objc
+ func clearSession() {
+ vaultStore.clearSession()
+ }
+
+ /// Clear all vault data including from persisted storage.
+ /// This is used for user-initiated logout.
@objc
func clearVault() {
do {
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift
index 74cc8d49b..bfe7596c2 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift
@@ -10,7 +10,28 @@ extension VaultStore {
self.dbConnection = nil
}
+ /// Clear session data only (for forced logout).
+ /// Preserves vault data on disk for recovery on next login.
+ /// This is used when the user is forcibly logged out (e.g., 401, token revocation)
+ /// to allow recovery of unsynced local changes.
+ public func clearSession() {
+ print("Clearing session - preserving vault data for recovery")
+
+ // Clear in-memory data only
+ self.encryptionKey = nil
+ self.dbConnection = nil
+
+ // Clear biometric-protected key from keychain (user will need to re-authenticate)
+ do {
+ try removeKeyFromKeychain()
+ print("Successfully removed encryption key from keychain")
+ } catch {
+ print("Failed to remove encryption key from keychain: \(error)")
+ }
+ }
+
/// Clear the vault storage - remove the encryption key and encrypted database from the device
+ /// This is used for user-initiated logout where they explicitly choose to clear all local data.
public func clearVault() throws {
print("Clearing vault - removing all stored data")
@@ -34,12 +55,21 @@ extension VaultStore {
self.userDefaults.removeObject(forKey: VaultConstants.authMethodsKey)
self.userDefaults.removeObject(forKey: VaultConstants.autoLockTimeoutKey)
self.userDefaults.removeObject(forKey: VaultConstants.encryptionKeyDerivationParamsKey)
+ self.userDefaults.removeObject(forKey: VaultConstants.usernameKey)
+ self.userDefaults.removeObject(forKey: VaultConstants.offlineModeKey)
+ self.userDefaults.removeObject(forKey: VaultConstants.pinEnabledKey)
+ self.userDefaults.removeObject(forKey: VaultConstants.serverVersionKey)
// Clear sync state
self.userDefaults.removeObject(forKey: VaultConstants.isDirtyKey)
self.userDefaults.removeObject(forKey: VaultConstants.mutationSequenceKey)
self.userDefaults.removeObject(forKey: VaultConstants.isSyncingKey)
+ // Clear WebApiService keys (auth tokens, API URL)
+ self.userDefaults.removeObject(forKey: "apiUrl")
+ self.userDefaults.removeObject(forKey: "accessToken")
+ self.userDefaults.removeObject(forKey: "refreshToken")
+
self.userDefaults.synchronize()
print("Cleared UserDefaults")
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift
index ac424b41f..3eae902ae 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift
@@ -226,6 +226,19 @@ extension VaultStore {
mutationSeqAtStart: mutationSeqAtStart,
retryCount: retryCount
)
+ } else if serverRevision < syncState.serverRevision {
+ // Server revision DECREASED - server data loss/rollback detected.
+ // Client has more advanced revision - upload to recover server state.
+ //
+ // This will create a revision gap in server history (e.g., 95 → 101),
+ // which serves as an audit trail of the recovery event.
+ print("[VaultSync] Server data loss detected! Server at rev \(serverRevision), " +
+ "client at rev \(syncState.serverRevision). Uploading to recover server state.")
+ return await performUploadSync(
+ using: webApiService,
+ mutationSeqAtStart: mutationSeqAtStart,
+ retryCount: retryCount
+ )
} else {
// Already in sync
setIsSyncing(false)
diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.ts
index 49a403bbf..36bb719fd 100644
--- a/apps/mobile-app/specs/NativeVaultManager.ts
+++ b/apps/mobile-app/specs/NativeVaultManager.ts
@@ -19,7 +19,8 @@ export interface Spec extends TurboModule {
isVaultUnlocked(): Promise<boolean>;
getVaultMetadata(): Promise<string>;
unlockVault(): Promise<boolean>;
- clearVault(): Promise<void>;
+ clearSession(): Promise<void>; // Clears session only, preserves vault for potential RPO recovery
+ clearVault(): Promise<void>; // Clears everything including vault data
// Vault sync - single method handles all sync logic including merge
// Returns detailed result about what action was taken