Skip to content

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

Move enabled auth methods to native module and add conditional faceid check (#771)

Leendert de Borst038e22db62a5
diff --git a/mobile-app/app/(tabs)/(settings)/vault-unlock.tsx b/mobile-app/app/(tabs)/(settings)/vault-unlock.tsx
index d13cdffbc..7a85d560a 100644
--- a/mobile-app/app/(tabs)/(settings)/vault-unlock.tsx
+++ b/mobile-app/app/(tabs)/(settings)/vault-unlock.tsx
@@ -9,40 +9,50 @@ import { AuthMethod, useAuth } from '@/context/AuthContext';
export default function VaultUnlockSettingsScreen() {
const colors = useColors();
const [initialized, setInitialized] = useState(false);
- const { setAuthMethods, enabledAuthMethods } = useAuth();
+ const { setAuthMethods, getEnabledAuthMethods } = useAuth();
const [hasFaceID, setHasFaceID] = useState(false);
const [isFaceIDEnabled, setIsFaceIDEnabled] = useState(false);
+ const [enabledAuthMethods, setEnabledAuthMethods] = useState<AuthMethod[]>([]);
useEffect(() => {
- const checkFaceIDAvailability = async () => {
+ const initializeAuth = async () => {
const compatible = await LocalAuthentication.hasHardwareAsync();
const enrolled = await LocalAuthentication.isEnrolledAsync();
setHasFaceID(compatible && enrolled);
- };
- checkFaceIDAvailability();
- if (enabledAuthMethods.includes('faceid')) {
- setIsFaceIDEnabled(true);
- }
+ const methods = await getEnabledAuthMethods();
+ setEnabledAuthMethods(methods);
+
+ if (methods.includes('faceid') && enrolled) {
+ setIsFaceIDEnabled(true);
+ }
+
+ setInitialized(true);
+ };
- setInitialized(true);
- }, []);
+ initializeAuth();
+ }, [getEnabledAuthMethods]);
useEffect(() => {
if (!initialized) {
return;
}
- // Check if there are actually differences between the current and the new auth methods
- const currentAuthMethods = enabledAuthMethods;
- const newAuthMethods = isFaceIDEnabled ? ['faceid', 'password'] : ['password'];
- if (currentAuthMethods.length === newAuthMethods.length && currentAuthMethods.every(method => newAuthMethods.includes(method))) {
- return;
- }
+ const updateAuthMethods = async () => {
+ const currentAuthMethods = await getEnabledAuthMethods();
+ const newAuthMethods = isFaceIDEnabled ? ['faceid', 'password'] : ['password'];
+
+ if (currentAuthMethods.length === newAuthMethods.length &&
+ currentAuthMethods.every(method => newAuthMethods.includes(method))) {
+ return;
+ }
+
+ console.log('Updating auth methods to', newAuthMethods);
+ setAuthMethods(newAuthMethods as AuthMethod[]);
+ };
- console.log('Updating auth methods to', newAuthMethods);
- setAuthMethods(newAuthMethods as AuthMethod[]);
- }, [isFaceIDEnabled, setAuthMethods, enabledAuthMethods, initialized]);
+ updateAuthMethods();
+ }, [isFaceIDEnabled, setAuthMethods, getEnabledAuthMethods, initialized]);
const handleFaceIDToggle = useCallback(async (value: boolean) => {
if (value && !hasFaceID) {
diff --git a/mobile-app/app/unlock.tsx b/mobile-app/app/unlock.tsx
index 10fd498ba..0f6be6500 100644
--- a/mobile-app/app/unlock.tsx
+++ b/mobile-app/app/unlock.tsx
@@ -1,4 +1,4 @@
-import { useState } from 'react';
+import { useState, useEffect } from 'react';
import { StyleSheet, View, TextInput, TouchableOpacity, Alert, Image, KeyboardAvoidingView, Platform } from 'react-native';
import { router } from 'expo-router';
import { useAuth } from '@/context/AuthContext';
@@ -17,10 +17,18 @@ export default function UnlockScreen() {
const { testDatabaseConnection } = useDb();
const [password, setPassword] = useState('');
const [isLoading, setIsLoading] = useState(false);
+ const [isFaceIDAvailable, setIsFaceIDAvailable] = useState(false);
const colors = useColors();
const webApi = useWebApi();
const srpUtil = new SrpUtility(webApi);
+ useEffect(() => {
+ const checkFaceIDStatus = async () => {
+ const enabled = await isFaceIDEnabled();
+ setIsFaceIDAvailable(enabled);
+ };
+ checkFaceIDStatus();
+ }, [isFaceIDEnabled]);
const handleUnlock = async () => {
if (!password) {
@@ -223,7 +231,7 @@ export default function UnlockScreen() {
</ThemedText>
</TouchableOpacity>
- {isFaceIDEnabled() && (
+ {isFaceIDAvailable && (
<TouchableOpacity
style={styles.faceIdButton}
onPress={handleFaceIDRetry}
diff --git a/mobile-app/context/AuthContext.tsx b/mobile-app/context/AuthContext.tsx
index 4f16af129..4686f05ba 100644
--- a/mobile-app/context/AuthContext.tsx
+++ b/mobile-app/context/AuthContext.tsx
@@ -4,6 +4,7 @@ import { useDb } from './DbContext';
import { NativeModules, AppState } from 'react-native';
import { router, usePathname } from 'expo-router';
import { NavigationContainerRef, ParamListBase } from '@react-navigation/native';
+import * as LocalAuthentication from 'expo-local-authentication';
// Create a navigation reference
export const navigationRef = React.createRef<NavigationContainerRef<ParamListBase>>();
@@ -14,8 +15,8 @@ type AuthContextType = {
isLoggedIn: boolean;
isInitialized: boolean;
username: string | null;
- enabledAuthMethods: AuthMethod[];
- isFaceIDEnabled: () => boolean;
+ getEnabledAuthMethods: () => Promise<AuthMethod[]>;
+ isFaceIDEnabled: () => Promise<boolean>;
setAuthTokens: (username: string, accessToken: string, refreshToken: string) => Promise<void>;
initializeAuth: () => Promise<{ isLoggedIn: boolean; enabledAuthMethods: AuthMethod[] }>;
login: () => Promise<void>;
@@ -23,7 +24,7 @@ type AuthContextType = {
globalMessage: string | null;
clearGlobalMessage: () => void;
setAuthMethods: (methods: AuthMethod[]) => Promise<void>;
- getAuthMethodDisplay: () => string;
+ getAuthMethodDisplay: () => Promise<string>;
getAutoLockTimeout: () => Promise<number>;
setAutoLockTimeout: (timeout: number) => Promise<void>;
}
@@ -41,22 +42,43 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
const [isInitialized, setIsInitialized] = useState(false);
const [username, setUsername] = useState<string | null>(null);
const [globalMessage, setGlobalMessage] = useState<string | null>(null);
- const [enabledAuthMethods, setEnabledAuthMethods] = useState<AuthMethod[]>(['password']);
const appState = useRef(AppState.currentState);
const dbContext = useDb();
const pathname = usePathname();
+ /**
+ * Get enabled auth methods from the native module
+ */
+ const getEnabledAuthMethods = useCallback(async (): Promise<AuthMethod[]> => {
+ try {
+ let methods = await NativeModules.CredentialManager.getAuthMethods() as AuthMethod[];
+ // Check if Face ID is actually available despite being enabled
+ if (methods.includes('faceid')) {
+ const isEnrolled = await LocalAuthentication.isEnrolledAsync();
+ if (!isEnrolled) {
+ // Remove Face ID from the list of enabled auth methods
+ methods = methods.filter(method => method !== 'faceid');
+ }
+ }
+ return methods;
+ } catch (error) {
+ console.error('Failed to get enabled auth methods:', error);
+ return ['password'];
+ }
+ }, []);
+
/**
* Check if Face ID is enabled based on enabled auth methods
*/
- const isFaceIDEnabled = useCallback(() : boolean => {
- return enabledAuthMethods.includes('faceid');
- }, [enabledAuthMethods]);
+ const isFaceIDEnabled = useCallback(async (): Promise<boolean> => {
+ const methods = await getEnabledAuthMethods();
+ return methods.includes('faceid');
+ }, [getEnabledAuthMethods]);
/**
* Set auth tokens in storage as part of the login process. After db is initialized, the login method should be called as well.
*/
- const setAuthTokens = useCallback(async (username: string, accessToken: string, refreshToken: string) : Promise<void> => {
+ const setAuthTokens = useCallback(async (username: string, accessToken: string, refreshToken: string): Promise<void> => {
await AsyncStorage.setItem('username', username);
await AsyncStorage.setItem('accessToken', accessToken);
await AsyncStorage.setItem('refreshToken', refreshToken);
@@ -68,11 +90,10 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
* Initialize the authentication state, called on initial load by _layout.tsx.
* @returns object containing whether the user is logged in and enabled auth methods
*/
- const initializeAuth = useCallback(async () : Promise<{ isLoggedIn: boolean; enabledAuthMethods: AuthMethod[] }> => {
+ const initializeAuth = useCallback(async (): Promise<{ isLoggedIn: boolean; enabledAuthMethods: AuthMethod[] }> => {
const accessToken = await AsyncStorage.getItem('accessToken') as string;
const refreshToken = await AsyncStorage.getItem('refreshToken') as string;
const username = await AsyncStorage.getItem('username') as string;
- const savedAuthMethods = await AsyncStorage.getItem('authMethods');
let isAuthenticated = false;
let methods: AuthMethod[] = ['password'];
@@ -80,34 +101,23 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
setUsername(username);
setIsLoggedIn(true);
isAuthenticated = true;
- if (savedAuthMethods) {
- try {
- const parsedMethods = JSON.parse(savedAuthMethods) as AuthMethod[];
- if (Array.isArray(parsedMethods) && parsedMethods.every(method => method === 'faceid' || method === 'password')) {
- methods = parsedMethods;
- setEnabledAuthMethods(parsedMethods);
- }
- } catch (e) {
- // If parsing fails, use default
- setEnabledAuthMethods(['password']);
- }
- }
+ methods = await getEnabledAuthMethods();
}
setIsInitialized(true);
return { isLoggedIn: isAuthenticated, enabledAuthMethods: methods };
- }, []);
+ }, [getEnabledAuthMethods]);
/**
* Set logged in status to true which refreshes the app.
*/
- const login = useCallback(async () : Promise<void> => {
+ const login = useCallback(async (): Promise<void> => {
setIsLoggedIn(true);
}, []);
/**
* Logout the user and clear the auth tokens from chrome storage.
*/
- const logout = useCallback(async (errorMessage?: string) : Promise<void> => {
+ const logout = useCallback(async (errorMessage?: string): Promise<void> => {
await AsyncStorage.removeItem('username');
await AsyncStorage.removeItem('accessToken');
await AsyncStorage.removeItem('refreshToken');
@@ -121,56 +131,53 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
setUsername(null);
setIsLoggedIn(false);
- setEnabledAuthMethods(['password']);
}, [dbContext]);
/**
* Clear global message (called after displaying the message).
*/
- const clearGlobalMessage = useCallback(() : void => {
+ const clearGlobalMessage = useCallback((): void => {
setGlobalMessage(null);
}, []);
/**
* Set the authentication methods and save them to storage
*/
- const setAuthMethods = useCallback(async (methods: AuthMethod[]) : Promise<void> => {
+ const setAuthMethods = useCallback(async (methods: AuthMethod[]): Promise<void> => {
// Ensure password is always included
const methodsToSave = methods.includes('password') ? methods : [...methods, 'password'];
- // Save to AsyncStorage
- await AsyncStorage.setItem('authMethods', JSON.stringify(methodsToSave));
-
// Update iOS credentials manager
try {
await NativeModules.CredentialManager.setAuthMethods(methodsToSave);
} catch (error) {
console.error('Failed to update iOS auth methods:', error);
- // Continue with the update even if iOS update fails
}
-
- // Use a state update function to ensure we're working with the latest state
- setEnabledAuthMethods(prevMethods => {
- // Only update if the methods have actually changed
- if (JSON.stringify(prevMethods) !== JSON.stringify(methodsToSave)) {
- return methodsToSave as AuthMethod[];
- }
- return prevMethods;
- });
}, []);
/**
* Get the display label for the current auth method
* Prefers Face ID if enabled, otherwise falls back to Password
*/
- const getAuthMethodDisplay = useCallback(() : string => {
- return enabledAuthMethods.includes('faceid') ? 'Face ID' : 'Password';
- }, [enabledAuthMethods]);
+ const getAuthMethodDisplay = useCallback(async (): Promise<string> => {
+ const methods = await getEnabledAuthMethods();
+ if (methods.includes('faceid')) {
+ try {
+ const isEnrolled = await LocalAuthentication.isEnrolledAsync();
+ if (isEnrolled) {
+ return 'Face ID';
+ }
+ } catch (error) {
+ console.error('Failed to check Face ID enrollment:', error);
+ }
+ }
+ return 'Password';
+ }, [getEnabledAuthMethods]);
/**
* Get the auto-lock timeout from the iOS credentials manager
*/
- const getAutoLockTimeout = async () : Promise<number> => {
+ const getAutoLockTimeout = async (): Promise<number> => {
try {
const timeout = await NativeModules.CredentialManager.getAutoLockTimeout();
return timeout;
@@ -185,18 +192,13 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
*/
const setAutoLockTimeout = async (timeout: number) => {
try {
- // Update iOS credentials manager
- try {
- await NativeModules.CredentialManager.setAutoLockTimeout(timeout);
- } catch (error) {
- console.error('Failed to update iOS auto-lock timeout:', error);
- }
+ await NativeModules.CredentialManager.setAutoLockTimeout(timeout);
} catch (error) {
- console.error('Error saving settings:', error);
+ console.error('Failed to update iOS auto-lock timeout:', error);
}
};
- const isVaultUnlocked = async () : Promise<boolean> => {
+ const isVaultUnlocked = async (): Promise<boolean> => {
try {
const isUnlocked = await NativeModules.CredentialManager.isVaultUnlocked();
return isUnlocked;
@@ -242,7 +244,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
isLoggedIn,
isInitialized,
username,
- enabledAuthMethods,
+ getEnabledAuthMethods,
isFaceIDEnabled,
initializeAuth,
setAuthTokens,
@@ -254,7 +256,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
getAuthMethodDisplay,
getAutoLockTimeout,
setAutoLockTimeout,
- }), [isLoggedIn, isInitialized, username, globalMessage, enabledAuthMethods, setAuthTokens, login, logout, clearGlobalMessage, initializeAuth, setAuthMethods, getAuthMethodDisplay, isFaceIDEnabled, getAutoLockTimeout, setAutoLockTimeout]);
+ }), [isLoggedIn, isInitialized, username, globalMessage, getEnabledAuthMethods, setAuthTokens, login, logout, clearGlobalMessage, initializeAuth, setAuthMethods, getAuthMethodDisplay, isFaceIDEnabled, getAutoLockTimeout, setAutoLockTimeout]);
return (
<AuthContext.Provider value={contextValue}>
@@ -266,7 +268,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
/**
* Hook to use the AuthContext
*/
-export const useAuth = () : AuthContextType => {
+export const useAuth = (): AuthContextType => {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider');
diff --git a/mobile-app/ios/CredentialManager/CredentialManager.m b/mobile-app/ios/CredentialManager/CredentialManager.m
index cde6efc12..edf8f8e3c 100644
--- a/mobile-app/ios/CredentialManager/CredentialManager.m
+++ b/mobile-app/ios/CredentialManager/CredentialManager.m
@@ -44,4 +44,7 @@ RCT_EXTERN_METHOD(setAutoLockTimeout:(NSInteger)timeout
RCT_EXTERN_METHOD(getAutoLockTimeout:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
+RCT_EXTERN_METHOD(getAuthMethods:(RCTPromiseResolveBlock)resolve
+ rejecter:(RCTPromiseRejectBlock)reject)
+
@end
diff --git a/mobile-app/ios/CredentialManager/CredentialManager.swift b/mobile-app/ios/CredentialManager/CredentialManager.swift
index 8b32c0259..d112600e2 100644
--- a/mobile-app/ios/CredentialManager/CredentialManager.swift
+++ b/mobile-app/ios/CredentialManager/CredentialManager.swift
@@ -54,7 +54,6 @@ class CredentialManager: NSObject {
resolver resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
do {
- // Store the key in the keychain with authentication protection
try credentialStore.storeEncryptionKey(base64Key: base64EncryptionKey)
resolve(nil)
} catch {
@@ -210,6 +209,26 @@ class CredentialManager: NSObject {
resolve(timeout)
}
+ @objc
+ func getAuthMethods(_ resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ do {
+ let methods = try credentialStore.getAuthMethods()
+ var methodStrings: [String] = []
+
+ if methods.contains(.faceID) {
+ methodStrings.append("faceid")
+ }
+ if methods.contains(.password) {
+ methodStrings.append("password")
+ }
+
+ resolve(methodStrings)
+ } catch {
+ reject("AUTH_METHOD_ERROR", "Failed to get authentication methods: \(error.localizedDescription)", error)
+ }
+ }
+
@objc
static func moduleName() -> String! {
return "CredentialManager"
diff --git a/mobile-app/ios/CredentialManager/SharedCredentialStore.swift b/mobile-app/ios/CredentialManager/SharedCredentialStore.swift
index 9d68b742f..feb5ff704 100644
--- a/mobile-app/ios/CredentialManager/SharedCredentialStore.swift
+++ b/mobile-app/ios/CredentialManager/SharedCredentialStore.swift
@@ -20,23 +20,30 @@ class SharedCredentialStore {
private let keychain = Keychain(service: "net.aliasvault.autofill", accessGroup: "group.net.aliasvault.autofill")
.accessibility(.whenPasscodeSetThisDeviceOnly, authenticationPolicy: .biometryAny)
+ private var db: Connection?
+ private var encryptionKey: Data?
+ private var clearCacheTimer: Timer?
+
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
+
+ // User config with default values
+ private var enabledAuthMethods: AuthMethods = [.password, .faceID] // Default to Face ID and password
+ private var autoLockTimeout: Int = 3600 // Default to 1 hour (3600 seconds)
public init() {
- // Load saved auth methods from UserDefaults
- let savedRawValue = UserDefaults.standard.integer(forKey: authMethodsKey)
- enabledAuthMethods = AuthMethods(rawValue: savedRawValue)
+ // Load saved auth methods from UserDefaults if they exist
+ if UserDefaults.standard.object(forKey: authMethodsKey) != nil {
+ let savedRawValue = UserDefaults.standard.integer(forKey: authMethodsKey)
+ enabledAuthMethods = AuthMethods(rawValue: savedRawValue)
+ }
- // Load auto-lock timeout from UserDefaults
- autoLockTimeout = UserDefaults.standard.integer(forKey: autoLockTimeoutKey)
+ // Load auto-lock timeout from UserDefaults if it exists
+ if UserDefaults.standard.object(forKey: autoLockTimeoutKey) != nil {
+ autoLockTimeout = UserDefaults.standard.integer(forKey: autoLockTimeoutKey)
+ }
// Add notification observers
NotificationCenter.default.addObserver(
@@ -109,6 +116,21 @@ class SharedCredentialStore {
}
}
+ func getAuthMethods() -> AuthMethods {
+ return enabledAuthMethods
+ }
+
+ func getAuthMethodsAsStrings() -> [String] {
+ var methods: [String] = []
+ if enabledAuthMethods.contains(.faceID) {
+ methods.append("faceid")
+ }
+ if enabledAuthMethods.contains(.password) {
+ methods.append("password")
+ }
+ return methods
+ }
+
// MARK: - Vault Status
func isVaultInitialized() -> Bool {
// Check if encrypted database file exists
@@ -175,8 +197,10 @@ class SharedCredentialStore {
.set(keyData, key: encryptionKeyKey)
print("Key saved to keychain")
} catch {
+ // If storing the key fails, we don't throw an error because it's not critical.
+ // The decryption key will then only be stored in memory which requires the user
+ // to re-authenticate on next app launch. We only print for logging purposes.
print("Failed to save key to keychain: \(error)")
- throw error
}
}
else {
diff --git a/mobile-app/ios/aliasvault/Info.plist b/mobile-app/ios/aliasvault/Info.plist
index fcc2b5819..1df28a5fd 100644
--- a/mobile-app/ios/aliasvault/Info.plist
+++ b/mobile-app/ios/aliasvault/Info.plist
@@ -57,7 +57,7 @@
<true/>
</dict>
<key>NSFaceIDUsageDescription</key>
- <string>AliasVault uses Face ID to store and retrieve your credentials securely on your device.</string>
+ <string>AliasVault uses Face ID to securely store your encryption key, allowing you to access your encrypted data with facial authentication.</string>
<key>NSUserActivityTypes</key>
<array>
<string>$(PRODUCT_BUNDLE_IDENTIFIER).expo.index_route</string>