Skip to content

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

Store autolock timeout in native code (#771)

Leendert de Borst079415184fe0
diff --git a/mobile-app/app/(tabs)/(settings)/auto-lock.tsx b/mobile-app/app/(tabs)/(settings)/auto-lock.tsx
index 7c6e76489..1d60601bb 100644
--- a/mobile-app/app/(tabs)/(settings)/auto-lock.tsx
+++ b/mobile-app/app/(tabs)/(settings)/auto-lock.tsx
@@ -1,23 +1,32 @@
-import { StyleSheet, View, TouchableOpacity } from 'react-native';
+import { StyleSheet, View, TouchableOpacity, ScrollView } 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';
+import { useEffect, useState } from 'react';
export default function AutoLockScreen() {
const colors = useColors();
- const { autoLockTimeout, setAutoLockTimeout } = useAuth();
+ const { getAutoLockTimeout, setAutoLockTimeout } = useAuth();
+ const [autoLockTimeout, setAutoLockTimeoutState] = useState<number>(0);
+
+ useEffect(() => {
+ const loadAutoLockTimeout = async () => {
+ const timeout = await getAutoLockTimeout();
+ setAutoLockTimeoutState(timeout);
+ };
+ loadAutoLockTimeout();
+ }, []);
const timeoutOptions = [
{ label: 'Never', value: 0 },
+ { label: '5 seconds', value: 5 },
+ { label: '30 seconds', value: 30 },
{ 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 },
];
@@ -26,9 +35,20 @@ export default function AutoLockScreen() {
container: {
flex: 1,
},
- content: {
+ scrollView: {
flex: 1,
+ },
+ scrollContent: {
+ paddingBottom: 40,
+ },
+ header: {
padding: 16,
+ borderBottomWidth: StyleSheet.hairlineWidth,
+ borderBottomColor: colors.accentBorder,
+ },
+ headerText: {
+ fontSize: 13,
+ color: colors.textMuted,
},
option: {
flexDirection: 'row',
@@ -52,12 +72,23 @@ export default function AutoLockScreen() {
return (
<ThemedView style={styles.container}>
- <View style={styles.content}>
+ <ScrollView
+ style={styles.scrollView}
+ contentContainerStyle={styles.scrollContent}
+ >
+ <View style={styles.header}>
+ <ThemedText style={styles.headerText}>
+ Choose how long the app can stay in the background before requiring re-authentication. You'll need to use Face ID or enter your password to unlock the vault again.
+ </ThemedText>
+ </View>
{timeoutOptions.map((option) => (
<TouchableOpacity
key={option.value}
style={styles.option}
- onPress={() => setAutoLockTimeout(option.value)}
+ onPress={() => {
+ setAutoLockTimeout(option.value);
+ setAutoLockTimeoutState(option.value);
+ }}
>
<ThemedText style={styles.optionText}>{option.label}</ThemedText>
{autoLockTimeout === option.value && (
@@ -65,7 +96,7 @@ export default function AutoLockScreen() {
)}
</TouchableOpacity>
))}
- </View>
+ </ScrollView>
</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 b1d8ee852..ba68af064 100644
--- a/mobile-app/app/(tabs)/(settings)/index.tsx
+++ b/mobile-app/app/(tabs)/(settings)/index.tsx
@@ -10,15 +10,36 @@ import { useAuth } from '@/context/AuthContext';
import { ThemedSafeAreaView } from '@/components/ThemedSafeAreaView';
import { Ionicons } from '@expo/vector-icons';
import { CollapsibleHeader } from '@/components/CollapsibleHeader';
-import { useRef } from 'react';
+import { useRef, useState, useEffect } from 'react';
export default function SettingsScreen() {
const webApi = useWebApi();
const colors = useColors();
const { username, getAuthMethodDisplay } = useAuth();
- const { autoLockTimeout } = useAuth();
+ const { getAutoLockTimeout } = useAuth();
const scrollY = useRef(new Animated.Value(0)).current;
const scrollViewRef = useRef<ScrollView>(null);
+ const [autoLockDisplay, setAutoLockDisplay] = useState<string>('');
+
+ useEffect(() => {
+ const loadAutoLockDisplay = async () => {
+ const autoLockTimeout = await getAutoLockTimeout();
+ let display = 'Never';
+
+ if (autoLockTimeout === 5) display = '5 seconds';
+ else if (autoLockTimeout === 30) display = '30 seconds';
+ else if (autoLockTimeout === 60) display = '1 minute';
+ else if (autoLockTimeout === 900) display = '15 minutes';
+ else if (autoLockTimeout === 1800) display = '30 minutes';
+ else if (autoLockTimeout === 3600) display = '1 hour';
+ else if (autoLockTimeout === 14400) display = '4 hours';
+ else if (autoLockTimeout === 28800) display = '8 hours';
+
+ setAutoLockDisplay(display);
+ };
+
+ loadAutoLockDisplay();
+ }, [getAutoLockTimeout]);
const handleLogout = async () => {
await webApi.logout();
@@ -33,19 +54,6 @@ export default function SettingsScreen() {
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,
@@ -196,7 +204,7 @@ export default function SettingsScreen() {
</View>
<View style={[styles.settingItemContent]}>
<ThemedText style={styles.settingItemText}>Auto-lock Timeout</ThemedText>
- <ThemedText style={styles.settingItemValue}>{getAutoLockDisplay()}</ThemedText>
+ <ThemedText style={styles.settingItemValue}>{autoLockDisplay}</ThemedText>
<Ionicons name="chevron-forward" size={20} color={colors.textMuted} />
</View>
</TouchableOpacity>
diff --git a/mobile-app/context/AuthContext.tsx b/mobile-app/context/AuthContext.tsx
index 6fd96fb7e..6b8294786 100644
--- a/mobile-app/context/AuthContext.tsx
+++ b/mobile-app/context/AuthContext.tsx
@@ -24,7 +24,7 @@ type AuthContextType = {
clearGlobalMessage: () => void;
setAuthMethods: (methods: AuthMethod[]) => Promise<void>;
getAuthMethodDisplay: () => string;
- autoLockTimeout: number;
+ getAutoLockTimeout: () => Promise<number>;
setAutoLockTimeout: (timeout: number) => Promise<void>;
returnPath: string | null;
setReturnPath: (path: string | null) => Promise<void>;
@@ -44,7 +44,6 @@ 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();
@@ -171,26 +170,30 @@ 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();
- }, []);
+ /**
+ * Get the auto-lock timeout from the iOS credentials manager
+ */
+ const getAutoLockTimeout = async () : Promise<number> => {
+ try {
+ const timeout = await NativeModules.CredentialManager.getAutoLockTimeout();
+ return timeout;
+ } catch (error) {
+ console.error('Failed to get auto-lock timeout:', error);
+ return 0;
+ }
+ }
+ /**
+ * Set the auto-lock timeout in the iOS credentials manager
+ */
const setAutoLockTimeout = async (timeout: number) => {
try {
- await AsyncStorage.setItem('autoLockTimeout', timeout.toString());
- setAutoLockTimeoutState(timeout);
+ // Update iOS credentials manager
+ try {
+ await NativeModules.CredentialManager.setAutoLockTimeout(timeout);
+ } catch (error) {
+ console.error('Failed to update iOS auto-lock timeout:', error);
+ }
} catch (error) {
console.error('Error saving settings:', error);
}
@@ -230,7 +233,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
console.log('Vault is not unlocked anymore, navigating to unlock flow');
await setReturnPath(pathname);
// Reset navigation to root using Expo Router
- router.replace('/login');
+ router.replace('/sync');
} else {
console.log('Vault is still unlocked, staying on current screen');
}
@@ -238,7 +241,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
// 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');
+ router.replace('/sync');
}
}
} else if (appState.current === 'active' && nextAppState.match(/inactive|background/)) {
@@ -270,11 +273,11 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
clearGlobalMessage,
setAuthMethods,
getAuthMethodDisplay,
- autoLockTimeout,
+ getAutoLockTimeout,
setAutoLockTimeout,
returnPath,
setReturnPath,
- }), [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, getAutoLockTimeout, setAutoLockTimeout, returnPath, setReturnPath]);
return (
<AuthContext.Provider value={contextValue}>
diff --git a/mobile-app/ios/CredentialManager/CredentialManager.m b/mobile-app/ios/CredentialManager/CredentialManager.m
index aaecb23d7..cde6efc12 100644
--- a/mobile-app/ios/CredentialManager/CredentialManager.m
+++ b/mobile-app/ios/CredentialManager/CredentialManager.m
@@ -37,5 +37,11 @@ RCT_EXTERN_METHOD(executeUpdate:(NSString *)query
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
+RCT_EXTERN_METHOD(setAutoLockTimeout:(NSInteger)timeout
+ resolver:(RCTPromiseResolveBlock)resolve
+ rejecter:(RCTPromiseRejectBlock)reject)
+
+RCT_EXTERN_METHOD(getAutoLockTimeout:(RCTPromiseResolveBlock)resolve
+ rejecter:(RCTPromiseRejectBlock)reject)
@end
diff --git a/mobile-app/ios/CredentialManager/CredentialManager.swift b/mobile-app/ios/CredentialManager/CredentialManager.swift
index 3cd0ebddf..8b32c0259 100644
--- a/mobile-app/ios/CredentialManager/CredentialManager.swift
+++ b/mobile-app/ios/CredentialManager/CredentialManager.swift
@@ -195,6 +195,21 @@ class CredentialManager: NSObject {
return false
}
+ @objc
+ func setAutoLockTimeout(_ timeout: Int,
+ resolver resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ credentialStore.setAutoLockTimeout(timeout)
+ resolve(nil)
+ }
+
+ @objc
+ func getAutoLockTimeout(_ resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ let timeout = credentialStore.getAutoLockTimeout()
+ resolve(timeout)
+ }
+
@objc
static func moduleName() -> String! {
return "CredentialManager"
diff --git a/mobile-app/ios/CredentialManager/SharedCredentialStore.swift b/mobile-app/ios/CredentialManager/SharedCredentialStore.swift
index a10d6ae20..9d68b742f 100644
--- a/mobile-app/ios/CredentialManager/SharedCredentialStore.swift
+++ b/mobile-app/ios/CredentialManager/SharedCredentialStore.swift
@@ -23,16 +23,21 @@ class SharedCredentialStore {
private let encryptionKeyKey = "aliasvault_encryption_key"
private let encryptedDbFileName = "encrypted_db.sqlite"
private let authMethodsKey = "aliasvault_auth_methods"
+ private let autoLockTimeoutKey = "aliasvault_auto_lock_timeout"
private var db: Connection?
private var encryptionKey: Data?
private var enabledAuthMethods: AuthMethods = .none
private var clearCacheTimer: Timer?
+ private var autoLockTimeout: Int = 0
public init() {
// Load saved auth methods from UserDefaults
let savedRawValue = UserDefaults.standard.integer(forKey: authMethodsKey)
enabledAuthMethods = AuthMethods(rawValue: savedRawValue)
+ // Load auto-lock timeout from UserDefaults
+ autoLockTimeout = UserDefaults.standard.integer(forKey: autoLockTimeoutKey)
+
// Add notification observers
NotificationCenter.default.addObserver(
self,
@@ -55,11 +60,13 @@ class SharedCredentialStore {
}
@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()
+ print("App entered background, starting auto-lock timer with \(autoLockTimeout) seconds")
+ // Start timer to clear cache after auto-lock timeout
+ if autoLockTimeout > 0 {
+ clearCacheTimer = Timer.scheduledTimer(withTimeInterval: TimeInterval(autoLockTimeout), repeats: false) { [weak self] _ in
+ print("Auto-lock timer fired, clearing cache")
+ self?.clearCache()
+ }
}
}
@@ -433,4 +440,16 @@ class SharedCredentialStore {
}
}
}
+
+ // MARK: - Auto Lock Timeout Management
+ func setAutoLockTimeout(_ timeout: Int) {
+ print("Setting auto-lock timeout to \(timeout) seconds")
+ autoLockTimeout = timeout
+ UserDefaults.standard.set(timeout, forKey: autoLockTimeoutKey)
+ UserDefaults.standard.synchronize()
+ }
+
+ func getAutoLockTimeout() -> Int {
+ return autoLockTimeout
+ }
}