Skip to content

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

Refactor app index flow, add auto lock settings (#771)

Leendert de Borstdb58bc894207
diff --git a/mobile-app/app/(tabs)/(settings)/_layout.tsx b/mobile-app/app/(tabs)/(settings)/_layout.tsx
index f7fd539b5..eb707f359 100644
--- a/mobile-app/app/(tabs)/(settings)/_layout.tsx
+++ b/mobile-app/app/(tabs)/(settings)/_layout.tsx
@@ -22,6 +22,16 @@ export default function SettingsLayout() {
},
}}
/>
+ <Stack.Screen
+ name="auto-lock"
+ options={{
+ title: 'Auto-lock Settings',
+ headerBackTitle: 'Settings',
+ headerStyle: {
+ backgroundColor: colors.headerBackground,
+ },
+ }}
+ />
</Stack>
);
}
\ No newline at end of file
diff --git a/mobile-app/app/(tabs)/(settings)/auto-lock.tsx b/mobile-app/app/(tabs)/(settings)/auto-lock.tsx
new file mode 100644
index 000000000..7c6e76489
--- /dev/null
+++ b/mobile-app/app/(tabs)/(settings)/auto-lock.tsx
@@ -0,0 +1,71 @@
+import { StyleSheet, View, TouchableOpacity } from 'react-native';
+import { ThemedText } from '@/components/ThemedText';
+import { ThemedView } from '@/components/ThemedView';
+import { useColors } from '@/hooks/useColorScheme';
+import { TitleContainer } from '@/components/TitleContainer';
+import { Ionicons } from '@expo/vector-icons';
+import { useAuth } from '@/context/AuthContext';
+
+export default function AutoLockScreen() {
+ const colors = useColors();
+ const { autoLockTimeout, setAutoLockTimeout } = useAuth();
+
+ const timeoutOptions = [
+ { label: 'Never', value: 0 },
+ { label: '1 minute', value: 60 },
+ { label: '5 minutes', value: 300 },
+ { label: '15 minutes', value: 900 },
+ { label: '30 minutes', value: 1800 },
+ { label: '1 hour', value: 3600 },
+ { label: '2 hours', value: 7200 },
+ { label: '4 hours', value: 14400 },
+ { label: '8 hours', value: 28800 },
+ ];
+
+ const styles = StyleSheet.create({
+ container: {
+ flex: 1,
+ },
+ content: {
+ flex: 1,
+ padding: 16,
+ },
+ option: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ paddingVertical: 16,
+ paddingHorizontal: 16,
+ backgroundColor: colors.accentBackground,
+ borderBottomWidth: StyleSheet.hairlineWidth,
+ borderBottomColor: colors.accentBorder,
+ },
+ optionText: {
+ flex: 1,
+ fontSize: 16,
+ color: colors.text,
+ },
+ selectedIcon: {
+ marginLeft: 8,
+ color: colors.primary,
+ },
+ });
+
+ return (
+ <ThemedView style={styles.container}>
+ <View style={styles.content}>
+ {timeoutOptions.map((option) => (
+ <TouchableOpacity
+ key={option.value}
+ style={styles.option}
+ onPress={() => setAutoLockTimeout(option.value)}
+ >
+ <ThemedText style={styles.optionText}>{option.label}</ThemedText>
+ {autoLockTimeout === option.value && (
+ <Ionicons name="checkmark" size={24} style={styles.selectedIcon} />
+ )}
+ </TouchableOpacity>
+ ))}
+ </View>
+ </ThemedView>
+ );
+}
\ No newline at end of file
diff --git a/mobile-app/app/(tabs)/(settings)/index.tsx b/mobile-app/app/(tabs)/(settings)/index.tsx
index 147cf5b35..b1d8ee852 100644
--- a/mobile-app/app/(tabs)/(settings)/index.tsx
+++ b/mobile-app/app/(tabs)/(settings)/index.tsx
@@ -16,6 +16,7 @@ export default function SettingsScreen() {
const webApi = useWebApi();
const colors = useColors();
const { username, getAuthMethodDisplay } = useAuth();
+ const { autoLockTimeout } = useAuth();
const scrollY = useRef(new Animated.Value(0)).current;
const scrollViewRef = useRef<ScrollView>(null);
@@ -28,6 +29,23 @@ export default function SettingsScreen() {
router.push('/(tabs)/(settings)/vault-unlock');
};
+ const handleAutoLockPress = () => {
+ router.push('/(tabs)/(settings)/auto-lock');
+ };
+
+ const getAutoLockDisplay = () => {
+ if (autoLockTimeout === 0) return 'Never';
+ if (autoLockTimeout === 60) return '1 minute';
+ if (autoLockTimeout === 300) return '5 minutes';
+ if (autoLockTimeout === 900) return '15 minutes';
+ if (autoLockTimeout === 1800) return '30 minutes';
+ if (autoLockTimeout === 3600) return '1 hour';
+ if (autoLockTimeout === 7200) return '2 hours';
+ if (autoLockTimeout === 14400) return '4 hours';
+ if (autoLockTimeout === 28800) return '8 hours';
+ return 'Never';
+ };
+
const styles = StyleSheet.create({
container: {
flex: 1,
@@ -168,6 +186,20 @@ export default function SettingsScreen() {
<Ionicons name="chevron-forward" size={20} color={colors.textMuted} />
</View>
</TouchableOpacity>
+
+ <TouchableOpacity
+ style={[styles.settingItem, styles.settingItemContentWithBorder]}
+ onPress={handleAutoLockPress}
+ >
+ <View style={styles.settingItemIcon}>
+ <Ionicons name="timer-outline" size={20} color={colors.text} />
+ </View>
+ <View style={[styles.settingItemContent]}>
+ <ThemedText style={styles.settingItemText}>Auto-lock Timeout</ThemedText>
+ <ThemedText style={styles.settingItemValue}>{getAutoLockDisplay()}</ThemedText>
+ <Ionicons name="chevron-forward" size={20} color={colors.textMuted} />
+ </View>
+ </TouchableOpacity>
</View>
<View style={styles.section}>
diff --git a/mobile-app/app/_layout.tsx b/mobile-app/app/_layout.tsx
index 02261ef53..9868b55e9 100644
--- a/mobile-app/app/_layout.tsx
+++ b/mobile-app/app/_layout.tsx
@@ -138,6 +138,7 @@ function RootLayoutNav() {
}}>
<Stack.Screen name="index" options={{ headerShown: false }} />
<Stack.Screen name="login" options={{ title: 'Login', headerShown: false }} />
+ <Stack.Screen name="sync" options={{ headerShown: false }} />
<Stack.Screen name="unlock" options={{ headerShown: false }} />
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
<Stack.Screen name="+not-found" options={{ title: 'Not Found' }} />
diff --git a/mobile-app/app/index.tsx b/mobile-app/app/index.tsx
index 60fee5b4d..5e1b4ac1d 100644
--- a/mobile-app/app/index.tsx
+++ b/mobile-app/app/index.tsx
@@ -1,115 +1,10 @@
-import { useEffect, useRef, useState } from 'react';
-import { router } from 'expo-router';
-import { useAuth } from '@/context/AuthContext';
-import { useDb } from '@/context/DbContext';
-import { useVaultSync } from '@/hooks/useVaultSync';
-import { ThemedView } from '@/components/ThemedView';
-import LoadingIndicator from '@/components/LoadingIndicator';
+import { Redirect } from 'expo-router';
import { install } from 'react-native-quick-crypto';
-import { NativeModules } from 'react-native';
-
-export default function InitialLoadingScreen() {
- const { isInitialized: isAuthInitialized, isLoggedIn } = useAuth();
- const { dbInitialized, dbAvailable } = useDb();
- const { syncVault } = useVaultSync();
- const authContext = useAuth();
- const [status, setStatus] = useState('');
- const hasInitialized = useRef(false);
-
- // TODO: isauthinitialized and dbinitialize do not have to be checekd anymore separately.
- // Refactor this and check usages of isAuthInitialized and dbInitialized in other places.
- // Doing the check in this file once should be enough. Especially after adding the server
- // status check later which should fire periodically..
- const isFullyInitialized = isAuthInitialized && dbInitialized;
- const requireLoginOrUnlock = isFullyInitialized && (!isLoggedIn || !dbAvailable);
+export default function AppIndex() {
// Install the react-native-quick-crypto library which is used by the EncryptionUtility
- // which acts as a drop-in replacement for the subtle crypto API.
install();
- useEffect(() => {
- if (hasInitialized.current) {
- return;
- }
-
- hasInitialized.current = true;
-
- async function initialize() {
- const { isLoggedIn, enabledAuthMethods } = await authContext.initializeAuth();
-
- // If user is not logged in, navigate to login immediately
- if (!isLoggedIn) {
- console.log('User not logged in, navigating to login');
- router.replace('/login');
- return;
- }
-
- // Perform initial vault sync
- console.log('Initial vault sync');
- await syncVault({
- initialSync: true,
- onStatus: (message) => {
- setStatus(message);
- }
- });
-
- // Try to unlock with FaceID
- try {
- // This will check if the encrypted database file exists locally.
- // TODO: this isvaultinitialized should be renamed to "isVaultExists" or something similar
- // as we're just checking if the file exists.
- const isInitialized = await NativeModules.CredentialManager.isVaultInitialized();
- if (isInitialized) {
- const isFaceIDEnabled = enabledAuthMethods.includes('faceid');
- if (!isFaceIDEnabled) {
- console.log('FaceID is not enabled, navigating to unlock screen');
- router.replace('/unlock');
- return;
- }
-
- // Attempt to unlock the vault with FaceID.
- setStatus('Unlocking vault|');
- const isUnlocked = await NativeModules.CredentialManager.unlockVault();
- if (isUnlocked) {
- await new Promise(resolve => setTimeout(resolve, 1000));
- setStatus('Decrypting vault');
- await new Promise(resolve => setTimeout(resolve, 1000));
- console.log('FaceID unlock successful, navigating to credentials');
- router.replace('/(tabs)/(credentials)');
- return;
- }
- else {
- console.log('FaceID unlock failed, navigating to unlock screen');
- router.replace('/unlock');
- }
- }
- else {
- // Vault is not initialized which means the database does not exist or decryption key is missing
- // from device's keychain. Navigate to the unlock screen.
- console.log('Vault is not initialized (db file does not exist), navigating to unlock screen');
- router.replace('/unlock');
- return;
- }
- } catch (error) {
- console.log('FaceID unlock failed:', error);
- // If FaceID fails (too many attempts, manual cancel, etc.)
- // navigate to unlock screen
- router.replace('/unlock');
- return;
- }
-
- // If we get here, something went wrong with the FaceID unlock
- // Navigate to unlock screen as a fallback
- console.log('FaceID unlock failed, navigating to unlock screen');
- router.replace('/unlock');
- }
-
- initialize();
- }, [isFullyInitialized, requireLoginOrUnlock, syncVault]);
+ return <Redirect href={'/sync'} />
- return (
- <ThemedView style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
- {(isLoggedIn && status) ? <LoadingIndicator status={status} /> : null}
- </ThemedView>
- );
}
\ No newline at end of file
diff --git a/mobile-app/app/sync.tsx b/mobile-app/app/sync.tsx
new file mode 100644
index 000000000..5b5485acb
--- /dev/null
+++ b/mobile-app/app/sync.tsx
@@ -0,0 +1,100 @@
+import { useEffect, useRef, useState } from 'react';
+import { router } from 'expo-router';
+import { useAuth } from '@/context/AuthContext';
+import { useVaultSync } from '@/hooks/useVaultSync';
+import { ThemedView } from '@/components/ThemedView';
+import LoadingIndicator from '@/components/LoadingIndicator';
+import { NativeModules } from 'react-native';
+import { useDb } from '@/context/DbContext';
+
+export default function SyncScreen() {
+ const authContext = useAuth();
+ const dbContext = useDb();
+ const { syncVault } = useVaultSync();
+ const [status, setStatus] = useState('');
+ const hasInitialized = useRef(false);
+
+ useEffect(() => {
+ if (hasInitialized.current) {
+ return;
+ }
+
+ hasInitialized.current = true;
+
+
+ async function initialize() {
+ const { isLoggedIn, enabledAuthMethods } = await authContext.initializeAuth();
+
+ // If user is not logged in, navigate to login immediately
+ if (!isLoggedIn) {
+ console.log('User not logged in, navigating to login');
+ router.replace('/login');
+ return;
+ }
+
+ // Perform initial vault sync
+ console.log('Initial vault sync');
+ await syncVault({
+ initialSync: true,
+ onStatus: (message) => {
+ setStatus(message);
+ }
+ });
+
+ // Try to unlock with FaceID
+ try {
+ const isInitialized = await NativeModules.CredentialManager.isVaultInitialized();
+ if (isInitialized) {
+ const isFaceIDEnabled = enabledAuthMethods.includes('faceid');
+ if (!isFaceIDEnabled) {
+ console.log('FaceID is not enabled, navigating to unlock screen');
+ router.replace('/unlock');
+ return;
+ }
+
+ // Attempt to unlock the vault with FaceID.
+ setStatus('Unlocking vault');
+ const isUnlocked = await dbContext.unlockVault();
+ if (isUnlocked) {
+ await new Promise(resolve => setTimeout(resolve, 1000));
+ setStatus('Decrypting vault');
+ await new Promise(resolve => setTimeout(resolve, 1000));
+ console.log('FaceID unlock successful, navigating to credentials');
+ router.replace('/(tabs)/(credentials)');
+ return;
+ }
+ else {
+ console.log('FaceID unlock failed, navigating to unlock screen');
+ router.replace('/unlock');
+ }
+ }
+ else {
+ // Vault is not initialized which means the database does not exist or decryption key is missing
+ // from device's keychain. Navigate to the unlock screen.
+ console.log('Vault is not initialized (db file does not exist), navigating to unlock screen');
+ router.replace('/unlock');
+ return;
+ }
+ } catch (error) {
+ console.log('FaceID unlock failed:', error);
+ // If FaceID fails (too many attempts, manual cancel, etc.)
+ // navigate to unlock screen
+ router.replace('/unlock');
+ return;
+ }
+
+ // If we get here, something went wrong with the FaceID unlock
+ // Navigate to unlock screen as a fallback
+ console.log('FaceID unlock failed, navigating to unlock screen');
+ router.replace('/unlock');
+ }
+
+ initialize();
+ }, [syncVault]);
+
+ return (
+ <ThemedView style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
+ {status ? <LoadingIndicator status={status} /> : null}
+ </ThemedView>
+ );
+}
\ No newline at end of file
diff --git a/mobile-app/app/unlock.tsx b/mobile-app/app/unlock.tsx
index 1099d497d..5b346c6d2 100644
--- a/mobile-app/app/unlock.tsx
+++ b/mobile-app/app/unlock.tsx
@@ -39,6 +39,8 @@ export default function UnlockScreen() {
// Initialize the database with the provided password
const loginResponse = await srpUtil.initiateLogin(username);
+ console.log('loginResponse', loginResponse);
+
const passwordHash = await EncryptionUtility.deriveKeyFromPassword(
password,
loginResponse.salt,
@@ -54,10 +56,10 @@ export default function UnlockScreen() {
router.replace('/(tabs)/(credentials)');
}
else {
- Alert.alert('Error', 'Incorrect password. Please try again or use Face ID.');
+ Alert.alert('Error', 'Incorrect password. Please try again.');
}
} catch (error) {
- Alert.alert('Error', 'Incorrect password. Please try again or use Face ID.');
+ Alert.alert('Error', 'Incorrect password. Please try again.');
} finally {
setIsLoading(false);
}
diff --git a/mobile-app/context/AuthContext.tsx b/mobile-app/context/AuthContext.tsx
index 4ca0b68d6..6fd96fb7e 100644
--- a/mobile-app/context/AuthContext.tsx
+++ b/mobile-app/context/AuthContext.tsx
@@ -1,7 +1,12 @@
-import React, { createContext, useContext, useState, useEffect, useMemo, useCallback } from 'react';
+import React, { createContext, useContext, useState, useEffect, useMemo, useCallback, useRef } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useDb } from './DbContext';
-import { NativeModules } from 'react-native';
+import { NativeModules, AppState } from 'react-native';
+import { router, usePathname } from 'expo-router';
+import { NavigationContainerRef, ParamListBase } from '@react-navigation/native';
+
+// Create a navigation reference
+export const navigationRef = React.createRef<NavigationContainerRef<ParamListBase>>();
export type AuthMethod = 'faceid' | 'password';
@@ -19,6 +24,10 @@ type AuthContextType = {
clearGlobalMessage: () => void;
setAuthMethods: (methods: AuthMethod[]) => Promise<void>;
getAuthMethodDisplay: () => string;
+ autoLockTimeout: number;
+ setAutoLockTimeout: (timeout: number) => Promise<void>;
+ returnPath: string | null;
+ setReturnPath: (path: string | null) => Promise<void>;
}
/**
@@ -35,7 +44,11 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
const [username, setUsername] = useState<string | null>(null);
const [globalMessage, setGlobalMessage] = useState<string | null>(null);
const [enabledAuthMethods, setEnabledAuthMethods] = useState<AuthMethod[]>(['password']);
+ const [autoLockTimeout, setAutoLockTimeoutState] = useState<number>(0);
+ const [returnPath, setReturnPathState] = useState<string | null>(null);
+ const appState = useRef(AppState.currentState);
const dbContext = useDb();
+ const pathname = usePathname();
/**
* Check if Face ID is enabled based on enabled auth methods
@@ -158,6 +171,91 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
return enabledAuthMethods.includes('faceid') ? 'Face ID' : 'Password';
}, [enabledAuthMethods]);
+ useEffect(() => {
+ // Load saved settings on mount
+ const loadSettings = async () => {
+ try {
+ const savedTimeout = await AsyncStorage.getItem('autoLockTimeout');
+ if (savedTimeout) {
+ setAutoLockTimeoutState(parseInt(savedTimeout, 10));
+ }
+ } catch (error) {
+ console.error('Error loading settings:', error);
+ }
+ };
+
+ loadSettings();
+ }, []);
+
+ const setAutoLockTimeout = async (timeout: number) => {
+ try {
+ await AsyncStorage.setItem('autoLockTimeout', timeout.toString());
+ setAutoLockTimeoutState(timeout);
+ } catch (error) {
+ console.error('Error saving settings:', error);
+ }
+ };
+
+ const isVaultUnlocked = async () : Promise<boolean> => {
+ try {
+ const isUnlocked = await NativeModules.CredentialManager.isVaultUnlocked();
+ return isUnlocked;
+ } catch (error) {
+ console.error('Failed to check vault status:', error);
+ return false;
+ }
+ };
+
+ const setReturnPath = useCallback(async (path: string | null) => {
+ if (path) {
+ await AsyncStorage.setItem('returnPath', path);
+ } else {
+ await AsyncStorage.removeItem('returnPath');
+ }
+ setReturnPathState(path);
+ }, []);
+
+ // Handle app state changes
+ useEffect(() => {
+ const subscription = AppState.addEventListener('change', async (nextAppState) => {
+ if (appState.current.match(/inactive|background/) && nextAppState === 'active') {
+ // App coming to foreground
+ console.log('App coming to foreground in AuthContext');
+ if (pathname && !pathname.includes('unlock') && !pathname.includes('login')) {
+ try {
+ // Check if vault is unlocked.
+ const isUnlocked = await isVaultUnlocked();
+ if (!isUnlocked) {
+ // Database connection failed, store current path and navigate to unlock flow
+ console.log('Vault is not unlocked anymore, navigating to unlock flow');
+ await setReturnPath(pathname);
+ // Reset navigation to root using Expo Router
+ router.replace('/login');
+ } else {
+ console.log('Vault is still unlocked, staying on current screen');
+ }
+ } catch (error) {
+ // Database query failed, store current path and navigate to unlock flow
+ console.log('Failed to check vault status, navigating to unlock flow:', error);
+ await setReturnPath(pathname);
+ router.replace('/login');
+ }
+ }
+ } else if (appState.current === 'active' && nextAppState.match(/inactive|background/)) {
+ // App going to background
+ console.log('App going to background in AuthContext');
+ if (pathname && !pathname.includes('unlock') && !pathname.includes('login')) {
+ await setReturnPath(pathname);
+ }
+ }
+ appState.current = nextAppState;
+ });
+
+ return () => {
+ subscription.remove();
+ };
+ }, [pathname, isVaultUnlocked, setReturnPath]);
+
const contextValue = useMemo(() => ({
isLoggedIn,
isInitialized,
@@ -172,7 +270,11 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
clearGlobalMessage,
setAuthMethods,
getAuthMethodDisplay,
- }), [isLoggedIn, isInitialized, username, globalMessage, enabledAuthMethods, setAuthTokens, login, logout, clearGlobalMessage, initializeAuth, setAuthMethods, getAuthMethodDisplay, isFaceIDEnabled]);
+ autoLockTimeout,
+ setAutoLockTimeout,
+ returnPath,
+ setReturnPath,
+ }), [isLoggedIn, isInitialized, username, globalMessage, enabledAuthMethods, setAuthTokens, login, logout, clearGlobalMessage, initializeAuth, setAuthMethods, getAuthMethodDisplay, isFaceIDEnabled, autoLockTimeout, setAutoLockTimeout, returnPath, setReturnPath]);
return (
<AuthContext.Provider value={contextValue}>
diff --git a/mobile-app/context/DbContext.tsx b/mobile-app/context/DbContext.tsx
index 90225a7a7..03eb35e97 100644
--- a/mobile-app/context/DbContext.tsx
+++ b/mobile-app/context/DbContext.tsx
@@ -12,6 +12,7 @@ type DbContextType = {
clearDatabase: () => void;
getVaultMetadata: () => Promise<VaultMetadata | null>;
testDatabaseConnection: (derivedKey: string) => Promise<boolean>;
+ unlockVault: () => Promise<boolean>;
}
const DbContext = createContext<DbContextType | undefined>(undefined);
@@ -105,6 +106,14 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
credentialManager.clearVault();
}, []);
+ /**
+ * Unlock the vault in the native module which will decrypt the database using the stored encryption key
+ * and load it into memory.
+ */
+ const unlockVault = useCallback(async () : Promise<boolean> => {
+ return await credentialManager.unlockVault();
+ }, []);
+
/**
* Get the current vault metadata directly from SQLite client
*/
@@ -122,6 +131,9 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
// Store the encryption key
await sqliteClient.storeEncryptionKey(derivedKey);
+ // Initialize the database
+ await unlockVault();
+
// Try to get the database version as a simple test query
const version = await sqliteClient.getDatabaseVersion();
@@ -142,8 +154,9 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
initializeDatabase,
clearDatabase,
getVaultMetadata,
- testDatabaseConnection
- }), [sqliteClient, dbInitialized, dbAvailable, initializeDatabase, clearDatabase, getVaultMetadata, testDatabaseConnection]);
+ testDatabaseConnection,
+ unlockVault
+ }), [sqliteClient, dbInitialized, dbAvailable, initializeDatabase, clearDatabase, getVaultMetadata, testDatabaseConnection, unlockVault]);
return (
<DbContext.Provider value={contextValue}>
diff --git a/mobile-app/ios/CredentialManager/CredentialManager.m b/mobile-app/ios/CredentialManager/CredentialManager.m
index 32378b428..aaecb23d7 100644
--- a/mobile-app/ios/CredentialManager/CredentialManager.m
+++ b/mobile-app/ios/CredentialManager/CredentialManager.m
@@ -9,6 +9,7 @@ RCT_EXTERN_METHOD(clearVault)
// TODO: isvaultinitialized should be renamed to "isVaultExists" or something similar as we're just checking if the file exists.
// The initializevault actually initializes the vault by decrypting it and loading the DB into memory.
RCT_EXTERN_METHOD(isVaultInitialized:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
+RCT_EXTERN_METHOD(isVaultUnlocked:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(getVaultMetadata:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(unlockVault:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
diff --git a/mobile-app/ios/CredentialManager/CredentialManager.swift b/mobile-app/ios/CredentialManager/CredentialManager.swift
index 0f841216e..3cd0ebddf 100644
--- a/mobile-app/ios/CredentialManager/CredentialManager.swift
+++ b/mobile-app/ios/CredentialManager/CredentialManager.swift
@@ -68,9 +68,6 @@ class CredentialManager: NSObject {
resolver resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
do {
- // Ensure database is initialized
- try credentialStore.initializeDatabase()
-
// Convert all params to strings
let bindingParams = params.map { param -> Binding? in
return String(describing: param)
@@ -90,9 +87,6 @@ class CredentialManager: NSObject {
resolver resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
do {
- // Ensure database is initialized
- try credentialStore.initializeDatabase()
-
// Convert all params to strings
let bindingParams = params.map { param -> Binding? in
return String(describing: param)
@@ -154,6 +148,13 @@ class CredentialManager: NSObject {
}
}
+ @objc
+ func isVaultUnlocked(_ resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ let isUnlocked = try credentialStore.isVaultUnlocked()
+ resolve(isUnlocked)
+ }
+
@objc
func getVaultMetadata(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
diff --git a/mobile-app/ios/CredentialManager/SharedCredentialStore.swift b/mobile-app/ios/CredentialManager/SharedCredentialStore.swift
index 7daf6532d..a10d6ae20 100644
--- a/mobile-app/ios/CredentialManager/SharedCredentialStore.swift
+++ b/mobile-app/ios/CredentialManager/SharedCredentialStore.swift
@@ -26,11 +26,55 @@ class SharedCredentialStore {
private var db: Connection?
private var encryptionKey: Data?
private var enabledAuthMethods: AuthMethods = .none
+ private var clearCacheTimer: Timer?
public init() {
// Load saved auth methods from UserDefaults
let savedRawValue = UserDefaults.standard.integer(forKey: authMethodsKey)
enabledAuthMethods = AuthMethods(rawValue: savedRawValue)
+
+ // Add notification observers
+ NotificationCenter.default.addObserver(
+ self,
+ selector: #selector(appDidEnterBackground),
+ name: UIApplication.didEnterBackgroundNotification,
+ object: nil
+ )
+
+ NotificationCenter.default.addObserver(
+ self,
+ selector: #selector(appWillEnterForeground),
+ name: UIApplication.willEnterForegroundNotification,
+ object: nil
+ )
+ }
+
+ deinit {
+ NotificationCenter.default.removeObserver(self)
+ clearCacheTimer?.invalidate()
+ }
+
+ @objc private func appDidEnterBackground() {
+ print("App entered background, starting 5-second timer to clear cache")
+ // Start timer to clear cache after 5 seconds
+ clearCacheTimer = Timer.scheduledTimer(withTimeInterval: 5, repeats: false) { [weak self] _ in
+ print("5-second background timer fired, clearing cache")
+ self?.clearCache()
+ }
+ }
+
+ @objc private func appWillEnterForeground() {
+ print("App will enter foreground, canceling clear cache timer")
+
+ // Check if timer has elapsed
+ if let timer = clearCacheTimer, timer.fireDate < Date() {
+ print("Timer has elapsed, cache should have been cleared already when app was in background, but clearing it again to be sure")
+ clearCache()
+ }
+
+ // Cancel the timer if app comes back to foreground
+ clearCacheTimer?.invalidate()
+ clearCacheTimer = nil
}
// MARK: - Auth Methods Management
@@ -66,6 +110,11 @@ class SharedCredentialStore {
return hasDatabase
}
+ func isVaultUnlocked() -> Bool {
+ // Check if encryption key is in memory
+ return encryptionKey != nil
+ }
+
// MARK: - Encryption Key Management
private func getEncryptionKey() throws -> Data {
if let key = encryptionKey {
@@ -233,10 +282,6 @@ class SharedCredentialStore {
// MARK: - Credential Operations
func addCredential(_ credential: Credential) throws {
- if db == nil {
- try initializeDatabase()
- }
-
// After initialization attempt, check if db is still nil
guard let db = db else {
throw NSError(domain: "SharedCredentialStore", code: 4, userInfo: [NSLocalizedDescriptionKey: "Database not initialized"])
@@ -263,10 +308,6 @@ class SharedCredentialStore {
}
func getAllCredentials() throws -> [Credential] {
- if db == nil {
- try initializeDatabase()
- }
-
// After initialization attempt, check if db is still nil
guard let db = db else {
throw NSError(domain: "SharedCredentialStore", code: 4, userInfo: [NSLocalizedDescriptionKey: "Database not initialized"])
@@ -301,6 +342,7 @@ class SharedCredentialStore {
// Clears cached encryption key and encrypted database to force re-initialization on next access.
func clearCache() {
+ print("Clearing cache - removing encryption key and decrypted database from memory")
// Clear the cached encryption key
encryptionKey = nil
@@ -310,6 +352,7 @@ class SharedCredentialStore {
// Clears cached and saved encryption key and encrypted database to force re-initialization on next access.
func clearVault() {
+ print("Clearing vault - removing all stored data")
// Remove the encryption key from keychain
try? keychain.remove(encryptionKeyKey)