Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Update main nav and cleanup (#771)
Leendert de Borsta73d6adad562
diff --git a/mobile-app/app.json b/mobile-app/app.jsonindex 0fee3af89..e5d0cebd9 100644--- a/mobile-app/app.json+++ b/mobile-app/app.json@@ -5,7 +5,7 @@"version": "1.0.0","orientation": "portrait","icon": "./assets/images/icon.png",- "scheme": "aliasvault",+ "scheme": "AliasVault","userInterfaceStyle": "automatic","newArchEnabled": true,"ios": {diff --git a/mobile-app/app/(tabs)/_layout.tsx b/mobile-app/app/(tabs)/_layout.tsxindex f43f0fdeb..9a453c8b9 100644--- a/mobile-app/app/(tabs)/_layout.tsx+++ b/mobile-app/app/(tabs)/_layout.tsx@@ -1,6 +1,7 @@import { Tabs } from 'expo-router';-import React from 'react';-import { Platform } from 'react-native';+import React, { useEffect } from 'react';+import { Platform, View } from 'react-native';+import { router } from 'expo-router';import { HapticTab } from '@/components/HapticTab';import { IconSymbol } from '@/components/ui/IconSymbol';@@ -8,12 +9,30 @@ import TabBarBackground from '@/components/ui/TabBarBackground';import { Colors } from '@/constants/Colors';import { useColorScheme } from '@/hooks/useColorScheme';import { useAuth } from '@/context/AuthContext';+import { useDb } from '@/context/DbContext';export default function TabLayout() {const colorScheme = useColorScheme();- const { isLoggedIn, isInitialized } = useAuth();+ const authContext = useAuth();+ const dbContext = useDb();- if (!isInitialized) {+ // Check if user is authenticated and database is available+ const isFullyInitialized = authContext.isInitialized && dbContext.dbInitialized;+ const isAuthenticated = authContext.isLoggedIn;+ const isDatabaseAvailable = dbContext.dbAvailable;+ const requireLoginOrUnlock = isFullyInitialized && (!isAuthenticated || !isDatabaseAvailable);++ useEffect(() => {+ if (requireLoginOrUnlock) {+ // Use setTimeout to ensure navigation happens after the component is mounted+ const timer = setTimeout(() => {+ router.replace('/login');+ }, 0);+ return () => clearTimeout(timer);+ }+ }, [requireLoginOrUnlock]);++ if (!isFullyInitialized || requireLoginOrUnlock) {return null;}@@ -24,19 +43,18 @@ export default function TabLayout() {headerShown: false,tabBarButton: HapticTab,tabBarBackground: TabBarBackground,- // Hide tab bar when not logged in- tabBarStyle: isLoggedIn ? Platform.select({+ tabBarStyle: Platform.select({ios: {position: 'absolute',},default: {},- }) : { display: 'none' },+ }),}}><Tabs.Screenname="index"options={{- title: 'Home',- tabBarIcon: ({ color }) => <IconSymbol size={28} name="house.fill" color={color} />,+ title: 'Credentials',+ tabBarIcon: ({ color }) => <IconSymbol size={28} name="key.fill" color={color} />,}}/><Tabs.Screen@@ -56,3 +74,8 @@ export default function TabLayout() {</Tabs>);}++// Simple icon component since we don't have access to the actual icon library+const Icon = ({ name, size, color }: { name: string; size: number; color: string }) => (+ <View style={{ width: size, height: size, backgroundColor: color }} />+);diff --git a/mobile-app/app/(tabs)/index.bak.tsx b/mobile-app/app/(tabs)/index.bak.tsxdeleted file mode 100644index 387cf671d..000000000--- a/mobile-app/app/(tabs)/index.bak.tsx+++ /dev/null@@ -1,123 +0,0 @@-import { Image, StyleSheet, Platform, Button, View, FlatList, Text, SafeAreaView, AppState } from 'react-native';-import { NativeModules } from 'react-native';-import { useState, useEffect, useRef } from 'react';--import { ThemedText } from '@/components/ThemedText';-import { ThemedView } from '@/components/ThemedView';--interface Credential {- username: string;- password: string;- service: string;-}--export default function HomeScreen() {- const [credentials, setCredentials] = useState<Credential[]>([]);- const appState = useRef(AppState.currentState);-- const fetchCredentials = async () => {- console.log('Fetching credentials called');- try {- const result = await NativeModules.CredentialManager.getCredentials();- setCredentials(result);- } catch (error) {- console.error('Error fetching credentials:', error);- }- };-- useEffect(() => {- const subscription = AppState.addEventListener('change', nextAppState => {- if (- appState.current.match(/inactive|background/) &&- nextAppState === 'active'- ) {- console.log('App has come to the foreground!');- fetchCredentials();- }- appState.current = nextAppState;- });-- return () => {- subscription.remove();- };- }, []);-- useEffect(() => {- console.log('Fetching credentials in useEffect once on mount');- fetchCredentials();- }, []);-- const handleInsertEntry = async () => {- // Generate a random credential- const randomUsername = `user${Math.floor(Math.random() * 1000)}`;- const randomPassword = `pass${Math.floor(Math.random() * 1000)}`;- const randomService = `service${Math.floor(Math.random() * 1000)}`;-- // Call native module to add credential- await NativeModules.CredentialManager.addCredential(randomUsername, randomPassword, randomService);- // Add a small delay to ensure the operation is complete- await new Promise(resolve => setTimeout(resolve, 100));-- console.log('Fetching credentials after insert');- fetchCredentials(); // Refresh the list- };-- const renderCredential = (item: Credential) => (- <ThemedView style={styles.credentialItem} key={`${item.service}-${item.username}`}>- <ThemedText type="defaultSemiBold">Service: {item.service}</ThemedText>- <ThemedText>Username: {item.username}</ThemedText>- <ThemedText>Password: {item.password}</ThemedText>- </ThemedView>- );-- return (- <SafeAreaView style={styles.container}>- <ThemedView style={styles.content}>- <ThemedView style={styles.titleContainer}>- <ThemedText type="title">AliasVault</ThemedText>- </ThemedView>- <ThemedView style={styles.stepContainer}>- <ThemedText type="subtitle">Credentials</ThemedText>- <Button title="Add Random Credential" onPress={handleInsertEntry} />- <FlatList- data={credentials}- renderItem={({ item }) => renderCredential(item)}- keyExtractor={(item) => `${item.service}-${item.username}`}- />- </ThemedView>- </ThemedView>- </SafeAreaView>- );-}--const styles = StyleSheet.create({- container: {- flex: 1,- },- content: {- flex: 1,- padding: 16,- },- titleContainer: {- flexDirection: 'row',- alignItems: 'center',- gap: 8,- marginBottom: 16,- },- stepContainer: {- flex: 1,- gap: 8,- },- reactLogo: {- height: 178,- width: 290,- bottom: 0,- left: 0,- position: 'absolute',- },- credentialItem: {- padding: 10,- marginVertical: 5,- borderRadius: 5,- },-});diff --git a/mobile-app/app/(tabs)/index.tsx b/mobile-app/app/(tabs)/index.tsxindex 1432bcce5..2b2917508 100644--- a/mobile-app/app/(tabs)/index.tsx+++ b/mobile-app/app/(tabs)/index.tsx@@ -1,223 +1,40 @@-import { Image, StyleSheet, Platform, Button, View, FlatList, Text, SafeAreaView, AppState, TextInput, TouchableOpacity, ActivityIndicator } from 'react-native';-import { NativeModules } from 'react-native';-import { useState, useEffect, useRef } from 'react';-import { Buffer } from 'buffer';+import { StyleSheet, View, Text, SafeAreaView, FlatList, ActivityIndicator, useColorScheme } from 'react-native';+import { useState, useEffect } from 'react';import { ThemedText } from '@/components/ThemedText';import { ThemedView } from '@/components/ThemedView';import { useDb } from '@/context/DbContext';import { useAuth } from '@/context/AuthContext';-import { SrpUtility } from '@/utils/SrpUtility';-import EncryptionUtility from '@/utils/EncryptionUtility';-import { ApiAuthError } from '@/utils/types/errors/ApiAuthError';-import { useWebApi } from '@/context/WebApiContext';import { Credential } from '@/utils/types/Credential';-export default function HomeScreen() {- const [credentials, setCredentials] = useState({- username: '',- password: '',- });- const [rememberMe, setRememberMe] = useState(true);- const [isLoading, setIsLoading] = useState(false);- const [error, setError] = useState<string | null>(null);- const [twoFactorRequired, setTwoFactorRequired] = useState(false);- const [twoFactorCode, setTwoFactorCode] = useState('');- const [loginResponse, setLoginResponse] = useState<any>(null);- const [passwordHashString, setPasswordHashString] = useState<string | null>(null);- const [passwordHashBase64, setPasswordHashBase64] = useState<string | null>(null);- const appState = useRef(AppState.currentState);+export default function CredentialsScreen() {+ const colorScheme = useColorScheme();+ const isDarkMode = colorScheme === 'dark';++ const dynamicStyles = {+ credentialItem: {+ backgroundColor: isDarkMode ? '#1f2937' : '#ffffff',+ borderColor: isDarkMode ? '#4b5563' : '#d1d5db',+ },+ serviceName: {+ color: isDarkMode ? '#f3f4f6' : '#1f2937',+ },+ credentialText: {+ color: isDarkMode ? '#d1d5db' : '#4b5563',+ },+ emptyText: {+ color: isDarkMode ? '#9ca3af' : '#6b7280',+ },+ };++ const [credentialsList, setCredentialsList] = useState<Credential[]>([]);+ const [isLoadingCredentials, setIsLoadingCredentials] = useState(false);+const authContext = useAuth();const dbContext = useDb();- const webApi = useWebApi();-- const srpUtil = new SrpUtility(webApi);- // Initialization state.- const isFullyInitialized = authContext.isInitialized && dbContext.dbInitialized;const isAuthenticated = authContext.isLoggedIn;const isDatabaseAvailable = dbContext.dbAvailable;- const requireLoginOrUnlock = isFullyInitialized && (!isAuthenticated || !isDatabaseAvailable);-- const handleSubmit = async () => {- setIsLoading(true);- setError(null);-- try {- console.log('handleSubmit');- // Clear global message if set with every login attempt.- authContext.clearGlobalMessage();-- // Use the srpUtil instance instead of the imported singleton- const loginResponse = await srpUtil.initiateLogin(credentials.username);-- console.log('loginResponse', loginResponse);-- // 1. Derive key from password using Argon2id- const passwordHash = await EncryptionUtility.deriveKeyFromPassword(- credentials.password,- loginResponse.salt,- loginResponse.encryptionType,- loginResponse.encryptionSettings- );-- console.log('passwordHash', passwordHash);-- // Convert uint8 array to uppercase hex string which is expected by the server.- const passwordHashString = Buffer.from(passwordHash).toString('hex').toUpperCase();-- // Get the derived key as base64 string required for decryption.- const passwordHashBase64 = Buffer.from(passwordHash).toString('base64');-- console.log('passwordHashString', passwordHashString);-- // 2. Validate login with SRP protocol- const validationResponse = await srpUtil.validateLogin(- credentials.username,- passwordHashString,- rememberMe,- loginResponse- );-- console.log('validationResponse', validationResponse);-- // 3. Handle 2FA if required- if (validationResponse.requiresTwoFactor) {- // Store login response as we need it for 2FA validation- setLoginResponse(loginResponse);- // Store password hash string as we need it for 2FA validation- setPasswordHashString(passwordHashString);- // Store password hash base64 as we need it for decryption- setPasswordHashBase64(passwordHashBase64);- setTwoFactorRequired(true);- setIsLoading(false);- return;- }-- // Check if token was returned.- if (!validationResponse.token) {- throw new Error('Login failed -- no token returned');- }-- console.log('validationResponse.token', validationResponse.token);-- // Try to get latest vault manually providing auth token.- const vaultResponseJson = await webApi.authFetch<any>('Vault', { method: 'GET', headers: {- 'Authorization': `Bearer ${validationResponse.token.token}`- } });-- console.log('vaultResponseJson', vaultResponseJson);-- const vaultError = webApi.validateVaultResponse(vaultResponseJson);- if (vaultError) {- console.error('vaultError', vaultError);- setError(vaultError);- setIsLoading(false);- return;- }-- console.log('vaultResponseJson', vaultResponseJson);-- // All is good. Store auth info which is required to make requests to the web API.- await authContext.setAuthTokens(credentials.username, validationResponse.token.token, validationResponse.token.refreshToken);-- console.log('auth tokens set');- // Initialize the SQLite context with the new vault data.- await dbContext.initializeDatabase(vaultResponseJson, passwordHashBase64);-- console.log('database initialized');-- // Set logged in status to true which refreshes the app.- await authContext.login();-- console.log('logged in');-- setIsLoading(false);- } catch (err) {- // Show API authentication errors as-is.- if (err instanceof ApiAuthError) {- console.error('ApiAuthError error:', err);- setError(err.message);- } else {- console.error('Login error:', err);- setError('Could not reach AliasVault server. Please try again later or contact support if the problem persists.');- }- setIsLoading(false);- }- };-- const handleTwoFactorSubmit = async () => {- setIsLoading(true);- setError(null);-- try {- if (!passwordHashString || !passwordHashBase64 || !loginResponse) {- throw new Error('Required login data not found');- }-- // Validate that 2FA code is a 6-digit number- const code = twoFactorCode.trim();- if (!/^\d{6}$/.test(code)) {- throw new ApiAuthError('Please enter a valid 6-digit authentication code.');- }-- const validationResponse = await srpUtil.validateLogin2Fa(- credentials.username,- passwordHashString,- rememberMe,- loginResponse,- parseInt(twoFactorCode)- );-- // Check if token was returned.- if (!validationResponse.token) {- throw new Error('Login failed -- no token returned');- }-- // Try to get latest vault manually providing auth token.- const vaultResponseJson = await webApi.authFetch<any>('Vault', { method: 'GET', headers: {- 'Authorization': `Bearer ${validationResponse.token.token}`- } });-- const vaultError = webApi.validateVaultResponse(vaultResponseJson);- if (vaultError) {- setError(vaultError);- setIsLoading(false);- return;- }-- // All is good. Store auth info which is required to make requests to the web API.- await authContext.setAuthTokens(credentials.username, validationResponse.token.token, validationResponse.token.refreshToken);-- // Initialize the SQLite context with the new vault data.- await dbContext.initializeDatabase(vaultResponseJson, passwordHashBase64);-- // Set logged in status to true which refreshes the app.- await authContext.login();-- // Reset 2FA state and login response as it's no longer needed- setTwoFactorRequired(false);- setTwoFactorCode('');- setPasswordHashString(null);- setPasswordHashBase64(null);- setLoginResponse(null);- setIsLoading(false);- } catch (err) {- // Show API authentication errors as-is.- console.error('2FA error:', err);- if (err instanceof ApiAuthError) {- setError(err.message);- } else {- console.error('2FA error:', err);- setError('Could not reach AliasVault server. Please try again later or contact support if the problem persists.');- }- setIsLoading(false);- }- };--- const [credentialsList, setCredentialsList] = useState<Credential[]>([]);- const [isLoadingCredentials, setIsLoadingCredentials] = useState(false);useEffect(() => {if (!isAuthenticated || !isDatabaseAvailable) {@@ -238,116 +55,14 @@ export default function HomeScreen() {loadCredentials();}, [isAuthenticated, isDatabaseAvailable]);-- if (!isAuthenticated || !isDatabaseAvailable) {- return (- <SafeAreaView style={styles.container}>- <ThemedView style={styles.content}>- <ThemedView style={styles.titleContainer}>- <ThemedText type="title">AliasVault</ThemedText>- </ThemedView>-- {error && (- <View style={styles.errorContainer}>- <Text style={styles.errorText}>{error}</Text>- </View>- )}-- {twoFactorRequired ? (- <View style={styles.formContainer}>- <Text style={styles.label}>Authentication Code</Text>- <TextInput- style={styles.input}- value={twoFactorCode}- onChangeText={setTwoFactorCode}- placeholder="Enter 6-digit code"- keyboardType="numeric"- maxLength={6}- />- <View style={styles.buttonContainer}>- <TouchableOpacity- style={[styles.button, styles.primaryButton]}- onPress={handleTwoFactorSubmit}- disabled={isLoading}- >- {isLoading ? (- <ActivityIndicator color="#fff" />- ) : (- <Text style={styles.buttonText}>Verify</Text>- )}- </TouchableOpacity>- <TouchableOpacity- style={[styles.button, styles.secondaryButton]}- onPress={() => {- setCredentials({ username: '', password: '' });- setTwoFactorRequired(false);- setTwoFactorCode('');- setPasswordHashString(null);- setPasswordHashBase64(null);- setLoginResponse(null);- setError(null);- }}- >- <Text style={styles.buttonText}>Cancel</Text>- </TouchableOpacity>- </View>- <Text style={styles.noteText}>- 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.- </Text>- </View>- ) : (- <View style={styles.formContainer}>- <Text style={styles.label}>Username or email</Text>- <TextInput- style={styles.input}- value={credentials.username}- onChangeText={(text) => setCredentials({ ...credentials, username: text })}- placeholder="name / [email protected]"- autoCapitalize="none"- />- <Text style={styles.label}>Password</Text>- <TextInput- style={styles.input}- value={credentials.password}- onChangeText={(text) => setCredentials({ ...credentials, password: text })}- placeholder="Enter your password"- secureTextEntry- />- <View style={styles.rememberMeContainer}>- <TouchableOpacity- style={styles.checkbox}- onPress={() => setRememberMe(!rememberMe)}- >- <View style={[styles.checkboxInner, rememberMe && styles.checkboxChecked]} />- </TouchableOpacity>- <Text style={styles.rememberMeText}>Remember me</Text>- </View>- <TouchableOpacity- style={[styles.button, styles.primaryButton]}- onPress={handleSubmit}- disabled={isLoading}- >- {isLoading ? (- <ActivityIndicator color="#fff" />- ) : (- <Text style={styles.buttonText}>Login</Text>- )}- </TouchableOpacity>- </View>- )}- </ThemedView>- </SafeAreaView>- );- }return (<SafeAreaView style={styles.container}><ThemedView style={styles.content}><ThemedView style={styles.titleContainer}>- <ThemedText type="title">AliasVault</ThemedText>+ <ThemedText type="title">Credentials</ThemedText></ThemedView><ThemedView style={styles.stepContainer}>- <ThemedText type="subtitle">Your Credentials</ThemedText>{isLoadingCredentials ? (<ActivityIndicator size="large" color="#f97316" />) : (@@ -355,14 +70,14 @@ export default function HomeScreen() {data={credentialsList}keyExtractor={(item) => item.Id}renderItem={({ item }) => (- <View style={styles.credentialItem}>- <Text style={styles.serviceName}>{item.ServiceName ?? 'Unknown Service'}</Text>- {item.Username && <Text style={styles.credentialText}>Username: {item.Username}</Text>}- {item.Alias?.Email && <Text style={styles.credentialText}>Email: {item.Alias.Email}</Text>}+ <View style={[styles.credentialItem, dynamicStyles.credentialItem]}>+ <Text style={[styles.serviceName, dynamicStyles.serviceName]}>{item.ServiceName ?? 'Unknown Service'}</Text>+ {item.Username && <Text style={[styles.credentialText, dynamicStyles.credentialText]}>Username: {item.Username}</Text>}+ {item.Alias?.Email && <Text style={[styles.credentialText, dynamicStyles.credentialText]}>Email: {item.Alias.Email}</Text>}</View>)}ListEmptyComponent={- <Text style={styles.emptyText}>No credentials found</Text>+ <Text style={[styles.emptyText, dynamicStyles.emptyText]}>No credentials found</Text>}/>)}@@ -390,99 +105,11 @@ const styles = StyleSheet.create({flex: 1,gap: 8,},- formContainer: {- gap: 16,- },- errorContainer: {- backgroundColor: '#fee2e2',- padding: 12,- borderRadius: 8,- marginBottom: 16,- },- errorText: {- color: '#dc2626',- fontSize: 14,- },- label: {- fontSize: 14,- fontWeight: '600',- marginBottom: 4,- },- input: {- borderWidth: 1,- borderColor: '#d1d5db',- borderRadius: 8,- padding: 12,- fontSize: 16,- },- buttonContainer: {- gap: 8,- },- button: {- padding: 12,- borderRadius: 8,- alignItems: 'center',- },- primaryButton: {- backgroundColor: '#f97316',- },- secondaryButton: {- backgroundColor: '#6b7280',- },- buttonText: {- color: '#fff',- fontSize: 16,- fontWeight: '600',- },- rememberMeContainer: {- flexDirection: 'row',- alignItems: 'center',- gap: 8,- },- checkbox: {- width: 20,- height: 20,- borderWidth: 2,- borderColor: '#d1d5db',- borderRadius: 4,- justifyContent: 'center',- alignItems: 'center',- },- checkboxInner: {- width: 12,- height: 12,- borderRadius: 2,- },- checkboxChecked: {- backgroundColor: '#f97316',- },- rememberMeText: {- fontSize: 14,- },- noteText: {- fontSize: 12,- color: '#6b7280',- textAlign: 'center',- marginTop: 16,- },- logoutButton: {- backgroundColor: '#f97316',- padding: 12,- borderRadius: 8,- alignItems: 'center',- },- logoutButtonText: {- color: '#fff',- fontSize: 16,- fontWeight: '600',- },credentialItem: {- backgroundColor: '#fff',padding: 16,borderRadius: 8,marginBottom: 8,borderWidth: 1,- borderColor: '#d1d5db',},serviceName: {fontSize: 16,@@ -491,12 +118,10 @@ const styles = StyleSheet.create({},credentialText: {fontSize: 14,- color: '#4b5563',},emptyText: {textAlign: 'center',fontSize: 16,- color: '#6b7280',marginTop: 24,},-});+});\ No newline at end of filediff --git a/mobile-app/app/(tabs)/settings.tsx b/mobile-app/app/(tabs)/settings.tsxindex 126db5549..6bfca37c7 100644--- a/mobile-app/app/(tabs)/settings.tsx+++ b/mobile-app/app/(tabs)/settings.tsx@@ -9,7 +9,7 @@ export default function SettingsScreen() {const handleLogout = async () => {await webApi.logout();- router.replace('/');+ router.replace('/login');};return (diff --git a/mobile-app/app/+not-found.tsx b/mobile-app/app/+not-found.tsxindex 963b04fbc..0aa54cef5 100644--- a/mobile-app/app/+not-found.tsx+++ b/mobile-app/app/+not-found.tsx@@ -10,7 +10,7 @@ export default function NotFoundScreen() {<Stack.Screen options={{ title: 'Oops!' }} /><ThemedView style={styles.container}><ThemedText type="title">This screen doesn't exist.</ThemedText>- <Link href="/" style={styles.link}>+ <Link href="/login" style={styles.link}><ThemedText type="link">Go to home screen!</ThemedText></Link></ThemedView>diff --git a/mobile-app/app/_layout.tsx b/mobile-app/app/_layout.tsxindex 5a63765dd..c524b4f82 100644--- a/mobile-app/app/_layout.tsx+++ b/mobile-app/app/_layout.tsx@@ -14,12 +14,49 @@ import { LoadingProvider } from '@/context/LoadingContext';import { DbProvider } from '@/context/DbContext';import { AuthProvider } from '@/context/AuthContext';import { WebApiProvider } from '@/context/WebApiContext';+import { useAuth } from '@/context/AuthContext';+import { useDb } from '@/context/DbContext';+import { View, ActivityIndicator } from 'react-native';// Prevent the splash screen from auto-hiding before asset loading is complete.SplashScreen.preventAutoHideAsync();-export default function RootLayout() {+function RootLayoutNav() {const colorScheme = useColorScheme();+ const authContext = useAuth();+ const dbContext = useDb();++ // Check if user is authenticated and database is available+ const isFullyInitialized = authContext.isInitialized && dbContext.dbInitialized;+ const isAuthenticated = authContext.isLoggedIn;+ const isDatabaseAvailable = dbContext.dbAvailable;+ const requireLoginOrUnlock = isFullyInitialized && (!isAuthenticated || !isDatabaseAvailable);++ // Show loading screen while initializing+ if (!isFullyInitialized) {+ return (+ <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>+ <ActivityIndicator size="large" />+ </View>+ );+ }++ return (+ <ThemeProvider value={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>+ <Stack screenOptions={{ headerShown: false }}>+ {requireLoginOrUnlock ? (+ <Stack.Screen name="login" />+ ) : (+ <Stack.Screen name="(tabs)" />+ )}+ <Stack.Screen name="+not-found" />+ </Stack>+ <StatusBar style="auto" />+ </ThemeProvider>+ );+}++export default function RootLayout() {const [loaded] = useFonts({SpaceMono: require('../assets/fonts/SpaceMono-Regular.ttf'),});@@ -35,20 +72,14 @@ export default function RootLayout() {}return (- <DbProvider>- <AuthProvider>- <WebApiProvider>- <LoadingProvider>- <ThemeProvider value={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>- <Stack>- <Stack.Screen name="(tabs)" options={{ headerShown: false }} />- <Stack.Screen name="+not-found" />- </Stack>- <StatusBar style="auto" />- </ThemeProvider>- </LoadingProvider>- </WebApiProvider>- </AuthProvider>- </DbProvider>+ <DbProvider>+ <AuthProvider>+ <WebApiProvider>+ <LoadingProvider>+ <RootLayoutNav />+ </LoadingProvider>+ </WebApiProvider>+ </AuthProvider>+ </DbProvider>);}diff --git a/mobile-app/app/login.tsx b/mobile-app/app/login.tsxnew file mode 100644index 000000000..bd6cf1ba6--- /dev/null+++ b/mobile-app/app/login.tsx@@ -0,0 +1,394 @@+import { StyleSheet, Platform, View, Text, SafeAreaView, AppState, TextInput, TouchableOpacity, ActivityIndicator, useColorScheme } from 'react-native';+import { useState, useEffect, useRef } from 'react';+import { Buffer } from 'buffer';+import { router } from 'expo-router';++import { ThemedText } from '@/components/ThemedText';+import { ThemedView } from '@/components/ThemedView';+import { useDb } from '@/context/DbContext';+import { useAuth } from '@/context/AuthContext';+import { SrpUtility } from '@/utils/SrpUtility';+import EncryptionUtility from '@/utils/EncryptionUtility';+import { ApiAuthError } from '@/utils/types/errors/ApiAuthError';+import { useWebApi } from '@/context/WebApiContext';++export default function LoginScreen() {+ const colorScheme = useColorScheme();+ const isDarkMode = colorScheme === 'dark';++ const dynamicStyles = {+ input: {+ borderColor: isDarkMode ? '#4b5563' : '#d1d5db',+ color: isDarkMode ? '#f3f4f6' : '#1f2937',+ backgroundColor: isDarkMode ? '#1f2937' : '#ffffff',+ },+ label: {+ color: isDarkMode ? '#f3f4f6' : '#1f2937',+ },+ checkbox: {+ borderColor: isDarkMode ? '#4b5563' : '#d1d5db',+ },+ rememberMeText: {+ color: isDarkMode ? '#f3f4f6' : '#1f2937',+ },+ noteText: {+ color: isDarkMode ? '#9ca3af' : '#6b7280',+ },+ };++ const [credentials, setCredentials] = useState({+ username: '',+ password: '',+ });+ const [rememberMe, setRememberMe] = useState(true);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [twoFactorRequired, setTwoFactorRequired] = useState(false);+ const [twoFactorCode, setTwoFactorCode] = useState('');+ const [loginResponse, setLoginResponse] = useState<any>(null);+ const [passwordHashString, setPasswordHashString] = useState<string | null>(null);+ const [passwordHashBase64, setPasswordHashBase64] = useState<string | null>(null);++ const appState = useRef(AppState.currentState);+ const authContext = useAuth();+ const dbContext = useDb();+ const webApi = useWebApi();++ const srpUtil = new SrpUtility(webApi);++ const handleSubmit = async () => {+ setIsLoading(true);+ setError(null);++ try {+ console.log('handleSubmit');+ authContext.clearGlobalMessage();++ const loginResponse = await srpUtil.initiateLogin(credentials.username);++ console.log('loginResponse', loginResponse);++ const passwordHash = await EncryptionUtility.deriveKeyFromPassword(+ credentials.password,+ loginResponse.salt,+ loginResponse.encryptionType,+ loginResponse.encryptionSettings+ );++ console.log('passwordHash', passwordHash);++ const passwordHashString = Buffer.from(passwordHash).toString('hex').toUpperCase();+ const passwordHashBase64 = Buffer.from(passwordHash).toString('base64');++ console.log('passwordHashString', passwordHashString);++ const validationResponse = await srpUtil.validateLogin(+ credentials.username,+ passwordHashString,+ rememberMe,+ loginResponse+ );++ console.log('validationResponse', validationResponse);++ if (validationResponse.requiresTwoFactor) {+ setLoginResponse(loginResponse);+ setPasswordHashString(passwordHashString);+ setPasswordHashBase64(passwordHashBase64);+ setTwoFactorRequired(true);+ setIsLoading(false);+ return;+ }++ if (!validationResponse.token) {+ throw new Error('Login failed -- no token returned');+ }++ console.log('validationResponse.token', validationResponse.token);++ const vaultResponseJson = await webApi.authFetch<any>('Vault', { method: 'GET', headers: {+ 'Authorization': `Bearer ${validationResponse.token.token}`+ } });++ console.log('vaultResponseJson', vaultResponseJson);++ const vaultError = webApi.validateVaultResponse(vaultResponseJson);+ if (vaultError) {+ console.error('vaultError', vaultError);+ setError(vaultError);+ setIsLoading(false);+ return;+ }++ console.log('vaultResponseJson', vaultResponseJson);++ await authContext.setAuthTokens(credentials.username, validationResponse.token.token, validationResponse.token.refreshToken);+ await dbContext.initializeDatabase(vaultResponseJson, passwordHashBase64);+ await authContext.login();++ console.log('logged in');+ router.replace('/(tabs)');++ setIsLoading(false);+ } catch (err) {+ if (err instanceof ApiAuthError) {+ console.error('ApiAuthError error:', err);+ setError(err.message);+ } else {+ console.error('Login error:', err);+ setError('Could not reach AliasVault server. Please try again later or contact support if the problem persists.');+ }+ setIsLoading(false);+ }+ };++ const handleTwoFactorSubmit = async () => {+ setIsLoading(true);+ setError(null);++ try {+ if (!passwordHashString || !passwordHashBase64 || !loginResponse) {+ throw new Error('Required login data not found');+ }++ const code = twoFactorCode.trim();+ if (!/^\d{6}$/.test(code)) {+ throw new ApiAuthError('Please enter a valid 6-digit authentication code.');+ }++ const validationResponse = await srpUtil.validateLogin2Fa(+ credentials.username,+ passwordHashString,+ rememberMe,+ loginResponse,+ parseInt(twoFactorCode)+ );++ if (!validationResponse.token) {+ throw new Error('Login failed -- no token returned');+ }++ const vaultResponseJson = await webApi.authFetch<any>('Vault', { method: 'GET', headers: {+ 'Authorization': `Bearer ${validationResponse.token.token}`+ } });++ const vaultError = webApi.validateVaultResponse(vaultResponseJson);+ if (vaultError) {+ setError(vaultError);+ setIsLoading(false);+ return;+ }++ await authContext.setAuthTokens(credentials.username, validationResponse.token.token, validationResponse.token.refreshToken);+ await dbContext.initializeDatabase(vaultResponseJson, passwordHashBase64);+ await authContext.login();++ setTwoFactorRequired(false);+ setTwoFactorCode('');+ setPasswordHashString(null);+ setPasswordHashBase64(null);+ setLoginResponse(null);+ router.replace('/(tabs)');+ setIsLoading(false);+ } catch (err) {+ console.error('2FA error:', err);+ if (err instanceof ApiAuthError) {+ setError(err.message);+ } else {+ console.error('2FA error:', err);+ setError('Could not reach AliasVault server. Please try again later or contact support if the problem persists.');+ }+ setIsLoading(false);+ }+ };++ return (+ <SafeAreaView style={styles.container}>+ <ThemedView style={styles.content}>+ <ThemedView style={styles.titleContainer}>+ <ThemedText type="title">AliasVault</ThemedText>+ </ThemedView>++ {error && (+ <View style={styles.errorContainer}>+ <Text style={styles.errorText}>{error}</Text>+ </View>+ )}++ {twoFactorRequired ? (+ <View style={styles.formContainer}>+ <Text style={[styles.label, dynamicStyles.label]}>Authentication Code</Text>+ <TextInput+ style={[styles.input, dynamicStyles.input]}+ value={twoFactorCode}+ onChangeText={setTwoFactorCode}+ placeholder="Enter 6-digit code"+ keyboardType="numeric"+ maxLength={6}+ placeholderTextColor={isDarkMode ? '#9ca3af' : '#6b7280'}+ />+ <View style={styles.buttonContainer}>+ <TouchableOpacity+ style={[styles.button, styles.primaryButton]}+ onPress={handleTwoFactorSubmit}+ disabled={isLoading}+ >+ {isLoading ? (+ <ActivityIndicator color="#fff" />+ ) : (+ <Text style={styles.buttonText}>Verify</Text>+ )}+ </TouchableOpacity>+ <TouchableOpacity+ style={[styles.button, styles.secondaryButton]}+ onPress={() => {+ setCredentials({ username: '', password: '' });+ setTwoFactorRequired(false);+ setTwoFactorCode('');+ setPasswordHashString(null);+ setPasswordHashBase64(null);+ setLoginResponse(null);+ setError(null);+ }}+ >+ <Text style={styles.buttonText}>Cancel</Text>+ </TouchableOpacity>+ </View>+ <Text style={[styles.noteText, dynamicStyles.noteText]}>+ 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.+ </Text>+ </View>+ ) : (+ <View style={styles.formContainer}>+ <Text style={[styles.label, dynamicStyles.label]}>Username or email</Text>+ <TextInput+ style={[styles.input, dynamicStyles.input]}+ value={credentials.username}+ onChangeText={(text) => setCredentials({ ...credentials, username: text })}+ placeholder="name / [email protected]"+ autoCapitalize="none"+ placeholderTextColor={isDarkMode ? '#9ca3af' : '#6b7280'}+ />+ <Text style={[styles.label, dynamicStyles.label]}>Password</Text>+ <TextInput+ style={[styles.input, dynamicStyles.input]}+ value={credentials.password}+ onChangeText={(text) => setCredentials({ ...credentials, password: text })}+ placeholder="Enter your password"+ secureTextEntry+ placeholderTextColor={isDarkMode ? '#9ca3af' : '#6b7280'}+ />+ <View style={styles.rememberMeContainer}>+ <TouchableOpacity+ style={[styles.checkbox, dynamicStyles.checkbox]}+ onPress={() => setRememberMe(!rememberMe)}+ >+ <View style={[styles.checkboxInner, rememberMe && styles.checkboxChecked]} />+ </TouchableOpacity>+ <Text style={[styles.rememberMeText, dynamicStyles.rememberMeText]}>Remember me</Text>+ </View>+ <TouchableOpacity+ style={[styles.button, styles.primaryButton]}+ onPress={handleSubmit}+ disabled={isLoading}+ >+ {isLoading ? (+ <ActivityIndicator color="#fff" />+ ) : (+ <Text style={styles.buttonText}>Login</Text>+ )}+ </TouchableOpacity>+ </View>+ )}+ </ThemedView>+ </SafeAreaView>+ );+}++const styles = StyleSheet.create({+ container: {+ flex: 1,+ },+ content: {+ flex: 1,+ padding: 16,+ },+ titleContainer: {+ flexDirection: 'row',+ alignItems: 'center',+ gap: 8,+ marginBottom: 16,+ },+ formContainer: {+ gap: 16,+ },+ errorContainer: {+ backgroundColor: '#fee2e2',+ padding: 12,+ borderRadius: 8,+ marginBottom: 16,+ },+ errorText: {+ color: '#dc2626',+ fontSize: 14,+ },+ label: {+ fontSize: 14,+ fontWeight: '600',+ marginBottom: 4,+ },+ input: {+ borderWidth: 1,+ borderRadius: 8,+ padding: 12,+ fontSize: 16,+ },+ buttonContainer: {+ gap: 8,+ },+ button: {+ padding: 12,+ borderRadius: 8,+ alignItems: 'center',+ },+ primaryButton: {+ backgroundColor: '#f97316',+ },+ secondaryButton: {+ backgroundColor: '#6b7280',+ },+ buttonText: {+ color: '#fff',+ fontSize: 16,+ fontWeight: '600',+ },+ rememberMeContainer: {+ flexDirection: 'row',+ alignItems: 'center',+ gap: 8,+ },+ checkbox: {+ width: 20,+ height: 20,+ borderWidth: 2,+ borderRadius: 4,+ justifyContent: 'center',+ alignItems: 'center',+ },+ checkboxInner: {+ width: 12,+ height: 12,+ borderRadius: 2,+ },+ checkboxChecked: {+ backgroundColor: '#f97316',+ },+ rememberMeText: {+ fontSize: 14,+ },+ noteText: {+ fontSize: 12,+ textAlign: 'center',+ marginTop: 16,+ },+});\ No newline at end of filediff --git a/mobile-app/context/DbContext.tsx b/mobile-app/context/DbContext.tsxindex ab6cf7eea..a6c043dc1 100644--- a/mobile-app/context/DbContext.tsx+++ b/mobile-app/context/DbContext.tsx@@ -1,8 +1,6 @@import React, { createContext, useContext, useState, useEffect, useCallback, useMemo } from 'react';import SqliteClient from '@/utils/SqliteClient';import { VaultResponse } from '@/utils/types/webapi/VaultResponse';-import EncryptionUtility from '@/utils/EncryptionUtility';-import { VaultResponse as messageVaultResponse } from '@/utils/types/messaging/VaultResponse';import { NativeModules } from 'react-native';type DbContextType = {@@ -81,6 +79,25 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }}, []);const checkStoredVault = useCallback(async () => {+ // Try to do a simple query to see if the database is available.+ try {+ const isVaultInitialized = credentialManager.isVaultInitialized();+ if (isVaultInitialized) {+ // TODO: sqlclient can be initialized in constructor instead?+ const client = new SqliteClient();+ setSqliteClient(client);+ setDbInitialized(true);+ setDbAvailable(true);+ } else {+ setDbInitialized(true);+ setDbAvailable(false);+ }+ } catch (error) {+ console.error('Error checking vault initialization:', error);+ setDbInitialized(true);+ setDbAvailable(false);+ }+/*try {const response = await sendMessage('GET_VAULT', {}, 'background') as messageVaultResponse;if (response?.vault) {@@ -103,9 +120,6 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }setDbAvailable(false);}*/- // TODO: implement actual vault retrieval.- setDbInitialized(true);- setDbAvailable(false);}, []);/**@@ -124,6 +138,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }setSqliteClient(null);setDbInitialized(false);// TODO: implement actual vault clearing.+ credentialManager.clearVault();}, []);const contextValue = useMemo(() => ({diff --git a/mobile-app/ios/Autofill/CredentialProviderView.swift b/mobile-app/ios/Autofill/CredentialProviderView.swiftindex 8ee55eac3..5c8bc8c89 100644--- a/mobile-app/ios/Autofill/CredentialProviderView.swift+++ b/mobile-app/ios/Autofill/CredentialProviderView.swift@@ -13,21 +13,29 @@ struct CredentialProviderView: View {.progressViewStyle(.circular).scaleEffect(1.5)} else {- List(viewModel.credentials, id: \.service) { credential in- Button(action: {- viewModel.selectCredential(credential)- }) {- VStack(alignment: .leading) {- Text(credential.service)- .font(.headline)- Text(credential.username)- .font(.subheadline)- .foregroundColor(.secondary)+ VStack {+ SearchBar(text: $viewModel.searchText)+ .padding(.horizontal)+ .onChange(of: viewModel.searchText) { _ in+ viewModel.filterCredentials()+ }++ List(viewModel.filteredCredentials, id: \.service) { credential in+ Button(action: {+ viewModel.selectCredential(credential)+ }) {+ VStack(alignment: .leading) {+ Text(credential.service)+ .font(.headline)+ Text(credential.username)+ .font(.subheadline)+ .foregroundColor(.secondary)+ }}}- }- .refreshable {- viewModel.loadCredentials()+ .refreshable {+ viewModel.loadCredentials()+ }}}}@@ -118,8 +126,34 @@ struct AddCredentialView: View {}}+struct SearchBar: View {+ @Binding var text: String++ var body: some View {+ HStack {+ Image(systemName: "magnifyingglass")+ .foregroundColor(.gray)++ TextField("Search credentials...", text: $text)+ .textFieldStyle(RoundedBorderTextFieldStyle())+ .autocapitalization(.none)++ if !text.isEmpty {+ Button(action: {+ text = ""+ }) {+ Image(systemName: "xmark.circle.fill")+ .foregroundColor(.gray)+ }+ }+ }+ }+}+class CredentialProviderViewModel: ObservableObject {@Published var credentials: [Credential] = []+ @Published var filteredCredentials: [Credential] = []+ @Published var searchText = ""@Published var isLoading = true@Published var showError = false@Published var errorMessage = ""@@ -142,6 +176,7 @@ class CredentialProviderViewModel: ObservableObject {do {let sharedCredentialStore = SharedCredentialStore()credentials = try sharedCredentialStore.getAllCredentials()+ filteredCredentials = credentialsTask {do {@@ -158,6 +193,17 @@ class CredentialProviderViewModel: ObservableObject {}}+ func filterCredentials() {+ if searchText.isEmpty {+ filteredCredentials = credentials+ } else {+ filteredCredentials = credentials.filter { credential in+ credential.service.localizedCaseInsensitiveContains(searchText) ||+ credential.username.localizedCaseInsensitiveContains(searchText)+ }+ }+ }+func selectCredential(_ credential: Credential) {let passwordCredential = ASPasswordCredential(user: credential.username,password: credential.password)diff --git a/mobile-app/ios/CredentialManager/CredentialManager.m b/mobile-app/ios/CredentialManager/CredentialManager.mindex 71fd7c3e2..725032381 100644--- a/mobile-app/ios/CredentialManager/CredentialManager.m+++ b/mobile-app/ios/CredentialManager/CredentialManager.m@@ -1,10 +1,12 @@#import <React/RCTBridgeModule.h>@interface RCT_EXTERN_MODULE(CredentialManager, NSObject)+RCT_EXTERN_METHOD(requiresMainQueueSetup)RCT_EXTERN_METHOD(addCredential:(NSString *)username password:(NSString *)password service:(NSString *)service)RCT_EXTERN_METHOD(getCredentials)-RCT_EXTERN_METHOD(requiresMainQueueSetup)+RCT_EXTERN_METHOD(clearVault)+RCT_EXTERN_METHOD(isVaultInitialized:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)// New methods for SQLite database operationsRCT_EXTERN_METHOD(storeDatabase:(NSString *)base64EncryptedDbdiff --git a/mobile-app/ios/CredentialManager/CredentialManager.swift b/mobile-app/ios/CredentialManager/CredentialManager.swiftindex f3052859d..d8f31ddd2 100644--- a/mobile-app/ios/CredentialManager/CredentialManager.swift+++ b/mobile-app/ios/CredentialManager/CredentialManager.swift@@ -10,11 +10,6 @@ class CredentialManager: NSObject {super.init()}- @objc- func requiresMainQueueSetup() -> Bool {- return false- }-@objcfunc storeDatabase(_ base64EncryptedDb: String,resolver resolve: @escaping RCTPromiseResolveBlock,@@ -120,6 +115,31 @@ class CredentialManager: NSObject {return [:]}}++ @objc+ func clearVault() {+ do {+ try credentialStore.clearVault()+ } catch {+ print("Failed to clear vault: \(error)")+ }+ }++ @objc+ func isVaultInitialized(_ resolve: @escaping RCTPromiseResolveBlock,+ rejecter reject: @escaping RCTPromiseRejectBlock) {+ do {+ let isInitialized = try credentialStore.isVaultInitialized()+ resolve(isInitialized)+ } catch {+ reject("VAULT_ERROR", "Failed to check vault initialization: \(error.localizedDescription)", error)+ }+ }++ @objc+ func requiresMainQueueSetup() -> Bool {+ return false+ }@objcstatic func moduleName() -> String! {diff --git a/mobile-app/ios/CredentialManager/SharedCredentialStore.swift b/mobile-app/ios/CredentialManager/SharedCredentialStore.swiftindex 99a29ae7c..f20e185c0 100644--- a/mobile-app/ios/CredentialManager/SharedCredentialStore.swift+++ b/mobile-app/ios/CredentialManager/SharedCredentialStore.swift@@ -15,9 +15,16 @@ class SharedCredentialStore {private var encryptionKey: Data?public init() {}++ // MARK: - Vault Status+ func isVaultInitialized() -> Bool {+ // Check if encrypted database file exists+ let hasDatabase = FileManager.default.fileExists(atPath: getEncryptedDbPath().path)++ return hasDatabase+ }// MARK: - Encryption Key Management-private func getEncryptionKey() throws -> Data {if let key = encryptionKey {// print as base64 for debugging@@ -104,44 +111,14 @@ class SharedCredentialStore {throw NSError(domain: "SharedCredentialStore", code: 10, userInfo: [NSLocalizedDescriptionKey: "Failed to decode base64 data after decryption"])}- // Check SQLite header- let header = decryptedDbData.prefix(24)- let headerString = String(bytes: header, encoding: .ascii) ?? "Non-ascii"- print("SQLite header: \(headerString)")- print("Header bytes: \(header.map { String(format: "%02x", $0) }.joined(separator: " "))")-- // Verify it matches expected SQLite header- let expectedHeader = "SQLite format 3\0"- if headerString != expectedHeader {- print("WARNING: SQLite header does not match expected format!")- }-- print("decrypted data raw print?")- print(decryptedDbData)-- let tag = decryptedDbData.suffix(16)- print("tag: \(tag.base64EncodedString())")-// Create a temporary file for the decrypted database in the same directory as the encrypted onelet tempDbPath = FileManager.default.temporaryDirectory.appendingPathComponent("temp_db.sqlite")try decryptedDbData.write(to: tempDbPath)- do {- let tempDb = try Connection(tempDbPath.path)- let tables = try tempDb.prepare("SELECT name FROM sqlite_master WHERE type='table'")- for table in tables {- print("Table:", table[0] as? String ?? "Unknown")- }- } catch {- print("Direct DB open error:", error)- }-// Create an in-memory databasedb = try Connection(":memory:")// Import the decrypted database into memory- //try db?.attach(.uri(tempDbPath.path, parameters: [.mode(.readOnly)]), as: "source")- // make query and print it before actually attachingtry db?.attach(.uri(tempDbPath.path, parameters: [.mode(.readOnly)]), as: "source")try db?.execute("BEGIN TRANSACTION")@@ -256,6 +233,17 @@ class SharedCredentialStore {// Clear the cached encrypted databasedb = nil}++ // Clears cached and saved encryption key and encrypted database to force re-initialization on next access.+ func clearVault() {+ // Remove the encryption key from keychain+ try? keychain.remove(encryptionKeyKey)++ // Remove the encrypted database from the app's documents directory+ try? FileManager.default.removeItem(at: getEncryptedDbPath())++ clearCache()+ }// MARK: - Query Execution