Skip to content

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

Refactor unlock and centralize logic (#1347)

Leendert de Borst428c715ec226
diff --git a/.vscode/AliasVault.code-workspace b/.vscode/AliasVault.code-workspace
index 6c1c3e307..eec6c1292 100644
--- a/.vscode/AliasVault.code-workspace
+++ b/.vscode/AliasVault.code-workspace
@@ -24,6 +24,7 @@
}
],
"settings": {
- "java.configuration.updateBuildConfiguration": "disabled"
+ "java.configuration.updateBuildConfiguration": "disabled",
+ "i18n-ally.keystyle": "nested"
}
}
diff --git a/apps/mobile-app/app/(tabs)/settings/mobile-unlock/[id].tsx b/apps/mobile-app/app/(tabs)/settings/mobile-unlock/[id].tsx
index 3dabbe778..1e59b4c01 100644
--- a/apps/mobile-app/app/(tabs)/settings/mobile-unlock/[id].tsx
+++ b/apps/mobile-app/app/(tabs)/settings/mobile-unlock/[id].tsx
@@ -3,6 +3,8 @@ import { useState, useEffect } from 'react';
import { View, Alert, StyleSheet } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
+import { VaultUnlockHelper } from '@/utils/VaultUnlockHelper';
+
import { useColors } from '@/hooks/useColorScheme';
import { useTranslation } from '@/hooks/useTranslation';
@@ -174,33 +176,8 @@ export default function MobileUnlockConfirmScreen() : React.ReactNode {
setIsProcessing(true);
try {
- // Check if biometric or PIN is enabled
- const authMethods = await NativeVaultManager.getAuthMethods();
- const isPinEnabled = await NativeVaultManager.isPinEnabled();
- const isBiometricEnabled = authMethods.includes('faceid');
-
- if (!isBiometricEnabled && !isPinEnabled) {
- Alert.alert(
- t('common.error'),
- t('settings.qrScanner.mobileLogin.noAuthMethodEnabled'),
- [
- {
- text: t('common.ok'),
- /**
- * Navigate to the settings tab.
- */
- onPress: (): void => {
- router.replace('/(tabs)/settings');
- },
- },
- ]
- );
- setIsProcessing(false);
- return;
- }
-
// Authenticate user with either biometric or PIN (automatically detected)
- const authenticated = await NativeVaultManager.authenticateUser(
+ const authenticated = await VaultUnlockHelper.authenticateForAction(
t('settings.qrScanner.mobileLogin.confirmTitle'),
t('settings.qrScanner.mobileLogin.confirmSubtitle')
);
diff --git a/apps/mobile-app/app/initialize.tsx b/apps/mobile-app/app/initialize.tsx
index 27c05baec..e215cdd9d 100644
--- a/apps/mobile-app/app/initialize.tsx
+++ b/apps/mobile-app/app/initialize.tsx
@@ -4,6 +4,8 @@ import { useEffect, useRef, useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { Alert, StyleSheet, TouchableOpacity, View } from 'react-native';
+import { VaultUnlockHelper } from '@/utils/VaultUnlockHelper';
+
import { useColors } from '@/hooks/useColorScheme';
import { useVaultSync } from '@/hooks/useVaultSync';
@@ -208,62 +210,30 @@ export default function Initialize() : React.ReactNode {
const hasEncryptedDatabase = await NativeVaultManager.hasEncryptedDatabase();
if (hasEncryptedDatabase) {
- const isFaceIDEnabled = enabledAuthMethods.includes('faceid');
- const isPinEnabled = await NativeVaultManager.isPinEnabled();
-
- // Attempt automatic unlock if FaceID or PIN is enabled
- if (isFaceIDEnabled) {
- // Unlock vault FIRST (before network sync) - this is not skippable
- updateStatus(t('app.status.unlockingVault'));
- const isUnlocked = await dbContext.unlockVault();
-
- if (!isUnlocked) {
- // Failed to unlock, redirect to unlock screen
- router.replace('/unlock');
- return;
- }
-
- // Check if the vault needs migration before syncing
- if (await dbContext.hasPendingMigrations()) {
- router.replace('/upgrade');
- return;
- }
-
- // Vault unlocked successfully - now allow skip button for network operations
- canShowSkipButtonRef.current = true;
- } else if (isPinEnabled) {
- // Attempt PIN unlock
- updateStatus(t('app.status.unlockingVault'));
- try {
- await NativeVaultManager.showPinUnlock();
-
- // Check if vault is now unlocked
- const isNowUnlocked = await NativeVaultManager.isVaultUnlocked();
- if (!isNowUnlocked) {
- // Failed to unlock, redirect to unlock screen
- router.replace('/unlock');
- return;
- }
-
- // Check if the vault needs migration before syncing
- if (await dbContext.hasPendingMigrations()) {
- router.replace('/upgrade');
- return;
- }
-
- // Vault unlocked successfully - now allow skip button for network operations
- canShowSkipButtonRef.current = true;
- } catch (pinErr) {
- // PIN unlock failed or cancelled, redirect to unlock screen
- console.error('PIN unlock failed during initialize:', pinErr);
- router.replace('/unlock');
- return;
+ // Attempt automatic unlock using centralized helper
+ updateStatus(t('app.status.unlockingVault'));
+ const unlockResult = await VaultUnlockHelper.attemptAutomaticUnlock({ enabledAuthMethods, unlockVault: dbContext.unlockVault });
+
+ if (!unlockResult.success) {
+ /*
+ * Unlock failed or cancelled, redirect to unlock screen.
+ * Only log non-cancellation errors to avoid noise.
+ */
+ if (!unlockResult.error?.includes('cancelled')) {
+ console.error('Automatic unlock failed:', unlockResult.error);
}
- } else {
- // No FaceID or PIN, redirect to unlock screen for manual unlock
router.replace('/unlock');
return;
}
+
+ // Check if the vault needs migration before syncing
+ if (await dbContext.hasPendingMigrations()) {
+ router.replace('/upgrade');
+ return;
+ }
+
+ // Vault unlocked successfully - now allow skip button for network operations
+ canShowSkipButtonRef.current = true;
}
} catch (err) {
console.error('Error during initial vault unlock:', err);
diff --git a/apps/mobile-app/app/reinitialize.tsx b/apps/mobile-app/app/reinitialize.tsx
index 7894f7f5c..0b2b46b30 100644
--- a/apps/mobile-app/app/reinitialize.tsx
+++ b/apps/mobile-app/app/reinitialize.tsx
@@ -4,6 +4,8 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { StyleSheet, View, Alert, TouchableOpacity } from 'react-native';
+import { VaultUnlockHelper } from '@/utils/VaultUnlockHelper';
+
import { useColors } from '@/hooks/useColorScheme';
import { useVaultSync } from '@/hooks/useVaultSync';
@@ -191,72 +193,30 @@ export default function ReinitializeScreen() : React.ReactNode {
const hasEncryptedDatabase = await NativeVaultManager.hasEncryptedDatabase();
if (hasEncryptedDatabase) {
- const isFaceIDEnabled = enabledAuthMethods.includes('faceid');
- const isPinEnabled = await NativeVaultManager.isPinEnabled();
-
- // Attempt automatic unlock if FaceID or PIN is enabled
- if (isFaceIDEnabled) {
- // Unlock vault FIRST (before network sync) - this is not skippable
- updateStatus(t('app.status.unlockingVault'));
- const isUnlocked = await dbContext.unlockVault();
-
- if (!isUnlocked) {
- // Failed to unlock, redirect to unlock screen
- router.replace('/unlock');
- return;
- }
+ // Attempt automatic unlock using centralized helper
+ updateStatus(t('app.status.unlockingVault'));
+ const unlockResult = await VaultUnlockHelper.attemptAutomaticUnlock({ enabledAuthMethods, unlockVault: dbContext.unlockVault });
- // Add small delay for UX
- await new Promise(resolve => setTimeout(resolve, 500));
- updateStatus(t('app.status.decryptingVault'));
- await new Promise(resolve => setTimeout(resolve, 750));
+ if (!unlockResult.success) {
+ // Unlock failed, redirect to unlock screen
+ console.error('Automatic unlock failed:', unlockResult.error);
+ router.replace('/unlock');
+ return;
+ }
- // Check if the vault needs migration before syncing
- if (await dbContext.hasPendingMigrations()) {
- router.replace('/upgrade');
- return;
- }
+ // Add small delay for UX
+ await new Promise(resolve => setTimeout(resolve, 300));
+ updateStatus(t('app.status.decryptingVault'));
+ await new Promise(resolve => setTimeout(resolve, 500));
- // Vault unlocked successfully - now allow skip button for network operations
- canShowSkipButtonRef.current = true;
- } else if (isPinEnabled) {
- // Attempt PIN unlock
- updateStatus(t('app.status.unlockingVault'));
- try {
- await NativeVaultManager.showPinUnlock();
-
- // Check if vault is now unlocked
- const isNowUnlocked = await NativeVaultManager.isVaultUnlocked();
- if (!isNowUnlocked) {
- // Failed to unlock, redirect to unlock screen
- router.replace('/unlock');
- return;
- }
-
- // Add small delay for UX
- await new Promise(resolve => setTimeout(resolve, 300));
- updateStatus(t('app.status.decryptingVault'));
- await new Promise(resolve => setTimeout(resolve, 500));
-
- // Check if the vault needs migration before syncing
- if (await dbContext.hasPendingMigrations()) {
- router.replace('/upgrade');
- return;
- }
-
- // Vault unlocked successfully - now allow skip button for network operations
- canShowSkipButtonRef.current = true;
- } catch (pinErr) {
- // PIN unlock failed or cancelled, redirect to unlock screen
- console.error('PIN unlock failed during reinitialize:', pinErr);
- router.replace('/unlock');
- return;
- }
- } else {
- // No FaceID or PIN, redirect to unlock screen
- router.replace('/unlock');
+ // Check if the vault needs migration before syncing
+ if (await dbContext.hasPendingMigrations()) {
+ router.replace('/upgrade');
return;
}
+
+ // Vault unlocked successfully - now allow skip button for network operations
+ canShowSkipButtonRef.current = true;
} else {
// No encrypted database, redirect to unlock screen
router.replace('/unlock');
diff --git a/apps/mobile-app/app/unlock.tsx b/apps/mobile-app/app/unlock.tsx
index cc7f95edc..6af94798c 100644
--- a/apps/mobile-app/app/unlock.tsx
+++ b/apps/mobile-app/app/unlock.tsx
@@ -58,90 +58,30 @@ export default function UnlockScreen() : React.ReactNode {
return params;
}, [logout, getEncryptionKeyDerivationParams]);
- /**
- * Handle PIN unlock using native UI.
- * Falls back to showing password input on cancel.
- */
- const handlePinUnlock = useCallback(async () : Promise<void> => {
- try {
- /*
- * Show native PIN unlock UI
- * This will handle the unlock internally and store the encryption key
- */
- await NativeVaultManager.showPinUnlock();
-
- /*
- * Check if the vault is ready
- */
- if (dbContext.dbAvailable) {
- // Check if the vault is up to date, if not, redirect to the upgrade page.
- if (await dbContext.hasPendingMigrations()) {
- router.replace('/upgrade');
- return;
- }
-
- /*
- * Navigate using centralized navigation logic
- * This ensures we handle pending deep links and return URLs correctly
- */
- navigation.navigateAfterUnlock();
- } else {
- // If db is not available for whatever reason, fallback to password unlock.
- setIsLoading(false);
- Alert.alert(
- t('common.error'),
- t('auth.errors.incorrectPassword'),
- [{ text: t('common.ok'), style: 'default' }]
- );
- }
- } catch (err: unknown) {
- // User cancelled or error occurred
- setIsLoading(false);
-
- if (err && typeof err === 'object' && 'code' in err) {
- // Show password input as fallback on error
- console.error('PIN unlock failed:', err);
-
- // Check if PIN is still enabled and update state accordingly
- const pinStillEnabled = await NativeVaultManager.isPinEnabled();
- setPinAvailable(pinStillEnabled);
- return;
- }
- }
- }, [dbContext, t, setPinAvailable, navigation]);
-
useEffect(() => {
getKeyDerivationParams();
/**
- * Fetch the biometric config and PIN availability, then attempt unlock.
+ * Fetch the biometric config and PIN availability.
*/
- const fetchConfigAndUnlock = async () : Promise<void> => {
+ const fetchConfig = async () : Promise<void> => {
+ // Check if biometrics is available
const enabled = await isBiometricsEnabled();
setIsBiometricsAvailable(enabled);
const displayName = await getBiometricDisplayName();
setBiometricDisplayName(displayName);
- // Check PIN availability
+ // Check if PIN is enabled
const pinEnabled = await NativeVaultManager.isPinEnabled();
setPinAvailable(pinEnabled);
- /*
- * If PIN is enabled, automatically try PIN unlock first
- * Show loading state, then launch native PIN UI
- * If user cancels or PIN is not available, loading stops and password input shows
- */
- if (pinEnabled) {
- await handlePinUnlock();
- } else {
- // No PIN available, stop loading to show password input
- setIsLoading(false);
- }
+ // Stop loading to show password input
+ setIsLoading(false);
};
- fetchConfigAndUnlock();
+ fetchConfig();
- }, [isBiometricsEnabled, getKeyDerivationParams, getBiometricDisplayName, t, handlePinUnlock]);
+ }, [isBiometricsEnabled, getKeyDerivationParams, getBiometricDisplayName]);
/**
* Handle the unlock.
@@ -233,7 +173,7 @@ export default function UnlockScreen() : React.ReactNode {
/**
* Handle the biometrics retry.
*/
- const handleBiometricsRetry = async () : Promise<void> => {
+ const handleUnlockRetry = async () : Promise<void> => {
router.replace('/reinitialize');
};
@@ -460,7 +400,7 @@ export default function UnlockScreen() : React.ReactNode {
{isBiometricsAvailable && (
<RobustPressable
style={styles.faceIdButton}
- onPress={handleBiometricsRetry}
+ onPress={handleUnlockRetry}
>
<ThemedText style={styles.faceIdButtonText}>{t('auth.tryBiometricAgain', { biometric: biometricDisplayName })}</ThemedText>
</RobustPressable>
@@ -468,15 +408,12 @@ export default function UnlockScreen() : React.ReactNode {
{/* Use PIN Button */}
{pinAvailable && (
- <Pressable
- style={styles.linkButton}
- onPress={() => {
- setIsLoading(true);
- handlePinUnlock();
- }}
+ <RobustPressable
+ style={styles.faceIdButton}
+ onPress={handleUnlockRetry}
>
- <ThemedText style={styles.linkButtonText}>{t('auth.unlockWithPin')}</ThemedText>
- </Pressable>
+ <ThemedText style={styles.faceIdButtonText}>{t('auth.tryPinAgain')}</ThemedText>
+ </RobustPressable>
)}
</View>
diff --git a/apps/mobile-app/context/NavigationContext.tsx b/apps/mobile-app/context/NavigationContext.tsx
index 9c17cd9ae..d274d6b18 100644
--- a/apps/mobile-app/context/NavigationContext.tsx
+++ b/apps/mobile-app/context/NavigationContext.tsx
@@ -167,10 +167,10 @@ export const NavigationProvider: React.FC<{ children: React.ReactNode }> = ({ ch
* where the AppState listener fires during app initialization, especially on iOS release builds.
* Also skip during mobile-unlock flow as it has its own authentication.
*/
- if (!pathname?.startsWith('unlock') &&
- !pathname?.startsWith('login') &&
- !pathname?.startsWith('initialize') &&
- !pathname?.startsWith('reinitialize') &&
+ if (!pathname?.startsWith('/unlock') &&
+ !pathname?.startsWith('/login') &&
+ !pathname?.startsWith('/initialize') &&
+ !pathname?.startsWith('/reinitialize') &&
!pathname?.includes('/mobile-unlock/')) {
try {
// Check if vault is unlocked.
@@ -186,10 +186,12 @@ export const NavigationProvider: React.FC<{ children: React.ReactNode }> = ({ ch
}
// Database connection failed, navigate to reinitialize flow
+ console.log('database connection failed, navigating to reinitialize');
router.replace('/reinitialize');
}
} catch {
// Database query failed, navigate to reinitialize flow
+ console.log('database query failed, navigating to reinitialize');
router.replace('/reinitialize');
}
}
diff --git a/apps/mobile-app/i18n/locales/en.json b/apps/mobile-app/i18n/locales/en.json
index 7e74ee0ca..ebb95d8fe 100644
--- a/apps/mobile-app/i18n/locales/en.json
+++ b/apps/mobile-app/i18n/locales/en.json
@@ -49,6 +49,7 @@
"enableBiometric": "Enable {{biometric}}?",
"biometricPrompt": "Would you like to use {{biometric}} to unlock your vault?",
"tryBiometricAgain": "Try {{biometric}} Again",
+ "tryPinAgain": "Try PIN Again",
"authCodeNote": "Note: if you don't have access to your authenticator device, you can reset your 2FA with a recovery code by logging in via the website.",
"errors": {
"credentialsRequired": "Username and password are required",
diff --git a/apps/mobile-app/utils/PostUnlockNavigation.ts b/apps/mobile-app/utils/PostUnlockNavigation.ts
index 83e3e58dd..388178f2e 100644
--- a/apps/mobile-app/utils/PostUnlockNavigation.ts
+++ b/apps/mobile-app/utils/PostUnlockNavigation.ts
@@ -44,7 +44,6 @@ export class PostUnlockNavigation {
// Priority 1: Handle return URL (from reinitialize flow)
if (returnUrl?.path) {
- console.log('[_postunlocknavigation] navigate with returnUrl:', returnUrl);
this.handleReturnUrl(returnUrl, router);
if (clearReturnUrl) {
clearReturnUrl();
@@ -53,7 +52,6 @@ export class PostUnlockNavigation {
}
// Priority 2: Default navigation to credentials
- console.log('[_postunlocknavigation] navigate to default credentials tab');
router.replace('/(tabs)/credentials');
}
diff --git a/apps/mobile-app/utils/VaultUnlockHelper.ts b/apps/mobile-app/utils/VaultUnlockHelper.ts
new file mode 100644
index 000000000..46e38a56f
--- /dev/null
+++ b/apps/mobile-app/utils/VaultUnlockHelper.ts
@@ -0,0 +1,126 @@
+import NativeVaultManager from '@/specs/NativeVaultManager';
+
+export type AuthMethod = 'faceid' | 'password';
+
+export type UnlockResult = {
+ success: boolean;
+ error?: string;
+ redirectToUnlock?: boolean;
+};
+
+/**
+ * Centralized vault unlock logic that handles both biometric and PIN unlock.
+ * This utility is used by initialize.tsx, reinitialize.tsx, and unlock.tsx to avoid code duplication.
+ */
+export class VaultUnlockHelper {
+ /**
+ * Attempt to unlock the vault using available authentication methods.
+ * Tries biometric first (if available), then PIN (if enabled), otherwise indicates manual unlock needed.
+ *
+ * @param params Configuration for unlock attempt
+ * @returns Promise<UnlockResult> indicating success/failure and any actions needed
+ */
+ static async attemptAutomaticUnlock(params: {
+ enabledAuthMethods: AuthMethod[];
+ unlockVault: () => Promise<boolean>; // dbContext.unlockVault for biometric
+ }): Promise<UnlockResult> {
+ const { enabledAuthMethods, unlockVault } = params;
+
+ // Check which authentication methods are available
+ const isFaceIDEnabled = enabledAuthMethods.includes('faceid');
+ const isPinEnabled = await NativeVaultManager.isPinEnabled();
+
+ // Try biometric unlock first (Face ID / Touch ID)
+ if (isFaceIDEnabled) {
+ try {
+ const isUnlocked = await unlockVault();
+ if (!isUnlocked) {
+ return {
+ success: false,
+ error: 'Biometric unlock failed',
+ redirectToUnlock: true,
+ };
+ }
+ return { success: true };
+ } catch (error) {
+ console.error('Biometric unlock error:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Biometric unlock failed',
+ redirectToUnlock: true,
+ };
+ }
+ }
+
+ // Try PIN unlock if biometric is not available
+ if (isPinEnabled) {
+ try {
+ await NativeVaultManager.showPinUnlock();
+
+ // Verify vault is now unlocked
+ const isNowUnlocked = await NativeVaultManager.isVaultUnlocked();
+ if (!isNowUnlocked) {
+ return {
+ success: false,
+ error: 'PIN unlock failed',
+ redirectToUnlock: true,
+ };
+ }
+ return { success: true };
+ } catch (error) {
+ // User cancelled or PIN unlock failed
+ // Only log non-cancellation errors to reduce noise
+ const errorMessage = error instanceof Error ? error.message : 'PIN unlock failed or cancelled';
+ if (!errorMessage.includes('cancelled')) {
+ console.error('PIN unlock error:', error);
+ }
+ return {
+ success: false,
+ error: errorMessage,
+ redirectToUnlock: true,
+ };
+ }
+ }
+
+ // No automatic unlock method available - manual unlock required
+ return {
+ success: false,
+ error: 'No automatic unlock method available',
+ redirectToUnlock: true,
+ };
+ }
+
+ /**
+ * Authenticate user for a specific action (e.g., mobile unlock confirmation).
+ * Uses the native authenticateUser which automatically detects and uses the appropriate method.
+ *
+ * @param title Authentication prompt title
+ * @param subtitle Authentication prompt subtitle
+ * @returns Promise<boolean> indicating if authentication succeeded
+ */
+ static async authenticateForAction(
+ title: string,
+ subtitle: string
+ ): Promise<boolean> {
+ try {
+ const authenticated = await NativeVaultManager.authenticateUser(title, subtitle);
+ return authenticated;
+ } catch (error) {
+ console.error('Authentication error:', error);
+ return false;
+ }
+ }
+
+ /**
+ * Check if any automatic unlock method is available.
+ * @param enabledAuthMethods The enabled authentication methods
+ * @returns Promise<boolean> indicating if automatic unlock is possible
+ */
+ static async hasAutomaticUnlockMethod(
+ enabledAuthMethods: AuthMethod[]
+ ): Promise<boolean> {
+ const isFaceIDEnabled = enabledAuthMethods.includes('faceid');
+ const isPinEnabled = await NativeVaultManager.isPinEnabled();
+ return isFaceIDEnabled || isPinEnabled;
+ }
+}