Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add read-only offline mode (#771)
Leendert de Borst4ed6b3025690
diff --git a/apps/mobile-app/app/(tabs)/credentials/add-edit.tsx b/apps/mobile-app/app/(tabs)/credentials/add-edit.tsxindex 6474960a5..e8abbe0fd 100644--- a/apps/mobile-app/app/(tabs)/credentials/add-edit.tsx+++ b/apps/mobile-app/app/(tabs)/credentials/add-edit.tsx@@ -22,6 +22,7 @@ import { PasswordGenerator } from '@/utils/shared/password-generator';import { ValidatedFormField, ValidatedFormFieldRef } from '@/components/form/ValidatedFormField';import { credentialSchema } from '@/utils/validationSchema';import LoadingOverlay from '@/components/LoadingOverlay';+import { useAuth } from '@/context/AuthContext';type CredentialMode = 'random' | 'manual';@@ -33,6 +34,7 @@ export default function AddEditCredentialScreen() : React.ReactNode {const router = useRouter();const colors = useColors();const dbContext = useDb();+ const authContext = useAuth();const [mode, setMode] = useState<CredentialMode>('random');const { executeVaultMutation, syncStatus } = useVaultMutate();const navigation = useNavigation();@@ -96,6 +98,19 @@ export default function AddEditCredentialScreen() : React.ReactNode {* if we're in add mode and the service URL is provided (by native autofill component).*/useEffect(() => {+ if (authContext.isOffline) {+ // Show toast and close the modal+ setTimeout(() => {+ Toast.show({+ type: 'error',+ text1: 'You are offline and in read-only mode. Please connect to the internet to add or edit a credential.',+ position: 'bottom'+ });+ }, 100);+ router.dismiss();+ return;+ }+if (isEditMode) {loadExistingCredential();} else if (serviceUrl) {@@ -104,7 +119,7 @@ export default function AddEditCredentialScreen() : React.ReactNode {setValue('ServiceUrl', decodedUrl);setValue('ServiceName', serviceName);}- }, [id, isEditMode, serviceUrl, loadExistingCredential, setValue]);+ }, [id, isEditMode, serviceUrl, loadExistingCredential, setValue, authContext.isOffline, router]);/*** Initialize the identity and password generators with settings from user's vault.diff --git a/apps/mobile-app/app/(tabs)/credentials/index.tsx b/apps/mobile-app/app/(tabs)/credentials/index.tsxindex 252784610..124323fa5 100644--- a/apps/mobile-app/app/(tabs)/credentials/index.tsx+++ b/apps/mobile-app/app/(tabs)/credentials/index.tsx@@ -106,6 +106,14 @@ export default function CredentialsScreen() : React.ReactNode {setRefreshing(true);setIsLoadingCredentials(true);+ // Check if we are in offline mode, if so, we don't need to refresh the credentials+ const isOffline = authContext.isOffline;+ if (isOffline) {+ setRefreshing(false);+ setIsLoadingCredentials(false);+ return;+ }+try {// Sync vault and load credentialsawait syncVault({@@ -124,6 +132,18 @@ export default function CredentialsScreen() : React.ReactNode {visibilityTime: 1200,});},+ /**+ * On offline.+ */+ onOffline: () => {+ setRefreshing(false);+ setIsLoadingCredentials(false);+ Toast.show({+ type: 'error',+ text1: 'You are offline. Please connect to the internet to sync your vault',+ position: 'bottom',+ });+ },/*** On error.*/@@ -146,7 +166,7 @@ export default function CredentialsScreen() : React.ReactNode {text2: err instanceof Error ? err.message : 'Unknown error',});}- }, [syncVault, loadCredentials, setIsLoadingCredentials]);+ }, [syncVault, loadCredentials, setIsLoadingCredentials, authContext.isOffline]);useEffect(() => {if (!isAuthenticated || !isDatabaseAvailable) {diff --git a/apps/mobile-app/app/(tabs)/emails/index.tsx b/apps/mobile-app/app/(tabs)/emails/index.tsxindex 84c8dfc45..d6ac108a8 100644--- a/apps/mobile-app/app/(tabs)/emails/index.tsx+++ b/apps/mobile-app/app/(tabs)/emails/index.tsx@@ -2,6 +2,7 @@ import React, { useEffect, useState, useCallback, useRef } from 'react';import { StyleSheet, View, ScrollView, RefreshControl, Animated } from 'react-native';import { useNavigation } from 'expo-router';import { useSafeAreaInsets } from 'react-native-safe-area-context';+import Toast from 'react-native-toast-message';import { MailboxEmail } from '@/utils/types/webapi/MailboxEmail';import { useDb } from '@/context/DbContext';@@ -17,13 +18,14 @@ import { EmailCard } from '@/components/EmailCard';import { SkeletonLoader } from '@/components/ui/SkeletonLoader';import emitter from '@/utils/EventEmitter';import { useMinDurationLoading } from '@/hooks/useMinDurationLoading';-+import { useAuth } from '@/context/AuthContext';/*** Emails screen.*/export default function EmailsScreen() : React.ReactNode {const dbContext = useDb();const webApi = useWebApi();+ const authContext = useAuth();const colors = useColors();const navigation = useNavigation();const scrollY = useRef(new Animated.Value(0)).current;@@ -46,6 +48,13 @@ export default function EmailsScreen() : React.ReactNode {return;}+ // Check if we are in offline mode, if so, we don't need to load emails from the server+ const isOffline = authContext.isOffline;+ if (isOffline) {+ setIsLoading(false);+ return;+ }+// Get unique email addresses from all credentialsconst emailAddresses = await dbContext.sqliteClient.getAllEmailAddresses();@@ -66,12 +75,20 @@ export default function EmailsScreen() : React.ReactNode {setEmails(decryptedEmails);setIsLoading(false);} catch {+ // Show toast and throw error+ Toast.show({+ type: 'error',+ text1: 'Failed to load emails',+ position: 'bottom',+ });throw new Error('Failed to load emails');+ } finally {+ setIsLoading(false);}} catch (err) {setError(err instanceof Error ? err.message : 'An error occurred');}- }, [dbContext?.sqliteClient, webApi, setIsLoading]);+ }, [dbContext?.sqliteClient, webApi, setIsLoading, authContext.isOffline]);useEffect(() => {const unsubscribeFocus = navigation.addListener('focus', () => {@@ -149,7 +166,7 @@ export default function EmailsScreen() : React.ReactNode {textAlign: 'center',},errorText: {- color: colors.errorBackground,+ color: colors.errorText,textAlign: 'center',},loadingContainer: {@@ -169,6 +186,14 @@ export default function EmailsScreen() : React.ReactNode {);}+ if (authContext.isOffline) {+ return (+ <View style={styles.centerContainer}>+ <ThemedText style={styles.emptyText}>You are offline. Please connect to the internet to load your emails.</ThemedText>+ </View>+ );+ }+if (error) {return (<View style={styles.centerContainer}>diff --git a/apps/mobile-app/app/_layout.tsx b/apps/mobile-app/app/_layout.tsxindex 1b623c621..c012f1c9b 100644--- a/apps/mobile-app/app/_layout.tsx+++ b/apps/mobile-app/app/_layout.tsx@@ -1,4 +1,4 @@-import { Linking, StyleSheet } from 'react-native';+import { Linking, StyleSheet, Alert } from 'react-native';import { useEffect, useRef, useState } from 'react';import { DarkTheme, DefaultTheme, ThemeProvider } from '@react-navigation/native';import { useFonts } from 'expo-font';@@ -48,11 +48,52 @@ function RootLayoutNav() : React.ReactNode {hasBooted.current = true;+ /**+ * Handle vault unlocking process.+ */+ async function handleVaultUnlock() : Promise<void> {+ const { enabledAuthMethods } = await initializeAuth();++ try {+ const hasEncryptedDatabase = await NativeVaultManager.hasEncryptedDatabase();+ if (hasEncryptedDatabase) {+ const isFaceIDEnabled = enabledAuthMethods.includes('faceid');+ if (!isFaceIDEnabled) {+ setRedirectTarget('/unlock');+ setBootComplete(true);+ return;+ }++ setStatus('Unlocking vault');+ const isUnlocked = await dbContext.unlockVault();+ if (isUnlocked) {+ await new Promise(resolve => setTimeout(resolve, 750));+ setStatus('Decrypting vault');+ await new Promise(resolve => setTimeout(resolve, 750));+ setBootComplete(true);+ return;+ }++ setRedirectTarget('/unlock');+ setBootComplete(true);+ return;+ } else {+ setRedirectTarget('/unlock');+ setBootComplete(true);+ return;+ }+ } catch {+ setRedirectTarget('/unlock');+ setBootComplete(true);+ return;+ }+ }+/*** Initialize the app.*/const initialize = async () : Promise<void> => {- const { isLoggedIn, enabledAuthMethods } = await initializeAuth();+ const { isLoggedIn } = await initializeAuth();if (!isLoggedIn) {setRedirectTarget('/login');@@ -60,6 +101,7 @@ function RootLayoutNav() : React.ReactNode {return;}+ // First perform vault syncawait syncVault({initialSync: true,/**@@ -67,38 +109,46 @@ function RootLayoutNav() : React.ReactNode {*/onStatus: (message) => {setStatus(message);+ },+ /**+ * Handle successful vault sync and continue with vault unlock flow.+ */+ onSuccess: async () => {+ // Continue with the rest of the flow after successful sync+ handleVaultUnlock();+ },+ /**+ * Handle offline state and prompt user for action.+ */+ onOffline: () => {+ Alert.alert(+ 'Sync Issue',+ 'The AliasVault server could not be reached and the vault could not be synced. Would you like to open your local vault in read-only mode or retry the connection?',+ [+ {+ text: 'Open Local Vault',+ /**+ * Handle opening vault in read-only mode.+ */+ onPress: async () : Promise<void> => {+ setStatus('Opening vault in read-only mode');+ handleVaultUnlock();+ }+ },+ {+ text: 'Retry Sync',+ /**+ * Handle retrying the connection.+ */+ onPress: () : void => {+ setStatus('Retrying connection...');+ initialize();+ }+ }+ ]+ );}});-- const hasEncryptedDatabase = await NativeVaultManager.hasEncryptedDatabase();- if (hasEncryptedDatabase) {- const isFaceIDEnabled = enabledAuthMethods.includes('faceid');- if (!isFaceIDEnabled) {- setRedirectTarget('/unlock');- setBootComplete(true);- return;- }-- setStatus('Unlocking vault');- const isUnlocked = await dbContext.unlockVault();- if (isUnlocked) {- await new Promise(resolve => setTimeout(resolve, 750));- setStatus('Decrypting vault');- await new Promise(resolve => setTimeout(resolve, 750));-- // The vault is successfully unlocked, so we let the native code handle the default routing.- setBootComplete(true);- return;- }-- setRedirectTarget('/unlock');- setBootComplete(true);- return;- } else {- setRedirectTarget('/unlock');- setBootComplete(true);- return;- }};initialize();diff --git a/apps/mobile-app/app/reinitialize.tsx b/apps/mobile-app/app/reinitialize.tsxindex 083586943..79413579b 100644--- a/apps/mobile-app/app/reinitialize.tsx+++ b/apps/mobile-app/app/reinitialize.tsx@@ -1,6 +1,6 @@import { useEffect, useRef, useState } from 'react';import { Href, router } from 'expo-router';-import { StyleSheet, View } from 'react-native';+import { StyleSheet, View, Alert } from 'react-native';import NativeVaultManager from '@/specs/NativeVaultManager';import { useAuth } from '@/context/AuthContext';@@ -74,29 +74,11 @@ export default function ReinitializeScreen() : React.ReactNode {}/**- * Initialize the app.+ * Handle vault unlocking process.*/- const initialize = async () : Promise<void> => {- const { isLoggedIn, enabledAuthMethods } = await authContext.initializeAuth();-- // If user is not logged in, navigate to login immediately- if (!isLoggedIn) {- router.replace('/login');- return;- }-- // Perform initial vault sync- await syncVault({- initialSync: true,- /**- * Handle the status update.- */- onStatus: (message) => {- setStatus(message);- }- });+ async function handleVaultUnlock() : Promise<void> {+ const { enabledAuthMethods } = await authContext.initializeAuth();- // Try to unlock with FaceIDtry {const hasEncryptedDatabase = await NativeVaultManager.hasEncryptedDatabase();if (hasEncryptedDatabase) {@@ -106,44 +88,86 @@ export default function ReinitializeScreen() : React.ReactNode {return;}- // Attempt to unlock the vault with FaceID.setStatus('Unlocking vault');const isUnlocked = await dbContext.unlockVault();if (isUnlocked) {await new Promise(resolve => setTimeout(resolve, 1000));setStatus('Decrypting vault');await new Promise(resolve => setTimeout(resolve, 1000));-- // Vault is successfully unlocked, redirect to the stored return URL (if any) or default entry page.redirectToReturnUrl();-return;- } else {- router.replace('/unlock');}- } else {- /*- * Vault is not initialized which means the database does not exist or decryption key is missing- * from device's keychain. Navigate to the unlock screen.- */- router.replace('/unlock');- return;}+ router.replace('/unlock');} catch {- /*- * If FaceID fails (too many attempts, manual cancel, etc.)- * navigate to unlock screen- */router.replace('/unlock');+ }+ }++ /**+ * Initialize the app.+ */+ const initialize = async () : Promise<void> => {+ const { isLoggedIn } = await authContext.initializeAuth();++ // If user is not logged in, navigate to login immediately+ if (!isLoggedIn) {+ router.replace('/login');return;}- /*- * If we get here, something went wrong with the FaceID unlock- * Navigate to unlock screen as a fallback- */- router.replace('/unlock');- }+ // First perform vault sync+ const syncSuccess = await syncVault({+ initialSync: true,+ /**+ * Handle the status update.+ */+ onStatus: (message) => {+ setStatus(message);+ },+ /**+ * Handle successful vault sync and continue with vault unlock flow.+ */+ onSuccess: async () => {+ await handleVaultUnlock();+ },+ /**+ * Handle offline state and prompt user for action.+ */+ onOffline: () => {+ Alert.alert(+ 'Sync Issue',+ 'The AliasVault server could not be reached and the vault could not be synced. Would you like to open your local vault in read-only mode or retry the connection?',+ [+ {+ text: 'Open Local Vault',+ /**+ * Handle opening vault in read-only mode.+ */+ onPress: async () : Promise<void> => {+ setStatus('Opening vault in read-only mode');+ await handleVaultUnlock();+ }+ },+ {+ text: 'Retry Sync',+ /**+ * Handle retrying the connection.+ */+ onPress: () : void => {+ setStatus('Retrying connection...');+ initialize();+ }+ }+ ]+ );+ }+ });++ if (!syncSuccess) {+ router.replace('/unlock');+ }+ };initialize();}, [syncVault, authContext, dbContext]);@@ -168,7 +192,7 @@ export default function ReinitializeScreen() : React.ReactNode {return (<ThemedView style={styles.container}><View style={styles.messageContainer}>- <ThemedText style={styles.message}>Vault locked due to time-out, unlocking vault again...</ThemedText>+ <ThemedText style={styles.message}>Vault auto-locked after timeout. Attempting to unlock...</ThemedText>{status ? <LoadingIndicator status={status} /> : null}</View></ThemedView>diff --git a/apps/mobile-app/components/OfflineBanner.tsx b/apps/mobile-app/components/OfflineBanner.tsxnew file mode 100644index 000000000..98a4f9905--- /dev/null+++ b/apps/mobile-app/components/OfflineBanner.tsx@@ -0,0 +1,111 @@+import { StyleSheet, TouchableOpacity, View } from 'react-native';+import { Ionicons } from '@expo/vector-icons';+import Toast from 'react-native-toast-message';++import { ThemedText } from '@/components/themed/ThemedText';+import { ThemedView } from '@/components/themed/ThemedView';+import { useAuth } from '@/context/AuthContext';+import { useVaultSync } from '@/hooks/useVaultSync';+import { useColors } from '@/hooks/useColorScheme';++/**+ * A banner component that displays when the app is in offline mode.+ * @returns {React.ReactNode} The offline banner component or null if online+ */+export function OfflineBanner(): React.ReactNode {+ const { isOffline } = useAuth();+ const colors = useColors();+ const { syncVault } = useVaultSync();++ if (!isOffline) {+ return null;+ }++ /**+ * Handle retry connection attempt.+ * @returns {Promise<void>}+ */+ const handleRetry = async (): Promise<void> => {+ await syncVault({+ /**+ * Handle status updates during sync.+ * @param {string} _message - The status message+ */+ onStatus: (_message: string) => {+ // Status updates will be shown in the toast+ },+ /**+ * Handle successful sync.+ */+ onSuccess: () => {+ Toast.show({+ type: 'success',+ text1: 'Back online',+ position: 'bottom'+ });+ },+ /**+ * Handle offline.+ */+ onOffline: () => {+ Toast.show({+ type: 'error',+ text1: 'Still offline',+ position: 'bottom'+ });+ },+ /**+ * Handle sync errors.+ * @param {string} error - The error message+ */+ onError: (error: string) => {+ Toast.show({+ type: 'error',+ text1: 'Still offline',+ text2: error,+ position: 'bottom'+ });+ }+ });+ };++ const styles = StyleSheet.create({+ container: {+ backgroundColor: colors.primary,+ borderRadius: 10,+ marginBottom: 12,+ padding: 8,+ },+ content: {+ alignItems: 'center',+ flexDirection: 'row',+ justifyContent: 'center',+ },+ retryButton: {+ marginLeft: 8,+ padding: 4,+ },+ text: {+ color: colors.primarySurfaceText,+ flex: 1,+ fontSize: 14,+ textAlign: 'center',+ },+ });++ return (+ <ThemedView style={styles.container}>+ <View style={styles.content}>+ <ThemedText style={styles.text}>+ Offline mode (read-only)+ </ThemedText>+ <TouchableOpacity+ style={styles.retryButton}+ onPress={handleRetry}+ >+ <Ionicons name="refresh" size={20} color={colors.primarySurfaceText} />+ </TouchableOpacity>+ </View>+ </ThemedView>+ );+}diff --git a/apps/mobile-app/components/credentials/details/EmailPreview.tsx b/apps/mobile-app/components/credentials/details/EmailPreview.tsxindex 27543dc01..0eb8b8d48 100644--- a/apps/mobile-app/components/credentials/details/EmailPreview.tsx+++ b/apps/mobile-app/components/credentials/details/EmailPreview.tsx@@ -12,6 +12,7 @@ import { AppInfo } from '@/utils/AppInfo';import { PulseDot } from '@/components/PulseDot';import { ThemedText } from '@/components/themed/ThemedText';import { ThemedView } from '@/components/themed/ThemedView';+import { useAuth } from '@/context/AuthContext';type EmailPreviewProps = {email: string | undefined;@@ -27,6 +28,7 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) : React.Reaconst [isSpamOk, setIsSpamOk] = useState(false);const webApi = useWebApi();const dbContext = useDb();+ const authContext = useAuth();const colors = useColors();/**@@ -52,6 +54,12 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) : React.Reareturn;}+ // Check if we are in offline mode, if so, we don't need to load emails from the server+ const isOffline = authContext.isOffline;+ if (isOffline) {+ return;+ }+const isPublic = await isPublicDomain(email);setIsSpamOk(isPublic);@@ -125,7 +133,7 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) : React.Rea// Set up auto-refresh intervalconst interval = setInterval(loadEmails, 2000);return () : void => clearInterval(interval);- }, [email, loading, webApi, dbContext, isPublicDomain]);+ }, [email, loading, webApi, dbContext, isPublicDomain, authContext.isOffline]);const styles = StyleSheet.create({date: {@@ -183,6 +191,17 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) : React.Rea);}+ if (authContext.isOffline) {+ return (+ <ThemedView style={styles.section}>+ <View style={styles.titleContainer}>+ <ThemedText type="title" style={styles.title}>Recent emails</ThemedText>+ </View>+ <ThemedText style={styles.placeholderText}>You are offline. Please connect to the internet to load your emails.</ThemedText>+ </ThemedView>+ );+ }+if (emails.length === 0) {return (<ThemedView style={styles.section}>diff --git a/apps/mobile-app/components/ui/TitleContainer.tsx b/apps/mobile-app/components/ui/TitleContainer.tsxindex 7e3dbd614..e07984240 100644--- a/apps/mobile-app/components/ui/TitleContainer.tsx+++ b/apps/mobile-app/components/ui/TitleContainer.tsx@@ -1,5 +1,7 @@import { StyleSheet, View } from 'react-native';+import { OfflineBanner } from '../OfflineBanner';+import { ThemedText } from '@/components/themed/ThemedText';import Logo from '@/assets/images/logo.svg';@@ -13,10 +15,13 @@ type TitleContainerProps = {*/export function TitleContainer({ title, showLogo = true }: TitleContainerProps): React.ReactNode {return (- <View style={styles.titleContainer}>- {showLogo && <Logo width={40} height={40} style={styles.logo} />}- <ThemedText type="title">{title}</ThemedText>- </View>+ <>+ <OfflineBanner />+ <View style={styles.titleContainer}>+ {showLogo && <Logo width={40} height={40} style={styles.logo} />}+ <ThemedText type="title">{title}</ThemedText>+ </View>+ </>);}diff --git a/apps/mobile-app/context/AuthContext.tsx b/apps/mobile-app/context/AuthContext.tsxindex 229b73cd6..fc26f3c8e 100644--- a/apps/mobile-app/context/AuthContext.tsx+++ b/apps/mobile-app/context/AuthContext.tsx@@ -17,6 +17,7 @@ type AuthContextType = {isLoggedIn: boolean;isInitialized: boolean;username: string | null;+ isOffline: boolean;getEnabledAuthMethods: () => Promise<AuthMethod[]>;isFaceIDEnabled: () => Promise<boolean>;setAuthTokens: (username: string, accessToken: string, refreshToken: string) => Promise<void>;@@ -30,6 +31,7 @@ type AuthContextType = {getAutoLockTimeout: () => Promise<number>;setAutoLockTimeout: (timeout: number) => Promise<void>;getBiometricDisplayName: () => Promise<string>;+ setOfflineMode: (isOffline: boolean) => void;// iOS Autofill methodsshouldShowIosAutofillReminder: boolean;markIosAutofillConfigured: () => Promise<void>;@@ -55,6 +57,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ childrenconst [globalMessage, setGlobalMessage] = useState<string | null>(null);const [shouldShowIosAutofillReminder, setShouldShowIosAutofillReminder] = useState(false);const [returnUrl, setReturnUrl] = useState<{ path: string; params?: object } | null>(null);+ const [isOffline, setIsOffline] = useState(false);const appState = useRef(AppState.currentState);const dbContext = useDb();const pathname = usePathname();@@ -323,26 +326,48 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ childrenisLoggedIn,isInitialized,username,+ globalMessage,+ shouldShowIosAutofillReminder,+ returnUrl,+ isOffline,getEnabledAuthMethods,isFaceIDEnabled,- initializeAuth,setAuthTokens,+ initializeAuth,login,logout,- globalMessage,clearGlobalMessage,setAuthMethods,getAuthMethodDisplay,getAutoLockTimeout,setAutoLockTimeout,getBiometricDisplayName,- // iOS Autofill methods- shouldShowIosAutofillReminder,markIosAutofillConfigured,- // Return URL methods+ setReturnUrl,+ setOfflineMode: setIsOffline,+ }), [+ isLoggedIn,+ isInitialized,+ username,+ globalMessage,+ shouldShowIosAutofillReminder,returnUrl,+ isOffline,+ getEnabledAuthMethods,+ isFaceIDEnabled,+ setAuthTokens,+ initializeAuth,+ login,+ logout,+ clearGlobalMessage,+ setAuthMethods,+ getAuthMethodDisplay,+ getAutoLockTimeout,+ setAutoLockTimeout,+ getBiometricDisplayName,+ markIosAutofillConfigured,setReturnUrl,- }), [isLoggedIn, isInitialized, username, globalMessage, getEnabledAuthMethods, setAuthTokens, login, logout, clearGlobalMessage, initializeAuth, setAuthMethods, getAuthMethodDisplay, isFaceIDEnabled, getAutoLockTimeout, setAutoLockTimeout, getBiometricDisplayName, shouldShowIosAutofillReminder, markIosAutofillConfigured, returnUrl]);+ ]);return (<AuthContext.Provider value={contextValue}>diff --git a/apps/mobile-app/hooks/useVaultMutate.ts b/apps/mobile-app/hooks/useVaultMutate.tsindex 07f000dfa..8a28cb967 100644--- a/apps/mobile-app/hooks/useVaultMutate.ts+++ b/apps/mobile-app/hooks/useVaultMutate.ts@@ -89,16 +89,30 @@ export function useVaultMutate() : {version: await dbContext.sqliteClient!.getDatabaseVersion() ?? '0.0.0'};- // Upload to server- const response = await webApi.post<typeof newVault, VaultPostResponse>('Vault', newVault);-- if (response.status === 0) {- await NativeVaultManager.setCurrentVaultRevisionNumber(response.newRevisionNumber);- options.onSuccess?.();- } else if (response.status === 1) {- throw new Error('Vault merge required. Please login via the web app to merge the multiple pending updates to your vault.');- } else {- throw new Error('Failed to upload vault to server');+ try {+ // Upload to server+ const response = await webApi.post<typeof newVault, VaultPostResponse>('Vault', newVault);++ // If we get here, it means we have a valid connection to the server.+ authContext.setOfflineMode(false);++ if (response.status === 0) {+ await NativeVaultManager.setCurrentVaultRevisionNumber(response.newRevisionNumber);+ options.onSuccess?.();+ } else if (response.status === 1) {+ throw new Error('Vault merge required. Please login via the web app to merge the multiple pending updates to your vault.');+ } else {+ throw new Error('Failed to upload vault to server');+ }+ } catch (error) {+ // Check if it's a network error+ if (error instanceof Error && (error.message.includes('network') || error.message.includes('timeout'))) {+ // Network error, mark as offline and track pending changes+ authContext.setOfflineMode(true);+ options.onSuccess?.();+ return;+ }+ throw error;}}, [dbContext, authContext, webApi]);@@ -110,34 +124,59 @@ export function useVaultMutate() : {setIsLoading(true);setSyncStatus('Checking for vault updates');- await syncVault({- /**- * Update the sync status- */- onStatus: (message) => setSyncStatus(message),- /**- * Execute the operation if the vault has been updated- */- onSuccess: async (hasNewVault) => {- if (hasNewVault) {- // Vault was changed, but has now been reloaded so we can continue with the operation.+ // If we're in offline mode, try to sync once to see if we can get back online+ if (authContext.isOffline) {+ await syncVault({+ /**+ * Handle the status update.+ */+ onStatus: (message) => setSyncStatus(message),+ /**+ * Handle successful vault sync and continue with vault mutation.+ */+ onSuccess: async (hasNewVault) => {+ if (hasNewVault) {+ // Vault was changed, but has now been reloaded so we can continue with the operation.+ }+ await executeOperation(operation, options);+ },+ /**+ * Handle offline state and prompt user for action.+ */+ onError: () => {+ // Still offline, proceed with local operation+ executeOperation(operation, options);}-- await executeOperation(operation, options);- },- /**- * Handle errors- */- onError: (error) => {- Toast.show({- type: 'error',- text1: 'Failed to sync vault',- text2: error,- position: 'bottom'- });- options.onError?.(new Error(error));- }- });+ });+ } else {+ await syncVault({+ /**+ * Handle the status update.+ */+ onStatus: (message) => setSyncStatus(message),+ /**+ * Handle successful vault sync and continue with vault mutation.+ */+ onSuccess: async (hasNewVault) => {+ if (hasNewVault) {+ // Vault was changed, but has now been reloaded so we can continue with the operation.+ }+ await executeOperation(operation, options);+ },+ /**+ * Handle error during vault sync.+ */+ onError: (error) => {+ Toast.show({+ type: 'error',+ text1: 'Failed to sync vault',+ text2: error,+ position: 'bottom'+ });+ options.onError?.(new Error(error));+ }+ });+ }} catch (error) {console.error('Error during vault mutation:', error);Toast.show({@@ -151,7 +190,7 @@ export function useVaultMutate() : {setIsLoading(false);setSyncStatus('');}- }, [syncVault, executeOperation]);+ }, [syncVault, executeOperation, authContext.isOffline]);return {executeVaultMutation,diff --git a/apps/mobile-app/hooks/useVaultSync.ts b/apps/mobile-app/hooks/useVaultSync.tsindex 36495aaf6..a130a8c0e 100644--- a/apps/mobile-app/hooks/useVaultSync.ts+++ b/apps/mobile-app/hooks/useVaultSync.ts@@ -34,6 +34,7 @@ type VaultSyncOptions = {onSuccess?: (hasNewVault: boolean) => void;onError?: (error: string) => void;onStatus?: (message: string) => void;+ onOffline?: () => void;}/**@@ -47,7 +48,7 @@ export const useVaultSync = () : {const webApi = useWebApi();const syncVault = useCallback(async (options: VaultSyncOptions = {}) => {- const { initialSync = false, onSuccess, onError, onStatus } = options;+ const { initialSync = false, onSuccess, onError, onStatus, onOffline } = options;try {const { isLoggedIn } = await authContext.initializeAuth();@@ -69,11 +70,22 @@ export const useVaultSync = () : {);const statusError = webApi.validateStatusResponse(statusResponse);if (statusError !== null) {- await webApi.logout(statusError);- onError?.(statusError);- return false;+ // Only logout if it's an authentication error, not a network error+ if (statusError.includes('authentication') || statusError.includes('unauthorized')) {+ await webApi.logout(statusError);+ onError?.(statusError);+ return false;+ }++ // For other errors, go into offline mode+ authContext.setOfflineMode(true);+ onOffline?.();+ return true;}+ // If we get here, it means we have a valid connection to the server.+ authContext.setOfflineMode(false);+// Compare vault revisionsconst vaultMetadata = await dbContext.getVaultMetadata();const vaultRevisionNumber = vaultMetadata?.vaultRevisionNumber ?? 0;@@ -88,9 +100,16 @@ export const useVaultSync = () : {const vaultError = webApi.validateVaultResponse(vaultResponseJson as VaultResponse);if (vaultError) {- await webApi.logout(vaultError);- onError?.(vaultError);- return false;+ // Only logout if it's an authentication error, not a network error+ if (vaultError.includes('authentication') || vaultError.includes('unauthorized')) {+ await webApi.logout(vaultError);+ onError?.(vaultError);+ return false;+ }++ // For other errors, go into offline mode+ authContext.setOfflineMode(true);+ return true;}try {@@ -112,6 +131,13 @@ export const useVaultSync = () : {} catch (err) {const errorMessage = err instanceof Error ? err.message : 'Unknown error during vault sync';console.error('Vault sync error:', err);++ // Check if it's a network error+ if (errorMessage.includes('network') || errorMessage.includes('timeout')) {+ authContext.setOfflineMode(true);+ return true;+ }+onError?.(errorMessage);return false;}diff --git a/apps/mobile-app/ios/Podfile.lock b/apps/mobile-app/ios/Podfile.lockindex 147bdc7ae..299742905 100644--- a/apps/mobile-app/ios/Podfile.lock+++ b/apps/mobile-app/ios/Podfile.lock@@ -220,7 +220,7 @@ PODS:- ExpoModulesCore- ExpoBlur (14.0.3):- ExpoModulesCore- - ExpoClipboard (7.0.1):+ - ExpoClipboard (7.1.4):- ExpoModulesCore- ExpoFileSystem (18.0.12):- ExpoModulesCore@@ -228,7 +228,7 @@ PODS:- ExpoModulesCore- ExpoHaptics (14.0.1):- ExpoModulesCore- - ExpoHead (4.0.20):+ - ExpoHead (4.0.21):- ExpoModulesCore- ExpoKeepAwake (14.0.3):- ExpoModulesCore@@ -2517,11 +2517,11 @@ SPEC CHECKSUMS:expo-dev-menu-interface: 00dc42302a72722fdecec3fa048de84a9133bcc4ExpoAsset: 48386d40d53a8c1738929b3ed509bcad595b5516ExpoBlur: 392c1207f71d0ecf22371621c1fbd44ba84d9742- ExpoClipboard: 44fd1c8959ee8f6175d059dc011b154c9709a969+ ExpoClipboard: c9771e7aa5f1316183e4a6f40a5755a0b98a6b8dExpoFileSystem: 42d363d3b96f9afab980dcef60d5657a4443c655ExpoFont: f354e926f8feae5e831ec8087f36652b44a0b188ExpoHaptics: 8d199b2f33245ea85289ff6c954c7ee7c00a5b5d- ExpoHead: cee2d16ef197aaadb0ac481cf221a663636eb074+ ExpoHead: df924203fbf8e0913fc38b0f6aec71f9a9115482ExpoKeepAwake: b0171a73665bfcefcfcc311742a72a956e6aa680ExpoLinearGradient: 35ebd83b16f80b3add053a2fd68cc328ed927f60ExpoLinking: 8d12bee174ba0cdf31239706578e29e74a417402