Skip to content

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

Improve offline mode detection and error display

Leendert de Borsta3ca5a720231
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailDetails.tsx b/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailDetails.tsx
index 1ca9492bc..8fc9caaf2 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailDetails.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailDetails.tsx
@@ -1,3 +1,4 @@
+import { isServerUnreachable } from '@aliasvault/client/api/errors/ExpectedFailure';
import { getEmailAttachmentBytes } from '@aliasvault/client/email/EmailAttachments';
import { decryptEmail, type DecryptedEmail } from '@aliasvault/client/email/EmailDecryption';
import { sanitizeEmailHtml } from '@aliasvault/client/email/EmailHtmlSanitizer';
@@ -102,6 +103,11 @@ const EmailDetails: React.FC = (): React.ReactElement => {
setViewMode('source');
}
} catch (err) {
+ if (isServerUnreachable(err)) {
+ await dbContext.setIsOffline(true);
+ setError(t('emails.offlineMessage'));
+ return;
+ }
setError(err instanceof Error ? err.message : t('common.errors.unknownError'));
} finally {
setIsLoading(false);
@@ -110,7 +116,7 @@ const EmailDetails: React.FC = (): React.ReactElement => {
};
loadEmail();
- }, [id, dbContext?.sqliteClient, dbContext.isOffline, t, webApi, setIsLoading, setIsInitialLoading]);
+ }, [id, dbContext, t, webApi, setIsLoading, setIsInitialLoading]);
/*
* Resolve the credential (item) that owns the recipient address for this email so we can
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailsList.tsx b/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailsList.tsx
index c9413750c..6d94b1eb5 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailsList.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailsList.tsx
@@ -1,3 +1,4 @@
+import { isServerUnreachable } from '@aliasvault/client/api/errors/ExpectedFailure';
import { decryptEmailList } from '@aliasvault/client/email/EmailDecryption';
import React, { useEffect, useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -83,6 +84,10 @@ const EmailsList: React.FC = () => {
}
} catch (error) {
logFailure('[Emails] Loading the mailbox failed', error);
+ if (isServerUnreachable(error)) {
+ await dbContext.setIsOffline(true);
+ return;
+ }
throw new Error(t('common.errors.unknownError'));
}
} catch (err) {
@@ -91,7 +96,7 @@ const EmailsList: React.FC = () => {
setIsLoading(false);
setIsInitialLoading(false);
}
- }, [dbContext?.sqliteClient, dbContext.isOffline, webApi, setIsLoading, setIsInitialLoading, t, PAGE_SIZE]);
+ }, [dbContext, webApi, setIsLoading, setIsInitialLoading, t, PAGE_SIZE]);
/**
* Loads more emails (next page).
@@ -118,12 +123,16 @@ const EmailsList: React.FC = () => {
setCurrentPage(data.currentPage);
setTotalRecords(data.totalRecords);
} catch (err) {
- setError(err instanceof Error ? err.message : t('common.errors.unknownError'));
logFailure('Failed to load more emails', err);
+ if (isServerUnreachable(err)) {
+ await dbContext.setIsOffline(true);
+ return;
+ }
+ setError(err instanceof Error ? err.message : t('common.errors.unknownError'));
} finally {
setIsLoadingMore(false);
}
- }, [isLoadingMore, dbContext?.sqliteClient, dbContext.isOffline, webApi, currentPage, PAGE_SIZE, t]);
+ }, [isLoadingMore, dbContext, webApi, currentPage, PAGE_SIZE, t]);
useEffect(() => {
loadEmails();
diff --git a/apps/mobile-app/app/(tabs)/emails/[id].tsx b/apps/mobile-app/app/(tabs)/emails/[id].tsx
index c696735da..b3884775d 100644
--- a/apps/mobile-app/app/(tabs)/emails/[id].tsx
+++ b/apps/mobile-app/app/(tabs)/emails/[id].tsx
@@ -16,6 +16,7 @@ import type { DisplayItem } from '@/utils/DisplayItem';
import emitter from '@/utils/EventEmitter';
import { getFileForFilename } from '@/utils/FileUtility';
import { itemRoute } from '@/utils/ItemRoute';
+import { isServerUnreachable } from '@/utils/ServerReachability';
import { useAttachmentViewer } from '@/hooks/useAttachmentViewer';
import { useColors } from '@/hooks/useColorScheme';
@@ -107,6 +108,12 @@ export default function EmailDetailsScreen() : React.ReactNode {
setViewMode('source');
}
} catch (err) {
+ if (await isServerUnreachable()) {
+ await dbContext.setIsOffline(true);
+ setError(t('emails.offlineMessage'));
+ return;
+ }
+
/*
* Suppress errors while vault has unsynced changes
* Network errors during sync can trigger false positives
diff --git a/apps/mobile-app/app/(tabs)/emails/index.tsx b/apps/mobile-app/app/(tabs)/emails/index.tsx
index 88587404c..28a7f491a 100644
--- a/apps/mobile-app/app/(tabs)/emails/index.tsx
+++ b/apps/mobile-app/app/(tabs)/emails/index.tsx
@@ -8,9 +8,11 @@ import Toast from 'react-native-toast-message';
import emitter from '@/utils/EventEmitter';
import { HapticsUtility } from '@/utils/HapticsUtility';
+import { isServerUnreachable } from '@/utils/ServerReachability';
import { useColors } from '@/hooks/useColorScheme';
import { useMinDurationLoading } from '@/hooks/useMinDurationLoading';
+import { useVaultSync } from '@/hooks/useVaultSync';
import { EmailCard } from '@/components/EmailCard';
import { ThemedContainer } from '@/components/themed/ThemedContainer';
@@ -32,6 +34,7 @@ export default function EmailsScreen() : React.ReactNode {
const webApi = useWebApi();
const colors = useColors();
const navigation = useNavigation();
+ const { syncVault } = useVaultSync();
const [scrollY] = useState(() => new Animated.Value(0));
const scrollViewRef = useRef<ScrollView>(null);
const [error, setError] = useState<string | null>(null);
@@ -80,6 +83,12 @@ export default function EmailsScreen() : React.ReactNode {
}
setIsLoading(false);
} catch {
+ // An unreachable server puts the app in offline mode, like a vault sync does.
+ if (await isServerUnreachable()) {
+ await dbContext.setIsOffline(true);
+ return;
+ }
+
/*
* Suppress errors while vault has unsynced changes or if we're offline
* Network errors during sync can trigger false positives
@@ -129,6 +138,11 @@ export default function EmailsScreen() : React.ReactNode {
setCurrentPage(data.currentPage);
setTotalRecords(data.totalRecords);
} catch (err) {
+ if (await isServerUnreachable()) {
+ await dbContext.setIsOffline(true);
+ return;
+ }
+
setError(err instanceof Error ? err.message : t('common.error'));
console.error('Failed to load more emails:', err);
@@ -141,7 +155,7 @@ export default function EmailsScreen() : React.ReactNode {
} finally {
setIsLoadingMore(false);
}
- }, [isLoadingMore, dbContext.sqliteClient, dbContext.isOffline, webApi, currentPage, PAGE_SIZE, t]);
+ }, [isLoadingMore, dbContext, webApi, currentPage, PAGE_SIZE, t]);
useEffect(() => {
const unsubscribeFocus = navigation.addListener('focus', () => {
@@ -192,10 +206,15 @@ export default function EmailsScreen() : React.ReactNode {
setIsLoading(true);
setIsRefreshing(true);
- await loadEmails();
+ if (dbContext.isOffline) {
+ // Leaving offline mode reloads the emails through the mount effect.
+ await syncVault();
+ } else {
+ await loadEmails();
+ }
setIsRefreshing(false);
setIsLoading(false);
- }, [loadEmails, setIsLoading, setIsRefreshing]);
+ }, [dbContext.isOffline, loadEmails, syncVault, setIsLoading, setIsRefreshing]);
const styles = StyleSheet.create({
centerContainer: {
diff --git a/apps/mobile-app/app/(tabs)/settings/security/change-password.tsx b/apps/mobile-app/app/(tabs)/settings/security/change-password.tsx
index 0915be546..672a4905a 100644
--- a/apps/mobile-app/app/(tabs)/settings/security/change-password.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/security/change-password.tsx
@@ -1,11 +1,14 @@
import { apiErrorMessage } from '@aliasvault/client/api/errors/ApiErrorMessage';
import { IncorrectPasswordError, PasswordChangedElsewhereError } from '@aliasvault/client/auth/MasterPasswordService';
import { MIN_ACCEPTED_PASSWORD_LENGTH } from '@aliasvault/client/utilities/PasswordStrength';
+import { Ionicons } from '@expo/vector-icons';
import { router } from 'expo-router';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { StyleSheet, View, KeyboardAvoidingView, Platform } from 'react-native';
+import { isServerUnreachable } from '@/utils/ServerReachability';
+
import { useColors } from '@/hooks/useColorScheme';
import { useVaultMutate } from '@/hooks/useVaultMutate';
@@ -18,6 +21,7 @@ import { ThemedText } from '@/components/themed/ThemedText';
import { ThemedTextInput } from '@/components/themed/ThemedTextInput';
import { UsernameDisplay } from '@/components/ui/UsernameDisplay';
import { useAuth } from '@/context/AuthContext';
+import { useDb } from '@/context/DbContext';
import { useDialog } from '@/context/DialogContext';
/**
@@ -27,6 +31,7 @@ import { useDialog } from '@/context/DialogContext';
export default function ChangePasswordScreen(): React.ReactNode {
const colors = useColors();
const authContext = useAuth();
+ const dbContext = useDb();
const { executeVaultPasswordChange, syncStatus } = useVaultMutate();
const { t } = useTranslation();
const { showAlert } = useDialog();
@@ -63,6 +68,20 @@ export default function ChangePasswordScreen(): React.ReactNode {
fontSize: 16,
marginBottom: 8,
},
+ offlineWarning: {
+ alignItems: 'center',
+ backgroundColor: colors.warningBackground,
+ borderRadius: 12,
+ flexDirection: 'row',
+ gap: 12,
+ marginTop: 16,
+ padding: 12,
+ },
+ offlineWarningText: {
+ flex: 1,
+ fontSize: 14,
+ lineHeight: 20,
+ },
});
/**
@@ -84,6 +103,12 @@ export default function ChangePasswordScreen(): React.ReactNode {
* @returns {Promise<void>} A promise that resolves when the operation is complete
*/
const handleSubmit = async (): Promise<void> => {
+ // A password change is a handshake with the server, so it cannot run offline.
+ if (dbContext.isOffline) {
+ showAlert(t('common.error'), t('common.errors.serverNotAvailable'));
+ return;
+ }
+
if (!currentPassword || !newPassword || !confirmPassword) {
showAlert(t('common.error'), t('settings.securitySettings.changePassword.fillAllFields'));
return;
@@ -125,6 +150,11 @@ export default function ChangePasswordScreen(): React.ReactNode {
});
} catch (error) {
console.error('Password change error:', error);
+ if (await isServerUnreachable()) {
+ await dbContext.setIsOffline(true);
+ showAlert(t('common.error'), t('common.errors.serverNotAvailable'));
+ return;
+ }
showAlert(t('common.error'), errorMessage(error));
} finally {
setIsLoading(false);
@@ -147,6 +177,12 @@ export default function ChangePasswordScreen(): React.ReactNode {
{t('settings.securitySettings.changePassword.headerText')}
</ThemedText>
<UsernameDisplay />
+ {dbContext.isOffline && (
+ <View style={styles.offlineWarning}>
+ <Ionicons name="warning" size={20} color={colors.warning} />
+ <ThemedText style={styles.offlineWarningText}>{t('common.errors.serverNotAvailable')}</ThemedText>
+ </View>
+ )}
<View style={styles.form}>
<View style={styles.inputContainer}>
<ThemedText style={styles.label}>{t('settings.securitySettings.changePassword.currentPassword')}</ThemedText>
@@ -187,6 +223,7 @@ export default function ChangePasswordScreen(): React.ReactNode {
title={t('settings.securitySettings.changePassword.changePassword')}
onPress={handleSubmit}
loading={isLoading}
+ disabled={dbContext.isOffline}
style={styles.button}
/>
</View>
diff --git a/apps/mobile-app/utils/ServerReachability.ts b/apps/mobile-app/utils/ServerReachability.ts
new file mode 100644
index 000000000..1ccbb59f7
--- /dev/null
+++ b/apps/mobile-app/utils/ServerReachability.ts
@@ -0,0 +1,12 @@
+import NativeVaultManager from '@/specs/NativeVaultManager';
+
+/**
+ * Whether the server is unreachable, per the same status check the vault sync runs before syncing.
+ */
+export async function isServerUnreachable(): Promise<boolean> {
+ try {
+ return (await NativeVaultManager.checkSyncStatus()).isOffline;
+ } catch {
+ return false;
+ }
+}
diff --git a/apps/web/src/pages/emails/Home.tsx b/apps/web/src/pages/emails/Home.tsx
index c86581822..d68c18f59 100644
--- a/apps/web/src/pages/emails/Home.tsx
+++ b/apps/web/src/pages/emails/Home.tsx
@@ -1,4 +1,5 @@
import { apiErrorCodeOf } from '@aliasvault/client/api/errors/ApiRequestError';
+import { isServerUnreachable } from '@aliasvault/client/api/errors/ExpectedFailure';
import { decryptEmailList } from '@aliasvault/client/email/EmailDecryption';
import { getPlatform } from '@aliasvault/client/platform';
import { hasUnsyncedUserChanges } from '@aliasvault/client/sync/VaultDirtyState';
@@ -24,6 +25,7 @@ import { useNotifications } from '@/context/NotificationContext';
import { useWebApi } from '@/context/WebApiContext';
import { useMinDurationLoading } from '@/hooks/useMinDurationLoading';
import { usePageTitle } from '@/hooks/usePageTitle';
+import { useVaultSync } from '@/hooks/useVaultSync';
import { type EmailViewModel, loadAliasVaultEmail } from '@/utils/EmailViewModel';
import { itemRoute } from '@/utils/ItemRoute';
import { StorageKeys } from '@/utils/StorageKeys';
@@ -67,6 +69,7 @@ const EmailsHome: React.FC = () => {
const webApi = useWebApi();
const notifications = useNotifications();
const { showConfirmation } = useConfirmModal();
+ const { syncVault } = useVaultSync();
usePageTitle(t('emails.title'));
const [isLoading, setIsLoading] = useMinDurationLoading(true, 300);
@@ -149,6 +152,11 @@ const EmailsHome: React.FC = () => {
return { emails, totalRecords: data.totalRecords, currentPage: data.currentPage, pageSize: data.pageSize };
} catch (error) {
+ if (isServerUnreachable(error)) {
+ await dbContext.setIsOffline(true);
+ return null;
+ }
+
// Claim does not exist errors from the email API are expected while local changes are still being synced.
if (!dbContext.isSyncing && !await hasUnsyncedUserChanges()) {
if (apiErrorCodeOf(error) === 'CLAIM_DOES_NOT_EXIST') {
@@ -174,6 +182,11 @@ const EmailsHome: React.FC = () => {
setNewEmailIds(new Set());
knownEmailIds.current = new Set();
+ if (dbContext.getIsOffline()) {
+ setIsLoading(false);
+ return;
+ }
+
const targetPage = preserveCurrentPage ? page : 1;
const emailClaimList = await getEmailClaimList();
if (emailClaimList.length === 0) {
@@ -193,17 +206,27 @@ const EmailsHome: React.FC = () => {
}
}
setIsLoading(false);
- }, [getEmailClaimList, loadEmailsFromServer, setIsLoading]);
+ }, [dbContext, getEmailClaimList, loadEmailsFromServer, setIsLoading]);
useEffect(() => {
void refreshData();
}, [refreshData]);
+ /**
+ * Refresh button: while offline, retry the vault sync first, which leaves offline mode when the server is back.
+ */
+ const onRefreshClick = useCallback(async (): Promise<void> => {
+ if (dbContext.getIsOffline()) {
+ await syncVault();
+ }
+ await refreshData();
+ }, [dbContext, refreshData, syncVault]);
+
/**
* Check for new emails without disrupting the current view.
*/
const checkForNewEmails = useCallback(async (): Promise<void> => {
- if (!isPageVisible.current || !autoRefreshEnabled || currentPage !== 1 || noEmailClaims) {
+ if (!isPageVisible.current || !autoRefreshEnabled || currentPage !== 1 || noEmailClaims || dbContext.getIsOffline()) {
return;
}
const result = await loadEmailsFromServer(1, 5);
@@ -222,7 +245,7 @@ const EmailsHome: React.FC = () => {
setTimeout(() => {
setNewEmailIds(ids => new Set([...ids].filter(id => !arrivedIds.includes(id))));
}, NEW_EMAIL_INDICATOR_MS);
- }, [autoRefreshEnabled, currentPage, noEmailClaims, loadEmailsFromServer]);
+ }, [autoRefreshEnabled, currentPage, noEmailClaims, dbContext, loadEmailsFromServer]);
/**
* Poll while the tab is visible.
@@ -431,7 +454,7 @@ const EmailsHome: React.FC = () => {
{autoRefreshEnabled && currentPage === 1 && (
<div className="w-3 h-3 mr-2 rounded-full bg-primary-300 border-2 border-primary-100 animate-pulse" title={t('emails.home.autoRefreshEnabledTooltip')}></div>
)}
- <RefreshButton onClick={() => refreshData()} buttonText={t('common.refresh')} />
+ <RefreshButton onClick={onRefreshClick} buttonText={t('common.refresh')} />
{checkedEmailIds.size > 0 && (
<DeleteAllSelectedButton onClick={showBulkDeleteConfirmation} buttonText={t('emails.home.deleteSelectedEmails', { count: checkedEmailIds.size })} />
)}
@@ -461,6 +484,12 @@ const EmailsHome: React.FC = () => {
</div>
</div>
</div>
+ ) : dbContext.isOffline ? (
+ <div className="p-4 mx-4 mt-4 bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 dark:bg-gray-800">
+ <div className="px-4 py-2 text-gray-400 rounded">
+ <Text variant="muted">{t('emails.offlineMessage')}</Text>
+ </div>
+ </div>
) : noEmailClaims ? (
<div className="p-4 mx-4 mt-4 bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 dark:bg-gray-800">
<div className="px-4 py-2 text-gray-400 rounded">
diff --git a/core/client/src/api/errors/ExpectedFailure.ts b/core/client/src/api/errors/ExpectedFailure.ts
index 686213554..16c6f2a4a 100644
--- a/core/client/src/api/errors/ExpectedFailure.ts
+++ b/core/client/src/api/errors/ExpectedFailure.ts
@@ -52,3 +52,14 @@ export function logFailure(message: string, error: unknown): void {
}
logDefect(message, error);
}
+
+/**
+ * Whether a failed request means the server is unreachable: no response at all, or a gateway in front of it reporting it down.
+ * @param error - the error to classify
+ */
+export function isServerUnreachable(error: unknown): boolean {
+ if (error instanceof NetworkError) {
+ return true;
+ }
+ return error instanceof ApiRequestError && [502, 503, 504].includes(error.statusCode);
+}