Skip to content

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

Update mobile app error handling and display (#2437)

Leendert de Borst006f4c74ff5c
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
index e9507e397..4218b60c5 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
@@ -1377,7 +1377,7 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
putBoolean("hasDirtyChanges", versionCheck.syncState.isDirty)
putBoolean("isOffline", false)
putBoolean("requiresLogout", false)
- putNull("errorKey")
+ putNull("errorCode")
}
withContext(Dispatchers.Main) {
promise.resolve(resultMap)
@@ -1386,7 +1386,6 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
withContext(Dispatchers.Main) {
// Check for specific error types that require logout
val requiresLogout = e.isAuthenticationError || e.isVersionError
- val errorKey = e.translationKey
val isOffline = e.isNetworkError
if (isOffline) {
@@ -1397,7 +1396,7 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
putBoolean("hasDirtyChanges", syncState.isDirty)
putBoolean("isOffline", true)
putBoolean("requiresLogout", false)
- putNull("errorKey")
+ putNull("errorCode")
}
promise.resolve(resultMap)
} else {
@@ -1407,11 +1406,7 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
putBoolean("hasDirtyChanges", false)
putBoolean("isOffline", false)
putBoolean("requiresLogout", requiresLogout)
- if (errorKey != null) {
- putString("errorKey", errorKey)
- } else {
- putNull("errorKey")
- }
+ putString("errorCode", e.code)
}
promise.resolve(resultMap)
}
@@ -1425,7 +1420,7 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
putBoolean("hasDirtyChanges", false)
putBoolean("isOffline", false)
putBoolean("requiresLogout", false)
- putNull("errorKey")
+ putNull("errorCode")
}
promise.resolve(resultMap)
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/AppError.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/AppError.kt
index 41de47e65..9d7ddeb26 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/AppError.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/AppError.kt
@@ -425,72 +425,62 @@ sealed class AppError(message: String, cause: Throwable? = null) : Exception(mes
) : AppError("Sync engine failed: $message", cause)
/**
- * Get the error code string for React Native bridge.
- *
- * Error codes use the E-XXX format for easy user reporting:
- * - E-1xx: Authentication errors
- * - E-2xx: Network/connectivity errors
- * - E-3xx: Version/compatibility errors
- * - E-4xx: Vault status errors
- * - E-5xx: Decryption/Encryption errors
- * - E-6xx: Database/Storage errors
- * - E-7xx: Merge errors
- * - E-8xx: Upload errors
- * - E-9xx: Native module errors
- * - E-0xx: Generic errors
+ * Get the error code string for React Native bridge, in the E-XXX format for easy user reporting.
+ * The codes are shared by every client: `AppErrorCode` in core/client/src/api/errors/AppErrorCodes.ts is the registry,
+ * so add a new code there first and never reuse a number.
*/
val code: String
get() = when (this) {
- is AuthenticationFailed -> "E-101"
- is SessionExpired -> "E-102"
- is PasswordChanged -> "E-103"
- is ServerUnavailable -> "E-201"
- is NetworkError -> "E-202"
- is ServerError -> "E-204"
- is ClientVersionNotSupported -> "E-301"
- is ServerVersionNotSupported -> "E-302"
- is VaultVersionIncompatible -> "E-303"
- is ServerUpdateRequired -> "E-304"
- is VaultMergeRequired -> "E-401"
- is VaultOutdated -> "E-402"
- is SyncVaultFetchFailed -> "E-404"
- is VaultDecryptFailed -> "E-501"
- is EncryptionKeyNotFound -> "E-502"
- is Base64DecodeFailed -> "E-503"
- is DatabaseTempWriteFailed -> "E-504"
- is DatabaseOpenFailed -> "E-505"
- is DatabaseMemoryFailed -> "E-506"
- is DatabaseBackupFailed -> "E-507"
- is DatabasePragmaFailed -> "E-508"
- is BiometricCancelled -> "E-509"
- is BiometricFailed -> "E-510"
- is KeystoreKeyNotFound -> "E-511"
- is KeystoreAccessDenied -> "E-512"
- is KeystoreItemNotFound -> "E-513"
- is BiometricNotAvailable -> "E-514"
- is BiometricNotEnrolled -> "E-515"
- is BiometricLockout -> "E-516"
- is UnlockKeyRejected -> "E-517"
- is KeyChainUnreadable -> "E-518"
- is KeyOutOfSync -> "E-519"
- is ServerVaultDecryptFailed -> "E-520"
+ is AuthenticationFailed -> "E-104"
+ is SessionExpired -> "E-105"
+ is PasswordChanged -> "E-106"
+ is ServerUnavailable -> "E-505"
+ is NetworkError -> "E-003"
+ is ServerError -> "E-506"
+ is ClientVersionNotSupported -> "E-904"
+ is ServerVersionNotSupported -> "E-905"
+ is VaultVersionIncompatible -> "E-902"
+ is ServerUpdateRequired -> "E-903"
+ is VaultMergeRequired -> "E-907"
+ is VaultOutdated -> "E-906"
+ is SyncVaultFetchFailed -> "E-502"
+ is VaultDecryptFailed -> "E-203"
+ is EncryptionKeyNotFound -> "E-202"
+ is Base64DecodeFailed -> "E-606"
+ is DatabaseTempWriteFailed -> "E-607"
+ is DatabaseOpenFailed -> "E-608"
+ is DatabaseMemoryFailed -> "E-609"
+ is DatabaseBackupFailed -> "E-610"
+ is DatabasePragmaFailed -> "E-611"
+ is BiometricCancelled -> "E-209"
+ is BiometricFailed -> "E-210"
+ is KeystoreKeyNotFound -> "E-211"
+ is KeystoreAccessDenied -> "E-212"
+ is KeystoreItemNotFound -> "E-213"
+ is BiometricNotAvailable -> "E-214"
+ is BiometricNotEnrolled -> "E-215"
+ is BiometricLockout -> "E-216"
+ is UnlockKeyRejected -> "E-206"
+ is KeyChainUnreadable -> "E-207"
+ is KeyOutOfSync -> "E-208"
+ is ServerVaultDecryptFailed -> "E-503"
is StorageReadFailed -> "E-601"
is StorageWriteFailed -> "E-602"
is DatabaseInitFailed -> "E-603"
- is VaultStoreFailed -> "E-604"
+ is VaultStoreFailed -> "E-504"
is ManifestNotRecorded -> "E-605"
is VaultMergeFailed -> "E-701"
- is MergeUploadFailed -> "E-705"
+ is MergeUploadFailed -> "E-703"
is VaultUploadFailed -> "E-801"
is VaultTooLarge -> "E-804"
is VaultSyncTimeout -> "E-805"
- is MaxRetriesReached -> "E-901"
- is MigrationCheckFailed -> "E-903"
+ is MaxRetriesReached -> "E-702"
+ is MigrationCheckFailed -> "E-901"
is UnknownError -> "E-001"
- is ParseError -> "E-002"
- is SyncResponseInvalid -> "E-003"
- is SyncCodecFailed -> "E-004"
- is SyncEngineFailed -> "E-005"
+ is ParseError -> "E-004"
+ is SyncResponseInvalid -> "E-507"
+ is SyncCodecFailed -> "E-508"
+ is SyncEngineFailed -> "E-509"
}
/**
@@ -519,10 +509,4 @@ sealed class AppError(message: String, cause: Throwable? = null) : Exception(mes
is ServerUnavailable, is NetworkError -> true
else -> false
}
-
- /**
- * Get the translation key for this error (error code format for lookup in translation files).
- */
- val translationKey: String?
- get() = code
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt
index f3cccce9c..cc2c9e9bc 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt
@@ -242,7 +242,7 @@ class VaultSync(
* The engine's failure as the native error: a forced logout by its reason, else by its error code.
*/
private fun syncError(result: JSONObject): AppError {
- when (result.optString("errorKey")) {
+ when (result.optString("logoutReason")) {
"clientVersionNotSupported" -> return AppError.ClientVersionNotSupported()
"serverVersionNotSupported" -> return AppError.ServerVersionNotSupported()
"sessionExpired" -> return AppError.SessionExpired()
diff --git a/apps/mobile-app/app/login.tsx b/apps/mobile-app/app/login.tsx
index 9098e4a80..f9bc37025 100644
--- a/apps/mobile-app/app/login.tsx
+++ b/apps/mobile-app/app/login.tsx
@@ -1,7 +1,6 @@
import { Buffer } from 'buffer';
-import { apiErrorCodeOf } from '@aliasvault/client/api/errors/ApiRequestError';
-import { ClientUpgradeRequiredError } from '@aliasvault/client/api/errors/ClientUpgradeRequiredError';
+import { describeAuthError, formatErrorMessage } from '@aliasvault/client/auth/AuthErrorMessage';
import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';
import { SrpLoginService } from '@aliasvault/client/auth/SrpLoginService';
import { MaterialIcons } from '@expo/vector-icons';
@@ -11,7 +10,6 @@ import React, { useState, useEffect, useRef } from 'react';
import { StyleSheet, View, Text, TextInput, ActivityIndicator, Animated, ScrollView, KeyboardAvoidingView, Platform, Dimensions } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
-import { apiErrorMessage } from '@/utils/ApiErrors';
import { useApiUrl } from '@/utils/ApiUrlUtility';
import { AppUnlockUtility } from '@/utils/AppUnlockUtility';
import EncryptionUtility from '@/utils/EncryptionUtility';
@@ -157,6 +155,21 @@ export default function LoginScreen() : React.ReactNode {
const srpUtil = new SrpLoginService(webApi);
+ /**
+ * The message for a failed login: the shared auth error message, with the self-hosted variant of the server error.
+ * @param err - the thrown error
+ */
+ const loginErrorMessage = async (err: unknown): Promise<string> => {
+ if (err instanceof LocalAuthError) {
+ return err.message;
+ }
+ const message = await describeAuthError(err);
+ if (message.key === 'common.errors.serverError' && await webApi.isSelfHosted()) {
+ return t('auth.errors.serverErrorSelfHosted');
+ }
+ return formatErrorMessage(message, t);
+ };
+
/**
* Process the vault response by storing the vault and logging in the user.
* @param token - The token to use for the vault
@@ -432,22 +445,8 @@ export default function LoginScreen() : React.ReactNode {
initiateLoginResponse
);
} catch (err) {
- if (err instanceof ClientUpgradeRequiredError) {
- // Server refused this app version; show the notice translated, keyed on its error code.
- console.error('Client upgrade required:', err);
- setError(t('vault.errors.versionNotSupported'));
- } else if (apiErrorCodeOf(err)) {
- console.error('Login refused:', err);
- setError(apiErrorMessage(err, t, t('common.errors.serverError')));
- } else if (err instanceof LocalAuthError) {
- console.error('Network/SSL error:', err);
- setError((err as LocalAuthError).message);
- } else {
- console.error('Login error:', err);
- // Check if self-hosted to show appropriate server error message
- const isSelfHosted = await webApi.isSelfHosted();
- setError(isSelfHosted ? t('auth.errors.serverErrorSelfHosted') : t('common.errors.serverError'));
- }
+ console.error('Login error:', err);
+ setError(await loginErrorMessage(err));
setIsLoading(false);
setLoginStatus(null);
}
@@ -495,18 +494,7 @@ export default function LoginScreen() : React.ReactNode {
);
} catch (err) {
console.error('2FA error:', err);
- if (err instanceof ClientUpgradeRequiredError) {
- // Server refused this app version; show the notice translated, keyed on its error code.
- setError(t('vault.errors.versionNotSupported'));
- } else if (apiErrorCodeOf(err)) {
- setError(apiErrorMessage(err, t, t('common.errors.serverError')));
- } else if (err instanceof LocalAuthError) {
- setError((err as Error).message);
- } else {
- // Check if self-hosted to show appropriate server error message
- const isSelfHosted = await webApi.isSelfHosted();
- setError(t(isSelfHosted ? 'auth.errors.serverErrorSelfHosted' : 'common.errors.serverError'));
- }
+ setError(await loginErrorMessage(err));
setIsLoading(false);
}
};
diff --git a/apps/mobile-app/app/unlock.tsx b/apps/mobile-app/app/unlock.tsx
index 5492e6d34..45617695c 100644
--- a/apps/mobile-app/app/unlock.tsx
+++ b/apps/mobile-app/app/unlock.tsx
@@ -1,4 +1,6 @@
+import { AppErrorCode, formatErrorWithCode, getAppErrorCode, getErrorTranslationKey } from '@aliasvault/client/api/errors/AppErrorCodes';
import { VaultVersionIncompatibleError } from '@aliasvault/client/api/errors/VaultVersionIncompatibleError';
+import { describeAuthError, formatErrorMessage } from '@aliasvault/client/auth/AuthErrorMessage';
import * as Haptics from 'expo-haptics';
import { LinearGradient } from 'expo-linear-gradient';
import { router } from 'expo-router';
@@ -7,7 +9,6 @@ import { StyleSheet, View, KeyboardAvoidingView, Platform, ScrollView, Dimension
import { AppUnlockUtility } from '@/utils/AppUnlockUtility';
import { HapticsUtility } from '@/utils/HapticsUtility';
-import { AppErrorCode, getAppErrorCode, getErrorTranslationKey, formatErrorWithCode } from '@/utils/types/errors/AppErrorCodes';
import { useColors } from '@/hooks/useColorScheme';
import { useLogout } from '@/hooks/useLogout';
@@ -24,14 +25,12 @@ import { useDb } from '@/context/DbContext';
import NativeVaultManager from '@/specs/NativeVaultManager';
/**
- * Whether a failed unlock means the entered password was wrong.
- * @param errorCode - the error code the unlock failed with
+ * The message for a failed unlock.
+ * @param err - the thrown error
+ * @param t - the translation function
*/
-async function isWrongUnlockKey(errorCode: AppErrorCode): Promise<boolean> {
- if (errorCode === AppErrorCode.UNLOCK_KEY_REJECTED) {
- return true;
- }
- return errorCode === AppErrorCode.VAULT_DECRYPT_FAILED && (await NativeVaultManager.getAccountKeyChain()) === null;
+async function unlockErrorMessage(err: unknown, t: (key: string) => string): Promise<string> {
+ return formatErrorMessage(await describeAuthError(err, { uncodedIsWrongPassword: true }), t);
}
/**
@@ -154,17 +153,10 @@ export default function UnlockScreen() : React.ReactNode {
}
console.error('Unlock error:', err);
- const errorCode = getAppErrorCode(err);
// Haptic feedback for authentication error
HapticsUtility.notification(Haptics.NotificationFeedbackType.Error);
-
- if (!errorCode || await isWrongUnlockKey(errorCode)) {
- setError(t('common.errors.wrongPassword'));
- } else {
- const translationKey = getErrorTranslationKey(errorCode);
- setError(formatErrorWithCode(t(translationKey), errorCode));
- }
+ setError(await unlockErrorMessage(err, t));
setIsLoading(false);
}
} else {
@@ -241,20 +233,9 @@ export default function UnlockScreen() : React.ReactNode {
return;
}
- // Try to extract error code from the error
- const errorCode = getAppErrorCode(err);
-
// Haptic feedback for authentication error
HapticsUtility.notification(Haptics.NotificationFeedbackType.Error);
-
- if (!errorCode || await isWrongUnlockKey(errorCode)) {
- // Treat as incorrect password - show error and allow retry
- setError(t('common.errors.wrongPassword'));
- } else {
- // Other error codes: show the formatted message with raw error code
- const translationKey = getErrorTranslationKey(errorCode);
- setError(formatErrorWithCode(t(translationKey), errorCode));
- }
+ setError(await unlockErrorMessage(err, t));
} finally {
setIsLoading(false);
}
@@ -322,7 +303,7 @@ export default function UnlockScreen() : React.ReactNode {
// Check if this is a cancellation - don't show error, just allow retry
const errorCode = getAppErrorCode(err);
- if (errorCode === 'E-509') { // BIOMETRIC_CANCELLED
+ if (errorCode === AppErrorCode.BIOMETRIC_CANCELLED) {
// User cancelled - don't show error, just stay on screen
return;
}
diff --git a/apps/mobile-app/app/upgrade.tsx b/apps/mobile-app/app/upgrade.tsx
index aa3b59950..d0b9e9c37 100644
--- a/apps/mobile-app/app/upgrade.tsx
+++ b/apps/mobile-app/app/upgrade.tsx
@@ -1,3 +1,4 @@
+import { AppErrorCode, extractErrorCode, formatErrorWithCode, getErrorTranslationKey } from '@aliasvault/client/api/errors/AppErrorCodes';
import { VaultVersionIncompatibleError } from '@aliasvault/client/api/errors/VaultVersionIncompatibleError';
import { AppInfo } from '@aliasvault/client/platform/AppInfo';
import { DEFAULT_VAULT_MUTATION_SCOPE } from '@aliasvault/client/sync/VaultMutationScope';
@@ -9,8 +10,6 @@ import { useState, useEffect, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { StyleSheet, View, KeyboardAvoidingView, Platform, ScrollView, Dimensions, TouchableWithoutFeedback, Keyboard, Text } from 'react-native';
-import { AppErrorCode, extractErrorCode, formatErrorWithCode, getErrorTranslationKey } from '@/utils/types/errors/AppErrorCodes';
-
import { useColors } from '@/hooks/useColorScheme';
import { useLogout } from '@/hooks/useLogout';
diff --git a/apps/mobile-app/app/vault-error.tsx b/apps/mobile-app/app/vault-error.tsx
index 49dcd0bc7..6200191d9 100644
--- a/apps/mobile-app/app/vault-error.tsx
+++ b/apps/mobile-app/app/vault-error.tsx
@@ -5,7 +5,6 @@ import { useState, useCallback, useEffect } from 'react';
import { StyleSheet, View, ScrollView, Dimensions, Text, Platform } from 'react-native';
import { copyToClipboard } from '@/utils/ClipboardUtility';
-import { isVaultLockedError } from '@/utils/types/errors/AppErrorCodes';
import { useColors } from '@/hooks/useColorScheme';
import { useLogout } from '@/hooks/useLogout';
@@ -16,6 +15,15 @@ import { ThemedText } from '@/components/themed/ThemedText';
import { ThemedView } from '@/components/themed/ThemedView';
import { RobustPressable } from '@/components/ui/RobustPressable';
+/**
+ * Detect a "vault locked" error, i.e. the in-memory database has been cleared (auto-lock timeout, vault evicted from memory).
+ * @param error - the error or its message
+ */
+function isVaultLockedError(error: unknown): boolean {
+ const message = error instanceof Error ? error.message : typeof error === 'string' ? error : '';
+ return message.includes('Database not initialized');
+}
+
/**
* Vault error screen displayed when the app encounters an unrecoverable error
* during vault initialization or bootstrap.
diff --git a/apps/mobile-app/context/AppContext.tsx b/apps/mobile-app/context/AppContext.tsx
index a3bbf411d..ad2d57994 100644
--- a/apps/mobile-app/context/AppContext.tsx
+++ b/apps/mobile-app/context/AppContext.tsx
@@ -4,7 +4,7 @@ import { router } from 'expo-router';
import { useAuth } from '@/context/AuthContext';
import { useWebApi } from '@/context/WebApiContext';
-import { logoutEventEmitter } from '@/events/LogoutEventEmitter';
+import { logoutEventEmitter } from '@aliasvault/client/api/LogoutEventEmitter';
import i18n from '@/i18n';
@@ -68,8 +68,8 @@ export const AppProvider: React.FC<{ children: React.ReactNode }> = ({ children
* Subscribe to logout events from WebApiService.
*/
useEffect(() => {
- const unsubscribe = logoutEventEmitter.subscribe(async (errorKey: string) => {
- await logout(i18n.t(errorKey));
+ const unsubscribe = logoutEventEmitter.subscribe(async (messageKey) => {
+ await logout(i18n.t(messageKey));
});
return unsubscribe;
diff --git a/apps/mobile-app/events/LogoutEventEmitter.ts b/apps/mobile-app/events/LogoutEventEmitter.ts
deleted file mode 100644
index b18d3adc2..000000000
--- a/apps/mobile-app/events/LogoutEventEmitter.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-type LogoutListener = (errorMessage: string) => void | Promise<void>;
-
-/**
- * Simple event emitter for logout events to avoid circular dependencies
- * between WebApiService and Auth contexts.
- */
-class LogoutEventEmitter {
- private listeners: Set<LogoutListener> = new Set();
-
- /**
- * Subscribe to logout events.
- * Returns an unsubscribe function.
- */
- public subscribe(listener: LogoutListener): () => void {
- this.listeners.add(listener);
- return () => {
- this.listeners.delete(listener);
- };
- }
-
- /**
- * Emit a logout event to all listeners.
- *
- * @param errorTranslationKey - The translation key of the error message to emit.
- */
- public emit(errorTranslationKey: string): void {
- this.listeners.forEach(listener => {
- try {
- listener(errorTranslationKey);
- } catch (error) {
- console.error('Error in logout listener:', error);
- }
- });
- }
-}
-
-// Export singleton instance
-export const logoutEventEmitter = new LogoutEventEmitter();
diff --git a/apps/mobile-app/hooks/useVaultMutate.ts b/apps/mobile-app/hooks/useVaultMutate.ts
index d7bcaaf8e..9847a49a1 100644
--- a/apps/mobile-app/hooks/useVaultMutate.ts
+++ b/apps/mobile-app/hooks/useVaultMutate.ts
@@ -13,7 +13,7 @@ import { DEFAULT_VAULT_MUTATION_SCOPE } from '@aliasvault/client/sync/VaultMutat
import { useVaultSync } from '@/hooks/useVaultSync';
-import { AppErrorCode, formatErrorWithCode } from '@/utils/types/errors/AppErrorCodes';
+import { AppErrorCode, formatErrorWithCode } from '@aliasvault/client/api/errors/AppErrorCodes';
import { PayloadTooLargeError } from '@aliasvault/client/api/errors/PayloadTooLargeError';
import { useApp } from '@/context/AppContext';
diff --git a/apps/mobile-app/hooks/useVaultSync.ts b/apps/mobile-app/hooks/useVaultSync.ts
index f88dde9a7..f836d5553 100644
--- a/apps/mobile-app/hooks/useVaultSync.ts
+++ b/apps/mobile-app/hooks/useVaultSync.ts
@@ -14,7 +14,8 @@ import {
extractErrorCode,
formatErrorWithCode,
getErrorTranslationKey,
-} from '@/utils/types/errors/AppErrorCodes';
+ isErrorCode,
+} from '@aliasvault/client/api/errors/AppErrorCodes';
/**
* Sync state tracking for race detection and offline support.
@@ -98,7 +99,8 @@ export const useVaultSync = (): {
// Handle logout requirement from status check
if (statusCheck.requiresLogout) {
- const errorMessage = statusCheck.errorKey ? t(getErrorTranslationKey(extractErrorCode(statusCheck.errorKey) ?? AppErrorCode.UNKNOWN_ERROR)) : undefined;
+ const errorCode = statusCheck.errorCode && isErrorCode(statusCheck.errorCode) ? statusCheck.errorCode : AppErrorCode.UNKNOWN_ERROR;
+ const errorMessage = statusCheck.errorCode ? t(getErrorTranslationKey(errorCode)) : undefined;
await app.logout(errorMessage);
return false;
}
@@ -209,9 +211,9 @@ export const useVaultSync = (): {
}
// Extract the specific error code from native layer if available
- // This preserves detailed error info (E-501 to E-511) for debugging
+ // This preserves detailed error info for debugging
const nativeErrorCode = getAppErrorCode(err);
- const errorCode = nativeErrorCode ?? AppErrorCode.NATIVE_UNLOCK_FAILED;
+ const errorCode = nativeErrorCode ?? AppErrorCode.VAULT_UNLOCK_FAILED;
console.error(`Failed to unlock vault (${errorCode}):`, err);
diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
index de939bcf1..f3716a68a 100644
--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
@@ -745,7 +745,7 @@ public class VaultManager: NSObject {
"hasDirtyChanges": versionCheck.syncState.isDirty,
"isOffline": false,
"requiresLogout": false,
- "errorKey": NSNull()
+ "errorCode": NSNull()
]
resolve(response)
}
@@ -753,7 +753,7 @@ public class VaultManager: NSObject {
await MainActor.run {
// Check for specific error types that require logout
let requiresLogout = error.isAuthenticationError || error.isVersionError
- let errorKey = error.translationKey
+ let errorCode = error.code
// Check if offline
let isOffline = error.isNetworkError
@@ -765,7 +765,7 @@ public class VaultManager: NSObject {
"hasDirtyChanges": syncState.isDirty,
"isOffline": true,
"requiresLogout": false,
- "errorKey": NSNull()
+ "errorCode": NSNull()
]
resolve(response)
} else {
@@ -775,7 +775,7 @@ public class VaultManager: NSObject {
"hasDirtyChanges": false,
"isOffline": false,
"requiresLogout": requiresLogout,
- "errorKey": errorKey as Any
+ "errorCode": errorCode
]
resolve(response)
}
@@ -788,7 +788,7 @@ public class VaultManager: NSObject {
"hasDirtyChanges": false,
"isOffline": false,
"requiresLogout": false,
- "errorKey": NSNull()
+ "errorCode": NSNull()
]
resolve(response)
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Enums/AppError.swift b/apps/mobile-app/ios/VaultStoreKit/Enums/AppError.swift
index 4ff02a603..bed827b5f 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Enums/AppError.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Enums/AppError.swift
@@ -85,87 +85,77 @@ public enum AppError: Error {
case syncCodecFailed(message: String)
case syncEngineFailed(message: String)
- /// Get the error code string for React Native bridge
- ///
- /// Error codes use the E-XXX format for easy user reporting:
- /// - E-1xx: Authentication errors
- /// - E-2xx: Network/connectivity errors
- /// - E-3xx: Version/compatibility errors
- /// - E-4xx: Vault status errors
- /// - E-5xx: Decryption/Encryption errors
- /// - E-6xx: Database/Storage errors
- /// - E-7xx: Merge errors
- /// - E-8xx: Upload errors
- /// - E-9xx: Native module errors
- /// - E-0xx: Generic errors
+ /// Get the error code string for React Native bridge, in the E-XXX format for easy user reporting.
+ /// The codes are shared by every client: `AppErrorCode` in core/client/src/api/errors/AppErrorCodes.ts is the registry,
+ /// so add a new code there first and never reuse a number.
public var code: String {
switch self {
case .authenticationFailed:
- return "E-101"
+ return "E-104"
case .sessionExpired:
- return "E-102"
+ return "E-105"
case .passwordChanged:
- return "E-103"
+ return "E-106"
case .serverUnavailable:
- return "E-201"
+ return "E-505"
case .networkError:
- return "E-202"
+ return "E-003"
case .serverError:
- return "E-204"
+ return "E-506"
case .clientVersionNotSupported:
- return "E-301"
+ return "E-904"
case .serverVersionNotSupported:
- return "E-302"
+ return "E-905"
case .vaultVersionIncompatible:
- return "E-303"
+ return "E-902"
case .serverUpdateRequired:
- return "E-304"
+ return "E-903"
case .vaultMergeRequired:
- return "E-401"
+ return "E-907"
case .vaultOutdated:
- return "E-402"
+ return "E-906"
case .syncVaultFetchFailed:
- return "E-404"
+ return "E-502"
case .vaultDecryptFailed:
- return "E-501"
+ return "E-203"
case .encryptionKeyNotFound:
- return "E-502"
+ return "E-202"
case .base64DecodeFailed:
- return "E-503"
+ return "E-606"
case .databaseTempWriteFailed:
- return "E-504"
+ return "E-607"
case .databaseOpenFailed:
- return "E-505"
+ return "E-608"
case .databaseMemoryFailed:
- return "E-506"
+ return "E-609"
case .databaseBackupFailed:
- return "E-507"
+ return "E-610"
case .databasePragmaFailed:
- return "E-508"
+ return "E-611"
case .biometricCancelled:
- return "E-509"
+ return "E-209"
case .biometricFailed:
- return "E-510"
+ return "E-210"
case .keystoreKeyNotFound:
- return "E-511"
+ return "E-211"
case .keychainAccessDenied:
- return "E-512"
+ return "E-212"
case .keychainItemNotFound:
- return "E-513"
+ return "E-213"
case .biometricNotAvailable:
- return "E-514"
+ return "E-214"
case .biometricNotEnrolled:
- return "E-515"
+ return "E-215"
case .biometricLockout:
- return "E-516"
+ return "E-216"
case .unlockKeyRejected:
- return "E-517"
+ return "E-206"
case .keyChainUnreadable:
- return "E-518"
+ return "E-207"
case .keyOutOfSync:
- return "E-519"
+ return "E-208"
case .serverVaultDecryptFailed:
- return "E-520"
+ return "E-503"
case .storageReadFailed:
return "E-601"
case .storageWriteFailed:
@@ -173,13 +163,13 @@ public enum AppError: Error {
case .databaseInitFailed:
return "E-603"
case .vaultStoreFailed:
- return "E-604"
+ return "E-504"
case .manifestNotRecorded:
return "E-605"
case .vaultMergeFailed:
return "E-701"
case .mergeUploadFailed:
- return "E-705"
+ return "E-703"
case .vaultUploadFailed:
return "E-801"
case .vaultTooLarge:
@@ -187,19 +177,19 @@ public enum AppError: Error {
case .vaultSyncTimeout:
return "E-805"
case .maxRetriesReached:
- return "E-901"
+ return "E-702"
case .migrationCheckFailed:
- return "E-903"
+ return "E-901"
case .unknownError:
return "E-001"
case .parseError:
- return "E-002"
+ return "E-004"
case .syncResponseInvalid:
- return "E-003"
+ return "E-507"
case .syncCodecFailed:
- return "E-004"
+ return "E-508"
case .syncEngineFailed:
- return "E-005"
+ return "E-509"
}
}
@@ -338,9 +328,4 @@ public enum AppError: Error {
return false
}
}
-
- /// Get the translation key for this error (error code format for lookup in translation files).
- public var translationKey: String? {
- return code
- }
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift
index af60b3285..25daec475 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift
@@ -205,7 +205,7 @@ internal final class VaultSync {
/// The engine's failure as the native error: a forced logout by its reason, else by its error code.
private static func syncError(from result: [String: Any]) -> AppError {
- if let reason = result["errorKey"] as? String, let error = logoutErrors[reason] {
+ if let reason = result["logoutReason"] as? String, let error = logoutErrors[reason] {
return error
}
// The engine's message is diagnostic detail; the code decides what the user sees.
diff --git a/apps/mobile-app/platform/MobilePlatform.ts b/apps/mobile-app/platform/MobilePlatform.ts
index 2f9beabcd..b914d3fa8 100644
--- a/apps/mobile-app/platform/MobilePlatform.ts
+++ b/apps/mobile-app/platform/MobilePlatform.ts
@@ -1,19 +1,13 @@
-import { setPlatform, TranslatableMessage, unavailableService } from '@aliasvault/client/platform';
+import { setPlatform, unavailableService } from '@aliasvault/client/platform';
import type { IClientPlatform, IKeyValueStore, ISqliteEngine } from '@aliasvault/client/platform';
+import type { TranslationKey } from '@aliasvault/i18n';
import i18n from '@/i18n';
import { nativeRustCore } from '@/platform/NativeRustCore';
+import NativeVaultManager from '@/specs/NativeVaultManager';
import { MobileAppIdentity } from '@/utils/AppInfo';
-/**
- * Which translation key backs each of the client core's own messages.
- */
-const TRANSLATION_KEYS: Record<TranslatableMessage, string> = {
- [TranslatableMessage.ClientOutdated]: 'vault.errors.appOutdated',
- [TranslatableMessage.VaultUpgradeRequired]: 'vault.errors.vaultOutdated',
-};
-
/*
* Only the client core's repositories and Rust wrappers run on mobile. Tokens, sync state and the vault itself live
* in native storage and the vault database is native too, so the core's key-value storage and in-JS SQLite engine
@@ -54,9 +48,13 @@ const mobilePlatform: IClientPlatform = {
rustCore: nativeRustCore,
sqlite: unavailableService<ISqliteEngine>('SQLite engine'),
/**
- * Translate one of the core's own messages through the app's i18n.
+ * Translate a shared message through the app's i18n.
+ */
+ translate: async (key: TranslationKey): Promise<string> => i18n.t(key),
+ /**
+ * Whether this device holds a key chain; the app keeps it in native storage.
*/
- translate: async (message: TranslatableMessage): Promise<string> => i18n.t(TRANSLATION_KEYS[message]),
+ hasLocalVaultKey: async (): Promise<boolean> => (await NativeVaultManager.getAccountKeyChain()) !== null,
/**
* The app's UI language.
*/
diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.ts
index 5b352b939..46b5482b8 100644
--- a/apps/mobile-app/specs/NativeVaultManager.ts
+++ b/apps/mobile-app/specs/NativeVaultManager.ts
@@ -39,7 +39,7 @@ export interface Spec extends TurboModule {
runSharingOperation(operation: string, paramsJson: string): Promise<{ success: boolean; apiErrorCode: string | null; vaultUpgradeRequired: boolean; error: string | null; errorMessage: string | null }>;
// Quick check if sync is needed
- checkSyncStatus(): Promise<{ success: boolean; hasNewerVault: boolean; hasDirtyChanges: boolean; isOffline: boolean; requiresLogout: boolean; errorKey: string | null }>;
+ checkSyncStatus(): Promise<{ success: boolean; hasNewerVault: boolean; hasDirtyChanges: boolean; isOffline: boolean; requiresLogout: boolean; errorCode: string | null }>;
// Logs of the recent sync engine runs, for the developer tools.
getVaultSyncLogs(): Promise<string>;
diff --git a/apps/mobile-app/utils/ApiErrors.ts b/apps/mobile-app/utils/ApiErrors.ts
deleted file mode 100644
index 542eac341..000000000
--- a/apps/mobile-app/utils/ApiErrors.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { apiErrorCodeOf } from '@aliasvault/client/api/errors/ApiRequestError';
-
-import type { TFunction } from 'i18next';
-
-/**
- * The message for a failed API call: the translated API error code when the server sent one, else the fallback.
- * @param error - the thrown error
- * @param t - the translation function
- * @param fallback - the message when no known code is present
- */
-export function apiErrorMessage(error: unknown, t: TFunction, fallback: string): string {
- const code = apiErrorCodeOf(error);
- if (code) {
- const key = `apiErrors.${code}`;
- const translated = t(key);
- return translated === key ? fallback : translated;
- }
- return fallback;
-}
diff --git a/apps/mobile-app/utils/SqliteClient.ts b/apps/mobile-app/utils/SqliteClient.ts
index 6b56bfcc5..53d8a3c2e 100644
--- a/apps/mobile-app/utils/SqliteClient.ts
+++ b/apps/mobile-app/utils/SqliteClient.ts
@@ -248,7 +248,7 @@ class SqliteClient {
const compatibilityResult = checkVersionCompatibility(databaseVersion);
if (!compatibilityResult.isCompatible) {
- throw new VaultVersionIncompatibleError('vault.errors.appOutdated');
+ throw new VaultVersionIncompatibleError('common.errors.clientOutdated');
}
// If the version is known, return the full version info
diff --git a/apps/mobile-app/utils/WebApiService.ts b/apps/mobile-app/utils/WebApiService.ts
index d8802df65..2846e20f3 100644
--- a/apps/mobile-app/utils/WebApiService.ts
+++ b/apps/mobile-app/utils/WebApiService.ts
@@ -9,7 +9,7 @@ import { ApiRequestError } from '@aliasvault/client/api/errors/ApiRequestError';
import { ClientUpgradeRequiredError } from '@aliasvault/client/api/errors/ClientUpgradeRequiredError';
import { LocalAuthError } from './types/errors/LocalAuthError';
import { PayloadTooLargeError } from '@aliasvault/client/api/errors/PayloadTooLargeError';
-import { logoutEventEmitter } from '@/events/LogoutEventEmitter';
+import { logoutEventEmitter } from '@aliasvault/client/api/LogoutEventEmitter';
import NativeVaultManager from '@/specs/NativeVaultManager';
type RequestInit = globalThis.RequestInit;
@@ -88,8 +88,8 @@ export class WebApiService {
// If native layer returns 401 session is truly expired (native layer already attempted token refresh automatically).
if (response.statusCode === 401) {
- logoutEventEmitter.emit('auth.errors.sessionExpired');
- throw new Error(i18n.t('auth.errors.sessionExpired'));
+ logoutEventEmitter.emit('common.errors.sessionExpired');
+ throw new Error(i18n.t('common.errors.sessionExpired'));
}
// Server refused this client version.
@@ -239,8 +239,8 @@ export class WebApiService {
// Handle auth errors
if (response.statusCode === 401) {
- logoutEventEmitter.emit('auth.errors.sessionExpired');
- throw new Error(i18n.t('auth.errors.sessionExpired'));
+ logoutEventEmitter.emit('common.errors.sessionExpired');
+ throw new Error(i18n.t('common.errors.sessionExpired'));
}
if (response.statusCode >= 400) {
@@ -324,7 +324,7 @@ export class WebApiService {
* If session expired, logout the user immediately as otherwise this would
* trigger a server offline banner.
*/
- logoutEventEmitter.emit('auth.errors.sessionExpired');
+ logoutEventEmitter.emit('common.errors.sessionExpired');
throw error;
}
diff --git a/apps/mobile-app/utils/types/errors/AppErrorCodes.ts b/apps/mobile-app/utils/types/errors/AppErrorCodes.ts
deleted file mode 100644
index ff0eb5fb8..000000000
--- a/apps/mobile-app/utils/types/errors/AppErrorCodes.ts
+++ /dev/null
@@ -1,284 +0,0 @@
-/**
- * App error codes for mobile app operations.
- *
- * These codes serve two purposes:
- * 1. Enable multi-language support by mapping codes to translation keys
- * 2. Provide debugging information when users report "unknown errors"
- *
- * When displayed to users, show: "Error occurred (Code: E-XXX)"
- * This allows users to report the code for debugging while keeping messages translatable.
- *
- * Code ranges:
- * - E-0xx: Generic errors
- * - E-1xx: Authentication errors
- * - E-2xx: Network/connectivity errors
- * - E-3xx: Version/compatibility errors
- * - E-4xx: Vault status errors
- * - E-5xx: Decryption/Encryption errors
- * - E-6xx: Database/Storage errors
- * - E-7xx: Merge errors
- * - E-8xx: Upload errors
- * - E-9xx: Native module errors
- */
-export enum AppErrorCode {
- // Generic errors (E-0xx) - from AppError.kt
- UNKNOWN_ERROR = 'E-001',
- PARSE_ERROR = 'E-002',
- SYNC_RESPONSE_INVALID = 'E-003', // Sync engine: a server response is not the JSON shape the client expects
- SYNC_CODEC_FAILED = 'E-004', // Sync engine: the core library (codec, merge or crypto) refused the vault data
- SYNC_ENGINE_FAILED = 'E-005', // Sync engine: a state it has no rule for (the detail says which)
-
- // Authentication errors (E-1xx) - from AppError.kt
- AUTHENTICATION_FAILED = 'E-101',
- SESSION_EXPIRED = 'E-102',
- PASSWORD_CHANGED = 'E-103',
-
- // Network/connectivity errors (E-2xx) - from AppError.kt
- SERVER_UNAVAILABLE = 'E-201',
- NETWORK_ERROR = 'E-202',
- SERVER_ERROR = 'E-204', // The server answered a sync request with an unexpected HTTP failure
-
- // Version/compatibility errors (E-3xx) - from AppError.kt
- CLIENT_VERSION_NOT_SUPPORTED = 'E-301',
- SERVER_VERSION_NOT_SUPPORTED = 'E-302',
- VAULT_VERSION_INCOMPATIBLE = 'E-303',
- SERVER_UPDATE_REQUIRED = 'E-304',
-
- // Vault status errors (E-4xx) - from AppError.kt + VaultSync.kt
- VAULT_MERGE_REQUIRED = 'E-401',
- VAULT_OUTDATED = 'E-402',
- VAULT_NOT_FOUND = 'E-403', // VaultSync.kt: no local vault for merge
- SYNC_VAULT_FETCH_FAILED = 'E-404', // Sync engine: the server's vault snapshot cannot be assembled
-
- // Decryption/Encryption errors (E-5xx) - from AppError.kt
- VAULT_DECRYPT_FAILED = 'E-501', // AppError: the locally stored vault does not decrypt with the session key
- ENCRYPTION_KEY_NOT_FOUND = 'E-502', // AppError: encryption key not available
- BASE64_DECODE_FAILED = 'E-503', // AppError: base64 decode failed after decryption
- DATABASE_TEMP_WRITE_FAILED = 'E-504', // AppError: could not write temp file
- DATABASE_OPEN_FAILED = 'E-505', // AppError: could not open source database
- DATABASE_MEMORY_FAILED = 'E-506', // AppError: could not create in-memory connection
- DATABASE_BACKUP_FAILED = 'E-507', // AppError: backup/copy failed
- DATABASE_PRAGMA_FAILED = 'E-508', // AppError: pragma execution failed
- BIOMETRIC_CANCELLED = 'E-509', // AppError: biometric authentication cancelled
- BIOMETRIC_FAILED = 'E-510', // AppError: biometric authentication failed
- KEYSTORE_KEY_NOT_FOUND = 'E-511', // AppError: encryption key not found in keystore
- KEYCHAIN_ACCESS_DENIED = 'E-512', // iOS: keychain access denied (entitlement or access group issue)
- KEYCHAIN_ITEM_NOT_FOUND = 'E-513', // iOS: keychain item not found (may need re-login)
- BIOMETRIC_NOT_AVAILABLE = 'E-514', // iOS: biometric not available on device
- BIOMETRIC_NOT_ENROLLED = 'E-515', // iOS: no biometrics enrolled on device
- BIOMETRIC_LOCKOUT = 'E-516', // iOS: biometric locked out due to too many failed attempts
- UNLOCK_KEY_REJECTED = 'E-517', // AppError: the unlock key does not open the account key (wrong password or PIN)
- KEY_CHAIN_UNREADABLE = 'E-518', // AppError: the account key opened, the vault encryption key under it did not
- KEY_OUT_OF_SYNC = 'E-519', // Sync engine: the session key does not open the key chain the server holds (re-login needed)
- SERVER_VAULT_DECRYPT_FAILED = 'E-520', // Sync engine: a server manifest or bucket fails its hash check or does not decrypt
-
- // Database/Storage errors (E-6xx) - from VaultSync.kt
- STORAGE_READ_FAILED = 'E-601', // Sync engine: a state, database or at-rest vault read failed
- STORAGE_WRITE_FAILED = 'E-602', // Sync engine: a state, database or at-rest vault write failed
- DATABASE_INIT_FAILED = 'E-603', // Sync engine: the staging database could not be opened
- VAULT_STORE_FAILED = 'E-604', // AppError: failed to store vault
- MANIFEST_NOT_RECORDED = 'E-605', // AppError: native write attempted before a personal manifest id was recorded
-
- // Merge errors (E-7xx) - from VaultSync.kt
- MERGE_FAILED = 'E-701', // AppError: vault merge failed
- MERGE_UPLOAD_FAILED = 'E-705', // AppError: upload after merge failed
-
- // Upload errors (E-8xx) - from VaultSync.kt
- UPLOAD_FAILED = 'E-801', // AppError: vault upload failed
- UPLOAD_TOO_LARGE = 'E-804', // Server rejected upload with HTTP 413 (vault exceeds MAX_UPLOAD_SIZE_MB)
- UPLOAD_TIMEOUT = 'E-805', // Sync engine: a vault transfer exceeded its request timeout (large vault or slow connection)
-
- // Native module/retry errors (E-9xx)
- MAX_RETRIES_REACHED = 'E-901', // AppError: max sync retries reached
- NATIVE_UNLOCK_FAILED = 'E-902', // useVaultSync.ts: vault unlock failed
- MIGRATION_CHECK_FAILED = 'E-903', // Sync engine: the vault migration check failed
-}
-
-/**
- * All valid error code values for quick lookup
- */
-const ERROR_CODE_VALUES = new Set(Object.values(AppErrorCode));
-
-/**
- * Check if a string is a valid error code (E-XXX format)
- */
-export function isErrorCode(code: string): code is AppErrorCode {
- return ERROR_CODE_VALUES.has(code as AppErrorCode);
-}
-
-/**
- * Check if an error is a vault sync error with a code property
- */
-export function isAppError(error: unknown): error is { code: string } {
- return (
- typeof error === 'object' &&
- error !== null &&
- 'code' in error &&
- typeof (error as { code: unknown }).code === 'string' &&
- isErrorCode((error as { code: string }).code)
- );
-}
-
-/**
- * Get the vault sync error code from an error object or string
- */
-export function getAppErrorCode(error: unknown): AppErrorCode | null {
- // Check if error object has code property
- if (isAppError(error)) {
- return error.code as AppErrorCode;
- }
-
- // Check if error message contains an error code
- if (error instanceof Error && error.message) {
- const code = extractErrorCode(error.message);
- if (code) {
- return code;
- }
- }
-
- // Check if it's a string that is or contains an error code
- if (typeof error === 'string') {
- if (isErrorCode(error)) {
- return error;
- }
- const code = extractErrorCode(error);
- if (code) {
- return code;
- }
- }
-
- return null;
-}
-
-/**
- * Detect a "vault locked" error — i.e. the in-memory database has been cleared
- * (auto-lock timeout, vault evicted from memory).
- */
-export function isVaultLockedError(error: unknown): boolean {
- const message =
- error instanceof Error
- ? error.message
- : typeof error === 'string'
- ? error
- : '';
- return message.includes('Database not initialized');
-}
-
-/**
- * Extract error code from a string (e.g., "Error occurred (Code: E-501)" -> "E-501")
- */
-export function extractErrorCode(message: string): AppErrorCode | null {
- // Match E-XXX pattern
- const match = message.match(/E-\d{3}/);
- if (match && isErrorCode(match[0])) {
- return match[0] as AppErrorCode;
- }
- return null;
-}
-
-/**
- * Format an error message with an error code for user display.
- * This allows users to report the code for debugging while keeping the message readable.
- *
- * @param message - The user-friendly error message (translated)
- * @param code - The error code for debugging
- * @returns Formatted message like "Error occurred (Code: E-501)"
- */
-export function formatErrorWithCode(message: string, code: AppErrorCode): string {
- return `${message} (Code: ${code})`;
-}
-
-/**
- * Create an error with an attached code for proper error handling chain.
- */
-export class AppCodedError extends Error {
- public readonly code: AppErrorCode;
-
- constructor(message: string, code: AppErrorCode) {
- super(formatErrorWithCode(message, code));
- this.code = code;
- this.name = 'AppCodedError';
- }
-}
-
-/**
- * Map error codes to translation keys for localized error messages.
- * Returns the translation key that should be used with t() function.
- */
-export function getErrorTranslationKey(code: AppErrorCode): string {
- const codeToKeyMap: Record<AppErrorCode, string> = {
- // Generic errors
- [AppErrorCode.UNKNOWN_ERROR]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.PARSE_ERROR]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.SYNC_RESPONSE_INVALID]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.SYNC_CODEC_FAILED]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.SYNC_ENGINE_FAILED]: 'common.errors.unknownErrorTryAgain',
-
- // Authentication errors
- [AppErrorCode.AUTHENTICATION_FAILED]: 'auth.errors.sessionExpired',
- [AppErrorCode.SESSION_EXPIRED]: 'auth.errors.sessionExpired',
- [AppErrorCode.PASSWORD_CHANGED]: 'common.errors.passwordChanged',
-
- // Network errors
- [AppErrorCode.SERVER_UNAVAILABLE]: 'common.errors.serverError',
- [AppErrorCode.NETWORK_ERROR]: 'auth.errors.networkError',
- [AppErrorCode.SERVER_ERROR]: 'common.errors.serverError',
-
- // Version errors
- [AppErrorCode.CLIENT_VERSION_NOT_SUPPORTED]: 'vault.errors.versionNotSupported',
- [AppErrorCode.SERVER_VERSION_NOT_SUPPORTED]: 'vault.errors.serverVersionNotSupported',
- [AppErrorCode.VAULT_VERSION_INCOMPATIBLE]: 'vault.errors.appOutdated',
- [AppErrorCode.SERVER_UPDATE_REQUIRED]: 'vault.errors.serverVersionNotSupported',
-
- // Vault status errors
- [AppErrorCode.VAULT_MERGE_REQUIRED]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.VAULT_OUTDATED]: 'vault.errors.vaultOutdated',
- [AppErrorCode.VAULT_NOT_FOUND]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.SYNC_VAULT_FETCH_FAILED]: 'common.errors.unknownErrorTryAgain',
-
- // Decryption/Encryption errors
- [AppErrorCode.VAULT_DECRYPT_FAILED]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.ENCRYPTION_KEY_NOT_FOUND]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.BASE64_DECODE_FAILED]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.DATABASE_TEMP_WRITE_FAILED]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.DATABASE_OPEN_FAILED]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.DATABASE_MEMORY_FAILED]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.DATABASE_BACKUP_FAILED]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.DATABASE_PRAGMA_FAILED]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.BIOMETRIC_CANCELLED]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.BIOMETRIC_FAILED]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.KEYSTORE_KEY_NOT_FOUND]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.KEYCHAIN_ACCESS_DENIED]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.KEYCHAIN_ITEM_NOT_FOUND]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.BIOMETRIC_NOT_AVAILABLE]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.BIOMETRIC_NOT_ENROLLED]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.BIOMETRIC_LOCKOUT]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.UNLOCK_KEY_REJECTED]: 'common.errors.wrongPassword',
- [AppErrorCode.KEY_CHAIN_UNREADABLE]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.KEY_OUT_OF_SYNC]: 'auth.errors.sessionExpired',
- [AppErrorCode.SERVER_VAULT_DECRYPT_FAILED]: 'common.errors.unknownErrorTryAgain',
-
- // Database/Storage errors
- [AppErrorCode.STORAGE_READ_FAILED]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.STORAGE_WRITE_FAILED]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.DATABASE_INIT_FAILED]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.VAULT_STORE_FAILED]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.MANIFEST_NOT_RECORDED]: 'common.errors.unknownErrorTryAgain',
-
- // Merge errors
- [AppErrorCode.MERGE_FAILED]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.MERGE_UPLOAD_FAILED]: 'common.errors.unknownErrorTryAgain',
-
- // Upload errors
- [AppErrorCode.UPLOAD_FAILED]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.UPLOAD_TOO_LARGE]: 'common.errors.vaultTooLarge',
- [AppErrorCode.UPLOAD_TIMEOUT]: 'common.errors.vaultSyncTimeout',
-
- // Native module/retry errors
- [AppErrorCode.MAX_RETRIES_REACHED]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.NATIVE_UNLOCK_FAILED]: 'common.errors.unknownErrorTryAgain',
- [AppErrorCode.MIGRATION_CHECK_FAILED]: 'common.errors.unknownErrorTryAgain',
- };
-
- return codeToKeyMap[code] || 'common.errors.unknownErrorTryAgain';
-}
diff --git a/core/client/src/api/errors/AppErrorCodes.ts b/core/client/src/api/errors/AppErrorCodes.ts
index 3a5a8ffde..434698275 100644
--- a/core/client/src/api/errors/AppErrorCodes.ts
+++ b/core/client/src/api/errors/AppErrorCodes.ts
@@ -1,8 +1,12 @@
import type { TranslationKey } from '@aliasvault/i18n';
/**
- * The error codes of all AliasVault clients: web app, browser extension and mobile app and the Rust sync engine.
- *
+ * The main registry for error codes of all AliasVault clients: web app, browser extension and mobile app and the Rust sync engine.
+ *
+ * When adding or changing any error codes, also make sure to apply them to:
+ * - apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/AppError.kt
+ * - apps/mobile-app/ios/VaultStoreKit/Enums/AppError.swift
+ *
* These codes serve two purposes:
* 1. Enable multi-language support by mapping codes to translation keys
* 2. Provide debugging information for additional context when a user reports an error