Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Refactor app boot to prevent translation initialization errors (#1060)
Leendert de Borst865d5c8fceb6
diff --git a/apps/mobile-app/app/+not-found.tsx b/apps/mobile-app/app/+not-found.tsxindex 9a1bc7f59..e696a215a 100644--- a/apps/mobile-app/app/+not-found.tsx+++ b/apps/mobile-app/app/+not-found.tsx@@ -13,7 +13,7 @@ export default function NotFoundScreen() : React.ReactNode {<Stack.Screen options={{ title: 'Oops!' }} /><ThemedView style={styles.container}><ThemedText type="title">This page doesn't exist.</ThemedText>- <Link href="/sync" style={styles.link}>+ <Link href="/reinitialize" style={styles.link}><ThemedText type="link">Go back to the home page</ThemedText></Link></ThemedView>diff --git a/apps/mobile-app/app/_layout.tsx b/apps/mobile-app/app/_layout.tsxindex 4b2c66783..66a98b981 100644--- a/apps/mobile-app/app/_layout.tsx+++ b/apps/mobile-app/app/_layout.tsx@@ -3,24 +3,20 @@ import { useFonts } from 'expo-font';import { Href, Stack, useRouter } from 'expo-router';import * as SplashScreen from 'expo-splash-screen';import { useEffect, useRef, useState } from 'react';-import { useTranslation } from 'react-i18next';-import { Linking, StyleSheet, Alert, Platform } from 'react-native';+import { Linking, StyleSheet, Platform } from 'react-native';import 'react-native-reanimated';import 'react-native-get-random-values';import { install } from 'react-native-quick-crypto';import { useColors, useColorScheme } from '@/hooks/useColorScheme';-import { useVaultSync } from '@/hooks/useVaultSync';import SpaceMono from '@/assets/fonts/SpaceMono-Regular.ttf';-import LoadingIndicator from '@/components/LoadingIndicator';import { ThemedView } from '@/components/themed/ThemedView';import { AliasVaultToast } from '@/components/Toast';-import { AuthProvider, useAuth } from '@/context/AuthContext';-import { DbProvider, useDb } from '@/context/DbContext';-import { useWebApi, WebApiProvider } from '@/context/WebApiContext';+import { AuthProvider } from '@/context/AuthContext';+import { DbProvider } from '@/context/DbContext';+import { WebApiProvider } from '@/context/WebApiContext';import { initI18n } from '@/i18n';-import NativeVaultManager from '@/specs/NativeVaultManager';SplashScreen.preventAutoHideAsync();@@ -31,12 +27,6 @@ function RootLayoutNav() : React.ReactNode {const colorScheme = useColorScheme();const colors = useColors();const router = useRouter();- const [status, setStatus] = useState('');- const { initializeAuth } = useAuth();- const { syncVault } = useVaultSync();- const dbContext = useDb();- const webApi = useWebApi();- const { t } = useTranslation();const [bootComplete, setBootComplete] = useState(false);const [redirectTarget, setRedirectTarget] = useState<string | null>(null);@@ -44,7 +34,7 @@ function RootLayoutNav() : React.ReactNode {useEffect(() => {/**- * Initialize the app.+ * Initialize the app by redirecting to the initialize page.*/const initializeApp = async () : Promise<void> => {if (hasBooted.current) {@@ -58,142 +48,12 @@ function RootLayoutNav() : React.ReactNode {await initI18n();hasBooted.current = true;-- /**- * Handle vault unlocking process.- */- async function handleVaultUnlock() : Promise<void> {- const { enabledAuthMethods } = await initializeAuth();-- try {- const hasEncryptedDatabase = await NativeVaultManager.hasEncryptedDatabase();- if (hasEncryptedDatabase) {- const isFaceIDEnabled = enabledAuthMethods.includes('faceid');- if (!isFaceIDEnabled) {- setRedirectTarget('/unlock');- setBootComplete(true);- return;- }-- setStatus(t('app.status.unlockingVault'));- const isUnlocked = await dbContext.unlockVault();- if (isUnlocked) {- await new Promise(resolve => setTimeout(resolve, 750));- setStatus(t('app.status.decryptingVault'));- await new Promise(resolve => setTimeout(resolve, 750));-- // Check if the vault is up to date, if not, redirect to the upgrade page.- if (await dbContext.hasPendingMigrations()) {- setRedirectTarget('/upgrade');- setBootComplete(true);- return;- }-- setBootComplete(true);- return;- }-- setRedirectTarget('/unlock');- setBootComplete(true);- return;- } else {- setRedirectTarget('/unlock');- setBootComplete(true);- return;- }- } catch {- setRedirectTarget('/unlock');- setBootComplete(true);- return;- }- }-- /**- * Initialize the app.- */- const initialize = async () : Promise<void> => {- const { isLoggedIn } = await initializeAuth();-- if (!isLoggedIn) {- setRedirectTarget('/login');- setBootComplete(true);- return;- }-- // First perform vault sync- await syncVault({- initialSync: true,- /**- * Handle the status update.- */- onStatus: (message) => {- setStatus(message);- },- /**- * Handle successful vault sync and continue with vault unlock flow.- */- onSuccess: async () => {- // Continue with the rest of the flow after successful sync- handleVaultUnlock();- },- /**- * Handle offline state and prompt user for action.- */- onOffline: async () => {- Alert.alert(- t('app.alerts.syncIssue'),- t('app.alerts.syncIssueMessage'),- [- {- text: t('app.alerts.openLocalVault'),- /**- * Handle opening vault in read-only mode.- */- onPress: async () : Promise<void> => {- setStatus(t('app.status.openingVaultReadOnly'));- await handleVaultUnlock();- }- },- {- text: t('app.alerts.retrySync'),- /**- * Handle retrying the connection.- */- onPress: () : void => {- setStatus(t('app.status.retryingConnection'));- initialize();- }- }- ]- );- },- /**- * Handle error during vault sync.- */- onError: async (error: string) => {- // Show modal with error message- Alert.alert(t('app.alerts.error'), error);-- // The logout user and navigate to the login screen.- await webApi.logout(error);- setRedirectTarget('/login');- setBootComplete(true);- },- /**- * On upgrade required.- */- onUpgradeRequired: () : void => {- setRedirectTarget('/upgrade');- setBootComplete(true);- },- });- };-- initialize();+ setRedirectTarget('/initialize');+ setBootComplete(true);};initializeApp();- }, [dbContext, syncVault, initializeAuth, webApi, t]);+ }, []);useEffect(() => {/**@@ -246,7 +106,7 @@ function RootLayoutNav() : React.ReactNode {if (!bootComplete) {return (<ThemedView style={styles.container}>- {status ? <LoadingIndicator status={status} /> : null}+ {/* Loading state while booting */}</ThemedView>);}@@ -286,13 +146,14 @@ function RootLayoutNav() : React.ReactNode {}}><Stack.Screen name="index" options={{ headerShown: false }} />- <Stack.Screen name="login" options={{ title: t('app.navigation.login'), headerShown: false }} />- <Stack.Screen name="login-settings" options={{ title: 'Login Settings' }} />+ <Stack.Screen name="initialize" options={{ headerShown: false }} />+ <Stack.Screen name="login" options={{ headerShown: false }} />+ <Stack.Screen name="login-settings" /><Stack.Screen name="reinitialize" options={{ headerShown: false }} /><Stack.Screen name="unlock" options={{ headerShown: false }} /><Stack.Screen name="upgrade" options={{ headerShown: false }} /><Stack.Screen name="(tabs)" options={{ headerShown: false }} />- <Stack.Screen name="+not-found" options={{ title: t('app.navigation.notFound') }} />+ <Stack.Screen name="+not-found" /></Stack><AliasVaultToast /></ThemeProvider>diff --git a/apps/mobile-app/app/initialize.tsx b/apps/mobile-app/app/initialize.tsxnew file mode 100644index 000000000..095b2bc0d--- /dev/null+++ b/apps/mobile-app/app/initialize.tsx@@ -0,0 +1,181 @@+import { useRouter } from 'expo-router';+import { useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { Alert, StyleSheet } from 'react-native';++import { useVaultSync } from '@/hooks/useVaultSync';++import LoadingIndicator from '@/components/LoadingIndicator';+import { ThemedView } from '@/components/themed/ThemedView';+import { useAuth } from '@/context/AuthContext';+import { useDb } from '@/context/DbContext';+import { useWebApi } from '@/context/WebApiContext';+import NativeVaultManager from '@/specs/NativeVaultManager';++/**+ * Initialize page that handles all boot logic.+ */+export default function Initialize() : React.ReactNode {+ const router = useRouter();+ const [status, setStatus] = useState('');+ const hasInitialized = useRef(false);+ const { t } = useTranslation();+ const { initializeAuth } = useAuth();+ const { syncVault } = useVaultSync();+ const dbContext = useDb();+ const webApi = useWebApi();++ useEffect(() => {+ // Ensure this only runs once.+ if (hasInitialized.current) {+ return;+ }++ hasInitialized.current = true;++ /**+ * Initialize the app.+ */+ const initializeApp = async () : Promise<void> => {+ /**+ * Handle vault unlocking process.+ */+ async function handleVaultUnlock() : Promise<void> {+ const { enabledAuthMethods } = await initializeAuth();++ try {+ const hasEncryptedDatabase = await NativeVaultManager.hasEncryptedDatabase();+ if (hasEncryptedDatabase) {+ const isFaceIDEnabled = enabledAuthMethods.includes('faceid');+ if (!isFaceIDEnabled) {+ router.replace('/unlock');+ return;+ }++ setStatus(t('app.status.unlockingVault'));+ const isUnlocked = await dbContext.unlockVault();+ if (isUnlocked) {+ await new Promise(resolve => setTimeout(resolve, 750));+ setStatus(t('app.status.decryptingVault'));+ await new Promise(resolve => setTimeout(resolve, 750));++ // Check if the vault is up to date, if not, redirect to the upgrade page.+ if (await dbContext.hasPendingMigrations()) {+ router.replace('/upgrade');+ return;+ }++ router.replace('/(tabs)/credentials');+ return;+ }++ router.replace('/unlock');+ return;+ } else {+ router.replace('/unlock');+ return;+ }+ } catch {+ router.replace('/unlock');+ return;+ }+ }++ /**+ * Initialize the app.+ */+ const initialize = async () : Promise<void> => {+ const { isLoggedIn } = await initializeAuth();++ if (!isLoggedIn) {+ router.replace('/login');+ return;+ }++ // First perform vault sync+ await syncVault({+ initialSync: true,+ /**+ * Handle the status update.+ */+ onStatus: (message) => {+ setStatus(message);+ },+ /**+ * Handle successful vault sync and continue with vault unlock flow.+ */+ onSuccess: async () => {+ // Continue with the rest of the flow after successful sync+ handleVaultUnlock();+ },+ /**+ * Handle offline state and prompt user for action.+ */+ onOffline: async () => {+ Alert.alert(+ t('app.alerts.syncIssue'),+ t('app.alerts.syncIssueMessage'),+ [+ {+ text: t('app.alerts.openLocalVault'),+ /**+ * Handle opening vault in read-only mode.+ */+ onPress: async () : Promise<void> => {+ setStatus(t('app.status.openingVaultReadOnly'));+ await handleVaultUnlock();+ }+ },+ {+ text: t('app.alerts.retrySync'),+ /**+ * Handle retrying the connection.+ */+ onPress: () : void => {+ setStatus(t('app.status.retryingConnection'));+ initialize();+ }+ }+ ]+ );+ },+ /**+ * Handle error during vault sync.+ */+ onError: async (error: string) => {+ // Show modal with error message+ Alert.alert(t('app.alerts.error'), error);++ // The logout user and navigate to the login screen.+ await webApi.logout(error);+ router.replace('/login');+ },+ /**+ * On upgrade required.+ */+ onUpgradeRequired: () : void => {+ router.replace('/upgrade');+ },+ });+ };++ initialize();+ };++ initializeApp();+ }, [dbContext, syncVault, initializeAuth, webApi, router, t]);++ const styles = StyleSheet.create({+ container: {+ alignItems: 'center',+ flex: 1,+ justifyContent: 'center',+ },+ });++ return (+ <ThemedView style={styles.container}>+ {status ? <LoadingIndicator status={status} /> : null}+ </ThemedView>+ );+}\ No newline at end of filediff --git a/apps/mobile-app/app/login-settings.tsx b/apps/mobile-app/app/login-settings.tsxindex 1e742938a..e272ae40e 100644--- a/apps/mobile-app/app/login-settings.tsx+++ b/apps/mobile-app/app/login-settings.tsx@@ -1,10 +1,12 @@import AsyncStorage from '@react-native-async-storage/async-storage';-import { useState, useEffect } from 'react';+import { useNavigation } from 'expo-router';+import { useState, useEffect, useCallback, useMemo, useLayoutEffect } from 'react';import { StyleSheet, View, Text, TextInput, TouchableOpacity, ActivityIndicator } from 'react-native';import { AppInfo } from '@/utils/AppInfo';import { useColors } from '@/hooks/useColorScheme';+import { useTranslation } from '@/hooks/useTranslation';import { ThemedContainer } from '@/components/themed/ThemedContainer';import { ThemedScrollView } from '@/components/themed/ThemedScrollView';@@ -15,28 +17,33 @@ type ApiOption = {value: string;};-const DEFAULT_OPTIONS: ApiOption[] = [- { label: 'Aliasvault.net', value: AppInfo.DEFAULT_API_URL },- { label: 'Self-hosted', value: 'custom' }-];-/*** Settings screen (for logged out users).*/export default function SettingsScreen() : React.ReactNode {const colors = useColors();- const [selectedOption, setSelectedOption] = useState<string>(DEFAULT_OPTIONS[0].value);+ const navigation = useNavigation();+ const { t } = useTranslation();+ const [selectedOption, setSelectedOption] = useState<string>(AppInfo.DEFAULT_API_URL);const [customUrl, setCustomUrl] = useState<string>('');const [isLoading, setIsLoading] = useState(true);- useEffect(() => {- loadStoredSettings();- }, []);+ const DEFAULT_OPTIONS: ApiOption[] = useMemo(() => [+ { label: t('app.loginSettings.aliasvaultNet'), value: AppInfo.DEFAULT_API_URL },+ { label: t('app.loginSettings.selfHosted'), value: 'custom' },+ ], [t]);++ useLayoutEffect(() => {+ navigation.setOptions({+ title: t('app.navigation.loginSettings'),+ headerBackTitle: t('app.navigation.login'),+ });+ }, [navigation, t]);/*** Load the stored settings.*/- const loadStoredSettings = async () : Promise<void> => {+ const loadStoredSettings = useCallback(async () : Promise<void> => {try {const apiUrl = await AsyncStorage.getItem('apiUrl');const matchingOption = DEFAULT_OPTIONS.find(opt => opt.value === apiUrl);@@ -52,7 +59,11 @@ export default function SettingsScreen() : React.ReactNode {} finally {setIsLoading(false);}- };+ }, [DEFAULT_OPTIONS]);++ useEffect(() => {+ loadStoredSettings();+ }, [loadStoredSettings]);/*** Handle the option change.@@ -146,50 +157,52 @@ export default function SettingsScreen() : React.ReactNode {}return (- <ThemedContainer>- <ThemedScrollView>- <ThemedView style={styles.content}>- <View style={styles.titleContainer}>- <Text style={styles.title}>API Connection</Text>- </View>-- <View style={styles.formContainer}>- {DEFAULT_OPTIONS.map(option => (- <TouchableOpacity- key={option.value}- style={[- styles.optionButton,- selectedOption === option.value && styles.optionButtonSelected- ]}- onPress={() => handleOptionChange(option.value)}- >- <Text style={[- styles.optionButtonText,- selectedOption === option.value && styles.optionButtonTextSelected- ]}>- {option.label}- </Text>- </TouchableOpacity>- ))}-- {selectedOption === 'custom' && (- <View>- <Text style={styles.label}>Custom API URL</Text>- <TextInput- style={styles.input}- value={customUrl}- onChangeText={handleCustomUrlChange}- placeholder="https://my-aliasvault-instance.com/api"- placeholderTextColor={colors.textMuted}- autoCapitalize="none"- autoCorrect={false}- />- </View>- )}- </View>- <Text style={styles.versionText}>Version: {AppInfo.VERSION}</Text>- </ThemedView>- </ThemedScrollView>- </ThemedContainer>+ <>+ <ThemedContainer>+ <ThemedScrollView>+ <ThemedView style={styles.content}>+ <View style={styles.titleContainer}>+ <Text style={styles.title}>{t('app.loginSettings.title')}</Text>+ </View>++ <View style={styles.formContainer}>+ {DEFAULT_OPTIONS.map(option => (+ <TouchableOpacity+ key={option.value}+ style={[+ styles.optionButton,+ selectedOption === option.value && styles.optionButtonSelected+ ]}+ onPress={() => handleOptionChange(option.value)}+ >+ <Text style={[+ styles.optionButtonText,+ selectedOption === option.value && styles.optionButtonTextSelected+ ]}>+ {option.label}+ </Text>+ </TouchableOpacity>+ ))}++ {selectedOption === 'custom' && (+ <View>+ <Text style={styles.label}>{t('app.loginSettings.customApiUrl')}</Text>+ <TextInput+ style={styles.input}+ value={customUrl}+ onChangeText={handleCustomUrlChange}+ placeholder={t('app.loginSettings.customApiUrlPlaceholder')}+ placeholderTextColor={colors.textMuted}+ autoCapitalize="none"+ autoCorrect={false}+ />+ </View>+ )}+ </View>+ <Text style={styles.versionText}>{t('app.loginSettings.version', { version: AppInfo.VERSION })}</Text>+ </ThemedView>+ </ThemedScrollView>+ </ThemedContainer>+ </>);}\ No newline at end of filediff --git a/apps/mobile-app/i18n/locales/en.json b/apps/mobile-app/i18n/locales/en.jsonindex f63dab234..aadc15d40 100644--- a/apps/mobile-app/i18n/locales/en.json+++ b/apps/mobile-app/i18n/locales/en.json@@ -370,11 +370,20 @@},"navigation": {"login": "Login",+ "loginSettings": "Login Settings","notFound": "Not Found"},"reinitialize": {"vaultAutoLockedMessage": "Vault auto-locked after timeout.","attemptingToUnlockMessage": "Attempting to unlock."+ },+ "loginSettings": {+ "title": "API Connection",+ "aliasvaultNet": "Aliasvault.net",+ "selfHosted": "Self-hosted",+ "customApiUrl": "Custom API URL",+ "customApiUrlPlaceholder": "https://my-aliasvault-instance.com/api",+ "version": "Version: {{version}}"}},"upgrade": {diff --git a/apps/mobile-app/i18n/locales/nl.json b/apps/mobile-app/i18n/locales/nl.jsonindex d434c25a0..4942acbf9 100644--- a/apps/mobile-app/i18n/locales/nl.json+++ b/apps/mobile-app/i18n/locales/nl.json@@ -370,6 +370,7 @@},"navigation": {"login": "Login",+ "loginSettings": "Login Settings","notFound": "Niet gevonden"},"reinitialize": {