Skip to content

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

Update routing logic and add NavigationContext (#1347)

Leendert de Borst06b510c496a9
diff --git a/apps/mobile-app/app/_layout.tsx b/apps/mobile-app/app/_layout.tsx
index 6d5e334d2..ce294b2bf 100644
--- a/apps/mobile-app/app/_layout.tsx
+++ b/apps/mobile-app/app/_layout.tsx
@@ -1,6 +1,6 @@
import { DarkTheme, DefaultTheme, ThemeProvider } from '@react-navigation/native';
import { useFonts } from 'expo-font';
-import { Href, Stack, useRouter } from 'expo-router';
+import { Stack, useRouter } from 'expo-router';
import * as SplashScreen from 'expo-splash-screen';
import { useEffect, useRef, useState } from 'react';
import { Linking, StyleSheet, Platform } from 'react-native';
@@ -19,6 +19,7 @@ import { AppProvider } from '@/context/AppContext';
import { AuthProvider } from '@/context/AuthContext';
import { ClipboardCountdownProvider } from '@/context/ClipboardCountdownContext';
import { DbProvider } from '@/context/DbContext';
+import { NavigationProvider, useNavigation } from '@/context/NavigationContext';
import { WebApiProvider } from '@/context/WebApiContext';
import { initI18n } from '@/i18n';
@@ -31,9 +32,9 @@ function RootLayoutNav() : React.ReactNode {
const colorScheme = useColorScheme();
const colors = useColors();
const router = useRouter();
+ const navigation = useNavigation();
const [bootComplete, setBootComplete] = useState(false);
- const [redirectTarget, setRedirectTarget] = useState<string | null>(null);
const hasBooted = useRef(false);
useEffect(() => {
@@ -52,6 +53,7 @@ function RootLayoutNav() : React.ReactNode {
await initI18n();
hasBooted.current = true;
+
// Check if we have a pending deep link and pass it to initialize
const initialUrl = await Linking.getInitialURL();
if (initialUrl) {
@@ -60,19 +62,14 @@ function RootLayoutNav() : React.ReactNode {
.replace('aliasvault://', '')
.replace('exp+aliasvault://', '');
- if (path.startsWith('mobile-login/') || path.includes('credentials/')) {
- setRedirectTarget(`/initialize?pendingDeepLink=${encodeURIComponent(initialUrl)}`);
- } else {
- setRedirectTarget('/initialize');
- }
- } else {
- setRedirectTarget('/initialize');
+ navigation.setReturnUrl({ path });
}
+
setBootComplete(true);
};
initializeApp();
- }, []);
+ }, [navigation, router]);
useEffect(() => {
/**
@@ -83,14 +80,11 @@ function RootLayoutNav() : React.ReactNode {
return;
}
- if (redirectTarget) {
- // Navigate to the redirect target (may include pendingDeepLink param)
- router.replace(redirectTarget as Href);
- }
+ router.replace('/initialize');
};
redirect();
- }, [bootComplete, redirectTarget, router]);
+ }, [bootComplete, router]);
const styles = StyleSheet.create({
container: {
@@ -177,18 +171,20 @@ export default function RootLayout() : React.ReactNode {
}
return (
- <DbProvider>
- <AuthProvider>
- <WebApiProvider>
- <AppProvider>
- <ClipboardCountdownProvider>
- <GestureHandlerRootView>
- <RootLayoutNav />
- </GestureHandlerRootView>
- </ClipboardCountdownProvider>
- </AppProvider>
- </WebApiProvider>
- </AuthProvider>
- </DbProvider>
+ <NavigationProvider>
+ <DbProvider>
+ <AuthProvider>
+ <WebApiProvider>
+ <AppProvider>
+ <ClipboardCountdownProvider>
+ <GestureHandlerRootView>
+ <RootLayoutNav />
+ </GestureHandlerRootView>
+ </ClipboardCountdownProvider>
+ </AppProvider>
+ </WebApiProvider>
+ </AuthProvider>
+ </DbProvider>
+ </NavigationProvider>
);
}
diff --git a/apps/mobile-app/app/initialize.tsx b/apps/mobile-app/app/initialize.tsx
index ce4cd8cee..299d15685 100644
--- a/apps/mobile-app/app/initialize.tsx
+++ b/apps/mobile-app/app/initialize.tsx
@@ -1,11 +1,9 @@
import { Ionicons } from '@expo/vector-icons';
-import { Href, useRouter, useLocalSearchParams } from 'expo-router';
+import { useRouter } from 'expo-router';
import { useEffect, useRef, useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { Alert, StyleSheet, TouchableOpacity, View } from 'react-native';
-import { PostUnlockNavigation } from '@/utils/PostUnlockNavigation';
-
import { useColors } from '@/hooks/useColorScheme';
import { useVaultSync } from '@/hooks/useVaultSync';
@@ -13,6 +11,7 @@ import LoadingIndicator from '@/components/LoadingIndicator';
import { ThemedView } from '@/components/themed/ThemedView';
import { useApp } from '@/context/AppContext';
import { useDb } from '@/context/DbContext';
+import { useNavigation } from '@/context/NavigationContext';
import NativeVaultManager from '@/specs/NativeVaultManager';
/**
@@ -20,7 +19,6 @@ import NativeVaultManager from '@/specs/NativeVaultManager';
*/
export default function Initialize() : React.ReactNode {
const router = useRouter();
- const { pendingDeepLink } = useLocalSearchParams<{ pendingDeepLink?: string }>();
const [status, setStatus] = useState('');
const [showSkipButton, setShowSkipButton] = useState(false);
const hasInitialized = useRef(false);
@@ -30,20 +28,11 @@ export default function Initialize() : React.ReactNode {
const abortControllerRef = useRef<AbortController | null>(null);
const { t } = useTranslation();
const app = useApp();
+ const navigation = useNavigation();
const { syncVault } = useVaultSync();
const dbContext = useDb();
const colors = useColors();
- /**
- * Build unlock URL with pending deep link parameter if available.
- */
- const getUnlockUrl = useCallback((): Href => {
- if (pendingDeepLink) {
- return `/unlock?pendingDeepLink=${encodeURIComponent(pendingDeepLink)}` as Href;
- }
- return '/unlock';
- }, [pendingDeepLink]);
-
/**
* Update status with smart skip button logic.
* Normalizes status by removing animation dots and manages skip button visibility.
@@ -85,15 +74,7 @@ export default function Initialize() : React.ReactNode {
// Don't show the alert if we're already in offline mode
if (app.isOffline) {
console.debug('Already in offline mode, skipping offline flow alert');
- PostUnlockNavigation.navigate({
- pendingDeepLink,
- returnUrl: app.returnUrl,
- router,
- /**
- * Clear the return URL after navigation.
- */
- clearReturnUrl: () => app.setReturnUrl(null),
- });
+ navigation.navigateAfterUnlock();
return;
}
@@ -115,7 +96,7 @@ export default function Initialize() : React.ReactNode {
// No encrypted database
if (!hasEncryptedDatabase) {
- router.replace(getUnlockUrl());
+ router.replace('/unlock');
return;
}
@@ -125,7 +106,7 @@ export default function Initialize() : React.ReactNode {
// FaceID not enabled
const isFaceIDEnabled = enabledAuthMethods.includes('faceid');
if (!isFaceIDEnabled) {
- router.replace(getUnlockUrl());
+ router.replace('/unlock');
return;
}
@@ -135,7 +116,7 @@ export default function Initialize() : React.ReactNode {
// Vault couldn't be unlocked
if (!isUnlocked) {
- router.replace(getUnlockUrl());
+ router.replace('/unlock');
return;
}
@@ -149,18 +130,10 @@ export default function Initialize() : React.ReactNode {
}
// Success - use centralized navigation logic
- PostUnlockNavigation.navigate({
- pendingDeepLink,
- returnUrl: app.returnUrl,
- router,
- /**
- * Clear the return URL after navigation.
- */
- clearReturnUrl: () => app.setReturnUrl(null),
- });
+ navigation.navigateAfterUnlock();
} catch (err) {
console.error('Error during offline vault unlock:', err);
- router.replace(getUnlockUrl());
+ router.replace('/unlock');
}
}
},
@@ -198,7 +171,7 @@ export default function Initialize() : React.ReactNode {
}
]
);
- }, [dbContext, router, app, t, updateStatus, pendingDeepLink, getUnlockUrl]);
+ }, [dbContext, router, app, navigation, t, updateStatus]);
useEffect(() => {
// Ensure this only runs once.
@@ -245,7 +218,7 @@ export default function Initialize() : React.ReactNode {
if (!isUnlocked) {
// Failed to unlock, redirect to unlock screen
- router.replace(getUnlockUrl());
+ router.replace('/unlock');
return;
}
@@ -259,13 +232,13 @@ export default function Initialize() : React.ReactNode {
canShowSkipButtonRef.current = true;
} else {
// No FaceID, redirect to unlock screen for manual unlock
- router.replace(getUnlockUrl());
+ router.replace('/unlock');
return;
}
}
} catch (err) {
console.error('Error during initial vault unlock:', err);
- router.replace(getUnlockUrl());
+ router.replace('/unlock');
return;
}
} else {
@@ -302,15 +275,7 @@ export default function Initialize() : React.ReactNode {
*/
onSuccess: async () => {
// Use centralized navigation logic
- PostUnlockNavigation.navigate({
- pendingDeepLink,
- returnUrl: app.returnUrl,
- router,
- /**
- * Clear the return URL after navigation.
- */
- clearReturnUrl: () => app.setReturnUrl(null),
- });
+ navigation.navigateAfterUnlock();
},
/**
* Handle offline state and prompt user for action.
@@ -331,7 +296,7 @@ export default function Initialize() : React.ReactNode {
error,
[{ text: t('common.ok'), style: 'default' }]
);
- router.replace(getUnlockUrl());
+ router.replace('/unlock');
return;
},
/**
@@ -354,7 +319,7 @@ export default function Initialize() : React.ReactNode {
clearTimeout(skipButtonTimeoutRef.current);
}
};
- }, [dbContext, syncVault, app, router, t, handleOfflineFlow, updateStatus, pendingDeepLink, getUnlockUrl]);
+ }, [dbContext, syncVault, app, router, navigation, t, handleOfflineFlow, updateStatus]);
/**
* Handle skip button press by calling the offline handler.
diff --git a/apps/mobile-app/app/reinitialize.tsx b/apps/mobile-app/app/reinitialize.tsx
index 2ff750a7f..411ec11f2 100644
--- a/apps/mobile-app/app/reinitialize.tsx
+++ b/apps/mobile-app/app/reinitialize.tsx
@@ -4,8 +4,6 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { StyleSheet, View, Alert, TouchableOpacity } from 'react-native';
-import { PostUnlockNavigation } from '@/utils/PostUnlockNavigation';
-
import { useColors } from '@/hooks/useColorScheme';
import { useVaultSync } from '@/hooks/useVaultSync';
@@ -14,6 +12,7 @@ import { ThemedText } from '@/components/themed/ThemedText';
import { ThemedView } from '@/components/themed/ThemedView';
import { useApp } from '@/context/AppContext';
import { useDb } from '@/context/DbContext';
+import { useNavigation } from '@/context/NavigationContext';
import NativeVaultManager from '@/specs/NativeVaultManager';
/**
@@ -23,6 +22,7 @@ import NativeVaultManager from '@/specs/NativeVaultManager';
export default function ReinitializeScreen() : React.ReactNode {
const app = useApp();
const dbContext = useDb();
+ const navigation = useNavigation();
const { syncVault } = useVaultSync();
const [status, setStatus] = useState('');
const [showSkipButton, setShowSkipButton] = useState(false);
@@ -123,14 +123,7 @@ export default function ReinitializeScreen() : React.ReactNode {
}
// Use centralized navigation logic
- PostUnlockNavigation.navigate({
- returnUrl: app.returnUrl,
- router,
- /**
- * Clear the return URL after navigation.
- */
- clearReturnUrl: () => app.setReturnUrl(null),
- });
+ navigation.navigateAfterUnlock();
} catch (err) {
console.error('Error during offline vault unlock:', err);
router.replace('/unlock');
@@ -165,7 +158,7 @@ export default function ReinitializeScreen() : React.ReactNode {
}
]
);
- }, [app, dbContext, t, updateStatus]);
+ }, [app, dbContext, navigation, t, updateStatus]);
useEffect(() => {
if (hasInitialized.current) {
@@ -303,14 +296,7 @@ export default function ReinitializeScreen() : React.ReactNode {
* Handle successful vault sync.
*/
onSuccess: async () => {
- PostUnlockNavigation.navigate({
- returnUrl: app.returnUrl,
- router,
- /**
- * Clear the return URL after navigation.
- */
- clearReturnUrl: () => app.setReturnUrl(null),
- });
+ navigation.navigateAfterUnlock();
},
/**
* Handle error during vault sync.
@@ -319,14 +305,7 @@ export default function ReinitializeScreen() : React.ReactNode {
onError: (error: string) => {
console.error('Vault sync error during reinitialize:', error);
// Even if sync fails, vault is already unlocked, use centralized navigation
- PostUnlockNavigation.navigate({
- returnUrl: app.returnUrl,
- router,
- /**
- * Clear the return URL after navigation.
- */
- clearReturnUrl: () => app.setReturnUrl(null),
- });
+ navigation.navigateAfterUnlock();
},
/**
* Handle offline state and prompt user for action.
@@ -344,7 +323,7 @@ export default function ReinitializeScreen() : React.ReactNode {
};
initialize();
- }, [syncVault, app, dbContext, t, handleOfflineFlow, updateStatus]);
+ }, [syncVault, app, dbContext, navigation, t, handleOfflineFlow, updateStatus]);
/**
* Handle skip button press by calling the offline handler.
diff --git a/apps/mobile-app/app/unlock.tsx b/apps/mobile-app/app/unlock.tsx
index 345854a85..cc7f95edc 100644
--- a/apps/mobile-app/app/unlock.tsx
+++ b/apps/mobile-app/app/unlock.tsx
@@ -2,12 +2,11 @@ import { Buffer } from 'buffer';
import { MaterialIcons } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
-import { router, useLocalSearchParams } from 'expo-router';
+import { router } from 'expo-router';
import { useState, useEffect, useCallback } from 'react';
import { StyleSheet, View, TextInput, Alert, KeyboardAvoidingView, Platform, ScrollView, Dimensions, TouchableWithoutFeedback, Keyboard, Text, Pressable } from 'react-native';
import EncryptionUtility from '@/utils/EncryptionUtility';
-import { PostUnlockNavigation } from '@/utils/PostUnlockNavigation';
import { VaultVersionIncompatibleError } from '@/utils/types/errors/VaultVersionIncompatibleError';
import { useColors } from '@/hooks/useColorScheme';
@@ -21,15 +20,16 @@ import { Avatar } from '@/components/ui/Avatar';
import { RobustPressable } from '@/components/ui/RobustPressable';
import { useApp } from '@/context/AppContext';
import { useDb } from '@/context/DbContext';
+import { useNavigation } from '@/context/NavigationContext';
import NativeVaultManager from '@/specs/NativeVaultManager';
/**
* Unlock screen.
*/
export default function UnlockScreen() : React.ReactNode {
- const { isLoggedIn, username, isBiometricsEnabled, getBiometricDisplayName, getEncryptionKeyDerivationParams, logout, returnUrl, setReturnUrl } = useApp();
+ const { isLoggedIn, username, isBiometricsEnabled, getBiometricDisplayName, getEncryptionKeyDerivationParams, logout } = useApp();
const dbContext = useDb();
- const { pendingDeepLink } = useLocalSearchParams<{ pendingDeepLink?: string }>();
+ const navigation = useNavigation();
const [password, setPassword] = useState('');
const [isLoading, setIsLoading] = useState(true);
const [isBiometricsAvailable, setIsBiometricsAvailable] = useState(false);
@@ -84,15 +84,7 @@ export default function UnlockScreen() : React.ReactNode {
* Navigate using centralized navigation logic
* This ensures we handle pending deep links and return URLs correctly
*/
- PostUnlockNavigation.navigate({
- pendingDeepLink,
- returnUrl,
- router,
- /**
- * Clear the return URL after navigation.
- */
- clearReturnUrl: () => setReturnUrl(null),
- });
+ navigation.navigateAfterUnlock();
} else {
// If db is not available for whatever reason, fallback to password unlock.
setIsLoading(false);
@@ -116,7 +108,7 @@ export default function UnlockScreen() : React.ReactNode {
return;
}
}
- }, [dbContext, t, setPinAvailable, pendingDeepLink, returnUrl, setReturnUrl]);
+ }, [dbContext, t, setPinAvailable, navigation]);
useEffect(() => {
getKeyDerivationParams();
@@ -201,15 +193,7 @@ export default function UnlockScreen() : React.ReactNode {
* Navigate using centralized navigation logic
* This ensures we handle pending deep links and return URLs correctly
*/
- PostUnlockNavigation.navigate({
- pendingDeepLink,
- returnUrl,
- router,
- /**
- * Clear the return URL after navigation.
- */
- clearReturnUrl: () => setReturnUrl(null),
- });
+ navigation.navigateAfterUnlock();
} else {
Alert.alert(
t('common.error'),
diff --git a/apps/mobile-app/context/AppContext.tsx b/apps/mobile-app/context/AppContext.tsx
index 61a9d941e..3c8493ed3 100644
--- a/apps/mobile-app/context/AppContext.tsx
+++ b/apps/mobile-app/context/AppContext.tsx
@@ -34,9 +34,6 @@ type AppContextType = {
// Autofill methods
shouldShowAutofillReminder: boolean;
markAutofillConfigured: () => Promise<void>;
- // Return URL methods
- returnUrl: { path: string; params?: Record<string, string> | undefined } | null;
- setReturnUrl: (url: { path: string; params?: Record<string, string> } | null) => void;
}
export type AuthMethod = 'faceid' | 'password';
@@ -105,7 +102,6 @@ export const AppProvider: React.FC<{ children: React.ReactNode }> = ({ children
username: auth.username,
isOffline: auth.isOffline,
shouldShowAutofillReminder: auth.shouldShowAutofillReminder,
- returnUrl: auth.returnUrl,
// Wrap auth methods
logout,
initializeAuth: auth.initializeAuth,
@@ -126,14 +122,12 @@ export const AppProvider: React.FC<{ children: React.ReactNode }> = ({ children
verifyPassword: auth.verifyPassword,
getEncryptionKeyDerivationParams: auth.getEncryptionKeyDerivationParams,
markAutofillConfigured: auth.markAutofillConfigured,
- setReturnUrl: auth.setReturnUrl
}), [
auth.isInitialized,
auth.isLoggedIn,
auth.username,
auth.isOffline,
auth.shouldShowAutofillReminder,
- auth.returnUrl,
auth.initializeAuth,
auth.setAuthTokens,
auth.login,
@@ -151,7 +145,6 @@ export const AppProvider: React.FC<{ children: React.ReactNode }> = ({ children
auth.verifyPassword,
auth.getEncryptionKeyDerivationParams,
auth.markAutofillConfigured,
- auth.setReturnUrl,
logout
]);
diff --git a/apps/mobile-app/context/AuthContext.tsx b/apps/mobile-app/context/AuthContext.tsx
index de2404ad7..7a821d821 100644
--- a/apps/mobile-app/context/AuthContext.tsx
+++ b/apps/mobile-app/context/AuthContext.tsx
@@ -3,9 +3,8 @@ import { Buffer } from 'buffer';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { NavigationContainerRef, ParamListBase } from '@react-navigation/native';
import * as LocalAuthentication from 'expo-local-authentication';
-import { router, useGlobalSearchParams, usePathname } from 'expo-router';
-import React, { createContext, useContext, useState, useEffect, useMemo, useCallback, useRef } from 'react';
-import { Alert, AppState, Platform } from 'react-native';
+import React, { createContext, useContext, useState, useEffect, useMemo, useCallback } from 'react';
+import { Alert, Platform } from 'react-native';
import EncryptionUtility from '@/utils/EncryptionUtility';
import { useDb } from '@/context/DbContext';
@@ -42,9 +41,6 @@ type AuthContextType = {
// Autofill methods
shouldShowAutofillReminder: boolean;
markAutofillConfigured: () => Promise<void>;
- // Return URL methods (basic return URL and deep link URL which if set acts as an override)
- returnUrl: { path: string; params?: Record<string, string> | undefined } | null;
- setReturnUrl: (url: { path: string; params?: object } | null) => void;
}
const AUTOFILL_CONFIGURED_KEY = 'autofill_configured';
@@ -58,22 +54,15 @@ const AuthContext = createContext<AuthContextType | undefined>(undefined);
/**
* AuthProvider to provide the authentication state to the app that components can use.
*/
-export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
+export const AuthProvider: React.FC<{
+ children: React.ReactNode;
+}> = ({ children }) => {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [isInitialized, setIsInitialized] = useState(false);
const [username, setUsername] = useState<string | null>(null);
const [shouldShowAutofillReminder, setShouldShowAutofillReminder] = useState(false);
- const [returnUrl, setReturnUrl] = useState<{ path: string; params?: object } | null>(null);
const [isOffline, setIsOffline] = useState(false);
- const appState = useRef(AppState.currentState);
const dbContext = useDb();
- const pathname = usePathname();
- const params = useGlobalSearchParams();
- const lastRouteRef = useRef<{ path: string, params?: object }>({ path: pathname, params });
-
- useEffect(() => {
- lastRouteRef.current = { path: pathname, params };
- }, [pathname, params]);
/**
* Get enabled auth methods from the native module
@@ -362,18 +351,6 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
}
}, []);
- /**
- * Check if the vault is unlocked.
- */
- const isVaultUnlocked = useCallback(async (): Promise<boolean> => {
- try {
- return await NativeVaultManager.isVaultUnlocked();
- } catch (error) {
- console.error('Failed to check vault status:', error);
- return false;
- }
- }, []);
-
/**
* Get the encryption key derivation parameters from native storage.
* Returns parsed parameters or null if not available.
@@ -424,46 +401,6 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
return currentPasswordHashBase64;
}, [dbContext, getEncryptionKeyDerivationParams]);
- // Handle app state changes
- useEffect(() => {
- const appstateSubscription = AppState.addEventListener('change', async (nextAppState) => {
- if (appState.current.match(/inactive|background/) && nextAppState === 'active') {
- /**
- * App coming to foreground
- * Skip vault re-initialization checks during unlock, login, initialize, and reinitialize flows to prevent race conditions
- * where the AppState listener fires during app initialization, especially on iOS release builds.
- */
- if (!pathname?.startsWith('unlock') && !pathname?.startsWith('login') && !pathname?.startsWith('initialize') && !pathname?.startsWith('reinitialize')) {
- try {
- // Check if vault is unlocked.
- const isUnlocked = await isVaultUnlocked();
- if (!isUnlocked) {
- // Get current full URL including query params
- const currentRoute = lastRouteRef.current;
- if (currentRoute?.path) {
- setReturnUrl({
- path: currentRoute.path,
- params: currentRoute.params
- });
- }
-
- // Database connection failed, navigate to reinitialize flow
- router.replace('/reinitialize');
- }
- } catch {
- // Database query failed, navigate to reinitialize flow
- router.replace('/reinitialize');
- }
- }
- }
- appState.current = nextAppState;
- });
-
- return (): void => {
- appstateSubscription.remove();
- };
- }, [isVaultUnlocked, pathname]);
-
/**
* Load autofill state from storage
*/
@@ -498,7 +435,6 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
isInitialized,
username,
shouldShowAutofillReminder,
- returnUrl,
isOffline,
getEnabledAuthMethods,
isBiometricsEnabled,
@@ -515,7 +451,6 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
setClipboardClearTimeout,
getBiometricDisplayName,
markAutofillConfigured,
- setReturnUrl,
verifyPassword,
getEncryptionKeyDerivationParams,
setOfflineMode,
@@ -524,7 +459,6 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
isInitialized,
username,
shouldShowAutofillReminder,
- returnUrl,
isOffline,
getEnabledAuthMethods,
isBiometricsEnabled,
@@ -541,7 +475,6 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
setClipboardClearTimeout,
getBiometricDisplayName,
markAutofillConfigured,
- setReturnUrl,
verifyPassword,
getEncryptionKeyDerivationParams,
setOfflineMode,
diff --git a/apps/mobile-app/context/NavigationContext.tsx b/apps/mobile-app/context/NavigationContext.tsx
new file mode 100644
index 000000000..82e4ffd2b
--- /dev/null
+++ b/apps/mobile-app/context/NavigationContext.tsx
@@ -0,0 +1,222 @@
+import { Href, useRouter, usePathname, useGlobalSearchParams } from 'expo-router';
+import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
+import { AppState } from 'react-native';
+
+import NativeVaultManager from '@/specs/NativeVaultManager';
+
+type NavigationContextType = {
+ /**
+ * Return URL to navigate to after successful vault unlock.
+ * This is set when the app is backgrounded and vault is locked.
+ */
+ returnUrl: { path: string; params?: Record<string, string> } | null;
+
+ /**
+ * Set the return URL for post-unlock navigation.
+ */
+ setReturnUrl: (url: { path: string; params?: Record<string, string> } | null) => void;
+
+ /**
+ * Navigate to the appropriate destination after successful vault unlock.
+ * Handles return URLs and default navigation to credentials tab.
+ */
+ navigateAfterUnlock: () => void;
+}
+
+const NavigationContext = createContext<NavigationContextType | undefined>(undefined);
+
+/**
+ * NavigationProvider to provide centralized navigation logic, particularly for post-unlock flows.
+ */
+export const NavigationProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
+ const router = useRouter();
+ const pathname = usePathname();
+ const params = useGlobalSearchParams();
+ const [returnUrl, setReturnUrl] = useState<{ path: string; params?: Record<string, string> } | null>(null);
+ const appState = useRef(AppState.currentState);
+ const lastRouteRef = useRef<{ path: string, params?: object }>({ path: pathname, params });
+
+ // Track current route for vault lock recovery
+ useEffect(() => {
+ lastRouteRef.current = { path: pathname, params };
+ }, [pathname, params]);
+
+ /**
+ * Navigate to the appropriate destination after successful vault unlock.
+ * Priority order:
+ * 1. Return URL (from reinitialize flow or _layout.tsx)
+ * 2. Default credentials tab
+ */
+ const navigateAfterUnlock = useCallback((): void => {
+ // Priority 1: Handle return URL (from reinitialize flow)
+ if (returnUrl?.path) {
+ const url = returnUrl;
+ setReturnUrl(null);
+ handleReturnUrl(url, router);
+ return;
+ }
+
+ // Priority 2: Default navigation to credentials
+ router.replace('/(tabs)/credentials');
+ }, [returnUrl, router]);
+
+ /**
+ * Handle return URL navigation (from reinitialize flow).
+ */
+ const handleReturnUrl = (
+ returnUrl: { path: string; params?: Record<string, string> },
+ router: ReturnType<typeof useRouter>
+ ): void => {
+ // Normalize the path using centralized function
+ const normalizedPath = normalizeDeepLinkPath(returnUrl.path);
+ const params = returnUrl.params || {};
+
+ // Check if this is a detail route (has a sub-page after the tab)
+ const isCredentialRoute = normalizedPath.includes('/(tabs)/credentials/');
+ const isSettingsRoute = normalizedPath.includes('/(tabs)/settings/') &&
+ !normalizedPath.endsWith('/(tabs)/settings');
+
+ if (isCredentialRoute) {
+ // Navigate to credentials tab first, then push detail page
+ router.replace('/(tabs)/credentials');
+ setTimeout(() => {
+ const queryParams = new URLSearchParams(params as Record<string, string>).toString();
+ const targetUrl = queryParams ? `${normalizedPath}?${queryParams}` : normalizedPath;
+ router.push(targetUrl as Href);
+ }, 0);
+ } else if (isSettingsRoute) {
+ // Navigate to settings tab first, then push detail page
+ router.replace('/(tabs)/settings');
+ setTimeout(() => {
+ const queryParams = new URLSearchParams(params as Record<string, string>).toString();
+ const targetUrl = queryParams ? `${normalizedPath}?${queryParams}` : normalizedPath;
+ router.push(targetUrl as Href);
+ }, 0);
+ } else {
+ // Direct navigation for root tab routes
+ // If there are query params, append them as query string
+ if (Object.keys(params).length > 0) {
+ const queryParams = new URLSearchParams(params as Record<string, string>).toString();
+ const targetUrl = `${normalizedPath}?${queryParams}`;
+ router.replace(targetUrl as Href);
+ } else {
+ router.replace(normalizedPath as Href);
+ }
+ }
+ };
+
+ /**
+ * Normalize a deep link or path to ensure it has the correct /(tabs)/ prefix.
+ *
+ * Supports:
+ * - Action-based URLs: aliasvault://open/mobile-unlock/[id]
+ * - Direct routes: aliasvault://credentials/[id], aliasvault://settings/[page]
+ */
+ const normalizeDeepLinkPath = (urlOrPath: string): string => {
+ // Remove all URL schemes first
+ let path = urlOrPath
+ .replace('net.aliasvault.app://', '')
+ .replace('aliasvault://', '')
+ .replace('exp+aliasvault://', '');
+
+ // If it already has /(tabs)/ prefix, return as is
+ if (path.startsWith('/(tabs)/')) {
+ return path;
+ }
+
+ // Handle credential paths
+ if (path.startsWith('credentials/') || path.includes('/credentials/')) {
+ if (!path.startsWith('/')) {
+ path = `/${path}`;
+ }
+ return `/(tabs)${path}`;
+ }
+
+ // Handle settings paths
+ if (path.startsWith('settings/') || path.startsWith('/settings')) {
+ if (!path.startsWith('/')) {
+ path = `/${path}`;
+ }
+ return `/(tabs)${path}`;
+ }
+
+ return path;
+ };
+
+ /**
+ * Check if the vault is unlocked.
+ */
+ const isVaultUnlocked = useCallback(async (): Promise<boolean> => {
+ try {
+ return await NativeVaultManager.isVaultUnlocked();
+ } catch (error) {
+ console.error('Failed to check vault status:', error);
+ return false;
+ }
+ }, []);
+
+ /**
+ * Handle app state changes - detect when vault is locked and save return URL.
+ */
+ useEffect(() => {
+ const appstateSubscription = AppState.addEventListener('change', async (nextAppState) => {
+ if (appState.current.match(/inactive|background/) && nextAppState === 'active') {
+ /**
+ * App coming to foreground
+ * Skip vault re-initialization checks during unlock, login, initialize, and reinitialize flows to prevent race conditions
+ * where the AppState listener fires during app initialization, especially on iOS release builds.
+ */
+ if (!pathname?.startsWith('unlock') && !pathname?.startsWith('login') && !pathname?.startsWith('initialize') && !pathname?.startsWith('reinitialize')) {
+ try {
+ // Check if vault is unlocked.
+ const isUnlocked = await isVaultUnlocked();
+ if (!isUnlocked) {
+ // Get current full URL including query params
+ const currentRoute = lastRouteRef.current;
+ if (currentRoute?.path) {
+ setReturnUrl({
+ path: currentRoute.path,
+ params: currentRoute.params as Record<string, string>
+ });
+ }
+
+ // Database connection failed, navigate to reinitialize flow
+ router.replace('/reinitialize');
+ }
+ } catch {
+ // Database query failed, navigate to reinitialize flow
+ router.replace('/reinitialize');
+ }
+ }
+ }
+ appState.current = nextAppState;
+ });
+
+ return (): void => {
+ appstateSubscription.remove();
+ };
+ }, [isVaultUnlocked, pathname, router]);
+
+ const contextValue = useMemo(() => ({
+ returnUrl,
+ setReturnUrl,
+ navigateAfterUnlock,
+ }), [returnUrl, navigateAfterUnlock]);
+
+ return (
+ <NavigationContext.Provider value={contextValue}>
+ {children}
+ </NavigationContext.Provider>
+ );
+};
+
+/**
+ * Hook to use the NavigationContext.
+ */
+export const useNavigation = (): NavigationContextType => {
+ const context = useContext(NavigationContext);
+ if (context === undefined) {
+ throw new Error('useNavigation must be used within a NavigationProvider');
+ }
+ return context;
+};
diff --git a/apps/mobile-app/utils/PostUnlockNavigation.ts b/apps/mobile-app/utils/PostUnlockNavigation.ts
index 0ed0cf488..83e3e58dd 100644
--- a/apps/mobile-app/utils/PostUnlockNavigation.ts
+++ b/apps/mobile-app/utils/PostUnlockNavigation.ts
@@ -1,64 +1,10 @@
import { Href } from 'expo-router';
import { Linking } from 'react-native';
-/**
- * Normalize a deep link or path to ensure it has the correct /(tabs)/ prefix.
- * Exported for use in _layout.tsx and other navigation logic.
- *
- * Supports:
- * - Action-based URLs: aliasvault://open/mobile-unlock/[id]
- * - Direct routes: aliasvault://credentials/[id], aliasvault://settings/[page]
- */
-export function normalizeDeepLinkPath(urlOrPath: string): string {
- // Remove all URL schemes first
- let path = urlOrPath
- .replace('net.aliasvault.app://', '')
- .replace('aliasvault://', '')
- .replace('exp+aliasvault://', '');
-
- // If it already has /(tabs)/ prefix, return as is
- if (path.startsWith('/(tabs)/')) {
- return path;
- }
-
- // Handle action-based paths: $/mobile-unlock/[requestId]
- if (path.startsWith('open/mobile-unlock/')) {
- return `/(tabs)/settings/mobile-unlock/${path.split('/')[2]}`;
- }
-
- // Handle credential paths
- if (path.startsWith('credentials/') || path.includes('/credentials/')) {
- if (!path.startsWith('/')) {
- path = `/${path}`;
- }
- return `/(tabs)${path}`;
- }
-
- // Handle settings paths
- if (path.startsWith('settings/') || path.startsWith('/settings')) {
- if (!path.startsWith('/')) {
- path = `/${path}`;
- }
- return `/(tabs)${path}`;
- }
-
- // If path starts with /, add /(tabs) prefix
- if (path.startsWith('/')) {
- return `/(tabs)${path}`;
- }
-
- return path;
-}
-
/**
* Post-unlock navigation options.
*/
export type PostUnlockNavigationOptions = {
- /**
- * Pending deep link URL to process after unlock (from QR code scan during boot).
- */
- pendingDeepLink?: string | null;
-
/**
* Return URL from app context (for reinitialize flow).
*/
@@ -84,27 +30,21 @@ export type PostUnlockNavigationOptions = {
* This ensures consistent navigation behavior across all unlock flows:
* - initialize.tsx (cold boot with biometric unlock)
* - unlock.tsx (manual password/PIN unlock)
- * - reinitialize.tsx (timeout recovery with biometric unlock)
+ * - reinitialize.tsx (vault lock due to timeout, requiring unlock again)
*/
export class PostUnlockNavigation {
/**
* Navigate to the appropriate destination after successful vault unlock.
* Priority order:
- * 1. Pending deep link (from QR code scan during cold boot)
- * 2. Return URL (from reinitialize flow)
- * 3. Default credentials tab
+ * 1. Return URL (from reinitialize flow or _layout.tsx)
+ * 2. Default credentials tab
*/
static navigate(options: PostUnlockNavigationOptions): void {
- const { pendingDeepLink, returnUrl, router, clearReturnUrl } = options;
+ const { returnUrl, router, clearReturnUrl } = options;
- // Priority 1: Handle pending deep link (e.g. from QR code scan or native autofill interface)
- if (pendingDeepLink) {
- this.handlePendingDeepLink(pendingDeepLink, router);
- return;
- }
-
- // Priority 2: Handle return URL (from reinitialize flow)
+ // 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();
@@ -112,53 +52,11 @@ export class PostUnlockNavigation {
return;
}
- // Priority 3: Default navigation to credentials
+ // Priority 2: Default navigation to credentials
+ console.log('[_postunlocknavigation] navigate to default credentials tab');
router.replace('/(tabs)/credentials');
}
- /**
- * Handle pending deep link after successful unlock.
- */
- private static handlePendingDeepLink(
- deepLink: string,
- router: PostUnlockNavigationOptions['router']
- ): void {
- // Normalize the deep link to get the correct path with /(tabs)/ prefix
- const normalizedPath = normalizeDeepLinkPath(deepLink);
-
- // Check if this is a mobile-login QR scanner route (already formatted with query params)
- if (normalizedPath.includes('/qr-scanner?url=')) {
- // First navigate to settings tab
- router.replace('/(tabs)/settings');
- // Then navigate to qr-scanner
- setTimeout(() => {
- router.push(normalizedPath as Href);
- }, 0);
- return;
- }
-
- // Check if this is a detail route (credentials or settings sub-pages)
- const isCredentialRoute = normalizedPath.includes('/(tabs)/credentials/');
- const isSettingsRoute = normalizedPath.includes('/(tabs)/settings/');
-
- if (isCredentialRoute) {
- // Navigate to credentials tab first, then push detail page
- router.replace('/(tabs)/credentials');
- setTimeout(() => {
- router.push(normalizedPath as Href);
- }, 0);
- } else if (isSettingsRoute) {
- // Navigate to settings tab first, then push detail page
- router.replace('/(tabs)/settings');
- setTimeout(() => {
- router.push(normalizedPath as Href);
- }, 0);
- } else {
- // Direct navigation for root tab routes
- router.replace(normalizedPath as Href);
- }
- }
-
/**
* Handle return URL navigation (from reinitialize flow).
*/
@@ -167,7 +65,7 @@ export class PostUnlockNavigation {
router: PostUnlockNavigationOptions['router']
): void {
// Normalize the path using centralized function
- const normalizedPath = normalizeDeepLinkPath(returnUrl.path);
+ const normalizedPath = this.normalizeDeepLinkPath(returnUrl.path);
const params = returnUrl.params || {};
// Check if this is a detail route (has a sub-page after the tab)
@@ -201,30 +99,41 @@ export class PostUnlockNavigation {
}
/**
- * Get the initial pending deep link URL if available.
- * This should be called during app boot to check for QR code scans.
+ * Normalize a deep link or path to ensure it has the correct /(tabs)/ prefix.
+ * Exported for use in _layout.tsx and other navigation logic.
+ *
+ * Supports:
+ * - Action-based URLs: aliasvault://open/mobile-unlock/[id]
+ * - Direct routes: aliasvault://credentials/[id], aliasvault://settings/[page]
*/
- static async getInitialPendingDeepLink(): Promise<string | null> {
- try {
- const initialUrl = await Linking.getInitialURL();
- if (!initialUrl) {
- return null;
- }
-
- // Check if it's a supported deep link type
- const path = initialUrl
- .replace('net.aliasvault.app://', '')
- .replace('aliasvault://', '')
- .replace('exp+aliasvault://', '');
+ private static normalizeDeepLinkPath(urlOrPath: string): string {
+ // Remove all URL schemes first
+ let path = urlOrPath
+ .replace('net.aliasvault.app://', '')
+ .replace('aliasvault://', '')
+ .replace('exp+aliasvault://', '');
+
+ // If it already has /(tabs)/ prefix, return as is
+ if (path.startsWith('/(tabs)/')) {
+ return path;
+ }
- if (path.startsWith('mobile-login/') || path.includes('credentials/')) {
- return initialUrl;
+ // Handle credential paths
+ if (path.startsWith('credentials/') || path.includes('/credentials/')) {
+ if (!path.startsWith('/')) {
+ path = `/${path}`;
}
+ return `/(tabs)${path}`;
+ }
- return null;
- } catch (error) {
- console.error('Error getting initial deep link:', error);
- return null;
+ // Handle settings paths
+ if (path.startsWith('settings/') || path.startsWith('/settings')) {
+ if (!path.startsWith('/')) {
+ path = `/${path}`;
+ }
+ return `/(tabs)${path}`;
}
+
+ return path;
}
}