Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add scaffolding for react native based on browser extension react (#771)
Leendert de Borst1b70c0c727bb
diff --git a/mobile-app/app.json b/mobile-app/app.jsonindex e39f8c772..0fee3af89 100644--- a/mobile-app/app.json+++ b/mobile-app/app.json@@ -34,7 +34,8 @@"resizeMode": "contain","backgroundColor": "#ffffff"}- ]+ ],+ "expo-sqlite"],"experiments": {"typedRoutes": truediff --git a/mobile-app/app/(tabs)/index.bak.tsx b/mobile-app/app/(tabs)/index.bak.tsxnew file mode 100644index 000000000..8eeb92d70--- /dev/null+++ b/mobile-app/app/(tabs)/index.bak.tsx@@ -0,0 +1,130 @@+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 handleClearCredentials = async () => {+ // Call native module to clear credentials+ await NativeModules.CredentialManager.clearCredentials();+ setCredentials([]); // Clear 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} />+ <Button title="Clear Credentials" onPress={handleClearCredentials} />+ <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 8eeb92d70..5d7e45edb 100644--- a/mobile-app/app/(tabs)/index.tsx+++ b/mobile-app/app/(tabs)/index.tsx@@ -1,80 +1,302 @@-import { Image, StyleSheet, Platform, Button, View, FlatList, Text, SafeAreaView, AppState } from 'react-native';+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 { ThemedText } from '@/components/ThemedText';import { ThemedView } from '@/components/ThemedView';--interface Credential {- username: string;- password: string;- service: string;-}+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 HomeScreen() {- const [credentials, setCredentials] = useState<Credential[]>([]);+ 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);++ // 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);- 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);+ 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+ );++ // 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');++ // 2. Validate login with SRP protocol+ const validationResponse = await srpUtil.validateLogin(+ credentials.username,+ passwordHashString,+ rememberMe,+ loginResponse+ );++ // 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');+ }++ // 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) {+ console.error('vaultError', 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();++ 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);}};- useEffect(() => {- const subscription = AppState.addEventListener('change', nextAppState => {- if (- appState.current.match(/inactive|background/) &&- nextAppState === 'active'- ) {- console.log('App has come to the foreground!');- fetchCredentials();+ const handleTwoFactorSubmit = async () => {+ setIsLoading(true);+ setError(null);++ try {+ if (!passwordHashString || !passwordHashBase64 || !loginResponse) {+ throw new Error('Required login data not found');}- 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 handleClearCredentials = async () => {- // Call native module to clear credentials- await NativeModules.CredentialManager.clearCredentials();- setCredentials([]); // Clear the list+ // 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 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>- );+ if (!isAuthenticated) {+ 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}>@@ -83,14 +305,7 @@ export default function HomeScreen() {<ThemedText type="title">AliasVault</ThemedText></ThemedView><ThemedView style={styles.stepContainer}>- <ThemedText type="subtitle">Credentials</ThemedText>- <Button title="Add Random Credential" onPress={handleInsertEntry} />- <Button title="Clear Credentials" onPress={handleClearCredentials} />- <FlatList- data={credentials}- renderItem={({ item }) => renderCredential(item)}- keyExtractor={(item) => `${item.service}-${item.username}`}- />+ <ThemedText type="subtitle">Logged in</ThemedText></ThemedView></ThemedView></SafeAreaView>@@ -115,16 +330,79 @@ const styles = StyleSheet.create({flex: 1,gap: 8,},- reactLogo: {- height: 178,- width: 290,- bottom: 0,- left: 0,- position: 'absolute',- },- credentialItem: {- padding: 10,- marginVertical: 5,- borderRadius: 5,+ 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,},});diff --git a/mobile-app/app/_layout.tsx b/mobile-app/app/_layout.tsxindex db7457899..43b5a7d99 100644--- a/mobile-app/app/_layout.tsx+++ b/mobile-app/app/_layout.tsx@@ -7,6 +7,10 @@ import { useEffect } from 'react';import 'react-native-reanimated';import { useColorScheme } from '@/hooks/useColorScheme';+import { LoadingProvider } from '@/context/LoadingContext';+import { DbProvider } from '@/context/DbContext';+import { AuthProvider } from '@/context/AuthContext';+import { WebApiProvider } from '@/context/WebApiContext';// Prevent the splash screen from auto-hiding before asset loading is complete.SplashScreen.preventAutoHideAsync();@@ -28,12 +32,20 @@ export default function RootLayout() {}return (- <ThemeProvider value={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>- <Stack>- <Stack.Screen name="(tabs)" options={{ headerShown: false }} />- <Stack.Screen name="+not-found" />- </Stack>- <StatusBar style="auto" />- </ThemeProvider>+ <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>);}diff --git a/mobile-app/context/AuthContext.tsx b/mobile-app/context/AuthContext.tsxnew file mode 100644index 000000000..8824b23fa--- /dev/null+++ b/mobile-app/context/AuthContext.tsx@@ -0,0 +1,122 @@+import React, { createContext, useContext, useState, useEffect, useMemo, useCallback } from 'react';+import AsyncStorage from '@react-native-async-storage/async-storage';+import { useDb } from './DbContext';++type AuthContextType = {+ isLoggedIn: boolean;+ isInitialized: boolean;+ username: string | null;+ setAuthTokens: (username: string, accessToken: string, refreshToken: string) => Promise<void>;+ login: () => Promise<void>;+ logout: (errorMessage?: string) => Promise<void>;+ globalMessage: string | null;+ clearGlobalMessage: () => void;+}++/**+ * Auth context.+ */+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 }) => {+ const [isLoggedIn, setIsLoggedIn] = useState(false);+ const [isInitialized, setIsInitialized] = useState(false);+ const [username, setUsername] = useState<string | null>(null);+ const [globalMessage, setGlobalMessage] = useState<string | null>(null);+ const dbContext = useDb();++ /**+ * Check for tokens in chrome storage on initial load.+ */+ useEffect(() => {+ /**+ * Initialize the authentication state.+ */+ const initializeAuth = async () : Promise<void> => {+ const accessToken = await AsyncStorage.getItem('accessToken') as string;+ const refreshToken = await AsyncStorage.getItem('refreshToken') as string;+ const username = await AsyncStorage.getItem('username') as string;+ if (accessToken && refreshToken && username) {+ setUsername(username);+ setIsLoggedIn(true);+ }+ setIsInitialized(true);+ };++ initializeAuth();+ }, []);++ /**+ * Set auth tokens in chrome storage as part of the login process. After db is initialized, the login method should be called as well.+ */+ const setAuthTokens = useCallback(async (username: string, accessToken: string, refreshToken: string) : Promise<void> => {+ await AsyncStorage.setItem('username', username);+ await AsyncStorage.setItem('accessToken', accessToken);+ await AsyncStorage.setItem('refreshToken', refreshToken);++ setUsername(username);+ }, []);++ /**+ * Set logged in status to true which refreshes the app.+ */+ const login = useCallback(async () : Promise<void> => {+ setIsLoggedIn(true);+ }, []);++ /**+ * Logout the user and clear the auth tokens from chrome storage.+ */+ const logout = useCallback(async (errorMessage?: string) : Promise<void> => {+ await AsyncStorage.removeItem('username');+ await AsyncStorage.removeItem('accessToken');+ await AsyncStorage.removeItem('refreshToken');+ dbContext?.clearDatabase();++ // Set local storage global message that will be shown on the login page.+ if (errorMessage) {+ setGlobalMessage(errorMessage);+ }++ setUsername(null);+ setIsLoggedIn(false);+ }, [dbContext]);++ /**+ * Clear global message (called after displaying the message).+ */+ const clearGlobalMessage = useCallback(() : void => {+ setGlobalMessage(null);+ }, []);++ const contextValue = useMemo(() => ({+ isLoggedIn,+ isInitialized,+ username,+ setAuthTokens,+ login,+ logout,+ globalMessage,+ clearGlobalMessage,+ }), [isLoggedIn, isInitialized, username, globalMessage, setAuthTokens, login, logout, clearGlobalMessage]);++ return (+ <AuthContext.Provider value={contextValue}>+ {children}+ </AuthContext.Provider>+ );+};++/**+ * Hook to use the AuthContext+ */+export const useAuth = () : AuthContextType => {+ const context = useContext(AuthContext);+ if (context === undefined) {+ throw new Error('useAuth must be used within an AuthProvider');+ }+ return context;+};\ No newline at end of filediff --git a/mobile-app/context/DbContext.tsx b/mobile-app/context/DbContext.tsxnew file mode 100644index 000000000..6e0384aea--- /dev/null+++ b/mobile-app/context/DbContext.tsx@@ -0,0 +1,151 @@+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';++type DbContextType = {+ sqliteClient: SqliteClient | null;+ dbInitialized: boolean;+ dbAvailable: boolean;+ initializeDatabase: (vaultResponse: VaultResponse, derivedKey: string) => Promise<void>;+ clearDatabase: () => void;+ vaultRevision: number;+ publicEmailDomains: string[];+ privateEmailDomains: string[];+}++const DbContext = createContext<DbContextType | undefined>(undefined);++/**+ * DbProvider to provide the SQLite client to the app that components can use to make database queries.+ */+export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {+ /**+ * SQLite client.+ */+ const [sqliteClient, setSqliteClient] = useState<SqliteClient | null>(null);++ /**+ * Database initialization state. If true, the database has been initialized and the dbAvailable state is correct.+ */+ const [dbInitialized, setDbInitialized] = useState(false);++ /**+ * Database availability state. If true, the database is available. If false, the database is not available and needs to be unlocked or retrieved again from the API.+ */+ const [dbAvailable, setDbAvailable] = useState(false);++ /**+ * Public email domains.+ */+ const [publicEmailDomains, setPublicEmailDomains] = useState<string[]>([]);++ /**+ * Vault revision.+ */+ const [vaultRevision, setVaultRevision] = useState(0);++ /**+ * Private email domains.+ */+ const [privateEmailDomains, setPrivateEmailDomains] = useState<string[]>([]);++ const initializeDatabase = useCallback(async (vaultResponse: VaultResponse, derivedKey: string) => {+ // Attempt to decrypt the blob.+ const decryptedBlob = await EncryptionUtility.symmetricDecrypt(+ vaultResponse.vault.blob,+ derivedKey+ );++ // Initialize the SQLite client.+ const client = new SqliteClient();+ await client.initializeFromBase64(decryptedBlob);++ setSqliteClient(client);+ setDbInitialized(true);+ setDbAvailable(true);+ setPublicEmailDomains(vaultResponse.vault.publicEmailDomainList);+ setPrivateEmailDomains(vaultResponse.vault.privateEmailDomainList);+ setVaultRevision(vaultResponse.vault.currentRevisionNumber);++ /*+ * Store encrypted vault in background worker.+ */+ // TODO: implement actual vault storage.+ }, []);++ const checkStoredVault = useCallback(async () => {+ /*try {+ const response = await sendMessage('GET_VAULT', {}, 'background') as messageVaultResponse;+ if (response?.vault) {+ const client = new SqliteClient();+ await client.initializeFromBase64(response.vault);++ setSqliteClient(client);+ setDbInitialized(true);+ setDbAvailable(true);+ setPublicEmailDomains(response.publicEmailDomains ?? []);+ setPrivateEmailDomains(response.privateEmailDomains ?? []);+ setVaultRevision(response.vaultRevisionNumber ?? 0);+ } else {+ setDbInitialized(true);+ setDbAvailable(false);+ }+ } catch (error) {+ console.error('Error retrieving vault from background:', error);+ setDbInitialized(true);+ setDbAvailable(false);+ }*/++ // TODO: implement actual vault retrieval.+ setDbInitialized(true);+ setDbAvailable(false);+ }, []);++ /**+ * Check if database is initialized and try to retrieve vault from background+ */+ useEffect(() : void => {+ if (!dbInitialized) {+ checkStoredVault();+ }+ }, [dbInitialized, checkStoredVault]);++ /**+ * Clear database and remove from background worker, called when logging out.+ */+ const clearDatabase = useCallback(() : void => {+ setSqliteClient(null);+ setDbInitialized(false);+ // TODO: implement actual vault clearing.+ }, []);++ const contextValue = useMemo(() => ({+ sqliteClient,+ dbInitialized,+ dbAvailable,+ initializeDatabase,+ clearDatabase,+ vaultRevision,+ publicEmailDomains,+ privateEmailDomains+ }), [sqliteClient, dbInitialized, dbAvailable, initializeDatabase, clearDatabase, vaultRevision, publicEmailDomains, privateEmailDomains]);++ return (+ <DbContext.Provider value={contextValue}>+ {children}+ </DbContext.Provider>+ );+};++/**+ * Hook to use the DbContext+ */+export const useDb = () : DbContextType => {+ const context = useContext(DbContext);+ if (context === undefined) {+ throw new Error('useDb must be used within a DbProvider');+ }+ return context;+};diff --git a/mobile-app/context/LoadingContext.tsx b/mobile-app/context/LoadingContext.tsxnew file mode 100644index 000000000..18eb8a46e--- /dev/null+++ b/mobile-app/context/LoadingContext.tsx@@ -0,0 +1,70 @@+import React, { createContext, useContext, useState, useMemo } from 'react';++type LoadingContextType = {+ isLoading: boolean;+ showLoading: () => void;+ hideLoading: () => void;+ isInitialLoading: boolean;+ setIsInitialLoading: (isInitialLoading: boolean) => void;+}++/**+ * Loading context.+ * TODO: can we remove this context for the mobile apps? Probably not needed.+ */+const LoadingContext = createContext<LoadingContextType | undefined>(undefined);++/**+ * Loading provider+ */+export const LoadingProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {+ /**+ * Initial loading state for when extension is first loaded. This initial loading state is+ * hidden by the component that is rendered when the extension is first loaded to prevent+ * multiple loading spinners from being shown.+ */+ const [isInitialLoading, setIsInitialLoading] = useState(true);++ /**+ * Loading state that can be used by other components during normal operation.+ */+ const [isLoading, setIsLoading] = useState(false);++ /**+ * Show loading spinner+ */+ const showLoading = (): void => setIsLoading(true);++ /**+ * Hide loading spinner+ */+ const hideLoading = (): void => setIsLoading(false);++ const value = useMemo(+ () => ({+ isLoading,+ showLoading,+ hideLoading,+ isInitialLoading,+ setIsInitialLoading,+ }),+ [isLoading, isInitialLoading]+ );++ return (+ <LoadingContext.Provider value={value}>+ {children}+ </LoadingContext.Provider>+ );+};++/**+ * Hook to use loading state+ */+export const useLoading = (): LoadingContextType => {+ const context = useContext(LoadingContext);+ if (context === undefined) {+ throw new Error('useLoading must be used within a LoadingProvider');+ }+ return context;+};\ No newline at end of filediff --git a/mobile-app/context/ThemeContext.tsx b/mobile-app/context/ThemeContext.tsxnew file mode 100644index 000000000..f16683bb7--- /dev/null+++ b/mobile-app/context/ThemeContext.tsx@@ -0,0 +1,134 @@+import React, { createContext, useContext, useState, useMemo, useEffect, useCallback } from 'react';+import AsyncStorage from '@react-native-async-storage/async-storage';++/**+ * Theme type.+ */+type Theme = 'light' | 'dark' | 'system';++/**+ * Theme preference key in storage.+ */+const THEME_PREFERENCE_KEY = 'local:theme';++/**+ * Theme context type.+ */+type ThemeContextType = {+ theme: Theme;+ setTheme: (theme: Theme) => void;+ isDarkMode: boolean;+}++/**+ * Theme context.+ */+const ThemeContext = createContext<ThemeContextType | undefined>(undefined);++/**+ * Theme provider+ */+export const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {+ /**+ * Theme state that can be 'light', 'dark', or 'system'.+ */+ const [theme, setTheme] = useState<Theme>('system');++ /**+ * Tracks whether dark mode is active (based on theme or system preference).+ */+ const [isDarkMode, setIsDarkMode] = useState<boolean>(false);++ useEffect(() => {+ /**+ * Load theme setting from storage.+ */+ const loadTheme = async () : Promise<void> => {+ const savedTheme = await getTheme();+ setTheme(savedTheme);+ };+ loadTheme();+ }, []);++ /**+ * Set the theme and save to storage.+ */+ const updateTheme = useCallback((newTheme: Theme): void => {+ setTheme(newTheme);+ setStoredTheme(newTheme);+ }, []);++ /**+ * Get the theme from storage.+ */+ const getTheme = async (): Promise<Theme> => {+ return (await AsyncStorage.getItem(THEME_PREFERENCE_KEY) as Theme) || 'system';+ };++ /**+ * Set the theme in storage.+ */+ const setStoredTheme = async (theme: Theme): Promise<void> => {+ await AsyncStorage.setItem(THEME_PREFERENCE_KEY, theme);+ };++ /**+ * Effect to apply theme to document and handle system preference changes+ */+ useEffect(() => {+ /**+ * Update the dark mode status.+ */+ const updateDarkMode = (): void => {+ if (theme === 'system') {+ const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;+ setIsDarkMode(prefersDark);+ document.documentElement.classList.toggle('dark', prefersDark);+ } else {+ const isDark = theme === 'dark';+ setIsDarkMode(isDark);+ document.documentElement.classList.toggle('dark', isDark);+ }+ };++ // Initial update+ updateDarkMode();++ // Listen for system preference changes if using 'system' theme+ if (theme === 'system') {+ const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');+ /**+ * Update the dark mode status when the system preference changes.+ */+ const handler = () : void => updateDarkMode();+ mediaQuery.addEventListener('change', handler);+ return () : void => mediaQuery.removeEventListener('change', handler);+ }+ }, [theme]);++ const value = useMemo(+ () => ({+ theme,+ setTheme: updateTheme,+ isDarkMode,+ }),+ [theme, isDarkMode, updateTheme]+ );++ return (+ <ThemeContext.Provider value={value}>+ {children}+ </ThemeContext.Provider>+ );+};++/**+ * Hook to use theme state+ */+export const useTheme = (): ThemeContextType => {+ const context = useContext(ThemeContext);+ if (context === undefined) {+ throw new Error('useTheme must be used within a ThemeProvider');+ }+ return context;+};\ No newline at end of filediff --git a/mobile-app/context/WebApiContext.tsx b/mobile-app/context/WebApiContext.tsxnew file mode 100644index 000000000..4daff274a--- /dev/null+++ b/mobile-app/context/WebApiContext.tsx@@ -0,0 +1,50 @@+import React, { createContext, useContext, useEffect, useState } from 'react';+import { WebApiService } from '@/utils/WebApiService';+import { useAuth } from './AuthContext';++const WebApiContext = createContext<WebApiService | null>(null);++/**+ * WebApiProvider to provide the WebApiService to the app that components can use.+ */+export const WebApiProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {+ const { logout } = useAuth();+ const [webApiService, setWebApiService] = useState<WebApiService | null>(null);++ /**+ * Initialize WebApiService+ */+ useEffect(() : void => {+ const service = new WebApiService(+ (statusError: string | null) => {+ if (statusError) {+ logout(statusError);+ } else {+ logout();+ }+ }+ );+ setWebApiService(service);+ }, [logout]);++ if (!webApiService) {+ return null;+ }++ return (+ <WebApiContext.Provider value={webApiService}>+ {children}+ </WebApiContext.Provider>+ );+};++/**+ * Hook to use the WebApiService+ */+export const useWebApi = () : WebApiService => {+ const context = useContext(WebApiContext);+ if (!context) {+ throw new Error('useWebApi must be used within a WebApiProvider');+ }+ return context;+};diff --git a/mobile-app/ios/Podfile.lock b/mobile-app/ios/Podfile.lockindex ea1d7875e..1ee4ad876 100644--- a/mobile-app/ios/Podfile.lock+++ b/mobile-app/ios/Podfile.lock@@ -256,6 +256,8 @@ PODS:- Yoga- ExpoSplashScreen (0.29.22):- ExpoModulesCore+ - ExpoSQLite (15.1.4):+ - ExpoModulesCore- ExpoSymbols (0.2.2):- ExpoModulesCore- ExpoSystemUI (4.0.9):@@ -1909,6 +1911,27 @@ PODS:- React-logger- React-perflogger- React-utils (= 0.76.9)+ - RNCAsyncStorage (2.1.2):+ - DoubleConversion+ - glog+ - hermes-engine+ - RCT-Folly (= 2024.10.14.00)+ - RCTRequired+ - RCTTypeSafety+ - React-Core+ - React-debug+ - React-Fabric+ - React-featureflags+ - React-graphics+ - React-ImageManager+ - React-NativeModulesApple+ - React-RCTFabric+ - React-rendererdebug+ - React-utils+ - ReactCodegen+ - ReactCommon/turbomodule/bridging+ - ReactCommon/turbomodule/core+ - Yoga- RNGestureHandler (2.20.2):- DoubleConversion- glog@@ -2086,6 +2109,7 @@ DEPENDENCIES:- ExpoLinking (from `../node_modules/expo-linking/ios`)- ExpoModulesCore (from `../node_modules/expo-modules-core`)- ExpoSplashScreen (from `../node_modules/expo-splash-screen/ios`)+ - ExpoSQLite (from `../node_modules/expo-sqlite/ios`)- ExpoSymbols (from `../node_modules/expo-symbols/ios`)- ExpoSystemUI (from `../node_modules/expo-system-ui/ios`)- ExpoWebBrowser (from `../node_modules/expo-web-browser/ios`)@@ -2156,6 +2180,7 @@ DEPENDENCIES:- React-utils (from `../node_modules/react-native/ReactCommon/react/utils`)- ReactCodegen (from `build/generated/ios`)- ReactCommon/turbomodule/core (from `../node_modules/react-native/ReactCommon`)+ - "RNCAsyncStorage (from `../node_modules/@react-native-async-storage/async-storage`)"- RNGestureHandler (from `../node_modules/react-native-gesture-handler`)- RNReanimated (from `../node_modules/react-native-reanimated`)- RNScreens (from `../node_modules/react-native-screens`)@@ -2207,6 +2232,8 @@ EXTERNAL SOURCES::path: "../node_modules/expo-modules-core"ExpoSplashScreen::path: "../node_modules/expo-splash-screen/ios"+ ExpoSQLite:+ :path: "../node_modules/expo-sqlite/ios"ExpoSymbols::path: "../node_modules/expo-symbols/ios"ExpoSystemUI:@@ -2342,6 +2369,8 @@ EXTERNAL SOURCES::path: build/generated/iosReactCommon::path: "../node_modules/react-native/ReactCommon"+ RNCAsyncStorage:+ :path: "../node_modules/@react-native-async-storage/async-storage"RNGestureHandler::path: "../node_modules/react-native-gesture-handler"RNReanimated:@@ -2372,6 +2401,7 @@ SPEC CHECKSUMS:ExpoLinking: 8d12bee174ba0cdf31239706578e29e74a417402ExpoModulesCore: c25d77625038b1968ea1afefc719862c0d8dd993ExpoSplashScreen: 0f281e3c2ded4757d2309276c682d023c6299c77+ ExpoSQLite: 10fceac6748e9e8f010c70733e0e704fa67399abExpoSymbols: f3002db15156cd4e505c77b6ea1df5c984db9965ExpoSystemUI: b82a45cf0f6a4fa18d07c46deba8725dd27688b4ExpoWebBrowser: a212e6b480d8857d3e441fba51e0c968333803b3@@ -2440,6 +2470,7 @@ SPEC CHECKSUMS:React-utils: ed818f19ab445000d6b5c4efa9d462449326cc9fReactCodegen: f853a20cc9125c5521c8766b4b49375fec20648bReactCommon: 300d8d9c5cb1a6cd79a67cf5d8f91e4d477195f9+ RNCAsyncStorage: ab0ad9a78ead8b9f143f0238a5aa535777b12e65RNGestureHandler: fffddeb8af59709c6d8de11b6461a6af63cad532RNReanimated: 2e5069649cbab2c946652d3b97589b2ae0526220RNScreens: 362f4c861dd155f898908d5035d97b07a3f1a9d1diff --git a/mobile-app/ios/aliasvault.xcodeproj/project.pbxproj b/mobile-app/ios/aliasvault.xcodeproj/project.pbxprojindex 818d2496b..278405dd2 100644--- a/mobile-app/ios/aliasvault.xcodeproj/project.pbxproj+++ b/mobile-app/ios/aliasvault.xcodeproj/project.pbxproj@@ -446,10 +446,12 @@);inputPaths = ("${PODS_ROOT}/Target Support Files/Pods-AliasVault/Pods-AliasVault-frameworks.sh",+ "${PODS_XCFRAMEWORKS_BUILD_DIR}/ExpoSQLite/crsqlite.framework/crsqlite","${PODS_XCFRAMEWORKS_BUILD_DIR}/hermes-engine/Pre-built/hermes.framework/hermes",);name = "[CP] Embed Pods Frameworks";outputPaths = (+ "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/crsqlite.framework","${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/hermes.framework",);runOnlyForDeploymentPostprocessing = 0;diff --git a/mobile-app/package-lock.json b/mobile-app/package-lock.jsonindex 967599db3..5a597d64e 100644--- a/mobile-app/package-lock.json+++ b/mobile-app/package-lock.json@@ -9,8 +9,10 @@"version": "1.0.0","dependencies": {"@expo/vector-icons": "^14.0.2",+ "@react-native-async-storage/async-storage": "^2.1.2","@react-navigation/bottom-tabs": "^7.2.0","@react-navigation/native": "^7.0.14",+ "argon2-browser": "^1.18.0","expo": "~52.0.43","expo-blur": "~14.0.3","expo-constants": "~17.0.8",@@ -20,6 +22,7 @@"expo-linking": "~7.0.5","expo-router": "~4.0.20","expo-splash-screen": "~0.29.22",+ "expo-sqlite": "~15.1.4","expo-status-bar": "~2.0.1","expo-symbols": "~0.2.2","expo-system-ui": "~4.0.9",@@ -32,13 +35,16 @@"react-native-safe-area-context": "4.12.0","react-native-screens": "~4.4.0","react-native-web": "~0.19.13",- "react-native-webview": "13.12.5"+ "react-native-webview": "13.12.5",+ "secure-remote-password": "github:LinusU/secure-remote-password#73e5f732b6ca0cdbdc19da1a0c5f48cdbad2cbf0"},"devDependencies": {"@babel/core": "^7.25.2",+ "@types/argon2-browser": "^1.18.4","@types/jest": "^29.5.12","@types/react": "~18.3.12","@types/react-test-renderer": "^18.3.0",+ "@types/sql.js": "^1.4.9","jest": "^29.2.1","jest-expo": "~52.0.6","react-test-renderer": "18.3.1",@@ -3536,6 +3542,18 @@"react": "^16.8 || ^17.0 || ^18.0"}},+ "node_modules/@react-native-async-storage/async-storage": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/@react-native-async-storage/async-storage/-/async-storage-2.1.2.tgz",+ "integrity": "sha512-dvlNq4AlGWC+ehtH12p65+17V0Dx7IecOWl6WanF2ja38O1Dcjjvn7jVzkUHJ5oWkQBlyASurTPlTHgKXyYiow==",+ "license": "MIT",+ "dependencies": {+ "merge-options": "^3.0.4"+ },+ "peerDependencies": {+ "react-native": "^0.0.0-0 || >=0.65 <1.0"+ }+ },"node_modules/@react-native/assets-registry": {"version": "0.76.9","resolved": "https://registry.npmjs.org/@react-native/assets-registry/-/assets-registry-0.76.9.tgz",@@ -4053,6 +4071,13 @@"node": ">= 10"}},+ "node_modules/@types/argon2-browser": {+ "version": "1.18.4",+ "resolved": "https://registry.npmjs.org/@types/argon2-browser/-/argon2-browser-1.18.4.tgz",+ "integrity": "sha512-K/PHAEKzdCY4mCRhgUTBcuTxeaJyLoPcd5pJ1UFSTb/FAPjj3TCK4EM/DvNmVtDzkQBMD5peJjtch3kVQDf4YQ==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@types/babel__core": {"version": "7.20.5","resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",@@ -4094,6 +4119,13 @@"@babel/types": "^7.20.7"}},+ "node_modules/@types/emscripten": {+ "version": "1.40.1",+ "resolved": "https://registry.npmjs.org/@types/emscripten/-/emscripten-1.40.1.tgz",+ "integrity": "sha512-sr53lnYkQNhjHNN0oJDdUm5564biioI5DuOpycufDVK7D3y+GR3oUswe2rlwY1nPNyusHbrJ9WoTyIHl4/Bpwg==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@types/eslint": {"version": "9.6.1","resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-9.6.1.tgz",@@ -4240,6 +4272,17 @@"@types/react": "^18"}},+ "node_modules/@types/sql.js": {+ "version": "1.4.9",+ "resolved": "https://registry.npmjs.org/@types/sql.js/-/sql.js-1.4.9.tgz",+ "integrity": "sha512-ep8b36RKHlgWPqjNG9ToUrPiwkhwh0AEzy883mO5Xnd+cL6VBH1EvSjBAAuxLUFF2Vn/moE3Me6v9E1Lo+48GQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/emscripten": "*",+ "@types/node": "*"+ }+ },"node_modules/@types/stack-utils": {"version": "2.0.3","resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz",@@ -4728,6 +4771,12 @@"integrity": "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==","license": "MIT"},+ "node_modules/argon2-browser": {+ "version": "1.18.0",+ "resolved": "https://registry.npmjs.org/argon2-browser/-/argon2-browser-1.18.0.tgz",+ "integrity": "sha512-ImVAGIItnFnvET1exhsQB7apRztcoC5TnlSqernMJDUjbc/DLq3UEYeXFrLPrlaIl8cVfwnXb6wX2KpFf2zxHw==",+ "license": "MIT"+ },"node_modules/argparse": {"version": "1.0.10","resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz",@@ -4737,6 +4786,12 @@"sprintf-js": "~1.0.2"}},+ "node_modules/array-buffer-to-hex": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/array-buffer-to-hex/-/array-buffer-to-hex-1.0.0.tgz",+ "integrity": "sha512-arycdkxgK1cj6s03GDb96tlCxOl1n3kg9M2OHseUc6Pqyqp+lgfceFPmG507eI5V+oxOSEnlOw/dFc7LXBXF4Q==",+ "license": "MIT"+ },"node_modules/array-union": {"version": "2.1.0","resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz",@@ -5849,6 +5904,21 @@"node": "*"}},+ "node_modules/crypto-digest-sync": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/crypto-digest-sync/-/crypto-digest-sync-1.0.0.tgz",+ "integrity": "sha512-UQBOB5z+HF4iA8shKQ3PPwhCmdFAihwcytD1Qh4uiz78x04cZZmKtZ1F1VyAjkrA8uEZqXt2tMXfj3dJHtcbng==",+ "license": "MIT"+ },+ "node_modules/crypto-random-hex": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/crypto-random-hex/-/crypto-random-hex-1.0.0.tgz",+ "integrity": "sha512-1DuZQ03El13TRgfrqbbjW40Gvi4OKInny/Wxqj23/JMXe214C/3Tlz92bKXWDW3NZT5RjXUGdYW4qiIOUPf+cA==",+ "license": "MIT",+ "dependencies": {+ "array-buffer-to-hex": "^1.0.0"+ }+ },"node_modules/crypto-random-string": {"version": "2.0.0","resolved": "https://registry.npmjs.org/crypto-random-string/-/crypto-random-string-2.0.0.tgz",@@ -6202,6 +6272,12 @@"integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==","license": "MIT"},+ "node_modules/encode-utf8": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/encode-utf8/-/encode-utf8-1.0.3.tgz",+ "integrity": "sha512-ucAnuBEhUK4boH2HjVYG5Q2mQyPorvv0u/ocS+zhdw0S8AlHYY+GOFhP1Gio5z4icpP2ivFSvhtFjQi8+T9ppw==",+ "license": "MIT"+ },"node_modules/encodeurl": {"version": "1.0.2","resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz",@@ -6967,6 +7043,17 @@"expo": "*"}},+ "node_modules/expo-sqlite": {+ "version": "15.1.4",+ "resolved": "https://registry.npmjs.org/expo-sqlite/-/expo-sqlite-15.1.4.tgz",+ "integrity": "sha512-1SG5Qi6/L2SK/o5EKtvEmlMVGdra/wYYh/intI94/ovsUfZGFrDG31YGtTt4rLpE95M6FwHUVpALO8g9/G9B2Q==",+ "license": "MIT",+ "peerDependencies": {+ "expo": "*",+ "react": "*",+ "react-native": "*"+ }+ },"node_modules/expo-status-bar": {"version": "2.0.1","resolved": "https://registry.npmjs.org/expo-status-bar/-/expo-status-bar-2.0.1.tgz",@@ -7707,6 +7794,12 @@"hermes-estree": "0.23.1"}},+ "node_modules/hex-to-array-buffer": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/hex-to-array-buffer/-/hex-to-array-buffer-1.1.0.tgz",+ "integrity": "sha512-vvl3IM8FfT1uOnHtEqyjkDK9Luqz6MQrH82qIvVnjyXxRhkeaEZyRRPiBgf2yym3nweRVEfayxt/1SoTXZYd4Q==",+ "license": "MIT"+ },"node_modules/hoist-non-react-statics": {"version": "3.3.2","resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz",@@ -8137,6 +8230,15 @@"node": ">=8"}},+ "node_modules/is-plain-obj": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-2.1.0.tgz",+ "integrity": "sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },"node_modules/is-plain-object": {"version": "2.0.4","resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz",@@ -9283,6 +9385,12 @@"js-yaml": "bin/js-yaml.js"}},+ "node_modules/jsbn": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-1.1.0.tgz",+ "integrity": "sha512-4bYVV3aAMtDTTu4+xsDYa6sy9GyJ69/amsu9sYF2zqjiEoZA5xJi3BrfX3uY+/IekIu7MwdObdbDWpoZdBv3/A==",+ "license": "MIT"+ },"node_modules/jsc-android": {"version": "250231.0.0","resolved": "https://registry.npmjs.org/jsc-android/-/jsc-android-250231.0.0.tgz",@@ -9962,6 +10070,18 @@"integrity": "sha512-zYiwtZUcYyXKo/np96AGZAckk+FWWsUdJ3cHGGmld7+AhvcWmQyGCYUh1hc4Q/pkOhb65dQR/pqCyK0cOaHz4Q==","license": "MIT"},+ "node_modules/merge-options": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/merge-options/-/merge-options-3.0.4.tgz",+ "integrity": "sha512-2Sug1+knBjkaMsMgf1ctR1Ujx+Ayku4EdJN4Z+C2+JzoeF7A3OZ9KM2GY0CpQS51NR61LTurMJrRKPhSs3ZRTQ==",+ "license": "MIT",+ "dependencies": {+ "is-plain-obj": "^2.1.0"+ },+ "engines": {+ "node": ">=10"+ }+ },"node_modules/merge-stream": {"version": "2.0.0","resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",@@ -11051,6 +11171,12 @@"integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==","license": "BlueOak-1.0.0"},+ "node_modules/pad-start": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/pad-start/-/pad-start-1.0.2.tgz",+ "integrity": "sha512-EBN8Ez1SVRcZT1XsIE4WkdnZ5coLoaChkIgAET6gIlaLhXqCz9upVk0DQWFtOYkrpTVvbEppRUnqhTiJrBdkfw==",+ "license": "MIT"+ },"node_modules/parse-json": {"version": "5.2.0","resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz",@@ -12386,6 +12512,21 @@"url": "https://opencollective.com/webpack"}},+ "node_modules/secure-remote-password": {+ "version": "0.3.0",+ "resolved": "git+ssh://[email protected]/LinusU/secure-remote-password.git#73e5f732b6ca0cdbdc19da1a0c5f48cdbad2cbf0",+ "integrity": "sha512-UT5eya0NtNvT+R/+L4DgReCLvCJttVTl4g4oy0sQ4aiRYspyHJf/X/ZA+zB2ZrZBXe7gyNpMnhQNT9MXFNPwvA==",+ "license": "MIT",+ "dependencies": {+ "array-buffer-to-hex": "^1.0.0",+ "crypto-digest-sync": "^1.0.0",+ "crypto-random-hex": "^1.0.0",+ "encode-utf8": "^1.0.1",+ "hex-to-array-buffer": "^1.1.0",+ "jsbn": "^1.1.0",+ "pad-start": "^1.0.2"+ }+ },"node_modules/selfsigned": {"version": "2.4.1","resolved": "https://registry.npmjs.org/selfsigned/-/selfsigned-2.4.1.tgz",diff --git a/mobile-app/package.json b/mobile-app/package.jsonindex 1d615c210..bb5c014c6 100644--- a/mobile-app/package.json+++ b/mobile-app/package.json@@ -16,16 +16,20 @@},"dependencies": {"@expo/vector-icons": "^14.0.2",+ "@react-native-async-storage/async-storage": "^2.1.2","@react-navigation/bottom-tabs": "^7.2.0","@react-navigation/native": "^7.0.14",+ "argon2-browser": "^1.18.0","expo": "~52.0.43","expo-blur": "~14.0.3","expo-constants": "~17.0.8",+ "expo-dev-client": "~5.0.19","expo-font": "~13.0.4","expo-haptics": "~14.0.1","expo-linking": "~7.0.5","expo-router": "~4.0.20","expo-splash-screen": "~0.29.22",+ "expo-sqlite": "~15.1.4","expo-status-bar": "~2.0.1","expo-symbols": "~0.2.2","expo-system-ui": "~4.0.9",@@ -39,13 +43,15 @@"react-native-screens": "~4.4.0","react-native-web": "~0.19.13","react-native-webview": "13.12.5",- "expo-dev-client": "~5.0.19"+ "secure-remote-password": "github:LinusU/secure-remote-password#73e5f732b6ca0cdbdc19da1a0c5f48cdbad2cbf0"},"devDependencies": {"@babel/core": "^7.25.2",+ "@types/argon2-browser": "^1.18.4","@types/jest": "^29.5.12","@types/react": "~18.3.12","@types/react-test-renderer": "^18.3.0",+ "@types/sql.js": "^1.4.9","jest": "^29.2.1","jest-expo": "~52.0.6","react-test-renderer": "18.3.1",diff --git a/mobile-app/utils/AppInfo.ts b/mobile-app/utils/AppInfo.tsnew file mode 100644index 000000000..f5d28bb93--- /dev/null+++ b/mobile-app/utils/AppInfo.ts@@ -0,0 +1,106 @@+/**+ * AppInfo class which contains information about the application version+ * and default server URLs.+ */+export class AppInfo {+ /**+ * The current extension version. This should be updated with each release of the extension.+ */+ public static readonly VERSION = '0.16.0';++ /**+ * The minimum supported AliasVault server (API) version. If the server version is below this, the+ * client will throw an error stating that the server should be updated.+ */+ public static readonly MIN_SERVER_VERSION = '0.12.0-dev';++ /**+ * The minimum supported AliasVault client vault version.+ */+ public static readonly MIN_VAULT_VERSION = '1.4.1';++ /**+ * The client name to use in the X-AliasVault-Client header.+ * Detects the specific browser being used.+ */+ public static readonly CLIENT_NAME = (() : 'ios' | 'android' => {+ // TODO: Add support for Android+ return 'ios';+ })();++ /**+ * The default AliasVault client URL.+ */+ public static readonly DEFAULT_CLIENT_URL = 'https://app.aliasvault.net';++ /**+ * The default AliasVault web API URL.+ */+ public static readonly DEFAULT_API_URL = 'https://app.aliasvault.net/api';++ /**+ * Prevent instantiation of this utility class+ */+ private constructor() {}++ /**+ * Checks if a given vault version is supported+ * @param vaultVersion The version to check+ * @returns boolean indicating if the version is supported+ */+ public static isVaultVersionSupported(vaultVersion: string): boolean {+ return this.versionGreaterThanOrEqualTo(vaultVersion, this.MIN_VAULT_VERSION);+ }++ /**+ * Checks if a given server version is supported+ * @param serverVersion The version to check+ * @returns boolean indicating if the version is supported+ */+ public static isServerVersionSupported(serverVersion: string): boolean {+ return this.versionGreaterThanOrEqualTo(serverVersion, this.MIN_SERVER_VERSION);+ }++ /**+ * Checks if version1 is greater than or equal to version2, following SemVer rules.+ * Pre-release versions (e.g., -alpha, -beta) are considered lower than release versions.+ * @param version1 First version string (e.g., "1.2.3" or "1.2.3-beta")+ * @param version2 Second version string (e.g., "1.2.0" or "1.2.0-alpha")+ * @returns true if version1 >= version2, false otherwise+ */+ public static versionGreaterThanOrEqualTo(version1: string, version2: string): boolean {+ // Split versions into core and pre-release parts+ const [core1, preRelease1] = version1.split('-');+ const [core2, preRelease2] = version2.split('-');++ const parts1 = core1.split('.').map(Number);+ const parts2 = core2.split('.').map(Number);++ // Compare core versions first+ for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {+ const part1 = parts1[i] ?? 0;+ const part2 = parts2[i] ?? 0;++ if (part1 > part2) {+ return true;+ }+ if (part1 < part2) {+ return false;+ }+ }++ // If core versions are equal, check pre-release versions.+ if (!preRelease1 && preRelease2) {+ return true;+ }+ if (preRelease1 && !preRelease2) {+ return false;+ }+ if (!preRelease1 && !preRelease2) {+ return true;+ }++ // Both have pre-release versions, compare them lexically+ return preRelease1 >= preRelease2;+ }+}diff --git a/mobile-app/utils/EncryptionUtility.tsx b/mobile-app/utils/EncryptionUtility.tsxnew file mode 100644index 000000000..421d18b5f--- /dev/null+++ b/mobile-app/utils/EncryptionUtility.tsx@@ -0,0 +1,315 @@+import argon2 from 'argon2-browser/dist/argon2-bundled.min.js';+import { Email } from './types/webapi/Email';+import { EncryptionKey } from './types/EncryptionKey';+import { MailboxEmail } from './types/webapi/MailboxEmail';+import { Buffer } from 'buffer';++/**+ * Utility class for encryption operations including:+ * - Argon2id key derivation+ * - AES-GCM symmetric encryption/decryption+ * - RSA-OAEP asymmetric encryption/decryption+ */+class EncryptionUtility {+ /**+ * Derives a key from a password using Argon2id+ */+ public static async deriveKeyFromPassword(+ password: string,+ salt: string,+ encryptionType: string = 'Argon2id',+ encryptionSettings: string = '{"Iterations":1,"MemorySize":1024,"DegreeOfParallelism":4}'+ ): Promise<Uint8Array> {+ const settings = JSON.parse(encryptionSettings);++ try {+ if (encryptionType !== 'Argon2Id') {+ throw new Error('Unsupported encryption type');+ }++ const hash = await argon2.hash({+ pass: password,+ salt: salt,+ time: settings.Iterations,+ mem: settings.MemorySize,+ parallelism: settings.DegreeOfParallelism,+ hashLen: 32,+ type: 2, // 0 = Argon2d, 1 = Argon2i, 2 = Argon2id+ });++ // Return bytes+ return hash.hash;+ } catch (error) {+ console.error('Argon2 hashing failed:', error);+ throw error;+ }+ }++ /**+ * Encrypts data using AES-GCM symmetric encryption+ */+ public static async symmetricEncrypt(plaintext: string, base64Key: string): Promise<string> {+ if (!plaintext) {+ return plaintext;+ }++ const key = await crypto.subtle.importKey(+ "raw",+ Uint8Array.from(atob(base64Key), c => c.charCodeAt(0)),+ {+ name: "AES-GCM",+ length: 256,+ },+ false,+ ["encrypt"]+ );++ const iv = crypto.getRandomValues(new Uint8Array(12));+ const encoder = new TextEncoder();+ const encoded = encoder.encode(plaintext);++ const ciphertext = await crypto.subtle.encrypt(+ { name: "AES-GCM", iv: iv },+ key,+ encoded+ );++ const combined = new Uint8Array(iv.length + ciphertext.byteLength);+ combined.set(iv, 0);+ combined.set(new Uint8Array(ciphertext), iv.length);++ return btoa(+ Array.from(combined)+ .map(byte => String.fromCharCode(byte))+ .join('')+ );+ }++ /**+ * Decrypts data using AES-GCM symmetric encryption+ */+ public static async symmetricDecrypt(base64Ciphertext: string, base64Key: string): Promise<string> {+ if (!base64Ciphertext) {+ return base64Ciphertext;+ }++ const key = await crypto.subtle.importKey(+ "raw",+ Uint8Array.from(atob(base64Key), c => c.charCodeAt(0)),+ {+ name: "AES-GCM",+ length: 256,+ },+ false,+ ["decrypt"]+ );++ const ivAndCiphertext = Uint8Array.from(atob(base64Ciphertext), c => c.charCodeAt(0));+ const iv = ivAndCiphertext.slice(0, 12);+ const ciphertext = ivAndCiphertext.slice(12);++ const decrypted = await crypto.subtle.decrypt(+ { name: "AES-GCM", iv: iv },+ key,+ ciphertext+ );++ const decoder = new TextDecoder();+ return decoder.decode(decrypted);+ }++ /**+ * Generates a new RSA key pair for asymmetric encryption+ */+ public static async generateRsaKeyPair(): Promise<{ publicKey: string, privateKey: string }> {+ const keyPair = await crypto.subtle.generateKey(+ {+ name: "RSA-OAEP",+ modulusLength: 2048,+ publicExponent: new Uint8Array([1, 0, 1]),+ hash: "SHA-256",+ },+ true,+ ["encrypt", "decrypt"]+ );++ const publicKey = await crypto.subtle.exportKey("jwk", keyPair.publicKey);+ const privateKey = await crypto.subtle.exportKey("jwk", keyPair.privateKey);++ return {+ publicKey: JSON.stringify(publicKey),+ privateKey: JSON.stringify(privateKey)+ };+ }++ /**+ * Encrypts data using RSA-OAEP asymmetric encryption with a public key+ */+ public static async encryptWithPublicKey(plaintext: string, publicKey: string): Promise<string> {+ const publicKeyObj = await crypto.subtle.importKey(+ "jwk",+ JSON.parse(publicKey),+ {+ name: "RSA-OAEP",+ hash: "SHA-256",+ },+ false,+ ["encrypt"]+ );++ const encodedPlaintext = new TextEncoder().encode(plaintext);+ const cipherBuffer = await crypto.subtle.encrypt(+ {+ name: "RSA-OAEP"+ },+ publicKeyObj,+ encodedPlaintext+ );++ return btoa(String.fromCharCode.apply(null, Array.from(new Uint8Array(cipherBuffer))));+ }++ /**+ * Decrypts data using RSA-OAEP asymmetric encryption with a private key+ */+ public static async decryptWithPrivateKey(ciphertext: string, privateKey: string): Promise<Uint8Array> {+ try {+ const privateKeyObj = await crypto.subtle.importKey(+ "jwk",+ JSON.parse(privateKey),+ {+ name: "RSA-OAEP",+ hash: "SHA-256",+ },+ true,+ ["decrypt"]+ );++ const cipherBuffer = Uint8Array.from(atob(ciphertext), c => c.charCodeAt(0));+ const plaintextBuffer = await crypto.subtle.decrypt(+ {+ name: "RSA-OAEP"+ },+ privateKeyObj,+ cipherBuffer+ );++ return new Uint8Array(plaintextBuffer);+ } catch (error) {+ console.error('RSA decryption failed:', error);+ throw new Error(`Failed to decrypt: ${error instanceof Error ? error.message : 'Unknown error'}`);+ }+ }++ /**+ * Decrypts an individual email based on the provided public/private key pairs.+ */+ public static async decryptEmail(+ email: Email,+ encryptionKeys: EncryptionKey[]+ ): Promise<Email> {+ try {+ const encryptionKey = encryptionKeys.find(key => key.PublicKey === email.encryptionKey);++ if (!encryptionKey) {+ throw new Error('Encryption key not found');+ }++ // Decrypt symmetric key with asymmetric private key+ const symmetricKey = await EncryptionUtility.decryptWithPrivateKey(+ email.encryptedSymmetricKey,+ encryptionKey.PrivateKey+ );+ const symmetricKeyBase64 = Buffer.from(symmetricKey).toString('base64');++ // Create a new object to avoid mutating the original+ const decryptedEmail = { ...email };++ // Decrypt all email fields+ decryptedEmail.subject = await EncryptionUtility.symmetricDecrypt(email.subject, symmetricKeyBase64);+ decryptedEmail.fromDisplay = await EncryptionUtility.symmetricDecrypt(email.fromDisplay, symmetricKeyBase64);+ decryptedEmail.fromDomain = await EncryptionUtility.symmetricDecrypt(email.fromDomain, symmetricKeyBase64);+ decryptedEmail.fromLocal = await EncryptionUtility.symmetricDecrypt(email.fromLocal, symmetricKeyBase64);++ if (email.messageHtml) {+ decryptedEmail.messageHtml = await EncryptionUtility.symmetricDecrypt(email.messageHtml, symmetricKeyBase64);+ }+ if (email.messagePlain) {+ decryptedEmail.messagePlain = await EncryptionUtility.symmetricDecrypt(email.messagePlain, symmetricKeyBase64);+ }++ return decryptedEmail;+ } catch (err) {+ throw new Error(err instanceof Error ? err.message : 'Failed to decrypt email');+ }+ }++ /**+ * Decrypts a list of emails based on the provided public/private key pairs.+ */+ public static async decryptEmailList(+ emails: MailboxEmail[],+ encryptionKeys: EncryptionKey[]+ ): Promise<MailboxEmail[]> {+ return Promise.all(emails.map(async email => {+ try {+ const encryptionKey = encryptionKeys.find(key => key.PublicKey === email.encryptionKey);++ if (!encryptionKey) {+ throw new Error('Encryption key not found');+ }++ // Decrypt symmetric key with asymmetric private key+ const symmetricKey = await EncryptionUtility.decryptWithPrivateKey(+ email.encryptedSymmetricKey,+ encryptionKey.PrivateKey+ );+ const symmetricKeyBase64 = Buffer.from(symmetricKey).toString('base64');++ // Create a new object to avoid mutating the original+ const decryptedEmail = { ...email };++ // Decrypt all email fields+ decryptedEmail.subject = await EncryptionUtility.symmetricDecrypt(email.subject, symmetricKeyBase64);+ decryptedEmail.fromDisplay = await EncryptionUtility.symmetricDecrypt(email.fromDisplay, symmetricKeyBase64);+ decryptedEmail.fromDomain = await EncryptionUtility.symmetricDecrypt(email.fromDomain, symmetricKeyBase64);+ decryptedEmail.fromLocal = await EncryptionUtility.symmetricDecrypt(email.fromLocal, symmetricKeyBase64);++ if (email.messagePreview) {+ decryptedEmail.messagePreview = await EncryptionUtility.symmetricDecrypt(email.messagePreview, symmetricKeyBase64);+ }++ return decryptedEmail;+ } catch (err) {+ throw new Error(err instanceof Error ? err.message : 'Failed to decrypt email');+ }+ }));+ }++ /**+ * Decrypts an attachment based on the provided public/private key pairs and returns the decrypted bytes as a base64 string.+ */+ public static async decryptAttachment(base64EncryptedAttachment: string, email: Email, encryptionKeys: EncryptionKey[]): Promise<string> {+ try {+ const encryptionKey = encryptionKeys.find(key => key.PublicKey === email.encryptionKey);++ if (!encryptionKey) {+ throw new Error('Encryption key not found');+ }++ // Decrypt symmetric key with asymmetric private key+ const symmetricKey = await EncryptionUtility.decryptWithPrivateKey(+ email.encryptedSymmetricKey,+ encryptionKey.PrivateKey+ );+ const symmetricKeyBase64 = Buffer.from(symmetricKey).toString('base64');++ const encryptedBytesString = await EncryptionUtility.symmetricDecrypt(base64EncryptedAttachment, symmetricKeyBase64);+ return encryptedBytesString;+ } catch (err) {+ throw new Error(err instanceof Error ? err.message : 'Failed to decrypt attachment');+ }+ }+}++export default EncryptionUtility;diff --git a/mobile-app/utils/SqliteClient.tsx b/mobile-app/utils/SqliteClient.tsxnew file mode 100644index 000000000..f98b82cae--- /dev/null+++ b/mobile-app/utils/SqliteClient.tsx@@ -0,0 +1,614 @@+import * as SQLite from 'expo-sqlite';+import { Credential } from './types/Credential';+import { EncryptionKey } from './types/EncryptionKey';+import { TotpCode } from './types/TotpCode';+import { PasswordSettings } from './types/PasswordSettings';++/**+ * Placeholder base64 image for credentials without a logo.+ */+const placeholderBase64 = 'UklGRjoEAABXRUJQVlA4IC4EAAAwFwCdASqAAIAAPpFCm0olo6Ihp5IraLASCWUA0eb/0s56RrLtCnYfLPiBshdXWMx8j1Ez65f169iA4xUDBTEV6ylMQeCIj2b7RngGi7gKZ9WjKdSoy9R8JcgOmjCMlDmLG20KhNo/i/Dc/Ah5GAvGfm8kfniV3AkR6fxN6eKwjDc6xrDgSfS48G5uGV6WzQt24YAVlLSK9BMwndzfHnePK1KFchFrL7O3ulB8cGNCeomu4o+l0SrS/JKblJ4WTzj0DAD++lCUEouSfgRKdiV2TiYCD+H+l3tANKSPQFPQuzi7rbvxqGeRmXB9kDwURaoSTTpYjA9REMUi9uA6aV7PWtBNXgUzMLowYMZeos6Xvyhb34GmufswMHA5ZyYpxzjTphOak4ZjNOiz8aScO5ygiTx99SqwX/uL+HSeVOSraHw8IymrMwm+jLxqN8BS8dGcItLlm/ioulqH2j4V8glDgSut+ExkxiD7m8TGPrrjCQNJbRDzpOFsyCyfBZupvp8QjGKW2KGziSZeIWes4aTB9tRmeEBhnUrmTDZQuXcc67Fg82KHrSfaeeOEq6jjuUjQ8wUnzM4Zz3dhrwSyslVz/WvnKqYkr4V/TTXPFF5EjF4rM1bHZ8bK63EfTnK41+n3n4gEFoYP4mXkNH0hntnYcdTqiE7Gn+q0BpRRxnkpBSZlA6Wa70jpW0FGqkw5e591A5/H+OV+60WAo+4Mi+NlsKrvLZ9EiVaPnoEFZlJQx1fA777AJ2MjXJ4KSsrWDWJi1lE8yPs8V6XvcC0chDTYt8456sKXAagCZyY+fzQriFMaddXyKQdG8qBqcdYjAsiIcjzaRFBBoOK9sU+sFY7N6B6+xtrlu3c37rQKkI3O2EoiJOris54EjJ5OFuumA0M6riNUuBf/MEPFBVx1JRcUEs+upEBsCnwYski7FT3TTqHrx7v5AjgFN97xhPTkmVpu6sxRnWBi1fxIRp8eWZeFM6mUcGgVk1WeVb1yhdV9hoMo2TsNEPE0tHo/wvuSJSzbZo7wibeXM9v/rRfKcx7X93rfiXVnyQ9f/5CaAQ4lxedPp/6uzLtOS4FyL0bCNeZ6L5w+AiuyWCTDFIYaUzhwfG+/YTQpWyeZCdQIKzhV+3GeXI2cxoP0ER/DlOKymf1gm+zRU3sqf1lBVQ0y+mK/Awl9bS3uaaQmI0FUyUwHUKP7PKuXnO+LcwDv4OfPT6hph8smc1EtMe5ib/apar/qZ9dyaEaElALJ1KKxnHziuvVl8atk1fINSQh7OtXDyqbPw9o/nGIpTnv5iFmwmWJLis2oyEgPkJqyx0vYI8rjkVEzKc8eQavAJBYSpjMwM193Swt+yJyjvaGYWPnqExxKiNarpB2WSO7soCAZXhS1uEYHryrK47BH6W1dRiruqT0xpLih3MXiwU3VDwAAAA==';++type SQLiteBindValue = string | number | null | Uint8Array;++interface SQLiteResult {+ rows: {+ length: number;+ item: (index: number) => any;+ };+ rowsAffected: number;+}++/**+ * Client for interacting with the SQLite database.+ */+class SqliteClient {+ private db: SQLite.SQLiteDatabase | null = null;++ /**+ * Initialize the SQLite database from a base64 string+ */+ public async initializeFromBase64(base64String: string): Promise<void> {+ try {+ // Open the database+ this.db = SQLite.openDatabaseSync('aliasvault.db');++ // Convert base64 to Uint8Array+ const binaryString = atob(base64String);+ const bytes = new Uint8Array(binaryString.length);+ for (let i = 0; i < binaryString.length; i++) {+ bytes[i] = binaryString.charCodeAt(i);+ }++ // Import the database+ await this.executeUpdate('PRAGMA journal_mode = WAL');+ await this.executeUpdate('PRAGMA synchronous = NORMAL');+ await this.executeUpdate('PRAGMA foreign_keys = ON');++ // TODO: Implement database import from bytes+ // This is a complex operation that would require writing the bytes to a file+ // and then importing that file into the SQLite database+ console.warn('Database import from base64 not yet implemented');+ } catch (error) {+ console.error('Error initializing SQLite database:', error);+ throw error;+ }+ }++ /**+ * Export the SQLite database to a base64 string+ * @returns Base64 encoded string of the database+ */+ public async exportToBase64(): Promise<string> {+ if (!this.db) {+ throw new Error('Database not initialized');+ }++ try {+ // TODO: Implement database export to base64+ // This would require reading the database file and converting it to base64+ console.warn('Database export to base64 not yet implemented');+ return '';+ } catch (error) {+ console.error('Error exporting SQLite database:', error);+ throw error;+ }+ }++ /**+ * Execute a SELECT query+ */+ public async executeQuery<T>(query: string, params: SQLiteBindValue[] = []): Promise<T[]> {+ if (!this.db) {+ throw new Error('Database not initialized');+ }++ try {+ const results = await this.db!.getAllAsync(+ query,+ ...params+ );+ return results as T[];+ } catch (error) {+ console.error('Error executing query:', error);+ throw error;+ }+ }++ /**+ * Execute an INSERT, UPDATE, or DELETE query+ */+ public async executeUpdate(query: string, params: SQLiteBindValue[] = []): Promise<number> {+ if (!this.db) {+ throw new Error('Database not initialized');+ }++ try {+ const result = await this.db!.runAsync(+ query,+ ...params+ );+ return result.changes;+ } catch (error) {+ console.error('Error executing update:', error);+ throw error;+ }+ }++ /**+ * Close the database connection and free resources.+ */+ public close(): void {+ if (this.db) {+ this.db.closeAsync();+ this.db = null;+ }+ }++ /**+ * Fetch a single credential with its associated service information.+ * @param credentialId - The ID of the credential to fetch.+ * @returns Credential object with service details or null if not found.+ */+ public async getCredentialById(credentialId: string): Promise<Credential | null> {+ const query = `+ SELECT DISTINCT+ c.Id,+ c.Username,+ c.Notes,+ c.ServiceId,+ s.Name as ServiceName,+ s.Url as ServiceUrl,+ s.Logo as Logo,+ a.FirstName,+ a.LastName,+ a.NickName,+ a.BirthDate,+ a.Gender,+ a.Email,+ p.Value as Password+ FROM Credentials c+ LEFT JOIN Services s ON c.ServiceId = s.Id+ LEFT JOIN Aliases a ON c.AliasId = a.Id+ LEFT JOIN Passwords p ON p.CredentialId = c.Id+ WHERE c.IsDeleted = 0+ AND c.Id = ?`;++ const results = await this.executeQuery(query, [credentialId]);++ if (results.length === 0) {+ return null;+ }++ // Convert the first row to a Credential object+ const row = results[0] as any;+ return {+ Id: row.Id,+ Username: row.Username,+ Password: row.Password,+ ServiceName: row.ServiceName,+ ServiceUrl: row.ServiceUrl,+ Logo: row.Logo,+ Notes: row.Notes,+ Alias: {+ FirstName: row.FirstName,+ LastName: row.LastName,+ NickName: row.NickName,+ BirthDate: row.BirthDate,+ Gender: row.Gender,+ Email: row.Email+ }+ };+ }++ /**+ * Fetch all credentials with their associated service information.+ * @returns Array of Credential objects with service details.+ */+ public async getAllCredentials(): Promise<Credential[]> {+ const query = `+ SELECT DISTINCT+ c.Id,+ c.Username,+ c.Notes,+ c.ServiceId,+ s.Name as ServiceName,+ s.Url as ServiceUrl,+ s.Logo as Logo,+ a.FirstName,+ a.LastName,+ a.NickName,+ a.BirthDate,+ a.Gender,+ a.Email,+ p.Value as Password+ FROM Credentials c+ LEFT JOIN Services s ON c.ServiceId = s.Id+ LEFT JOIN Aliases a ON c.AliasId = a.Id+ LEFT JOIN Passwords p ON p.CredentialId = c.Id+ WHERE c.IsDeleted = 0+ ORDER BY c.CreatedAt DESC`;++ const results = await this.executeQuery(query);++ return results.map((row: any) => ({+ Id: row.Id,+ Username: row.Username,+ Password: row.Password,+ ServiceName: row.ServiceName,+ ServiceUrl: row.ServiceUrl,+ Logo: row.Logo,+ Notes: row.Notes,+ Alias: {+ FirstName: row.FirstName,+ LastName: row.LastName,+ NickName: row.NickName,+ BirthDate: row.BirthDate,+ Gender: row.Gender,+ Email: row.Email+ }+ }));+ }++ /**+ * Fetch all unique email addresses from all credentials.+ * @returns Array of email addresses.+ */+ public async getAllEmailAddresses(): Promise<string[]> {+ const query = `+ SELECT DISTINCT+ a.Email+ FROM Credentials c+ LEFT JOIN Aliases a ON c.AliasId = a.Id+ WHERE a.Email IS NOT NULL AND a.Email != '' AND c.IsDeleted = 0+ `;++ const results = await this.executeQuery(query);++ return results.map((row: any) => row.Email);+ }++ /**+ * Fetch all encryption keys.+ */+ public async getAllEncryptionKeys(): Promise<EncryptionKey[]> {+ return this.executeQuery<EncryptionKey>(`SELECT+ x.PublicKey,+ x.PrivateKey,+ x.IsPrimary+ FROM EncryptionKeys x`);+ }++ /**+ * Get setting from database for a given key.+ * Returns default value (empty string by default) if setting is not found.+ */+ public async getSetting(key: string, defaultValue: string = ''): Promise<string> {+ const results = await this.executeQuery<{ Value: string }>(`SELECT+ s.Value+ FROM Settings s+ WHERE s.Key = ?`, [key]);++ return results.length > 0 ? results[0].Value : defaultValue;+ }++ /**+ * Get the default email domain from the database.+ */+ public async getDefaultEmailDomain(): Promise<string> {+ return this.getSetting('DefaultEmailDomain');+ }++ /**+ * Get the default identity language from the database.+ */+ public async getDefaultIdentityLanguage(): Promise<string> {+ return this.getSetting('DefaultIdentityLanguage', 'en');+ }++ /**+ * Get the password settings from the database.+ */+ public async getPasswordSettings(): Promise<PasswordSettings> {+ const settingsJson = await this.getSetting('PasswordGenerationSettings');++ // Default settings if none found or parsing fails+ const defaultSettings: PasswordSettings = {+ Length: 18,+ UseLowercase: true,+ UseUppercase: true,+ UseNumbers: true,+ UseSpecialChars: true,+ UseNonAmbiguousChars: false+ };++ try {+ if (settingsJson) {+ return { ...defaultSettings, ...JSON.parse(settingsJson) };+ }+ } catch (error) {+ console.warn('Failed to parse password settings:', error);+ }++ return defaultSettings;+ }++ /**+ * Create a new credential with associated entities+ * @param credential The credential object to insert+ * @returns The number of rows modified+ */+ public async createCredential(credential: Credential): Promise<number> {+ if (!this.db) {+ throw new Error('Database not initialized');+ }++ try {+ await this.executeUpdate('BEGIN TRANSACTION');++ // 1. Insert Service+ let logoData = null;+ try {+ if (credential.Logo) {+ // Handle object-like array conversion+ if (typeof credential.Logo === 'object' && !ArrayBuffer.isView(credential.Logo)) {+ const values = Object.values(credential.Logo);+ logoData = new Uint8Array(values);+ // Handle existing array types+ } else if (Array.isArray(credential.Logo) || credential.Logo instanceof ArrayBuffer || credential.Logo instanceof Uint8Array) {+ logoData = new Uint8Array(credential.Logo);+ }+ }+ } catch (error) {+ console.warn('Failed to convert logo to Uint8Array:', error);+ logoData = null;+ }++ const serviceQuery = `+ INSERT INTO Services (Id, Name, Url, Logo, CreatedAt, UpdatedAt)+ VALUES (?, ?, ?, ?, ?, ?)`;+ const serviceId = crypto.randomUUID().toUpperCase();+ const currentDateTime = new Date().toISOString()+ .replace('T', ' ')+ .replace('Z', '')+ .substring(0, 23);+ await this.executeUpdate(serviceQuery, [+ serviceId,+ credential.ServiceName,+ credential.ServiceUrl ?? null,+ logoData,+ currentDateTime,+ currentDateTime+ ]);++ // 2. Insert Alias+ const aliasQuery = `+ INSERT INTO Aliases (Id, FirstName, LastName, NickName, BirthDate, Gender, Email, CreatedAt, UpdatedAt)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`;+ const aliasId = crypto.randomUUID().toUpperCase();+ await this.executeUpdate(aliasQuery, [+ aliasId,+ credential.Alias.FirstName ?? null,+ credential.Alias.LastName ?? null,+ credential.Alias.NickName ?? null,+ credential.Alias.BirthDate ?? null,+ credential.Alias.Gender ?? null,+ credential.Alias.Email ?? null,+ currentDateTime,+ currentDateTime+ ]);++ // 3. Insert Credential+ const credentialQuery = `+ INSERT INTO Credentials (Id, Username, Notes, ServiceId, AliasId, CreatedAt, UpdatedAt)+ VALUES (?, ?, ?, ?, ?, ?, ?)`;+ const credentialId = crypto.randomUUID().toUpperCase();+ await this.executeUpdate(credentialQuery, [+ credentialId,+ credential.Username ?? null,+ credential.Notes ?? null,+ serviceId,+ aliasId,+ currentDateTime,+ currentDateTime+ ]);++ // 4. Insert Password+ if (credential.Password) {+ const passwordQuery = `+ INSERT INTO Passwords (Id, Value, CredentialId, CreatedAt, UpdatedAt)+ VALUES (?, ?, ?, ?, ?)`;+ const passwordId = crypto.randomUUID().toUpperCase();+ await this.executeUpdate(passwordQuery, [+ passwordId,+ credential.Password,+ credentialId,+ currentDateTime,+ currentDateTime+ ]);+ }++ await this.executeUpdate('COMMIT');+ return 1;++ } catch (error) {+ await this.executeUpdate('ROLLBACK');+ console.error('Error creating credential:', error);+ throw error;+ }+ }++ /**+ * Get the current database version from the migrations history.+ * Returns the semantic version (e.g., "1.4.1") from the latest migration.+ * Returns null if no migrations are found.+ */+ public async getDatabaseVersion(): Promise<string | null> {+ if (!this.db) {+ throw new Error('Database not initialized');+ }++ try {+ // Query the migrations history table for the latest migration+ const results = await this.executeQuery<{ MigrationId: string }>(`+ SELECT MigrationId+ FROM __EFMigrationsHistory+ ORDER BY MigrationId DESC+ LIMIT 1`);++ if (results.length === 0) {+ return null;+ }++ // Extract version using regex - matches patterns like "20240917191243_1.4.1-RenameAttachmentsPlural"+ const migrationId = results[0].MigrationId;+ const versionRegex = /_(\d+\.\d+\.\d+)-/;+ const versionMatch = versionRegex.exec(migrationId);++ if (versionMatch?.[1]) {+ return versionMatch[1];+ }++ return null;+ } catch (error) {+ console.error('Error getting database version:', error);+ throw error;+ }+ }++ /**+ * Get TOTP codes for a credential+ * @param credentialId - The ID of the credential to get TOTP codes for+ * @returns Array of TotpCode objects+ */+ public async getTotpCodesForCredential(credentialId: string): Promise<TotpCode[]> {+ if (!this.db) {+ throw new Error('Database not initialized');+ }++ try {+ /*+ * Check if TotpCodes table exists (for backward compatibility).+ * TODO: whenever the browser extension has a minimum client DB version of 1.5.0+,+ * we can remove this check as the TotpCodes table then is guaranteed to exist.+ */+ if (!await this.tableExists('TotpCodes')) {+ return [];+ }++ const query = `+ SELECT+ Id,+ Name,+ SecretKey,+ CredentialId+ FROM TotpCodes+ WHERE CredentialId = ? AND IsDeleted = 0`;++ return this.executeQuery<TotpCode>(query, [credentialId]);+ } catch (error) {+ console.error('Error getting TOTP codes:', error);+ // Return empty array instead of throwing to be robust+ return [];+ }+ }++ /**+ * Convert binary data to a base64 encoded image source.+ */+ public static imgSrcFromBytes(bytes: Uint8Array | number[] | undefined): string {+ // Handle base64 image data+ if (bytes) {+ try {+ const logoBytes = this.toUint8Array(bytes);+ const base64Logo = this.base64Encode(logoBytes);+ // Detect image type from first few bytes+ const mimeType = this.detectMimeType(logoBytes);+ return `data:${mimeType};base64,${base64Logo}`;+ } catch (error) {+ console.error('Error setting logo:', error);+ return `data:image/x-icon;base64,${placeholderBase64}`;+ }+ } else {+ return `data:image/x-icon;base64,${placeholderBase64}`;+ }+ }++ /**+ * Detect MIME type from file signature (magic numbers)+ */+ private static detectMimeType(bytes: Uint8Array): string {+ /**+ * Check if the file is an SVG file.+ */+ const isSvg = () : boolean => {+ const header = new TextDecoder().decode(bytes.slice(0, 5)).toLowerCase();+ return header.includes('<?xml') || header.includes('<svg');+ };++ /**+ * Check if the file is an ICO file.+ */+ const isIco = () : boolean => {+ return bytes[0] === 0x00 && bytes[1] === 0x00 && bytes[2] === 0x01 && bytes[3] === 0x00;+ };++ /**+ * Check if the file is an PNG file.+ */+ const isPng = () : boolean => {+ return bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47;+ };++ if (isSvg()) {+ return 'image/svg+xml';+ }+ if (isIco()) {+ return 'image/x-icon';+ }+ if (isPng()) {+ return 'image/png';+ }++ return 'image/x-icon';+ }++ /**+ * Convert various binary data formats to Uint8Array+ */+ private static toUint8Array(buffer: Uint8Array | number[] | {[key: number]: number}): Uint8Array {+ if (buffer instanceof Uint8Array) {+ return buffer;+ }++ if (Array.isArray(buffer)) {+ return new Uint8Array(buffer);+ }++ const length = Object.keys(buffer).length;+ const arr = new Uint8Array(length);+ for (let i = 0; i < length; i++) {+ arr[i] = buffer[i];+ }++ return arr;+ }++ /**+ * Base64 encode binary data.+ */+ private static base64Encode(buffer: Uint8Array | number[] | {[key: number]: number}): string | null {+ try {+ const arr = Array.from(this.toUint8Array(buffer));+ return btoa(arr.reduce((data, byte) => data + String.fromCharCode(byte), ''));+ } catch (error) {+ console.error('Error encoding to base64:', error);+ return null;+ }+ }++ /**+ * Check if a table exists in the database+ * @param tableName - The name of the table to check+ * @returns True if the table exists, false otherwise+ */+ private async tableExists(tableName: string): Promise<boolean> {+ if (!this.db) {+ throw new Error('Database not initialized');+ }++ try {+ const query = `+ SELECT name FROM sqlite_master+ WHERE type='table' AND name=?`;++ const results = await this.executeQuery(query, [tableName]);+ return results.length > 0;+ } catch (error) {+ console.error(`Error checking if table ${tableName} exists:`, error);+ return false;+ }+ }+}++export default SqliteClient;\ No newline at end of filediff --git a/mobile-app/utils/SrpUtility.tsx b/mobile-app/utils/SrpUtility.tsxnew file mode 100644index 000000000..7013ece0f--- /dev/null+++ b/mobile-app/utils/SrpUtility.tsx@@ -0,0 +1,153 @@+import srp from 'secure-remote-password/client';+import { WebApiService } from '@/utils/WebApiService';+import { LoginResponse } from '@/utils/types/webapi/Login';+import { ApiAuthError } from '@/utils/types/errors/ApiAuthError';+import { ValidateLoginResponse } from '@/utils/types/webapi/ValidateLogin';+import BadRequestResponse from '@/utils/types/webapi/BadRequestResponse';++export class SrpUtility {+ private webApiService: WebApiService;++ constructor(webApiService: WebApiService) {+ this.webApiService = webApiService;+ }++ /**+ * Initiates the login process with the server+ */+ public async initiateLogin(username: string): Promise<LoginResponse> {+ try {+ console.log('initiateLogin');+ const response = await this.webApiService.rawFetch('Auth/login', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({ username: username.toLowerCase().trim() }),+ });++ console.log('initiateLogin response', response);++ if (response.status === 400) {+ const badRequestResponse = await response.json() as BadRequestResponse;+ throw new ApiAuthError(badRequestResponse.title);+ }++ const loginResponse = await response.json() as LoginResponse;+ return loginResponse;+ } catch (error) {+ if (error instanceof ApiAuthError) {+ throw error;+ }+ throw new ApiAuthError('Could not reach AliasVault server. Please try again later or contact support if the problem persists.');+ }+ }++ /**+ * Validates the login with the server using SRP protocol+ */+ public async validateLogin(+ username: string,+ passwordHash: string,+ rememberMe: boolean,+ loginResponse: LoginResponse+ ): Promise<ValidateLoginResponse> {+ try {+ // Generate client ephemeral+ const clientEphemeral = srp.generateEphemeral();++ // Derive private key+ const privateKey = srp.derivePrivateKey(loginResponse.salt, username, passwordHash);++ // Derive session+ const sessionProof = srp.deriveSession(+ clientEphemeral.secret,+ loginResponse.serverEphemeral,+ loginResponse.salt,+ username,+ privateKey+ );++ const response = await this.webApiService.rawFetch('Login/Validate', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({+ username: username.toLowerCase().trim(),+ rememberMe,+ clientPublicEphemeral: clientEphemeral.public,+ clientSessionProof: sessionProof.proof,+ }),+ });++ if (response.status === 400) {+ const badRequestResponse = await response.json() as BadRequestResponse;+ throw new ApiAuthError(badRequestResponse.title);+ }++ const validateResponse = await response.json() as ValidateLoginResponse;+ return validateResponse;+ } catch (error) {+ if (error instanceof ApiAuthError) {+ throw error;+ }+ throw new ApiAuthError('Could not reach AliasVault server. Please try again later or contact support if the problem persists.');+ }+ }++ /**+ * Validates 2FA code with the server+ */+ public async validateLogin2Fa(+ username: string,+ passwordHash: string,+ rememberMe: boolean,+ loginResponse: LoginResponse,+ twoFactorCode: number+ ): Promise<ValidateLoginResponse> {+ try {+ // Generate client ephemeral+ const clientEphemeral = srp.generateEphemeral();++ // Derive private key+ const privateKey = srp.derivePrivateKey(loginResponse.salt, username, passwordHash);++ // Derive session+ const sessionProof = srp.deriveSession(+ clientEphemeral.secret,+ loginResponse.serverEphemeral,+ loginResponse.salt,+ username,+ privateKey+ );++ const response = await this.webApiService.rawFetch('Login/Validate2Fa', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({+ username: username.toLowerCase().trim(),+ rememberMe,+ clientPublicEphemeral: clientEphemeral.public,+ clientSessionProof: sessionProof.proof,+ twoFactorCode,+ }),+ });++ if (response.status === 400) {+ const badRequestResponse = await response.json() as BadRequestResponse;+ throw new ApiAuthError(badRequestResponse.title);+ }++ const validateResponse = await response.json() as ValidateLoginResponse;+ return validateResponse;+ } catch (error) {+ if (error instanceof ApiAuthError) {+ throw error;+ }+ throw new ApiAuthError('Could not reach AliasVault server. Please try again later or contact support if the problem persists.');+ }+ }+}\ No newline at end of filediff --git a/mobile-app/utils/WebApiService.ts b/mobile-app/utils/WebApiService.tsnew file mode 100644index 000000000..b648eff0b--- /dev/null+++ b/mobile-app/utils/WebApiService.ts@@ -0,0 +1,358 @@+import { AppInfo } from "./AppInfo";+import { StatusResponse } from "./types/webapi/StatusResponse";+import { VaultResponse } from "./types/webapi/VaultResponse";+import AsyncStorage from '@react-native-async-storage/async-storage';++type RequestInit = globalThis.RequestInit;++/**+ * Type for the token response from the API.+ */+type TokenResponse = {+ token: string;+ refreshToken: string;+}++/**+ * Service class for interacting with the web API.+ */+export class WebApiService {+ /**+ * Constructor for the WebApiService class.+ *+ * @param {Function} authContextLogout - Function to handle logout.+ */+ public constructor(private readonly authContextLogout: (statusError: string | null) => void) { }++ /**+ * Get the base URL for the API from settings.+ */+ private async getBaseUrl(): Promise<string> {+ const result = await AsyncStorage.getItem('apiUrl') as string;+ if (result && result.length > 0) {+ return result.replace(/\/$/, '') + '/v1/';+ }++ return AppInfo.DEFAULT_API_URL.replace(/\/$/, '') + '/v1/';+ }++ /**+ * Fetch data from the API with authentication headers and access token refresh retry.+ */+ public async authFetch<T>(+ endpoint: string,+ options: RequestInit = {},+ parseJson: boolean = true+ ): Promise<T> {+ const headers = new Headers(options.headers ?? {});++ // Add authorization header if we have an access token+ const accessToken = await this.getAccessToken();+ if (accessToken) {+ headers.set('Authorization', `Bearer ${accessToken}`);+ }++ const requestOptions: RequestInit = {+ ...options,+ headers,+ };++ try {+ const response = await this.rawFetch(endpoint, requestOptions);++ if (response.status === 401) {+ const newToken = await this.refreshAccessToken();+ if (newToken) {+ headers.set('Authorization', `Bearer ${newToken}`);+ const retryResponse = await this.rawFetch(endpoint, {+ ...requestOptions,+ headers,+ });++ if (!retryResponse.ok) {+ throw new Error('Request failed after token refresh');+ }++ return parseJson ? retryResponse.json() : retryResponse as unknown as T;+ } else {+ this.authContextLogout(null);+ throw new Error('Session expired');+ }+ }++ if (!response.ok) {+ throw new Error(`HTTP error! status: ${response.status}`);+ }++ return parseJson ? response.json() : response as unknown as T;+ } catch (error) {+ console.error('API request failed:', error);+ throw error;+ }+ }++ /**+ * Fetch data from the API without authentication headers and without access token refresh retry.+ */+ public async rawFetch(+ endpoint: string,+ options: RequestInit = {}+ ): Promise<Response> {+ const baseUrl = await this.getBaseUrl();+ const url = baseUrl + endpoint;+ const headers = new Headers(options.headers ?? {});++ // Add client version header+ headers.set('X-AliasVault-Client', `${AppInfo.CLIENT_NAME}-${AppInfo.VERSION}`);++ const requestOptions: RequestInit = {+ ...options,+ headers,+ };++ try {+ const response = await fetch(url, requestOptions);+ return response;+ } catch (error) {+ console.error('API request failed:', error);+ throw error;+ }+ }++ /**+ * Refresh the access token.+ */+ private async refreshAccessToken(): Promise<string | null> {+ const refreshToken = await this.getRefreshToken();+ if (!refreshToken) {+ return null;+ }++ try {+ const response = await this.rawFetch('Auth/refresh', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-Ignore-Failure': 'true',+ },+ body: JSON.stringify({+ token: await this.getAccessToken(),+ refreshToken: refreshToken,+ }),+ });++ if (!response.ok) {+ throw new Error('Failed to refresh token');+ }++ const tokenResponse: TokenResponse = await response.json();+ this.updateTokens(tokenResponse.token, tokenResponse.refreshToken);+ return tokenResponse.token;+ } catch {+ this.authContextLogout('Your session has expired. Please login again.');+ return null;+ }+ }++ /**+ * Issue GET request to the API.+ */+ public async get<T>(endpoint: string): Promise<T> {+ return this.authFetch<T>(endpoint, { method: 'GET' });+ }++ /**+ * Issue GET request to the API expecting a file download and return it as a Base64 string.+ */+ public async downloadBlobAndConvertToBase64(endpoint: string): Promise<string> {+ try {+ const response = await this.authFetch<Response>(endpoint, {+ method: 'GET',+ headers: {+ 'Accept': 'application/octet-stream',+ }+ }, false);++ // Ensure we get the response as a blob+ const blob = await response.blob();+ return await this.blobToBase64(blob);+ } catch (error) {+ console.error('Error fetching and converting to Base64:', error);+ throw error;+ }+ }++ /**+ * Issue POST request to the API.+ */+ public async post<TRequest, TResponse>(+ endpoint: string,+ data: TRequest,+ parseJson: boolean = true+ ): Promise<TResponse> {+ return this.authFetch<TResponse>(endpoint, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(data),+ }, parseJson);+ }++ /**+ * Issue PUT request to the API.+ */+ public async put<TRequest, TResponse>(endpoint: string, data: TRequest): Promise<TResponse> {+ return this.authFetch<TResponse>(endpoint, {+ method: 'PUT',+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(data),+ });+ }++ /**+ * Issue DELETE request to the API.+ */+ public async delete<T>(endpoint: string): Promise<T> {+ return this.authFetch<T>(endpoint, { method: 'DELETE' }, false);+ }++ /**+ * Logout and revoke tokens via WebApi and remove local storage tokens via AuthContext.+ */+ public async logout(statusError: string | null = null): Promise<void> {+ // Logout and revoke tokens via WebApi.+ try {+ const refreshToken = await this.getRefreshToken();+ if (!refreshToken) {+ return;+ }++ await this.post('Auth/revoke', {+ token: await this.getAccessToken(),+ refreshToken: refreshToken,+ }, false);+ } catch (err) {+ console.error('WebApi logout error:', err);+ }++ // Logout and remove tokens from local storage via AuthContext.+ this.authContextLogout(statusError);+ }++ /**+ * Calls the status endpoint to check if the auth tokens are still valid, app is supported and the vault is up to date.+ */+ public async getStatus(): Promise<StatusResponse> {+ try {+ return await this.get<StatusResponse>('Auth/status');+ } catch {+ /**+ * If the status endpoint is not available, return a default status response which will trigger+ * a logout and error message.+ */+ return {+ clientVersionSupported: true,+ serverVersion: '0.0.0',+ vaultRevision: 0+ };+ }+ }++ /**+ * Validates the status response and returns an error message if validation fails.+ */+ public validateStatusResponse(statusResponse: StatusResponse): string | null {+ if (statusResponse.serverVersion === '0.0.0') {+ return 'The AliasVault server is not available. Please try again later or contact support if the problem persists.';+ }++ if (!statusResponse.clientVersionSupported) {+ return 'This version of the AliasVault browser extension is outdated. Please update your browser extension to the latest version.';+ }++ if (!AppInfo.isServerVersionSupported(statusResponse.serverVersion)) {+ return 'The AliasVault server needs to be updated to a newer version in order to use this browser extension. Please contact support if you need help.';+ }++ return null;+ }++ /**+ * Validates the vault response and returns an error message if validation fails+ */+ public validateVaultResponse(vaultResponseJson: VaultResponse): string | null {+ /**+ * Status 0 = OK, vault is ready.+ * Status 1 = Merge required, which only the web client supports.+ */+ if (vaultResponseJson.status !== 0) {+ return 'Your vault needs to be updated. Please login on the AliasVault website and follow the steps.';+ }++ if (!vaultResponseJson.vault?.blob) {+ return 'Your account does not have a vault yet. Please complete the tutorial in the AliasVault web client before using the browser extension.';+ }++ if (!AppInfo.isVaultVersionSupported(vaultResponseJson.vault.version)) {+ return 'Your vault is outdated. Please login via the web client to update your vault.';+ }++ return null;+ }++ /**+ * Get the current access token from storage.+ */+ private async getAccessToken(): Promise<string | null> {+ const token = await AsyncStorage.getItem('accessToken') as string;+ return token ?? null;+ }++ /**+ * Get the current refresh token from storage.+ */+ private async getRefreshToken(): Promise<string | null> {+ const token = await AsyncStorage.getItem('refreshToken') as string;+ return token ?? null;+ }++ /**+ * Update both access and refresh tokens in storage.+ */+ private async updateTokens(accessToken: string, refreshToken: string): Promise<void> {+ await AsyncStorage.setItem('accessToken', accessToken);+ await AsyncStorage.setItem('refreshToken', refreshToken);+ }++ /**+ * Convert a Blob to a Base64 string.+ */+ private async blobToBase64(blob: Blob): Promise<string> {+ return new Promise((resolve, reject) => {+ const reader = new FileReader();++ /**+ * When the reader has finished loading, convert the result to a Base64 string.+ */+ reader.onloadend = (): void => {+ const result = reader.result;+ if (typeof result === 'string') {+ resolve(result.split(',')[1]); // Remove the data URL prefix+ } else {+ reject(new Error('Failed to convert Blob to Base64.'));+ }+ };++ /**+ * If the reader encounters an error, reject the promise with a proper Error object.+ */+ reader.onerror = (): void => {+ reject(new Error('Failed to read blob as Data URL'));+ };+ reader.readAsDataURL(blob);+ });+ }+}diff --git a/mobile-app/utils/generators/Identity/UsernameEmailGenerator.ts b/mobile-app/utils/generators/Identity/UsernameEmailGenerator.tsnew file mode 100644index 000000000..3993209ec--- /dev/null+++ b/mobile-app/utils/generators/Identity/UsernameEmailGenerator.ts@@ -0,0 +1,130 @@+import { Identity } from "./types/Identity";++/**+ * Generate a username or email prefix.+ */+export class UsernameEmailGenerator {+ private static readonly MIN_LENGTH = 6;+ private static readonly MAX_LENGTH = 20;+ private readonly symbols: string[] = ['.', '-'];++ /**+ * Generate a username based on an identity.+ */+ public generateUsername(identity: Identity): string {+ // Generate username based on email prefix but strip all non-alphanumeric characters+ let username = this.generateEmailPrefix(identity);+ username = username.replace(/[^a-zA-Z0-9]/g, '');++ // Adjust length+ if (username.length < UsernameEmailGenerator.MIN_LENGTH) {+ username += this.generateRandomString(UsernameEmailGenerator.MIN_LENGTH - username.length);+ } else if (username.length > UsernameEmailGenerator.MAX_LENGTH) {+ username = username.substring(0, UsernameEmailGenerator.MAX_LENGTH);+ }++ return username;+ }++ /**+ * Generate an email prefix based on an identity.+ */+ public generateEmailPrefix(identity: Identity): string {+ const parts: string[] = [];++ switch (this.getSecureRandom(4)) {+ case 0:+ // First initial + last name+ parts.push(identity.firstName.substring(0, 1).toLowerCase() + identity.lastName.toLowerCase());+ break;+ case 1:+ // Full name+ parts.push((identity.firstName + identity.lastName).toLowerCase());+ break;+ case 2:+ // First name + last initial+ parts.push(identity.firstName.toLowerCase() + identity.lastName.substring(0, 1).toLowerCase());+ break;+ case 3:+ // First 3 chars of first name + last name+ parts.push(identity.firstName.substring(0, Math.min(3, identity.firstName.length)).toLowerCase() + identity.lastName.toLowerCase());+ break;+ }++ // Add birth year variations+ if (this.getSecureRandom(3) !== 0) {+ switch (this.getSecureRandom(2)) {+ case 0:+ parts.push(identity.birthDate.getFullYear().toString().substring(2));+ break;+ case 1:+ parts.push(identity.birthDate.getFullYear().toString());+ break;+ }+ } else if (this.getSecureRandom(2) === 0) {+ // Add random numbers for more uniqueness+ parts.push((this.getSecureRandom(990) + 10).toString());+ }++ // Join parts with random symbols, possibly multiple+ let emailPrefix = parts.join(this.getRandomSymbol());++ // Add extra random symbol at random position+ if (this.getSecureRandom(2) === 0) {+ const position = this.getSecureRandom(emailPrefix.length);+ emailPrefix = emailPrefix.slice(0, position) + this.getRandomSymbol() + emailPrefix.slice(position);+ }++ emailPrefix = this.sanitizeEmailPrefix(emailPrefix);++ // Adjust length+ if (emailPrefix.length < UsernameEmailGenerator.MIN_LENGTH) {+ emailPrefix += this.generateRandomString(UsernameEmailGenerator.MIN_LENGTH - emailPrefix.length);+ } else if (emailPrefix.length > UsernameEmailGenerator.MAX_LENGTH) {+ emailPrefix = emailPrefix.substring(0, UsernameEmailGenerator.MAX_LENGTH);+ }++ return emailPrefix;+ }++ /**+ * Sanitize an email prefix.+ */+ private sanitizeEmailPrefix(input: string): string {+ // Remove any character that's not a letter, number, dot, underscore, or hyphen including special characters+ let sanitized = input.replace(/[^a-zA-Z0-9._-]/g, '');++ // Remove consecutive dots, underscores, or hyphens+ sanitized = sanitized.replace(/[-_.]{2,}/g, (match) => match[0]);++ // Remove leading and trailing dots, underscores, or hyphens+ sanitized = sanitized.replace(/^[-._]+/, ''); // Remove from start+ sanitized = sanitized.replace(/[-._]*$/, ''); // Remove from end++ return sanitized;+ }++ /**+ * Get a random symbol.+ */+ private getRandomSymbol(): string {+ return this.getSecureRandom(3) === 0 ? this.symbols[this.getSecureRandom(this.symbols.length)] : '';+ }++ /**+ * Generate a random string.+ */+ private generateRandomString(length: number): string {+ const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';+ return Array.from({ length }, () => chars.charAt(this.getSecureRandom(chars.length))).join('');+ }++ /**+ * Generate a secure random integer between 0 (inclusive) and max (exclusive)+ */+ private getSecureRandom(max: number): number {+ const array = new Uint32Array(1);+ crypto.getRandomValues(array);+ return array[0] % max;+ }+}diff --git a/mobile-app/utils/generators/Identity/__tests__/IdentityGenerator.test.ts b/mobile-app/utils/generators/Identity/__tests__/IdentityGenerator.test.tsnew file mode 100644index 000000000..416926251--- /dev/null+++ b/mobile-app/utils/generators/Identity/__tests__/IdentityGenerator.test.ts@@ -0,0 +1,54 @@+import { IdentityGeneratorEn } from '../implementations/IdentityGeneratorEn';+import { IdentityGeneratorNl } from '../implementations/IdentityGeneratorNl';+import { describe, it, expect } from 'vitest';+import { IIdentityGenerator } from '../interfaces/IIdentityGenerator';+import { Gender } from '../types/Gender';++/**+ * Test the identity generator.+ */+const testIdentityGenerator = (+ language: string,+ generator: IIdentityGenerator+) : void => {+ describe(`IdentityGenerator${language}`, () => {+ describe('generateRandomIdentity', () => {+ it('should generate a random gender identity when no gender is specified', async () => {+ const identity = await generator.generateRandomIdentity();++ expect(identity).toBeDefined();+ expect(identity.firstName).toBeTruthy();+ expect(identity.lastName).toBeTruthy();+ expect([Gender.Male, Gender.Female]).toContain(identity.gender);+ });++ it('should generate unique identities on subsequent calls', async () => {+ const identity1 = await generator.generateRandomIdentity();+ const identity2 = await generator.generateRandomIdentity();++ expect(identity1).not.toEqual(identity2);+ });++ it('should generate an identity with all non-empty fields', async () => {+ const identity = await generator.generateRandomIdentity();++ Object.entries(identity).forEach(([, value]) => {+ expect(value).toBeTruthy();+ expect(value).not.toBe('');+ expect(value).not.toBeNull();+ expect(value).not.toBeUndefined();+ });++ // Check if the first and last names are longer than 1 character.+ expect(identity.firstName.length).toBeGreaterThan(1);+ expect(identity.lastName.length).toBeGreaterThan(1);+ });+ });+ });+};++// Run tests for each language implementation+describe('Identity Generators', () => {+ testIdentityGenerator('En', new IdentityGeneratorEn());+ testIdentityGenerator('Nl', new IdentityGeneratorNl());+});\ No newline at end of filediff --git a/mobile-app/utils/generators/Identity/implementations/IdentityGeneratorEn.ts b/mobile-app/utils/generators/Identity/implementations/IdentityGeneratorEn.tsnew file mode 100644index 000000000..b43e3a623--- /dev/null+++ b/mobile-app/utils/generators/Identity/implementations/IdentityGeneratorEn.ts@@ -0,0 +1,39 @@+import { BaseIdentityGenerator } from "./base/BaseIdentityGenerator";++/**+ * Identity generator for English language using English word dictionaries.+ */+export class IdentityGeneratorEn extends BaseIdentityGenerator {+ /**+ * Get the male first names.+ */+ protected getFirstNamesMaleJson(): string[] {+ /*+ * This is a placeholder for the dictionary-loader to replace with the actual data.+ * See vite-plugins/dictionary-loader.ts for more information.+ */+ return '__FIRSTNAMES_MALE_EN__';+ }++ /**+ * Get the female first names.+ */+ protected getFirstNamesFemaleJson(): string[] {+ /*+ * This is a placeholder for the dictionary-loader to replace with the actual data.+ * See vite-plugins/dictionary-loader.ts for more information.+ */+ return '__FIRSTNAMES_FEMALE_EN__';+ }++ /**+ * Get the last names.+ */+ protected getLastNamesJson(): string[] {+ /*+ * This is a placeholder for the dictionary-loader to replace with the actual data.+ * See vite-plugins/dictionary-loader.ts for more information.+ */+ return '__LASTNAMES_EN__';+ }+}diff --git a/mobile-app/utils/generators/Identity/implementations/IdentityGeneratorNl.ts b/mobile-app/utils/generators/Identity/implementations/IdentityGeneratorNl.tsnew file mode 100644index 000000000..53ea8b958--- /dev/null+++ b/mobile-app/utils/generators/Identity/implementations/IdentityGeneratorNl.ts@@ -0,0 +1,39 @@+import { BaseIdentityGenerator } from "./base/BaseIdentityGenerator";++/**+ * Identity generator for Dutch language using Dutch word dictionaries.+ */+export class IdentityGeneratorNl extends BaseIdentityGenerator {+ /**+ * Get the male first names.+ */+ protected getFirstNamesMaleJson(): string[] {+ /*+ * This is a placeholder for the dictionary-loader to replace with the actual data.+ * See vite-plugins/dictionary-loader.ts for more information.+ */+ return '__FIRSTNAMES_MALE_NL__';+ }++ /**+ * Get the female first names.+ */+ protected getFirstNamesFemaleJson(): string[] {+ /*+ * This is a placeholder for the dictionary-loader to replace with the actual data.+ * See vite-plugins/dictionary-loader.ts for more information.+ */+ return '__FIRSTNAMES_FEMALE_NL__';+ }++ /**+ * Get the last names.+ */+ protected getLastNamesJson(): string[] {+ /*+ * This is a placeholder for the dictionary-loader to replace with the actual data.+ * See vite-plugins/dictionary-loader.ts for more information.+ */+ return '__LASTNAMES_NL__';+ }+}diff --git a/mobile-app/utils/generators/Identity/implementations/base/BaseIdentityGenerator.ts b/mobile-app/utils/generators/Identity/implementations/base/BaseIdentityGenerator.tsnew file mode 100644index 000000000..9453a4ac4--- /dev/null+++ b/mobile-app/utils/generators/Identity/implementations/base/BaseIdentityGenerator.ts@@ -0,0 +1,75 @@+import { UsernameEmailGenerator } from '../../UsernameEmailGenerator';+import { Gender } from '../../types/Gender';+import { IIdentityGenerator } from '../../interfaces/IIdentityGenerator';+import { Identity } from '../../types/Identity';++/**+ * Base identity generator.+ */+export abstract class BaseIdentityGenerator implements IIdentityGenerator {+ protected firstNamesMale: string[] = [];+ protected firstNamesFemale: string[] = [];+ protected lastNames: string[] = [];+ private readonly random = Math.random;++ /**+ * Constructor.+ */+ public constructor() {+ // Each implementing class should provide these as static JSON strings+ this.firstNamesMale = this.getFirstNamesMaleJson();+ this.firstNamesFemale = this.getFirstNamesFemaleJson();+ this.lastNames = this.getLastNamesJson();+ }++ protected abstract getFirstNamesMaleJson(): string[];+ protected abstract getFirstNamesFemaleJson(): string[];+ protected abstract getLastNamesJson(): string[];++ /**+ * Generate a random date of birth.+ */+ protected generateRandomDateOfBirth(): Date {+ const today = new Date();+ const minAge = 21;+ const maxAge = 65;++ const minDate = new Date(today.getFullYear() - maxAge, today.getMonth(), today.getDate());+ const maxDate = new Date(today.getFullYear() - minAge, today.getMonth(), today.getDate());++ const timestamp = minDate.getTime() + (this.random() * (maxDate.getTime() - minDate.getTime()));+ return new Date(timestamp);+ }++ /**+ * Generate a random identity.+ */+ public async generateRandomIdentity(): Promise<Identity> {+ const identity: Identity = {+ firstName: '',+ lastName: '',+ gender: Gender.Male,+ birthDate: new Date(),+ emailPrefix: '',+ nickName: ''+ };++ // Determine gender+ if (this.random() < 0.5) {+ identity.firstName = this.firstNamesMale[Math.floor(this.random() * this.firstNamesMale.length)];+ identity.gender = Gender.Male;+ } else {+ identity.firstName = this.firstNamesFemale[Math.floor(this.random() * this.firstNamesFemale.length)];+ identity.gender = Gender.Female;+ }++ identity.lastName = this.lastNames[Math.floor(this.random() * this.lastNames.length)];+ identity.birthDate = this.generateRandomDateOfBirth();++ const generator = new UsernameEmailGenerator();+ identity.emailPrefix = generator.generateEmailPrefix(identity);+ identity.nickName = generator.generateUsername(identity);++ return identity;+ }+}\ No newline at end of filediff --git a/mobile-app/utils/generators/Identity/interfaces/IIdentityGenerator.ts b/mobile-app/utils/generators/Identity/interfaces/IIdentityGenerator.tsnew file mode 100644index 000000000..437622b51--- /dev/null+++ b/mobile-app/utils/generators/Identity/interfaces/IIdentityGenerator.ts@@ -0,0 +1,5 @@+import { Identity } from "../types/Identity";++export interface IIdentityGenerator {+ generateRandomIdentity(): Promise<Identity>;+}diff --git a/mobile-app/utils/generators/Identity/types/Gender.ts b/mobile-app/utils/generators/Identity/types/Gender.tsnew file mode 100644index 000000000..631f6e3c8--- /dev/null+++ b/mobile-app/utils/generators/Identity/types/Gender.ts@@ -0,0 +1,5 @@+export enum Gender {+ Male = 'Male',+ Female = 'Female',+ Other = 'Other'+ }diff --git a/mobile-app/utils/generators/Identity/types/Identity.ts b/mobile-app/utils/generators/Identity/types/Identity.tsnew file mode 100644index 000000000..738b8ee83--- /dev/null+++ b/mobile-app/utils/generators/Identity/types/Identity.ts@@ -0,0 +1,13 @@+import { Gender } from './Gender';++/**+ * Identity.+ */+export type Identity = {+ firstName: string;+ lastName: string;+ gender: Gender;+ birthDate: Date;+ emailPrefix: string;+ nickName: string;+ }\ No newline at end of filediff --git a/mobile-app/utils/generators/Password/PasswordGenerator.ts b/mobile-app/utils/generators/Password/PasswordGenerator.tsnew file mode 100644index 000000000..145e80839--- /dev/null+++ b/mobile-app/utils/generators/Password/PasswordGenerator.ts@@ -0,0 +1,259 @@+import { PasswordSettings } from '../../types/PasswordSettings';++/**+ * Generate a random password.+ */+export class PasswordGenerator {+ private readonly lowercaseChars = 'abcdefghijklmnopqrstuvwxyz';+ private readonly uppercaseChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';+ private readonly numberChars = '0123456789';+ private readonly specialChars = '!@#$%^&*()_+-=[]{}|;:,.<>?';+ private readonly ambiguousChars = 'Il1O0';++ private length: number = 18;+ private useLowercase: boolean = true;+ private useUppercase: boolean = true;+ private useNumbers: boolean = true;+ private useSpecial: boolean = true;+ private useNonAmbiguous: boolean = false;++ /**+ * Create a new instance of PasswordGenerator.+ * @param settings Optional password settings to initialize with.+ */+ public constructor(settings?: PasswordSettings) {+ if (settings) {+ this.applySettings(settings);+ }+ }++ /**+ * Apply password settings to this generator.+ */+ public applySettings(settings: PasswordSettings): this {+ this.length = settings.Length;+ this.useLowercase = settings.UseLowercase;+ this.useUppercase = settings.UseUppercase;+ this.useNumbers = settings.UseNumbers;+ this.useSpecial = settings.UseSpecialChars;+ this.useNonAmbiguous = settings.UseNonAmbiguousChars;+ return this;+ }++ /**+ * Set the length of the password.+ */+ public setLength(length: number): this {+ this.length = length;+ return this;+ }++ /**+ * Set if lowercase letters should be used.+ */+ public useLowercaseLetters(use: boolean): this {+ this.useLowercase = use;+ return this;+ }++ /**+ * Set if uppercase letters should be used.+ */+ public useUppercaseLetters(use: boolean): this {+ this.useUppercase = use;+ return this;+ }++ /**+ * Set if numeric characters should be used.+ */+ public useNumericCharacters(use: boolean): this {+ this.useNumbers = use;+ return this;+ }++ /**+ * Set if special characters should be used.+ */+ public useSpecialCharacters(use: boolean): this {+ this.useSpecial = use;+ return this;+ }++ /**+ * Set if only non-ambiguous characters should be used.+ */+ public useNonAmbiguousCharacters(use: boolean): this {+ this.useNonAmbiguous = use;+ return this;+ }++ /**+ * Get a random index from the crypto module.+ */+ private getUnbiasedRandomIndex(max: number): number {+ // Calculate the largest multiple of max that fits within Uint32.+ const limit = Math.floor((2 ** 32) / max) * max;++ while (true) {+ const array = new Uint32Array(1);+ crypto.getRandomValues(array);+ const value = array[0];++ // Reject values that would introduce bias.+ if (value < limit) {+ return value % max;+ }+ }+ }++ /**+ * Generate a random password.+ */+ public generateRandomPassword(): string {+ // Build the character set based on settings+ const chars = this.buildCharacterSet();++ // Generate initial password.+ let password = this.generateInitialPassword(chars);++ // Ensure a character from each set is present as some websites require this.+ password = this.ensureRequirements(password);++ return password;+ }++ /**+ * Build character set based on selected options.+ */+ private buildCharacterSet(): string {+ let chars = '';++ if (this.useLowercase) {+ chars += this.lowercaseChars;+ }++ if (this.useUppercase) {+ chars += this.uppercaseChars;+ }++ if (this.useNumbers) {+ chars += this.numberChars;+ }++ if (this.useSpecial) {+ chars += this.specialChars;+ }++ // Ensure at least one character set is selected, otherwise default to lowercase.+ if (chars.length === 0) {+ chars = this.lowercaseChars;+ }++ // Remove ambiguous characters if needed.+ if (this.useNonAmbiguous) {+ chars = this.removeAmbiguousCharacters(chars);+ }++ return chars;+ }++ /**+ * Remove ambiguous characters from a character set.+ */+ private removeAmbiguousCharacters(chars: string): string {+ for (const ambChar of this.ambiguousChars) {+ chars = chars.replace(ambChar, '');+ }+ return chars;+ }++ /**+ * Generate initial random password.+ */+ private generateInitialPassword(chars: string): string {+ let password = '';+ for (let i = 0; i < this.length; i++) {+ password += chars[this.getUnbiasedRandomIndex(chars.length)];+ }+ return password;+ }++ /**+ * Ensure the generated password meets all specified requirements.+ */+ private ensureRequirements(password: string): string {+ if (this.useLowercase && !/[a-z]/.exec(password)) {+ password = this.addCharacterFromSet(+ password,+ this.getSafeCharacterSet(this.lowercaseChars, true)+ );+ }++ if (this.useUppercase && !/[A-Z]/.exec(password)) {+ password = this.addCharacterFromSet(+ password,+ this.getSafeCharacterSet(this.uppercaseChars, true)+ );+ }++ if (this.useNumbers && !/\d/.exec(password)) {+ password = this.addCharacterFromSet(+ password,+ this.getSafeCharacterSet(this.numberChars, false)+ );+ }++ if (this.useSpecial && !/[!@#$%^&*()_+\-=[\]{}|;:,.<>?]/.exec(password)) {+ password = this.addCharacterFromSet(+ password,+ this.specialChars+ );+ }++ return password;+ }++ /**+ * Get a character set with ambiguous characters removed if needed.+ */+ private getSafeCharacterSet(charSet: string, isAlpha: boolean): string {+ // If we're not using non-ambiguous characters, just return the original set.+ if (!this.useNonAmbiguous) {+ return charSet;+ }++ let safeSet = charSet;+ for (const ambChar of this.ambiguousChars) {+ // For numeric sets, only process numeric ambiguous characters+ if (!isAlpha && !/\d/.test(ambChar)) {+ continue;+ }++ let charToRemove = ambChar;++ // Handle case conversion for alphabetic characters.+ if (isAlpha) {+ if (charSet === this.lowercaseChars) {+ charToRemove = ambChar.toLowerCase();+ } else {+ charToRemove = ambChar.toUpperCase();+ }+ }++ safeSet = safeSet.replace(charToRemove, '');+ }++ return safeSet;+ }++ /**+ * Add a character from the given set at a random position in the password.+ */+ private addCharacterFromSet(password: string, charSet: string): string {+ const pos = this.getUnbiasedRandomIndex(this.length);+ const char = charSet[this.getUnbiasedRandomIndex(charSet.length)];++ return password.substring(0, pos) + char + password.substring(pos + 1);+ }+}diff --git a/mobile-app/utils/generators/Password/__tests__/PasswordGenerator.test.ts b/mobile-app/utils/generators/Password/__tests__/PasswordGenerator.test.tsnew file mode 100644index 000000000..385f39dc2--- /dev/null+++ b/mobile-app/utils/generators/Password/__tests__/PasswordGenerator.test.ts@@ -0,0 +1,106 @@+import { PasswordGenerator } from '../PasswordGenerator';+import { describe, it, expect, beforeEach } from 'vitest';++describe('PasswordGenerator', () => {+ let generator: PasswordGenerator;++ beforeEach(() => {+ generator = new PasswordGenerator();+ });++ it('generates password with default settings', () => {+ const password = generator.generateRandomPassword();++ // Default length is 18+ expect(password.length).toBe(18);++ // Should contain at least one of each character type by default+ expect(password).toMatch(/[a-z]/); // lowercase+ expect(password).toMatch(/[A-Z]/); // uppercase+ expect(password).toMatch(/[0-9]/); // numbers+ expect(password).toMatch(/[!@#$%^&*()_+\-=[\]{}|;:,.<>?]/); // special+ });++ it('respects custom length setting', () => {+ const customLength = 24;+ const password = generator.setLength(customLength).generateRandomPassword();+ expect(password.length).toBe(customLength);+ });++ it('respects lowercase setting', () => {+ const password = generator.useLowercaseLetters(false).generateRandomPassword();+ expect(password).not.toMatch(/[a-z]/);+ });++ it('respects uppercase setting', () => {+ const password = generator.useUppercaseLetters(false).generateRandomPassword();+ expect(password).not.toMatch(/[A-Z]/);+ });++ it('respects numbers setting', () => {+ const password = generator.useNumericCharacters(false).generateRandomPassword();+ expect(password).not.toMatch(/[0-9]/);+ });++ it('respects special characters setting', () => {+ const password = generator.useSpecialCharacters(false).generateRandomPassword();+ expect(password).not.toMatch(/[!@#$%^&*()_+\-=[\]{}|;:,.<>?]/);+ });++ it('generates different passwords on subsequent calls', () => {+ const password1 = generator.generateRandomPassword();+ const password2 = generator.generateRandomPassword();+ expect(password1).not.toBe(password2);+ });++ it('handles minimum character requirements', () => {+ let hasLower = false;+ let hasUpper = false;+ let hasNumber = false;+ let hasSpecial = false;++ // Generate 20 passwords and check if at least one contains all required characters+ for (let i = 0; i < 20; i++) {+ const password = generator.generateRandomPassword();++ hasLower = hasLower || /[a-z]/.test(password);+ hasUpper = hasUpper || /[A-Z]/.test(password);+ hasNumber = hasNumber || /[0-9]/.test(password);+ hasSpecial = hasSpecial || /[!@#$%^&*()_+\-=[\]{}|;:,.<>?]/.test(password);++ // Break early if we've found all character types+ if (hasLower && hasUpper && hasNumber && hasSpecial) {+ break;+ }+ }++ // Assert that we found at least one password with each character type+ expect(hasLower).toBe(true);+ expect(hasUpper).toBe(true);+ expect(hasNumber).toBe(true);+ expect(hasSpecial).toBe(true);+ });++ it('falls back to lowercase when all options disabled', () => {+ const password = generator+ .useLowercaseLetters(false)+ .useUppercaseLetters(false)+ .useNumericCharacters(false)+ .useSpecialCharacters(false)+ .generateRandomPassword();++ // Should fall back to lowercase+ expect(password).toMatch(/^[a-z]+$/);+ });++ it('maintains method chaining', () => {+ const result = generator+ .setLength(20)+ .useLowercaseLetters(true)+ .useUppercaseLetters(true)+ .useNumericCharacters(true)+ .useSpecialCharacters(true);++ expect(result).toBe(generator);+ });+});\ No newline at end of filediff --git a/mobile-app/utils/types/Credential.ts b/mobile-app/utils/types/Credential.tsnew file mode 100644index 000000000..4e797e056--- /dev/null+++ b/mobile-app/utils/types/Credential.ts@@ -0,0 +1,22 @@+import { Gender } from "../generators/Identity/types/Gender";++/**+ * Credential SQLite database type.+ */+export type Credential = {+ Id: string;+ Username?: string;+ Password: string;+ ServiceName: string;+ ServiceUrl?: string;+ Logo?: Uint8Array | number[];+ Notes?: string;+ Alias: {+ FirstName?: string;+ LastName?: string;+ NickName?: string;+ BirthDate: string;+ Gender?: Gender;+ Email?: string;+ };+}\ No newline at end of filediff --git a/mobile-app/utils/types/EncryptionKey.ts b/mobile-app/utils/types/EncryptionKey.tsnew file mode 100644index 000000000..7dc64d603--- /dev/null+++ b/mobile-app/utils/types/EncryptionKey.ts@@ -0,0 +1,9 @@+/**+ * Encryption key SQLite database type.+ */+export type EncryptionKey = {+ Id: string;+ PublicKey: string;+ PrivateKey: string;+ IsPrimary: boolean;+}diff --git a/mobile-app/utils/types/PasswordSettings.ts b/mobile-app/utils/types/PasswordSettings.tsnew file mode 100644index 000000000..50719e895--- /dev/null+++ b/mobile-app/utils/types/PasswordSettings.ts@@ -0,0 +1,34 @@+/**+ * Settings for password generation stored in SQLite database settings table as string.+ */+export type PasswordSettings = {+ /**+ * The length of the password.+ */+ Length: number;++ /**+ * Whether to use lowercase letters.+ */+ UseLowercase: boolean;++ /**+ * Whether to use uppercase letters.+ */+ UseUppercase: boolean;++ /**+ * Whether to use numbers.+ */+ UseNumbers: boolean;++ /**+ * Whether to use special characters.+ */+ UseSpecialChars: boolean;++ /**+ * Whether to use non-ambiguous characters.+ */+ UseNonAmbiguousChars: boolean;+}\ No newline at end of filediff --git a/mobile-app/utils/types/TotpCode.ts b/mobile-app/utils/types/TotpCode.tsnew file mode 100644index 000000000..0dc11bdb6--- /dev/null+++ b/mobile-app/utils/types/TotpCode.ts@@ -0,0 +1,16 @@+/**+ * TotpCode SQLite database type.+ */+export type TotpCode = {+ /** The ID of the TOTP code */+ Id: string;++ /** The name of the TOTP code */+ Name: string;++ /** The secret key for the TOTP code */+ SecretKey: string;++ /** The credential ID this TOTP code belongs to */+ CredentialId: string;+};\ No newline at end of filediff --git a/mobile-app/utils/types/errors/ApiAuthError.ts b/mobile-app/utils/types/errors/ApiAuthError.tsnew file mode 100644index 000000000..83b91b46a--- /dev/null+++ b/mobile-app/utils/types/errors/ApiAuthError.ts@@ -0,0 +1,14 @@+/**+ * Custom error class for API authentication-related errors.+ */+export class ApiAuthError extends Error {+ /**+ * Creates a new instance of ApiAuthError.+ *+ * @param message - The error message.+ */+ public constructor(message: string) {+ super(message);+ this.name = 'ApiAuthError';+ }+}diff --git a/mobile-app/utils/types/messaging/BoolResponse.ts b/mobile-app/utils/types/messaging/BoolResponse.tsnew file mode 100644index 000000000..aa51d281a--- /dev/null+++ b/mobile-app/utils/types/messaging/BoolResponse.ts@@ -0,0 +1,4 @@+export type BoolResponse = {+ success: boolean,+ error?: string+};\ No newline at end of filediff --git a/mobile-app/utils/types/messaging/CredentialsResponse.ts b/mobile-app/utils/types/messaging/CredentialsResponse.tsnew file mode 100644index 000000000..a751a0cee--- /dev/null+++ b/mobile-app/utils/types/messaging/CredentialsResponse.ts@@ -0,0 +1,7 @@+import { Credential } from "../Credential";++export type CredentialsResponse = {+ success: boolean,+ error?: string,+ credentials?: Credential[]+};diff --git a/mobile-app/utils/types/messaging/PasswordSettingsResponse.ts b/mobile-app/utils/types/messaging/PasswordSettingsResponse.tsnew file mode 100644index 000000000..56a10991f--- /dev/null+++ b/mobile-app/utils/types/messaging/PasswordSettingsResponse.ts@@ -0,0 +1,7 @@+import { PasswordSettings } from "@/utils/types/PasswordSettings";++export type PasswordSettingsResponse = {+ success: boolean,+ error?: string,+ settings?: PasswordSettings+};diff --git a/mobile-app/utils/types/messaging/StringResponse.ts b/mobile-app/utils/types/messaging/StringResponse.tsnew file mode 100644index 000000000..186c1a903--- /dev/null+++ b/mobile-app/utils/types/messaging/StringResponse.ts@@ -0,0 +1,5 @@+export type StringResponse = {+ success: boolean,+ error?: string,+ value?: string+};diff --git a/mobile-app/utils/types/messaging/VaultResponse.ts b/mobile-app/utils/types/messaging/VaultResponse.tsnew file mode 100644index 000000000..e57e54265--- /dev/null+++ b/mobile-app/utils/types/messaging/VaultResponse.ts@@ -0,0 +1,7 @@+export type VaultResponse = {+ success: boolean, error?: string,+ vault?: string,+ publicEmailDomains?: string[],+ privateEmailDomains?: string[],+ vaultRevisionNumber?: number+};diff --git a/mobile-app/utils/types/webapi/Attachment.ts b/mobile-app/utils/types/webapi/Attachment.tsnew file mode 100644index 000000000..cd74065fe--- /dev/null+++ b/mobile-app/utils/types/webapi/Attachment.ts@@ -0,0 +1,19 @@+/**+ * Email attachment type.+ */+export type Attachment = {+ /** The ID of the attachment */+ id: number;++ /** The ID of the email the attachment belongs to */+ emailId: number;++ /** The filename of the attachment */+ filename: string;++ /** The MIME type of the attachment */+ mimeType: string;++ /** The size of the attachment in bytes */+ filesize: number;+}\ No newline at end of filediff --git a/mobile-app/utils/types/webapi/BadRequestResponse.ts b/mobile-app/utils/types/webapi/BadRequestResponse.tsnew file mode 100644index 000000000..cc4598f7d--- /dev/null+++ b/mobile-app/utils/types/webapi/BadRequestResponse.ts@@ -0,0 +1,9 @@+type BadRequestResponse = {+ type: string;+ title: string;+ status: number;+ errors: Record<string, string[]>;+ traceId: string;+};++export default BadRequestResponse;diff --git a/mobile-app/utils/types/webapi/Email.ts b/mobile-app/utils/types/webapi/Email.tsnew file mode 100644index 000000000..f88518999--- /dev/null+++ b/mobile-app/utils/types/webapi/Email.ts@@ -0,0 +1,51 @@+import { Attachment } from "./Attachment";++export type Email = {+ /** The body of the email message */+ messageHtml: string;++ /** The plain text body of the email message */+ messagePlain: string;++ /** The ID of the email */+ id: number;++ /** The subject of the email */+ subject: string;++ /** The display name of the sender */+ fromDisplay: string;++ /** The domain of the sender's email address */+ fromDomain: string;++ /** The local part of the sender's email address */+ fromLocal: string;++ /** The domain of the recipient's email address */+ toDomain: string;++ /** The local part of the recipient's email address */+ toLocal: string;++ /** The date of the email */+ date: string;++ /** The system date of the email */+ dateSystem: string;++ /** The number of seconds ago the email was received */+ secondsAgo: number;++ /**+ * The encrypted symmetric key which was used to encrypt the email message.+ * This key is encrypted with the public key of the user.+ */+ encryptedSymmetricKey: string;++ /** The public key of the user used to encrypt the symmetric key */+ encryptionKey: string;++ /** The attachments of the email */+ attachments: Attachment[];+}diff --git a/mobile-app/utils/types/webapi/Login.ts b/mobile-app/utils/types/webapi/Login.tsnew file mode 100644index 000000000..40a0822d8--- /dev/null+++ b/mobile-app/utils/types/webapi/Login.ts@@ -0,0 +1,16 @@+/**+ * Login request type.+ */+export type LoginRequest = {+ username: string;+}++/**+ * Login response type.+ */+export type LoginResponse = {+ salt: string;+ serverEphemeral: string;+ encryptionType: string;+ encryptionSettings: string;+}diff --git a/mobile-app/utils/types/webapi/MailboxBulk.ts b/mobile-app/utils/types/webapi/MailboxBulk.tsnew file mode 100644index 000000000..775b8c56d--- /dev/null+++ b/mobile-app/utils/types/webapi/MailboxBulk.ts@@ -0,0 +1,21 @@+import { MailboxEmail } from "./MailboxEmail";++/**+ * Mailbox bulk request type.+ */+export type MailboxBulkRequest = {+ addresses: string[];+ page: number;+ pageSize: number;+}++/**+ * Mailbox bulk response type.+ */+export type MailboxBulkResponse = {+ addresses: string[];+ currentPage: number;+ pageSize: number;+ totalRecords: number;+ mails: MailboxEmail[];+}\ No newline at end of filediff --git a/mobile-app/utils/types/webapi/MailboxEmail.ts b/mobile-app/utils/types/webapi/MailboxEmail.tsnew file mode 100644index 000000000..dd15b9ae4--- /dev/null+++ b/mobile-app/utils/types/webapi/MailboxEmail.ts@@ -0,0 +1,46 @@+export type MailboxEmail = {+ /** The preview of the email message */+ messagePreview: string;++ /** Indicates whether the email has attachments */+ hasAttachments: boolean;++ /** The ID of the email */+ id: number;++ /** The subject of the email */+ subject: string;++ /** The display name of the sender */+ fromDisplay: string;++ /** The domain of the sender's email address */+ fromDomain: string;++ /** The local part of the sender's email address */+ fromLocal: string;++ /** The domain of the recipient's email address */+ toDomain: string;++ /** The local part of the recipient's email address */+ toLocal: string;++ /** The date of the email */+ date: string;++ /** The system date of the email */+ dateSystem: string;++ /** The number of seconds ago the email was received */+ secondsAgo: number;++ /**+ * The encrypted symmetric key which was used to encrypt the email message.+ * This key is encrypted with the public key of the user.+ */+ encryptedSymmetricKey: string;++ /** The public key of the user used to encrypt the symmetric key */+ encryptionKey: string;+}\ No newline at end of filediff --git a/mobile-app/utils/types/webapi/StatusResponse.ts b/mobile-app/utils/types/webapi/StatusResponse.tsnew file mode 100644index 000000000..53d4181f0--- /dev/null+++ b/mobile-app/utils/types/webapi/StatusResponse.ts@@ -0,0 +1,8 @@+/**+ * Status response type.+ */+export type StatusResponse = {+ clientVersionSupported: boolean;+ serverVersion: string;+ vaultRevision: number;+}diff --git a/mobile-app/utils/types/webapi/ValidateLogin.ts b/mobile-app/utils/types/webapi/ValidateLogin.tsnew file mode 100644index 000000000..e64eaf216--- /dev/null+++ b/mobile-app/utils/types/webapi/ValidateLogin.ts@@ -0,0 +1,32 @@+/**+ * Validate login request type.+ */+export type ValidateLoginRequest = {+ username: string;+ rememberMe: boolean;+ clientPublicEphemeral: string;+ clientSessionProof: string;+}++/**+ * Validate login request type for 2FA.+ */+export type ValidateLoginRequest2Fa = {+ username: string;+ code2Fa: number;+ rememberMe: boolean;+ clientPublicEphemeral: string;+ clientSessionProof: string;+}++/**+ * Validate login response type.+ */+export type ValidateLoginResponse = {+ requiresTwoFactor: boolean;+ token?: {+ token: string;+ refreshToken: string;+ };+ serverSessionProof: string;+ }\ No newline at end of filediff --git a/mobile-app/utils/types/webapi/Vault.ts b/mobile-app/utils/types/webapi/Vault.tsnew file mode 100644index 000000000..e318aa196--- /dev/null+++ b/mobile-app/utils/types/webapi/Vault.ts@@ -0,0 +1,17 @@+/**+ * Vault type.+ */+export type Vault = {+ blob: string;+ createdAt: string;+ credentialsCount: number;+ currentRevisionNumber: number;+ emailAddressList: string[];+ privateEmailDomainList: string[];+ publicEmailDomainList: string[];+ encryptionPublicKey: string;+ updatedAt: string;+ username: string;+ version: string;+ client: string;+}\ No newline at end of filediff --git a/mobile-app/utils/types/webapi/VaultPostResponse.ts b/mobile-app/utils/types/webapi/VaultPostResponse.tsnew file mode 100644index 000000000..33de71718--- /dev/null+++ b/mobile-app/utils/types/webapi/VaultPostResponse.ts@@ -0,0 +1,7 @@+/**+ * Vault post response type returned after uploading a new vault to the server.+ */+export type VaultPostResponse = {+ status: number;+ newRevisionNumber: number;+}\ No newline at end of filediff --git a/mobile-app/utils/types/webapi/VaultResponse.ts b/mobile-app/utils/types/webapi/VaultResponse.tsnew file mode 100644index 000000000..06207affb--- /dev/null+++ b/mobile-app/utils/types/webapi/VaultResponse.ts@@ -0,0 +1,9 @@+import { Vault } from "./Vault";++/**+ * Vault response type.+ */+export type VaultResponse = {+ status: number;+ vault: Vault;+}\ No newline at end of file