Skip to content

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

Add AppErrorCodes handling to mobile apps (#1619)

Leendert de Borst2a95c0938818
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyFormFragment.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyFormFragment.kt
index c1a621b8f..ea6acb269 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyFormFragment.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyFormFragment.kt
@@ -875,38 +875,38 @@ class PasskeyFormFragment : Fragment() {
var title = getString(R.string.connection_error_title)
var message = getString(R.string.connection_error_message)
- // Check if it's a VaultSyncError and customize message accordingly
- if (error is net.aliasvault.app.vaultstore.VaultSyncError) {
+ // Check if it's a AppError and customize message accordingly
+ if (error is net.aliasvault.app.vaultstore.AppError) {
when (error) {
- is net.aliasvault.app.vaultstore.VaultSyncError.SessionExpired,
- is net.aliasvault.app.vaultstore.VaultSyncError.AuthenticationFailed,
+ is net.aliasvault.app.vaultstore.AppError.SessionExpired,
+ is net.aliasvault.app.vaultstore.AppError.AuthenticationFailed,
-> {
title = getString(R.string.session_expired_title)
message = getString(R.string.session_expired_message)
}
- is net.aliasvault.app.vaultstore.VaultSyncError.PasswordChanged -> {
+ is net.aliasvault.app.vaultstore.AppError.PasswordChanged -> {
title = getString(R.string.password_changed_title)
message = getString(R.string.password_changed_message)
}
- is net.aliasvault.app.vaultstore.VaultSyncError.ClientVersionNotSupported -> {
+ is net.aliasvault.app.vaultstore.AppError.ClientVersionNotSupported -> {
title = getString(R.string.version_not_supported_title)
message = getString(R.string.version_not_supported_message)
}
- is net.aliasvault.app.vaultstore.VaultSyncError.ServerVersionNotSupported -> {
+ is net.aliasvault.app.vaultstore.AppError.ServerVersionNotSupported -> {
title = getString(R.string.server_version_not_supported_title)
message = getString(R.string.server_version_not_supported_message)
}
- is net.aliasvault.app.vaultstore.VaultSyncError.ServerUnavailable -> {
+ is net.aliasvault.app.vaultstore.AppError.ServerUnavailable -> {
title = getString(R.string.server_unavailable_title)
message = getString(R.string.server_unavailable_message)
}
- is net.aliasvault.app.vaultstore.VaultSyncError.NetworkError,
- is net.aliasvault.app.vaultstore.VaultSyncError.Timeout,
+ is net.aliasvault.app.vaultstore.AppError.NetworkError,
+ is net.aliasvault.app.vaultstore.AppError.Timeout,
-> {
title = getString(R.string.network_error_title)
message = getString(R.string.network_error_message)
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/UnlockCoordinator.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/UnlockCoordinator.kt
index d4fb15f5f..eed09fa49 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/UnlockCoordinator.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/UnlockCoordinator.kt
@@ -5,6 +5,7 @@ import android.util.Log
import androidx.fragment.app.FragmentActivity
import net.aliasvault.app.R
import net.aliasvault.app.pinunlock.PinUnlockActivity
+import net.aliasvault.app.vaultstore.AppError
import net.aliasvault.app.vaultstore.VaultStore
import net.aliasvault.app.vaultstore.keystoreprovider.AndroidKeystoreProvider
import net.aliasvault.app.vaultstore.keystoreprovider.KeystoreOperationCallback
@@ -155,11 +156,12 @@ class UnlockCoordinator(
* Handle errors during biometric unlock (after successful keystore retrieval).
*/
private fun handleBiometricUnlockError(e: Exception) {
- val errorMessage = when {
- e.message?.contains("No encryption key found", ignoreCase = true) == true ->
- "Please unlock vault in the app first"
- e.message?.contains("Database setup error", ignoreCase = true) == true ->
- "Failed to decrypt vault"
+ val errorMessage = when (e) {
+ is AppError.KeystoreKeyNotFound -> "Please unlock vault in the app first"
+ is AppError.VaultDecryptFailed,
+ is AppError.DatabaseOpenFailed,
+ is AppError.DatabaseBackupFailed,
+ -> "Failed to decrypt vault"
else -> "Failed to unlock vault"
}
onError(errorMessage)
@@ -178,10 +180,8 @@ class UnlockCoordinator(
}
// No PIN fallback available - report the error
- val errorMessage = when {
- e.message?.contains("user canceled", ignoreCase = true) == true ||
- e.message?.contains("canceled", ignoreCase = true) == true ->
- "Authentication cancelled"
+ val errorMessage = when (e) {
+ is AppError.BiometricCancelled -> "Authentication cancelled"
else -> "Failed to retrieve encryption key"
}
onError(errorMessage)
@@ -191,11 +191,12 @@ class UnlockCoordinator(
* Get user-friendly error message for unlock errors.
*/
private fun getUnlockErrorMessage(e: Exception): String {
- return when {
- e.message?.contains("No encryption key found", ignoreCase = true) == true ->
- "Please unlock vault in the app first"
- e.message?.contains("Database setup error", ignoreCase = true) == true ->
- "Failed to decrypt vault"
+ return when (e) {
+ is AppError.KeystoreKeyNotFound -> "Please unlock vault in the app first"
+ is AppError.VaultDecryptFailed,
+ is AppError.DatabaseOpenFailed,
+ is AppError.DatabaseBackupFailed,
+ -> "Failed to decrypt vault"
else -> "Failed to unlock vault"
}
}
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 e1396ad9d..362390913 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
@@ -22,6 +22,7 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import net.aliasvault.app.qrscanner.QRScannerActivity
+import net.aliasvault.app.vaultstore.AppError
import net.aliasvault.app.vaultstore.VaultStore
import net.aliasvault.app.vaultstore.keystoreprovider.AndroidKeystoreProvider
import net.aliasvault.app.vaultstore.storageprovider.AndroidStorageProvider
@@ -192,9 +193,12 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
try {
vaultStore.unlockVault()
promise.resolve(null)
+ } catch (e: AppError) {
+ Log.e(TAG, "Error unlocking vault: ${e.code}", e)
+ promise.reject(e.code, e.message, e)
} catch (e: Exception) {
- Log.e(TAG, "Error storing encryption key", e)
- promise.reject("ERR_STORE_KEY", "Failed to store encryption key: ${e.message}", e)
+ Log.e(TAG, "Error unlocking vault", e)
+ promise.reject("E-001", "Failed to unlock vault: ${e.message}", e)
}
}
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
new file mode 100644
index 000000000..276c3a934
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/AppError.kt
@@ -0,0 +1,304 @@
+package net.aliasvault.app.vaultstore
+
+/**
+ * App error codes for mobile app operations.
+ * These error codes are language-independent and can be properly handled by the client.
+ *
+ * This is a Kotlin port of the iOS Swift implementation:
+ * - Reference: apps/mobile-app/ios/VaultStoreKit/Enums/AppErrorCodes.swift
+ *
+ * IMPORTANT: Keep all implementations synchronized. Changes to the public interface must be
+ * reflected in all ports. Error types and codes should remain consistent.
+ */
+sealed class AppError(message: String, cause: Throwable? = null) : Exception(message, cause) {
+ // Authentication errors
+ /**
+ * Error indicating authentication failed.
+ */
+ class AuthenticationFailed(
+ message: String = "Authentication failed",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ /**
+ * Error indicating session expired.
+ */
+ class SessionExpired(
+ message: String = "Session expired",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ /**
+ * Error indicating password has changed.
+ */
+ class PasswordChanged(
+ message: String = "Password has changed",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ // Network/connectivity errors
+ /**
+ * Error indicating server unavailable.
+ */
+ class ServerUnavailable(
+ /** The HTTP status code. */
+ val statusCode: Int,
+ message: String = "Server unavailable (status: $statusCode)",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ /**
+ * Error indicating network error.
+ */
+ class NetworkError(
+ /** The underlying error. */
+ val underlyingError: Throwable,
+ ) : AppError("Network error: ${underlyingError.message}", underlyingError)
+
+ /**
+ * Error indicating request timeout.
+ */
+ class Timeout(
+ message: String = "Request timeout",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ // Version/compatibility errors
+ /**
+ * Error indicating client version not supported.
+ */
+ class ClientVersionNotSupported(
+ message: String = "Client version not supported",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ /**
+ * Error indicating server version not supported.
+ */
+ class ServerVersionNotSupported(
+ message: String = "Server version not supported",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ /**
+ * Error indicating vault version incompatible.
+ */
+ class VaultVersionIncompatible(
+ message: String = "Vault version incompatible",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ // Vault status errors
+ /**
+ * Error indicating vault merge required.
+ */
+ class VaultMergeRequired(
+ message: String = "Vault merge required",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ /**
+ * Error indicating vault outdated.
+ */
+ class VaultOutdated(
+ message: String = "Vault outdated",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ // Decryption errors
+ /**
+ * Error indicating failed to decrypt vault.
+ */
+ class VaultDecryptFailed(
+ message: String = "Failed to decrypt vault",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ /**
+ * Error indicating base64 decode failed after decryption.
+ */
+ class Base64DecodeFailed(
+ message: String = "Base64 decode failed after decryption",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ /**
+ * Error indicating database setup failed - could not write temp file.
+ */
+ class DatabaseTempWriteFailed(
+ message: String = "Database setup failed: could not write temp file",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ /**
+ * Error indicating database setup failed - could not open source database.
+ */
+ class DatabaseOpenFailed(
+ message: String = "Database setup failed: could not open source database",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ /**
+ * Error indicating database setup failed - could not create in-memory connection.
+ */
+ class DatabaseMemoryFailed(
+ message: String = "Database setup failed: could not create in-memory connection",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ /**
+ * Error indicating database setup failed - backup/copy failed.
+ */
+ class DatabaseBackupFailed(
+ message: String = "Database setup failed: backup/copy failed",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ /**
+ * Error indicating database setup failed - pragma execution failed.
+ */
+ class DatabasePragmaFailed(
+ message: String = "Database setup failed: pragma execution failed",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ /**
+ * Error indicating biometric authentication was cancelled by user.
+ */
+ class BiometricCancelled(
+ message: String = "Biometric authentication cancelled",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ /**
+ * Error indicating biometric authentication failed.
+ */
+ class BiometricFailed(
+ message: String = "Biometric authentication failed",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ /**
+ * Error indicating encryption key not found in keystore.
+ */
+ class KeystoreKeyNotFound(
+ message: String = "Encryption key not found in keystore",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ // Storage errors
+ /**
+ * Error indicating encryption key not available.
+ */
+ class EncryptionKeyNotFound(
+ message: String = "Encryption key not available",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ /**
+ * Error indicating failed to store vault.
+ */
+ class VaultStoreFailed(
+ message: String = "Failed to store vault",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ // Merge errors
+ /**
+ * Error indicating vault merge failed.
+ */
+ class VaultMergeFailed(
+ message: String = "Vault merge failed",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ /**
+ * Error indicating upload after merge failed.
+ */
+ class MergeUploadFailed(
+ message: String = "Upload after merge failed",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ // Upload errors
+ /**
+ * Error indicating vault upload failed.
+ */
+ class VaultUploadFailed(
+ message: String = "Vault upload failed",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ /**
+ * Error indicating max sync retries reached.
+ */
+ class MaxRetriesReached(
+ message: String = "Max sync retries reached",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ // Generic errors
+ /**
+ * Error indicating unknown error.
+ */
+ class UnknownError(
+ message: String,
+ cause: Throwable? = null,
+ ) : AppError("Unknown error: $message", cause)
+
+ /**
+ * Error indicating parse error.
+ */
+ class ParseError(
+ message: String,
+ cause: Throwable? = null,
+ ) : AppError("Parse error: $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
+ */
+ 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 Timeout -> "E-203"
+ is ClientVersionNotSupported -> "E-301"
+ is ServerVersionNotSupported -> "E-302"
+ is VaultVersionIncompatible -> "E-303"
+ is VaultMergeRequired -> "E-401"
+ is VaultOutdated -> "E-402"
+ 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 VaultStoreFailed -> "E-604"
+ is VaultMergeFailed -> "E-701"
+ is MergeUploadFailed -> "E-705"
+ is VaultUploadFailed -> "E-801"
+ is MaxRetriesReached -> "E-901"
+ is UnknownError -> "E-001"
+ is ParseError -> "E-002"
+ }
+}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt
index 6e4370c3f..c8dab3087 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt
@@ -200,12 +200,13 @@ class VaultCrypto(
override fun onError(e: Exception) {
Log.e(TAG, "Error retrieving key", e)
+ // Pass through the error - AndroidKeystoreProvider now throws proper AppError types
callback.onError(e)
}
},
)
} else {
- callback.onError(Exception("No encryption key found"))
+ callback.onError(AppError.KeystoreKeyNotFound("No encryption key found in memory or keystore"))
}
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultDatabase.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultDatabase.kt
index 3a49c4132..aaed32c81 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultDatabase.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultDatabase.kt
@@ -85,52 +85,88 @@ class VaultDatabase(
var tempDbFile: File? = null
var sourceDb: io.requery.android.database.sqlite.SQLiteDatabase? = null
try {
- val decryptedDbData = Base64.decode(decryptedDbBase64, Base64.NO_WRAP)
+ // Step 1: Decode base64
+ val decryptedDbData = try {
+ Base64.decode(decryptedDbBase64, Base64.NO_WRAP)
+ } catch (e: Exception) {
+ Log.e(TAG, "Failed to decode base64 data after decryption", e)
+ throw AppError.Base64DecodeFailed(cause = e)
+ }
- // Write decrypted data to temp file
+ // Step 2: Write decrypted data to temp file
tempDbFile = File.createTempFile("temp_db", ".sqlite")
tempDbFile.deleteOnExit()
- tempDbFile.writeBytes(decryptedDbData)
+ try {
+ tempDbFile.writeBytes(decryptedDbData)
+ } catch (e: Exception) {
+ Log.e(TAG, "Failed to write decrypted data to temp file", e)
+ throw AppError.DatabaseTempWriteFailed(cause = e)
+ }
- // Close any existing connection
+ // Step 3: Close any existing connection
dbConnection?.close()
dbConnection = null
- // Open the source database from file using requery's SQLite (read-only)
- sourceDb = io.requery.android.database.sqlite.SQLiteDatabase.openDatabase(
- tempDbFile.path,
- null,
- io.requery.android.database.sqlite.SQLiteDatabase.OPEN_READONLY,
- )
+ // Step 4: Open the source database from file using requery's SQLite (read-only)
+ sourceDb = try {
+ io.requery.android.database.sqlite.SQLiteDatabase.openDatabase(
+ tempDbFile.path,
+ null,
+ io.requery.android.database.sqlite.SQLiteDatabase.OPEN_READONLY,
+ )
+ } catch (e: Exception) {
+ Log.e(TAG, "Failed to open source database (file may be corrupt)", e)
+ throw AppError.DatabaseOpenFailed(cause = e)
+ }
// Close source database before we attach it to memory db
sourceDb.close()
sourceDb = null
- // Create in-memory database using requery's SQLite
- dbConnection = SQLiteDatabase.create(null)
-
- // Attach the temp file as 'source' to copy from
- val attachSql = "ATTACH DATABASE '${tempDbFile.path}' AS source"
- dbConnection?.compileStatement(attachSql)?.execute()
+ // Step 5: Create in-memory database using requery's SQLite
+ dbConnection = try {
+ SQLiteDatabase.create(null)
+ } catch (e: Exception) {
+ Log.e(TAG, "Failed to create in-memory database connection", e)
+ throw AppError.DatabaseMemoryFailed(cause = e)
+ }
- // Copy entire database using sqlite_master (preserves all schema)
- dbConnection?.beginTransaction()
+ // Step 6: Attach and copy database
try {
- copyCompleteDatabase()
- dbConnection?.setTransactionSuccessful()
- } finally {
- dbConnection?.endTransaction()
- }
+ // Attach the temp file as 'source' to copy from
+ val attachSql = "ATTACH DATABASE '${tempDbFile.path}' AS source"
+ dbConnection?.compileStatement(attachSql)?.execute()
- // Detach source
- dbConnection?.compileStatement("DETACH DATABASE source")?.execute()
+ // Copy entire database using sqlite_master (preserves all schema)
+ dbConnection?.beginTransaction()
+ try {
+ copyCompleteDatabase()
+ dbConnection?.setTransactionSuccessful()
+ } finally {
+ dbConnection?.endTransaction()
+ }
+
+ // Detach source
+ dbConnection?.compileStatement("DETACH DATABASE source")?.execute()
+ } catch (e: AppError) {
+ throw e
+ } catch (e: Exception) {
+ Log.e(TAG, "Failed to backup database to memory", e)
+ throw AppError.DatabaseBackupFailed(cause = e)
+ }
- // Set pragmas for optimal performance and safety
- // PRAGMA statements must use rawQuery, not compileStatement
- dbConnection?.rawQuery("PRAGMA journal_mode = WAL", null)
- dbConnection?.rawQuery("PRAGMA synchronous = NORMAL", null)
- dbConnection?.rawQuery("PRAGMA foreign_keys = ON", null)
+ // Step 7: Set pragmas for optimal performance and safety
+ try {
+ // PRAGMA statements must use rawQuery, not compileStatement
+ dbConnection?.rawQuery("PRAGMA journal_mode = WAL", null)
+ dbConnection?.rawQuery("PRAGMA synchronous = NORMAL", null)
+ dbConnection?.rawQuery("PRAGMA foreign_keys = ON", null)
+ } catch (e: Exception) {
+ Log.e(TAG, "Failed to set database pragmas", e)
+ throw AppError.DatabasePragmaFailed(cause = e)
+ }
+ } catch (e: AppError) {
+ throw e
} catch (e: Exception) {
Log.e(TAG, "Error setting up database with decrypted data", e)
throw e
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 b3092fe26..2e4e45192 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
@@ -80,13 +80,7 @@ class VaultSync(
// Prevent infinite recursion
if (retryCount >= maxRetries) {
- return VaultSyncResult(
- success = false,
- action = SyncAction.ERROR,
- newRevision = metadata.getVaultRevisionNumber(),
- wasOffline = metadata.getOfflineMode(),
- error = "Max sync retries reached",
- )
+ return handleSyncError(AppError.MaxRetriesReached())
}
// Mark as syncing
@@ -143,18 +137,13 @@ class VaultSync(
)
}
}
- } catch (e: VaultSyncError) {
+ } catch (e: AppError) {
metadata.setIsSyncing(false)
handleSyncError(e)
} catch (e: Exception) {
metadata.setIsSyncing(false)
- VaultSyncResult(
- success = false,
- action = SyncAction.ERROR,
- newRevision = metadata.getVaultRevisionNumber(),
- wasOffline = metadata.getOfflineMode(),
- error = e.message ?: "Unknown error",
- )
+ Log.e(TAG, "Sync error: ${e.message}", e)
+ handleSyncError(AppError.UnknownError(e.message ?: "Unknown sync error", e))
}
}
@@ -212,18 +201,13 @@ class VaultSync(
wasOffline = false,
error = null,
)
- } catch (e: VaultSyncError) {
+ } catch (e: AppError) {
metadata.setIsSyncing(false)
handleSyncError(e)
} catch (e: Exception) {
metadata.setIsSyncing(false)
- VaultSyncResult(
- success = false,
- action = SyncAction.ERROR,
- newRevision = metadata.getVaultRevisionNumber(),
- wasOffline = metadata.getOfflineMode(),
- error = e.message ?: "Unknown error",
- )
+ Log.e(TAG, "Download sync error: ${e.message}", e)
+ handleSyncError(AppError.VaultStoreFailed("Download sync failed: ${e.message}", e))
}
}
@@ -259,24 +243,14 @@ class VaultSync(
}
else -> {
metadata.setIsSyncing(false)
- VaultSyncResult(
- success = false,
- action = SyncAction.ERROR,
- newRevision = metadata.getVaultRevisionNumber(),
- wasOffline = false,
- error = uploadResult.error ?: "Upload failed",
- )
+ Log.e(TAG, "Upload failed: ${uploadResult.error}")
+ handleSyncError(AppError.VaultUploadFailed("Upload failed: ${uploadResult.error}"))
}
}
} catch (e: Exception) {
metadata.setIsSyncing(false)
- VaultSyncResult(
- success = false,
- action = SyncAction.ERROR,
- newRevision = metadata.getVaultRevisionNumber(),
- wasOffline = metadata.getOfflineMode(),
- error = e.message ?: "Unknown error",
- )
+ Log.e(TAG, "Upload sync error: ${e.message}", e)
+ handleSyncError(AppError.VaultUploadFailed("Upload sync error: ${e.message}", e))
}
}
@@ -296,13 +270,8 @@ class VaultSync(
val localVault = database.getEncryptedDatabase()
if (localVault.isEmpty()) {
metadata.setIsSyncing(false)
- return VaultSyncResult(
- success = false,
- action = SyncAction.ERROR,
- newRevision = metadata.getVaultRevisionNumber(),
- wasOffline = false,
- error = "No local vault available for merge",
- )
+ Log.e(TAG, "No local vault available for merge")
+ return handleSyncError(AppError.VaultMergeFailed("No local vault available for merge"))
}
// Perform LWW merge using Rust core library
@@ -353,27 +322,17 @@ class VaultSync(
}
else -> {
metadata.setIsSyncing(false)
- VaultSyncResult(
- success = false,
- action = SyncAction.ERROR,
- newRevision = metadata.getVaultRevisionNumber(),
- wasOffline = false,
- error = uploadResult.error ?: "Upload after merge failed",
- )
+ Log.e(TAG, "Upload after merge failed: ${uploadResult.error}")
+ handleSyncError(AppError.MergeUploadFailed("Upload after merge failed: ${uploadResult.error}"))
}
}
- } catch (e: VaultSyncError) {
+ } catch (e: AppError) {
metadata.setIsSyncing(false)
handleSyncError(e)
} catch (e: Exception) {
metadata.setIsSyncing(false)
- VaultSyncResult(
- success = false,
- action = SyncAction.ERROR,
- newRevision = metadata.getVaultRevisionNumber(),
- wasOffline = metadata.getOfflineMode(),
- error = e.message ?: "Unknown error",
- )
+ Log.e(TAG, "Merge sync error: ${e.message}", e)
+ handleSyncError(AppError.VaultMergeFailed("Merge sync error: ${e.message}", e))
}
}
@@ -386,7 +345,7 @@ class VaultSync(
*/
private fun performLWWMerge(localVault: String, serverVault: String): String {
val encryptionKey = crypto.encryptionKey
- ?: throw VaultOperationException("Encryption key not available for merge")
+ ?: throw AppError.EncryptionKeyNotFound("Encryption key not available for merge")
return try {
VaultMergeService.mergeVaults(
@@ -397,7 +356,7 @@ class VaultSync(
)
} catch (e: VaultMergeService.VaultMergeException) {
Log.e(TAG, "Rust merge failed: ${e.message}", e)
- throw VaultOperationException("Vault merge failed: ${e.message}", e)
+ throw AppError.VaultMergeFailed("Rust merge failed: ${e.message}", e)
}
}
@@ -605,11 +564,13 @@ class VaultSync(
/**
* Handle sync errors and return appropriate result.
*/
- private fun handleSyncError(error: VaultSyncError): VaultSyncResult {
+ private fun handleSyncError(error: AppError): VaultSyncResult {
+ Log.e(TAG, "Sync error: ${error.message}", error)
+
return when (error) {
- is VaultSyncError.NetworkError,
- is VaultSyncError.ServerUnavailable,
- is VaultSyncError.Timeout,
+ is AppError.NetworkError,
+ is AppError.ServerUnavailable,
+ is AppError.Timeout,
-> {
metadata.setOfflineMode(true)
VaultSyncResult(
@@ -617,20 +578,6 @@ class VaultSync(
action = SyncAction.ERROR,
newRevision = metadata.getVaultRevisionNumber(),
wasOffline = true,
- error = error.message,
- )
- }
- is VaultSyncError.SessionExpired,
- is VaultSyncError.AuthenticationFailed,
- is VaultSyncError.PasswordChanged,
- is VaultSyncError.ClientVersionNotSupported,
- is VaultSyncError.ServerVersionNotSupported,
- -> {
- VaultSyncResult(
- success = false,
- action = SyncAction.ERROR,
- newRevision = metadata.getVaultRevisionNumber(),
- wasOffline = false,
error = error.code,
)
}
@@ -640,7 +587,7 @@ class VaultSync(
action = SyncAction.ERROR,
newRevision = metadata.getVaultRevisionNumber(),
wasOffline = metadata.getOfflineMode(),
- error = error.message,
+ error = error.code,
)
}
}
@@ -681,14 +628,14 @@ class VaultSync(
requiresAuth = true,
)
} catch (e: Exception) {
- throw VaultSyncError.NetworkError(e)
+ throw AppError.NetworkError(e)
}
if (vaultResponse.statusCode != 200) {
if (vaultResponse.statusCode == 401) {
- throw VaultSyncError.SessionExpired()
+ throw AppError.SessionExpired()
}
- throw VaultSyncError.ServerUnavailable(vaultResponse.statusCode)
+ throw AppError.ServerUnavailable(vaultResponse.statusCode)
}
return parseVaultResponsePublic(vaultResponse.body)
@@ -708,16 +655,16 @@ class VaultSync(
requiresAuth = true,
)
} catch (e: Exception) {
- throw VaultSyncError.NetworkError(e)
+ throw AppError.NetworkError(e)
}
if (statusResponse.statusCode != 200) {
if (statusResponse.statusCode == 401) {
Log.e(TAG, "Authentication failed (401) - token refresh also failed")
- throw VaultSyncError.SessionExpired()
+ throw AppError.SessionExpired()
}
metadata.setOfflineMode(true)
- throw VaultSyncError.ServerUnavailable(statusResponse.statusCode)
+ throw AppError.ServerUnavailable(statusResponse.statusCode)
}
val status = try {
@@ -731,16 +678,16 @@ class VaultSync(
} catch (e: Exception) {
Log.e(TAG, "Failed to decode status response", e)
Log.e(TAG, "Response body: '${statusResponse.body}'")
- throw VaultSyncError.ParseError("Failed to decode status response: ${e.message}", e)
+ throw AppError.ParseError("Failed to decode status response: ${e.message}", e)
}
if (!status.clientVersionSupported) {
- throw VaultSyncError.ClientVersionNotSupported()
+ throw AppError.ClientVersionNotSupported()
}
if (!VersionComparison.isServerVersionSupported(status.serverVersion)) {
Log.e(TAG, "Server version ${status.serverVersion} does not meet minimum requirement ${AppInfo.MIN_SERVER_VERSION}")
- throw VaultSyncError.ServerVersionNotSupported()
+ throw AppError.ServerVersionNotSupported()
}
// Store server version in metadata
@@ -761,9 +708,9 @@ class VaultSync(
val json = JSONObject(keyDerivationParams)
val salt = json.optString("salt", "")
if (srpSalt.isNotEmpty() && srpSalt != salt) {
- throw VaultSyncError.PasswordChanged()
+ throw AppError.PasswordChanged()
}
- } catch (e: VaultSyncError.PasswordChanged) {
+ } catch (e: AppError.PasswordChanged) {
throw e
} catch (e: Exception) {
// Ignore generic parsing errors
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncError.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncError.kt
deleted file mode 100644
index 380d57a34..000000000
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncError.kt
+++ /dev/null
@@ -1,154 +0,0 @@
-package net.aliasvault.app.vaultstore
-
-/**
- * Error codes for vault sync operations
- * These error codes are language-independent and can be properly handled by the client
- *
- * This is a Kotlin port of the iOS Swift implementation:
- * - Reference: apps/mobile-app/ios/VaultStoreKit/Enums/VaultSyncError.swift
- *
- * IMPORTANT: Keep all implementations synchronized. Changes to the public interface must be
- * reflected in all ports. Error types and codes should remain consistent.
- */
-sealed class VaultSyncError(message: String, cause: Throwable? = null) : Exception(message, cause) {
- // Authentication errors
- /**
- * Error indicating authentication failed.
- */
- class AuthenticationFailed(
- message: String = "Authentication failed",
- cause: Throwable? = null,
- ) : VaultSyncError(message, cause)
-
- /**
- * Error indicating session expired.
- */
- class SessionExpired(
- message: String = "Session expired",
- cause: Throwable? = null,
- ) : VaultSyncError(message, cause)
-
- /**
- * Error indicating password has changed.
- */
- class PasswordChanged(
- message: String = "Password has changed",
- cause: Throwable? = null,
- ) : VaultSyncError(message, cause)
-
- // Network/connectivity errors
- /**
- * Error indicating server unavailable.
- */
- class ServerUnavailable(
- /** The HTTP status code. */
- val statusCode: Int,
- message: String = "Server unavailable (status: $statusCode)",
- cause: Throwable? = null,
- ) : VaultSyncError(message, cause)
-
- /**
- * Error indicating network error.
- */
- class NetworkError(
- /** The underlying error. */
- val underlyingError: Throwable,
- ) : VaultSyncError("Network error: ${underlyingError.message}", underlyingError)
-
- /**
- * Error indicating request timeout.
- */
- class Timeout(
- message: String = "Request timeout",
- cause: Throwable? = null,
- ) : VaultSyncError(message, cause)
-
- // Version/compatibility errors
- /**
- * Error indicating client version not supported.
- */
- class ClientVersionNotSupported(
- message: String = "Client version not supported",
- cause: Throwable? = null,
- ) : VaultSyncError(message, cause)
-
- /**
- * Error indicating server version not supported.
- */
- class ServerVersionNotSupported(
- message: String = "Server version not supported",
- cause: Throwable? = null,
- ) : VaultSyncError(message, cause)
-
- /**
- * Error indicating vault version incompatible.
- */
- class VaultVersionIncompatible(
- message: String = "Vault version incompatible",
- cause: Throwable? = null,
- ) : VaultSyncError(message, cause)
-
- // Vault status errors
- /**
- * Error indicating vault merge required.
- */
- class VaultMergeRequired(
- message: String = "Vault merge required",
- cause: Throwable? = null,
- ) : VaultSyncError(message, cause)
-
- /**
- * Error indicating vault outdated.
- */
- class VaultOutdated(
- message: String = "Vault outdated",
- cause: Throwable? = null,
- ) : VaultSyncError(message, cause)
-
- // Decryption errors
- /**
- * Error indicating failed to decrypt vault.
- */
- class VaultDecryptFailed(
- message: String = "Failed to decrypt vault",
- cause: Throwable? = null,
- ) : VaultSyncError(message, cause)
-
- // Generic errors
- /**
- * Error indicating unknown error.
- */
- class UnknownError(
- message: String,
- cause: Throwable? = null,
- ) : VaultSyncError("Unknown error: $message", cause)
-
- /**
- * Error indicating parse error.
- */
- class ParseError(
- message: String,
- cause: Throwable? = null,
- ) : VaultSyncError("Parse error: $message", cause)
-
- /**
- * Get the error code string for React Native bridge.
- */
- val code: String
- get() = when (this) {
- is AuthenticationFailed -> "VAULT_SYNC_AUTH_FAILED"
- is SessionExpired -> "VAULT_SYNC_SESSION_EXPIRED"
- is PasswordChanged -> "VAULT_SYNC_PASSWORD_CHANGED"
- is ServerUnavailable -> "VAULT_SYNC_SERVER_UNAVAILABLE"
- is NetworkError -> "VAULT_SYNC_NETWORK_ERROR"
- is Timeout -> "VAULT_SYNC_TIMEOUT"
- is ClientVersionNotSupported -> "VAULT_SYNC_CLIENT_VERSION_NOT_SUPPORTED"
- is ServerVersionNotSupported -> "VAULT_SYNC_SERVER_VERSION_NOT_SUPPORTED"
- is VaultVersionIncompatible -> "VAULT_SYNC_VAULT_VERSION_INCOMPATIBLE"
- is VaultMergeRequired -> "VAULT_SYNC_MERGE_REQUIRED"
- is VaultOutdated -> "VAULT_SYNC_OUTDATED"
- is VaultDecryptFailed -> "VAULT_SYNC_DECRYPT_FAILED"
- is UnknownError -> "VAULT_SYNC_UNKNOWN_ERROR"
- is ParseError -> "VAULT_SYNC_PARSE_ERROR"
- }
-}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/keystoreprovider/AndroidKeystoreProvider.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/keystoreprovider/AndroidKeystoreProvider.kt
index 95f1ee27f..48f5a20d3 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/keystoreprovider/AndroidKeystoreProvider.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/keystoreprovider/AndroidKeystoreProvider.kt
@@ -14,6 +14,7 @@ import androidx.biometric.BiometricManager
import androidx.biometric.BiometricPrompt
import androidx.fragment.app.FragmentActivity
import net.aliasvault.app.R
+import net.aliasvault.app.vaultstore.AppError
import java.io.File
import java.nio.ByteBuffer
import java.security.KeyStore
@@ -195,9 +196,18 @@ class AndroidKeystoreProvider(
errString: CharSequence,
) {
Log.e(TAG, "Authentication error: $errorCode - $errString")
- callback.onError(
- Exception("Authentication error: $errString (code: $errorCode)"),
- )
+ val error = when (errorCode) {
+ BiometricPrompt.ERROR_USER_CANCELED,
+ BiometricPrompt.ERROR_NEGATIVE_BUTTON,
+ BiometricPrompt.ERROR_CANCELED,
+ -> AppError.BiometricCancelled(
+ "Biometric authentication cancelled: $errString",
+ )
+ else -> AppError.BiometricFailed(
+ "Biometric authentication error: $errString (code: $errorCode)",
+ )
+ }
+ callback.onError(error)
}
override fun onAuthenticationFailed() {
@@ -209,7 +219,7 @@ class AndroidKeystoreProvider(
biometricPrompt.authenticate(promptInfo, BiometricPrompt.CryptoObject(cipher))
} catch (e: Exception) {
Log.e(TAG, "Error in biometric key storage", e)
- callback.onError(Exception("Failed to initialize key storage: ${e.message}"))
+ callback.onError(AppError.BiometricFailed("Failed to initialize key storage: ${e.message}", e))
}
}
}
@@ -274,7 +284,7 @@ class AndroidKeystoreProvider(
val keyFile = File(context.filesDir, ENCRYPTED_KEY_FILE)
if (!keyFile.exists()) {
Log.e(TAG, "No encryption key found")
- callback.onError(Exception("No encryption key found"))
+ callback.onError(AppError.KeystoreKeyNotFound("No encryption key found in storage"))
return
}
val encryptedKeyB64 = keyFile.readText()
@@ -286,7 +296,7 @@ class AndroidKeystoreProvider(
// Check if key exists
if (!keyStore.containsAlias(KEYSTORE_ALIAS)) {
Log.e(TAG, "Keystore key not found")
- callback.onError(Exception("Keystore key not found"))
+ callback.onError(AppError.KeystoreKeyNotFound("Keystore key not found in Android Keystore"))
return
}
@@ -313,9 +323,8 @@ class AndroidKeystoreProvider(
keyStore.deleteEntry(KEYSTORE_ALIAS)
keyFile.delete()
callback.onError(
- Exception(
- "Biometric enrollment changed. " +
- "Please sign in with your password to re-enable biometric unlock.",
+ AppError.KeystoreKeyNotFound(
+ "Biometric enrollment changed. Please sign in with your password to re-enable biometric unlock.",
e,
),
)
@@ -361,9 +370,18 @@ class AndroidKeystoreProvider(
errString: CharSequence,
) {
Log.e(TAG, "Authentication error: $errorCode - $errString")
- callback.onError(
- Exception("Authentication error: $errString (code: $errorCode)"),
- )
+ val error = when (errorCode) {
+ BiometricPrompt.ERROR_USER_CANCELED,
+ BiometricPrompt.ERROR_NEGATIVE_BUTTON,
+ BiometricPrompt.ERROR_CANCELED,
+ -> AppError.BiometricCancelled(
+ "Biometric authentication cancelled: $errString",
+ )
+ else -> AppError.BiometricFailed(
+ "Biometric authentication error: $errString (code: $errorCode)",
+ )
+ }
+ callback.onError(error)
}
override fun onAuthenticationFailed() {
diff --git a/apps/mobile-app/android/detekt.yml b/apps/mobile-app/android/detekt.yml
index b0aed8617..bf31d9de6 100644
--- a/apps/mobile-app/android/detekt.yml
+++ b/apps/mobile-app/android/detekt.yml
@@ -56,7 +56,7 @@ style:
active: false
ThrowsCount:
active: true
- max: 8
+ max: 16
ForbiddenComment:
active: false # Allow TODO, FIXME, STOPSHIP comments in code
diff --git a/apps/mobile-app/app/unlock.tsx b/apps/mobile-app/app/unlock.tsx
index 094c7d227..07afe3774 100644
--- a/apps/mobile-app/app/unlock.tsx
+++ b/apps/mobile-app/app/unlock.tsx
@@ -7,6 +7,7 @@ import { useState, useEffect, useCallback } from 'react';
import { StyleSheet, View, TextInput, KeyboardAvoidingView, Platform, ScrollView, Dimensions, Text, Pressable } from 'react-native';
import EncryptionUtility from '@/utils/EncryptionUtility';
+import { getAppErrorCode, getErrorTranslationKey, formatErrorWithCode } from '@/utils/types/errors/AppErrorCodes';
import { VaultVersionIncompatibleError } from '@/utils/types/errors/VaultVersionIncompatibleError';
import { useColors } from '@/hooks/useColorScheme';
@@ -137,22 +138,23 @@ export default function UnlockScreen() : React.ReactNode {
const passwordHashBase64 = Buffer.from(passwordHash).toString('base64');
- // Test the database connection with the derived encryption key
- if (await dbContext.testDatabaseConnection(passwordHashBase64)) {
- // Check if the vault is up to date, if not, redirect to the upgrade page.
- if (await dbContext.hasPendingMigrations()) {
- router.replace('/upgrade');
- return;
- }
+ /*
+ * Test the database connection with the derived encryption key.
+ * This throws an error if it fails (with error codes for specific failures).
+ */
+ await dbContext.testDatabaseConnection(passwordHashBase64);
- /*
- * Navigate to reinitialize which will sync vault with server
- * and then navigate to the appropriate destination.
- */
- router.replace('/reinitialize');
- } else {
- showAlert(t('common.error'), t('auth.errors.incorrectPassword'));
+ // Check if the vault is up to date, if not, redirect to the upgrade page.
+ if (await dbContext.hasPendingMigrations()) {
+ router.replace('/upgrade');
+ return;
}
+
+ /*
+ * Navigate to reinitialize which will sync vault with server
+ * and then navigate to the appropriate destination.
+ */
+ router.replace('/reinitialize');
} catch (err) {
if (err instanceof VaultVersionIncompatibleError) {
// Vault version incompatible - force logout without confirmation
@@ -161,7 +163,16 @@ export default function UnlockScreen() : React.ReactNode {
}
console.error('Unlock error:', err);
- showAlert(t('common.error'), t('auth.errors.incorrectPassword'));
+
+ // Try to extract error code from the error
+ const errorCode = getAppErrorCode(err);
+ if (errorCode) {
+ const translationKey = getErrorTranslationKey(errorCode);
+ showAlert(t('common.error'), formatErrorWithCode(t(translationKey), errorCode));
+ } else {
+ // Fallback to incorrect password for unknown errors (likely password mismatch)
+ showAlert(t('common.error'), t('auth.errors.incorrectPassword'));
+ }
} finally {
setIsLoading(false);
}
@@ -207,25 +218,32 @@ export default function UnlockScreen() : React.ReactNode {
setIsLoading(true);
setError(null);
try {
- const unlocked = await dbContext.unlockVault();
- if (unlocked) {
- // Check if the vault is up to date
- if (await dbContext.hasPendingMigrations()) {
- router.replace('/upgrade');
- return;
- }
- router.replace('/reinitialize');
- } else {
- // Biometric failed - try PIN fallback if available
- if (pinAvailable) {
- await performPinUnlock();
- }
+ // unlockVault now throws errors instead of returning false
+ await dbContext.unlockVault();
+
+ // Check if the vault is up to date
+ if (await dbContext.hasPendingMigrations()) {
+ router.replace('/upgrade');
+ return;
}
+ router.replace('/reinitialize');
} catch (err) {
console.error('Biometric retry error:', err);
- // Biometric failed - try PIN fallback if available
+
+ // Check if this is a cancellation - don't show error, just allow retry
+ const errorCode = getAppErrorCode(err);
+ if (errorCode === 'E-509') { // BIOMETRIC_CANCELLED
+ // User cancelled - don't show error, just stay on screen
+ return;
+ }
+
+ // For other errors, try PIN fallback if available
if (pinAvailable) {
await performPinUnlock();
+ } else if (errorCode) {
+ // Show the error with code if no PIN fallback
+ const translationKey = getErrorTranslationKey(errorCode);
+ setError(formatErrorWithCode(t(translationKey), errorCode));
}
} finally {
setIsLoading(false);
diff --git a/apps/mobile-app/context/DbContext.tsx b/apps/mobile-app/context/DbContext.tsx
index 8e81a958e..42afa16dc 100644
--- a/apps/mobile-app/context/DbContext.tsx
+++ b/apps/mobile-app/context/DbContext.tsx
@@ -81,18 +81,12 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
/**
* Unlock the vault in the native module which will decrypt the database using the stored encryption key
* and load it into memory.
+ *
+ * @throws Error with error code if unlock fails - caller should handle the error and display appropriate message
*/
const unlockVault = useCallback(async () : Promise<boolean> => {
- try {
- await NativeVaultManager.unlockVault();
- return true;
- } catch (error: any) {
- console.error('Failed to unlock vault:', error);
- if (error?.code === 'DATABASE_SETUP_ERROR') {
- console.error('Database setup error:', error.message);
- }
- return false;
- }
+ await NativeVaultManager.unlockVault();
+ return true;
}, []);
/**
@@ -230,17 +224,15 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
/**
* Test if the database is working with the provided (to be stored) encryption key by performing a simple query
* @param derivedKey The encryption key to test with
- * @returns true if the database is working, false otherwise
+ * @returns true if the database is working
+ * @throws Error with error code if unlock fails - caller should handle the error
*/
const testDatabaseConnection = useCallback(async (derivedKey: string): Promise<boolean> => {
// Store the encryption key
await sqliteClient.storeEncryptionKey(derivedKey);
- // Initialize the database
- const unlocked = await unlockVault();
- if (!unlocked) {
- return false;
- }
+ // Initialize the database - throws on failure with error code
+ await unlockVault();
// Try to get the database version as a simple test query
const version = await sqliteClient.getDatabaseVersion();
diff --git a/apps/mobile-app/hooks/useVaultSync.ts b/apps/mobile-app/hooks/useVaultSync.ts
index 3ec962aff..007eb320d 100644
--- a/apps/mobile-app/hooks/useVaultSync.ts
+++ b/apps/mobile-app/hooks/useVaultSync.ts
@@ -7,7 +7,13 @@ import { useApp } from '@/context/AppContext';
import { useDb } from '@/context/DbContext';
import NativeVaultManager from '@/specs/NativeVaultManager';
import { VaultVersionIncompatibleError } from '@/utils/types/errors/VaultVersionIncompatibleError';
-import { VaultSyncErrorCode, getVaultSyncErrorCode } from '@/utils/types/errors/VaultSyncErrorCodes';
+import {
+ AppErrorCode,
+ getAppErrorCode,
+ extractErrorCode,
+ formatErrorWithCode,
+ getErrorTranslationKey,
+} from '@/utils/types/errors/AppErrorCodes';
/**
* Sync state tracking for race detection and offline support.
@@ -96,7 +102,7 @@ export const useVaultSync = (): {
if (!result.success) {
// Check for specific error conditions
if (result.error) {
- const errorCode = getVaultSyncErrorCodeFromString(result.error);
+ const errorCode = extractErrorCode(result.error) ?? getAppErrorCode(result.error);
if (errorCode) {
return await handleSyncError(result.error, errorCode, app, dbContext, t, onError, onOffline);
}
@@ -110,7 +116,13 @@ export const useVaultSync = (): {
return true;
}
- onError?.(result.error ?? t('common.errors.unknownError'));
+ // For unrecognized errors (no error code found), use translated fallback with error code
+ // This ensures users always see a translated message with a code they can report
+ const fallbackError = formatErrorWithCode(
+ t('common.errors.unknownErrorTryAgain'),
+ AppErrorCode.UNKNOWN_ERROR
+ );
+ onError?.(fallbackError);
return false;
}
@@ -165,7 +177,10 @@ export const useVaultSync = (): {
}
console.error('Failed to unlock vault:', err);
- throw new Error(t('common.errors.unknownErrorTryAgain'));
+ throw new Error(formatErrorWithCode(
+ t('common.errors.unknownErrorTryAgain'),
+ AppErrorCode.NATIVE_UNLOCK_FAILED
+ ));
}
} catch (err) {
console.error('Vault sync error:', err);
@@ -181,13 +196,18 @@ export const useVaultSync = (): {
return false;
}
- // Check if it's a vault sync error with error code
- const errorCode = getVaultSyncErrorCode(err);
+ // Check if it's a vault sync error with error code (from error object or message)
+ const errorCode = getAppErrorCode(err);
if (errorCode) {
return await handleSyncError(err, errorCode, app, dbContext, t, onError, onOffline);
}
- const errorMessage = err instanceof Error ? err.message : t('common.errors.unknownError');
+ // For unrecognized errors, always use translated message with error code
+ // This ensures users never see raw English error messages from native layer
+ const extractedCode = err instanceof Error ? extractErrorCode(err.message) : null;
+ const fallbackCode = extractedCode ?? AppErrorCode.UNKNOWN_ERROR;
+ const translationKey = getErrorTranslationKey(fallbackCode);
+ const errorMessage = formatErrorWithCode(t(translationKey), fallbackCode);
onError?.(errorMessage);
return false;
} finally {
@@ -198,81 +218,61 @@ export const useVaultSync = (): {
return { syncVault, getSyncState };
};
-/**
- * Map error string from native to VaultSyncErrorCode.
- */
-function getVaultSyncErrorCodeFromString(error: string): VaultSyncErrorCode | null {
- switch (error) {
- case VaultSyncErrorCode.SESSION_EXPIRED:
- return VaultSyncErrorCode.SESSION_EXPIRED;
- case VaultSyncErrorCode.AUTHENTICATION_FAILED:
- return VaultSyncErrorCode.AUTHENTICATION_FAILED;
- case VaultSyncErrorCode.PASSWORD_CHANGED:
- return VaultSyncErrorCode.PASSWORD_CHANGED;
- case VaultSyncErrorCode.CLIENT_VERSION_NOT_SUPPORTED:
- return VaultSyncErrorCode.CLIENT_VERSION_NOT_SUPPORTED;
- case VaultSyncErrorCode.SERVER_VERSION_NOT_SUPPORTED:
- return VaultSyncErrorCode.SERVER_VERSION_NOT_SUPPORTED;
- case VaultSyncErrorCode.SERVER_UNAVAILABLE:
- return VaultSyncErrorCode.SERVER_UNAVAILABLE;
- case VaultSyncErrorCode.NETWORK_ERROR:
- return VaultSyncErrorCode.NETWORK_ERROR;
- case VaultSyncErrorCode.TIMEOUT:
- return VaultSyncErrorCode.TIMEOUT;
- default:
- return null;
- }
-}
-
/**
* Handle sync errors by mapping error codes to appropriate actions.
*
* For critical errors requiring logout (auth, version), we ALWAYS use app.logout(message)
* which shows a native Alert.alert that persists through navigation on both platforms.
* The onError callback is only used for non-critical errors that don't require logout.
+ *
+ * Error codes are included in messages to help users report issues for debugging.
*/
async function handleSyncError(
- err: unknown,
- errorCode: VaultSyncErrorCode | null,
+ _err: unknown,
+ errorCode: AppErrorCode,
app: ReturnType<typeof useApp>,
dbContext: ReturnType<typeof useDb>,
t: (key: string) => string,
onError?: (error: string) => void,
onOffline?: () => void
): Promise<boolean> {
+ // Get the translated message for this error code
+ const translationKey = getErrorTranslationKey(errorCode);
+ const translatedMessage = t(translationKey);
+
+ // Format with error code for user reporting
+ const messageWithCode = formatErrorWithCode(translatedMessage, errorCode);
+
switch (errorCode) {
// Authentication errors - logout with message (shows native alert)
- case VaultSyncErrorCode.SESSION_EXPIRED:
- case VaultSyncErrorCode.AUTHENTICATION_FAILED:
- await app.logout(t('auth.errors.sessionExpired'));
+ case AppErrorCode.SESSION_EXPIRED:
+ case AppErrorCode.AUTHENTICATION_FAILED:
+ await app.logout(messageWithCode);
return false;
- case VaultSyncErrorCode.PASSWORD_CHANGED:
- await app.logout(t('vault.errors.passwordChanged'));
+ case AppErrorCode.PASSWORD_CHANGED:
+ await app.logout(messageWithCode);
return false;
// Version compatibility errors - logout with message (shows native alert)
- case VaultSyncErrorCode.CLIENT_VERSION_NOT_SUPPORTED:
- await app.logout(t('vault.errors.versionNotSupported'));
- return false;
-
- case VaultSyncErrorCode.SERVER_VERSION_NOT_SUPPORTED:
- await app.logout(t('vault.errors.serverVersionNotSupported'));
+ case AppErrorCode.CLIENT_VERSION_NOT_SUPPORTED:
+ case AppErrorCode.SERVER_VERSION_NOT_SUPPORTED:
+ case AppErrorCode.VAULT_VERSION_INCOMPATIBLE:
+ await app.logout(messageWithCode);
return false;
// Network errors - set offline mode, don't logout
- case VaultSyncErrorCode.SERVER_UNAVAILABLE:
- case VaultSyncErrorCode.NETWORK_ERROR:
- case VaultSyncErrorCode.TIMEOUT:
+ case AppErrorCode.SERVER_UNAVAILABLE:
+ case AppErrorCode.NETWORK_ERROR:
+ case AppErrorCode.TIMEOUT:
await dbContext.setIsOffline(true);
onOffline?.();
// Return true to continue with local vault
return true;
- // Unknown errors - use onError callback if provided
+ // All other errors - show error with code for debugging
default:
- const errorMessage = err instanceof Error ? err.message : t('common.errors.unknownError');
- onError?.(errorMessage);
+ onError?.(messageWithCode);
return false;
}
}
diff --git a/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj b/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj
index 15635dfd8..9e22614ed 100644
--- a/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj
+++ b/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj
@@ -3,7 +3,7 @@
archiveVersion = 1;
classes = {
};
- objectVersion = 60;
+ objectVersion = 70;
objects = {
/* Begin PBXBuildFile section */
@@ -272,7 +272,7 @@
/* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */
- CEE9098F2DA548C7008D568F /* Exceptions for "Autofill" folder in "Autofill" target */ = {
+ CEE9098F2DA548C7008D568F /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
Info.plist,
@@ -282,84 +282,13 @@
/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */
/* Begin PBXFileSystemSynchronizedRootGroup section */
- CE59C7602E4F47FD0024A246 /* AliasVaultUITests */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = AliasVaultUITests;
- sourceTree = "<group>";
- };
- CE77825E2EA1822400A75E6F /* VaultUtils */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultUtils;
- sourceTree = "<group>";
- };
- CEE480882DBE86DC00F4A367 /* VaultStoreKit */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultStoreKit;
- sourceTree = "<group>";
- };
- CEE480972DBE86DD00F4A367 /* VaultStoreKitTests */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultStoreKitTests;
- sourceTree = "<group>";
- };
- CEE4816B2DBE8AC800F4A367 /* VaultUI */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultUI;
- sourceTree = "<group>";
- };
- CEE482AB2DBE8EFE00F4A367 /* VaultModels */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultModels;
- sourceTree = "<group>";
- };
- CEE909812DA548C7008D568F /* Autofill */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- CEE9098F2DA548C7008D568F /* Exceptions for "Autofill" folder in "Autofill" target */,
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = Autofill;
- sourceTree = "<group>";
- };
+ CE59C7602E4F47FD0024A246 /* AliasVaultUITests */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = AliasVaultUITests; sourceTree = "<group>"; };
+ CE77825E2EA1822400A75E6F /* VaultUtils */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultUtils; sourceTree = "<group>"; };
+ CEE480882DBE86DC00F4A367 /* VaultStoreKit */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultStoreKit; sourceTree = "<group>"; };
+ CEE480972DBE86DD00F4A367 /* VaultStoreKitTests */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultStoreKitTests; sourceTree = "<group>"; };
+ CEE4816B2DBE8AC800F4A367 /* VaultUI */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultUI; sourceTree = "<group>"; };
+ CEE482AB2DBE8EFE00F4A367 /* VaultModels */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultModels; sourceTree = "<group>"; };
+ CEE909812DA548C7008D568F /* Autofill */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (CEE9098F2DA548C7008D568F /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = Autofill; sourceTree = "<group>"; };
/* End PBXFileSystemSynchronizedRootGroup section */
/* Begin PBXFrameworksBuildPhase section */
@@ -519,7 +448,7 @@
path = Generated;
sourceTree = "<group>";
};
- 6114AD0A31612EA499210371 /* */ = {
+ 6114AD0A31612EA499210371 = {
isa = PBXGroup;
children = (
8F8258CE46969A87661E0302 /* RustCore.swift */,
@@ -555,7 +484,7 @@
832341AE1AAA6A7D00B99B32 /* Libraries */,
D65327D7A22EEC0BE12398D9 /* Pods */,
83CBBA001A601CBA00E9B192 /* Products */,
- 6114AD0A31612EA499210371 /* */,
+ 6114AD0A31612EA499210371,
CE5212B62F0C061800F4C835 /* Recovered References */,
3AD00C41DD88E219A26C2E41 /* RustCoreFramework */,
);
@@ -994,6 +923,7 @@
tr,
ca,
ro,
+ fa,
);
mainGroup = 83CBB9F61A601CBA00E9B192;
productRefGroup = 83CBBA001A601CBA00E9B192 /* Products */;
@@ -1710,10 +1640,7 @@
LIBRARY_SEARCH_PATHS = "$(SDKROOT)/usr/lib/swift\"$(inherited)\"";
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
- OTHER_LDFLAGS = (
- "$(inherited)",
- " ",
- );
+ OTHER_LDFLAGS = "$(inherited) ";
REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native";
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) DEBUG";
@@ -1767,10 +1694,7 @@
);
LIBRARY_SEARCH_PATHS = "$(SDKROOT)/usr/lib/swift\"$(inherited)\"";
MTL_ENABLE_DEBUG_INFO = NO;
- OTHER_LDFLAGS = (
- "$(inherited)",
- " ",
- );
+ OTHER_LDFLAGS = "$(inherited) ";
REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native";
SDKROOT = iphoneos;
USE_HERMES = true;
diff --git a/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift b/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift
index 4fdf92f62..144f1c925 100644
--- a/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift
+++ b/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift
@@ -356,7 +356,7 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
// Show appropriate error dialog based on error type
await MainActor.run {
- self.showSyncErrorAlert(error: VaultSyncError.unknownError(message: syncResult.error ?? "Sync failed"))
+ self.showSyncErrorAlert(error: AppError.unknownError(message: syncResult.error ?? "Sync failed"))
}
return
}
diff --git a/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift b/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
index fd4a4514c..769b4e534 100644
--- a/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
+++ b/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
@@ -574,8 +574,8 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
var title = NSLocalizedString("connection_error_title", comment: "Connection Error")
var message = NSLocalizedString("connection_error_message", comment: "No connection to the server can be made.")
- // Check if it's a VaultSyncError and customize message accordingly
- if let syncError = error as? VaultSyncError {
+ // Check if it's a AppError and customize message accordingly
+ if let syncError = error as? AppError {
switch syncError {
case .sessionExpired, .authenticationFailed:
title = NSLocalizedString("session_expired_title", comment: "Session Expired")
diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
index 59708f57e..77789e2c4 100644
--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
@@ -225,23 +225,12 @@ public class VaultManager: NSObject {
do {
try vaultStore.unlockVault()
resolve(true)
+ } catch let vaultError as AppError {
+ // Propagate AppError with proper error code
+ reject(vaultError.code, vaultError.message, vaultError)
} catch let error as NSError {
- if error.domain == "VaultStore" {
- // These are our known error codes for initialization failures (non-critical)
- if error.code == 1 || error.code == 2 || error.code == 8 || error.code == 10 {
- resolve(false)
- return
- }
-
- // Pass through detailed error messages for database setup failures (codes 11-18)
- if error.code >= 11 && error.code <= 18 {
- reject("DATABASE_SETUP_ERROR", error.localizedDescription, error)
- return
- }
- }
-
- // Default error handling
- reject("INIT_ERROR", "Failed to unlock vault: \(error.localizedDescription)", error)
+ // Default error handling for non-AppError errors
+ reject("E-001", "Failed to unlock vault: \(error.localizedDescription)", error)
}
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/AppInfo.swift b/apps/mobile-app/ios/VaultStoreKit/AppInfo.swift
index 657d343ea..9de3c6f77 100644
--- a/apps/mobile-app/ios/VaultStoreKit/AppInfo.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/AppInfo.swift
@@ -6,7 +6,7 @@ public enum AppInfo {
/// The minimum supported AliasVault server (API) version.
///
/// If the server version is below this minimum, the client will reject the connection
- /// and throw a `VaultSyncError.serverVersionNotSupported` error, indicating that the
+ /// and throw a `AppError.serverVersionNotSupported` error, indicating that the
/// server should be updated to a newer version.
///
/// This ensures that the mobile app only communicates with servers that support
diff --git a/apps/mobile-app/ios/VaultStoreKit/Enums/AppError.swift b/apps/mobile-app/ios/VaultStoreKit/Enums/AppError.swift
new file mode 100644
index 000000000..baa460035
--- /dev/null
+++ b/apps/mobile-app/ios/VaultStoreKit/Enums/AppError.swift
@@ -0,0 +1,194 @@
+import Foundation
+
+/// App error codes for mobile app operations.
+/// These error codes are language-independent and can be properly handled by the client.
+public enum AppError: Error {
+ // Authentication errors
+ case authenticationFailed
+ case sessionExpired
+ case passwordChanged
+
+ // Network/connectivity errors
+ case serverUnavailable(statusCode: Int)
+ case networkError(underlyingError: Error)
+ case timeout
+
+ // Version/compatibility errors
+ case clientVersionNotSupported
+ case serverVersionNotSupported
+ case vaultVersionIncompatible
+
+ // Vault status errors
+ case vaultMergeRequired
+ case vaultOutdated
+
+ // Decryption errors
+ case vaultDecryptFailed
+ case base64DecodeFailed
+ case databaseTempWriteFailed
+ case databaseOpenFailed
+ case databaseMemoryFailed
+ case databaseBackupFailed
+ case databasePragmaFailed
+ case biometricCancelled
+ case biometricFailed
+ case keystoreKeyNotFound
+
+ // Storage errors
+ case encryptionKeyNotFound
+ case vaultStoreFailed(message: String)
+
+ // Merge errors
+ case vaultMergeFailed(message: String)
+ case mergeUploadFailed(message: String)
+
+ // Upload errors
+ case vaultUploadFailed(message: String)
+
+ // Retry errors
+ case maxRetriesReached
+
+ // Generic errors
+ case unknownError(message: String)
+ case parseError(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
+ public var code: String {
+ switch self {
+ case .authenticationFailed:
+ return "E-101"
+ case .sessionExpired:
+ return "E-102"
+ case .passwordChanged:
+ return "E-103"
+ case .serverUnavailable:
+ return "E-201"
+ case .networkError:
+ return "E-202"
+ case .timeout:
+ return "E-203"
+ case .clientVersionNotSupported:
+ return "E-301"
+ case .serverVersionNotSupported:
+ return "E-302"
+ case .vaultVersionIncompatible:
+ return "E-303"
+ case .vaultMergeRequired:
+ return "E-401"
+ case .vaultOutdated:
+ return "E-402"
+ case .vaultDecryptFailed:
+ return "E-501"
+ case .encryptionKeyNotFound:
+ return "E-502"
+ case .base64DecodeFailed:
+ return "E-503"
+ case .databaseTempWriteFailed:
+ return "E-504"
+ case .databaseOpenFailed:
+ return "E-505"
+ case .databaseMemoryFailed:
+ return "E-506"
+ case .databaseBackupFailed:
+ return "E-507"
+ case .databasePragmaFailed:
+ return "E-508"
+ case .biometricCancelled:
+ return "E-509"
+ case .biometricFailed:
+ return "E-510"
+ case .keystoreKeyNotFound:
+ return "E-511"
+ case .vaultStoreFailed:
+ return "E-604"
+ case .vaultMergeFailed:
+ return "E-701"
+ case .mergeUploadFailed:
+ return "E-705"
+ case .vaultUploadFailed:
+ return "E-801"
+ case .maxRetriesReached:
+ return "E-901"
+ case .unknownError:
+ return "E-001"
+ case .parseError:
+ return "E-002"
+ }
+ }
+
+ /// Get a user-friendly message (for logging/debugging)
+ public var message: String {
+ switch self {
+ case .authenticationFailed:
+ return "Authentication failed"
+ case .sessionExpired:
+ return "Session expired"
+ case .passwordChanged:
+ return "Password has changed"
+ case .serverUnavailable(let statusCode):
+ return "Server unavailable (status: \(statusCode))"
+ case .networkError(let error):
+ return "Network error: \(error.localizedDescription)"
+ case .timeout:
+ return "Request timeout"
+ case .clientVersionNotSupported:
+ return "Client version not supported"
+ case .serverVersionNotSupported:
+ return "Server version not supported"
+ case .vaultVersionIncompatible:
+ return "Vault version incompatible"
+ case .vaultMergeRequired:
+ return "Vault merge required"
+ case .vaultOutdated:
+ return "Vault outdated"
+ case .vaultDecryptFailed:
+ return "Failed to decrypt vault"
+ case .encryptionKeyNotFound:
+ return "Encryption key not available"
+ case .base64DecodeFailed:
+ return "Base64 decode failed after decryption"
+ case .databaseTempWriteFailed:
+ return "Database setup failed: could not write temp file"
+ case .databaseOpenFailed:
+ return "Database setup failed: could not open source database"
+ case .databaseMemoryFailed:
+ return "Database setup failed: could not create in-memory connection"
+ case .databaseBackupFailed:
+ return "Database setup failed: backup/copy failed"
+ case .databasePragmaFailed:
+ return "Database setup failed: pragma execution failed"
+ case .biometricCancelled:
+ return "Biometric authentication cancelled"
+ case .biometricFailed:
+ return "Biometric authentication failed"
+ case .keystoreKeyNotFound:
+ return "Encryption key not found in keychain"
+ case .vaultStoreFailed(let message):
+ return "Failed to store vault: \(message)"
+ case .vaultMergeFailed(let message):
+ return "Vault merge failed: \(message)"
+ case .mergeUploadFailed(let message):
+ return "Upload after merge failed: \(message)"
+ case .vaultUploadFailed(let message):
+ return "Vault upload failed: \(message)"
+ case .maxRetriesReached:
+ return "Max sync retries reached"
+ case .unknownError(let message):
+ return "Unknown error: \(message)"
+ case .parseError(let message):
+ return "Parse error: \(message)"
+ }
+ }
+}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Enums/VaultSyncError.swift b/apps/mobile-app/ios/VaultStoreKit/Enums/VaultSyncError.swift
deleted file mode 100644
index 3e5aec56f..000000000
--- a/apps/mobile-app/ios/VaultStoreKit/Enums/VaultSyncError.swift
+++ /dev/null
@@ -1,99 +0,0 @@
-import Foundation
-
-/// Error codes for vault sync operations
-/// These error codes are language-independent and can be properly handled by the client
-public enum VaultSyncError: Error {
- // Authentication errors
- case authenticationFailed
- case sessionExpired
- case passwordChanged
-
- // Network/connectivity errors
- case serverUnavailable(statusCode: Int)
- case networkError(underlyingError: Error)
- case timeout
-
- // Version/compatibility errors
- case clientVersionNotSupported
- case serverVersionNotSupported
- case vaultVersionIncompatible
-
- // Vault status errors
- case vaultMergeRequired
- case vaultOutdated
-
- // Decryption errors
- case vaultDecryptFailed
-
- // Generic errors
- case unknownError(message: String)
- case parseError(message: String)
-
- /// Get the error code string for React Native bridge
- public var code: String {
- switch self {
- case .authenticationFailed:
- return "VAULT_SYNC_AUTH_FAILED"
- case .sessionExpired:
- return "VAULT_SYNC_SESSION_EXPIRED"
- case .passwordChanged:
- return "VAULT_SYNC_PASSWORD_CHANGED"
- case .serverUnavailable:
- return "VAULT_SYNC_SERVER_UNAVAILABLE"
- case .networkError:
- return "VAULT_SYNC_NETWORK_ERROR"
- case .timeout:
- return "VAULT_SYNC_TIMEOUT"
- case .clientVersionNotSupported:
- return "VAULT_SYNC_CLIENT_VERSION_NOT_SUPPORTED"
- case .serverVersionNotSupported:
- return "VAULT_SYNC_SERVER_VERSION_NOT_SUPPORTED"
- case .vaultVersionIncompatible:
- return "VAULT_SYNC_VAULT_VERSION_INCOMPATIBLE"
- case .vaultMergeRequired:
- return "VAULT_SYNC_MERGE_REQUIRED"
- case .vaultOutdated:
- return "VAULT_SYNC_OUTDATED"
- case .vaultDecryptFailed:
- return "VAULT_SYNC_DECRYPT_FAILED"
- case .unknownError:
- return "VAULT_SYNC_UNKNOWN_ERROR"
- case .parseError:
- return "VAULT_SYNC_PARSE_ERROR"
- }
- }
-
- /// Get a user-friendly message (for logging/debugging)
- public var message: String {
- switch self {
- case .authenticationFailed:
- return "Authentication failed"
- case .sessionExpired:
- return "Session expired"
- case .passwordChanged:
- return "Password has changed"
- case .serverUnavailable(let statusCode):
- return "Server unavailable (status: \(statusCode))"
- case .networkError(let error):
- return "Network error: \(error.localizedDescription)"
- case .timeout:
- return "Request timeout"
- case .clientVersionNotSupported:
- return "Client version not supported"
- case .serverVersionNotSupported:
- return "Server version not supported"
- case .vaultVersionIncompatible:
- return "Vault version incompatible"
- case .vaultMergeRequired:
- return "Vault merge required"
- case .vaultOutdated:
- return "Vault outdated"
- case .vaultDecryptFailed:
- return "Failed to decrypt vault"
- case .unknownError(let message):
- return "Unknown error: \(message)"
- case .parseError(let message):
- return "Parse error: \(message)"
- }
- }
-}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
index 70a8a9b34..4406dd80f 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
@@ -153,7 +153,7 @@ extension VaultStore {
print("Simulator detected, skipping biometric policy evaluation check and continuing with key retrieval from keychain")
#else
guard context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) else {
- throw NSError(domain: "VaultStore", code: 2, userInfo: [NSLocalizedDescriptionKey: "Face ID not available: \(error?.localizedDescription ?? "Unknown error")"])
+ throw AppError.biometricFailed
}
#endif
@@ -162,12 +162,14 @@ extension VaultStore {
let keyData = try retrieveKeyFromKeychain(context: context)
self.encryptionKey = keyData
return keyData
+ } catch let vaultError as AppError {
+ throw vaultError
} catch {
- throw NSError(domain: "VaultStore", code: 9, userInfo: [NSLocalizedDescriptionKey: "Failed to retrieve key from keychain: \(error.localizedDescription)"])
+ throw AppError.keystoreKeyNotFound
}
}
- throw NSError(domain: "VaultStore", code: 3, userInfo: [NSLocalizedDescriptionKey: "No encryption key found in memory"])
+ throw AppError.keystoreKeyNotFound
}
/// Store the encryption key in the keychain
@@ -243,11 +245,11 @@ extension VaultStore {
guard status == errSecSuccess,
let keyData = result as? Data else {
if status == errSecUserCanceled {
- throw NSError(domain: "VaultStore", code: 8, userInfo: [NSLocalizedDescriptionKey: "Authentication canceled by user"])
+ throw AppError.biometricCancelled
} else if status == errSecAuthFailed {
- throw NSError(domain: "VaultStore", code: 8, userInfo: [NSLocalizedDescriptionKey: "Authentication failed"])
+ throw AppError.biometricFailed
} else {
- throw NSError(domain: "VaultStore", code: 2, userInfo: [NSLocalizedDescriptionKey: "No encryption key found"])
+ throw AppError.keystoreKeyNotFound
}
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift
index 72ffd4ecd..0fca3647b 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift
@@ -25,31 +25,22 @@ extension VaultStore {
/// Unlock the vault - decrypt the database and setup the database with the decrypted data
public func unlockVault() throws {
guard let encryptedDbBase64 = getEncryptedDatabase() else {
- throw NSError(domain: "VaultStore", code: 1, userInfo: [NSLocalizedDescriptionKey: "No encrypted database found"])
+ throw AppError.encryptionKeyNotFound
}
guard let encryptedDbData = Data(base64Encoded: encryptedDbBase64) else {
- throw NSError(domain: "VaultStore", code: 1, userInfo: [NSLocalizedDescriptionKey: "Could not base64 decode encrypted database"])
+ throw AppError.base64DecodeFailed
}
do {
let decryptedDbBase64 = try decrypt(data: encryptedDbData)
try setupDatabaseWithDecryptedData(decryptedDbBase64)
- } catch let error as NSError {
- // If it's already a VaultStore error with detailed info, pass it through
- if error.domain == "VaultStore" && error.code >= 10 {
- throw error
- }
-
- // Otherwise, it's a decryption error
- throw NSError(
- domain: "VaultStore",
- code: 5,
- userInfo: [
- NSLocalizedDescriptionKey: "Could not unlock vault: Decryption failed",
- NSUnderlyingErrorKey: error
- ]
- )
+ } catch let vaultError as AppError {
+ // Pass through AppError types
+ throw vaultError
+ } catch {
+ // Wrap other errors as decryption failure
+ throw AppError.vaultDecryptFailed
}
}
@@ -70,11 +61,7 @@ extension VaultStore {
private func setupDatabaseWithDecryptedData(_ decryptedDbBase64: Data) throws {
// Step 1: Decode base64
guard let decryptedDbData = Data(base64Encoded: decryptedDbBase64) else {
- throw NSError(
- domain: "VaultStore",
- code: 10,
- userInfo: [NSLocalizedDescriptionKey: "Database setup failed: Could not decode base64 data after decryption"]
- )
+ throw AppError.base64DecodeFailed
}
// Step 2: Clean up any existing connection
@@ -85,14 +72,7 @@ extension VaultStore {
do {
try decryptedDbData.write(to: tempDbPath)
} catch {
- throw NSError(
- domain: "VaultStore",
- code: 11,
- userInfo: [
- NSLocalizedDescriptionKey: "Database setup failed: Could not write decrypted data to temp file",
- NSUnderlyingErrorKey: error
- ]
- )
+ throw AppError.databaseTempWriteFailed
}
// Step 4: Open source database from temp file
@@ -101,14 +81,7 @@ extension VaultStore {
sourceConnection = try Connection(tempDbPath.path)
} catch {
try? FileManager.default.removeItem(at: tempDbPath)
- throw NSError(
- domain: "VaultStore",
- code: 12,
- userInfo: [
- NSLocalizedDescriptionKey: "Database setup failed: Could not open source database (file may be corrupt)",
- NSUnderlyingErrorKey: error
- ]
- )
+ throw AppError.databaseOpenFailed
}
// Step 5: Create in-memory database connection
@@ -116,14 +89,7 @@ extension VaultStore {
self.dbConnection = try Connection(":memory:")
} catch {
try? FileManager.default.removeItem(at: tempDbPath)
- throw NSError(
- domain: "VaultStore",
- code: 13,
- userInfo: [
- NSLocalizedDescriptionKey: "Database setup failed: Could not create in-memory database connection",
- NSUnderlyingErrorKey: error
- ]
- )
+ throw AppError.databaseMemoryFailed
}
// Step 6: Use SQLite backup API to copy entire database with full schema preservation
@@ -134,14 +100,7 @@ extension VaultStore {
backup.finish()
} catch {
try? FileManager.default.removeItem(at: tempDbPath)
- throw NSError(
- domain: "VaultStore",
- code: 14,
- userInfo: [
- NSLocalizedDescriptionKey: "Database setup failed: Could not backup database to memory",
- NSUnderlyingErrorKey: error
- ]
- )
+ throw AppError.databaseBackupFailed
}
// Clean up temp file
@@ -153,14 +112,7 @@ extension VaultStore {
try self.dbConnection?.execute("PRAGMA synchronous = NORMAL")
try self.dbConnection?.execute("PRAGMA foreign_keys = ON")
} catch {
- throw NSError(
- domain: "VaultStore",
- code: 15,
- userInfo: [
- NSLocalizedDescriptionKey: "Database setup failed: Could not set database pragmas",
- NSUnderlyingErrorKey: error
- ]
- )
+ throw AppError.databasePragmaFailed
}
}
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift
index 09a8af622..b15c2ace5 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift
@@ -145,14 +145,14 @@ extension VaultStore {
requiresAuth: true
)
} catch {
- throw VaultSyncError.networkError(underlyingError: error)
+ throw AppError.networkError(underlyingError: error)
}
guard vaultResponse.statusCode == 200 else {
if vaultResponse.statusCode == 401 {
- throw VaultSyncError.sessionExpired
+ throw AppError.sessionExpired
}
- throw VaultSyncError.serverUnavailable(statusCode: vaultResponse.statusCode)
+ throw AppError.serverUnavailable(statusCode: vaultResponse.statusCode)
}
return try parseVaultResponse(vaultResponse.body)
@@ -250,7 +250,7 @@ extension VaultStore {
error: nil
)
}
- } catch let error as VaultSyncError {
+ } catch let error as AppError {
setIsSyncing(false)
return handleSyncError(error)
} catch {
@@ -313,7 +313,7 @@ extension VaultStore {
wasOffline: false,
error: nil
)
- } catch let error as VaultSyncError {
+ } catch let error as AppError {
setIsSyncing(false)
return handleSyncError(error)
} catch {
@@ -450,7 +450,7 @@ extension VaultStore {
error: uploadResult.error ?? "Upload after merge failed"
)
}
- } catch let error as VaultSyncError {
+ } catch let error as AppError {
setIsSyncing(false)
return handleSyncError(error)
} catch {
@@ -478,10 +478,10 @@ extension VaultStore {
/// - localVault: Base64-encoded encrypted local vault blob
/// - serverVault: Base64-encoded encrypted server vault blob
/// - Returns: Base64-encoded encrypted merged vault blob
- /// - Throws: VaultSyncError if merge fails
+ /// - Throws: AppError if merge fails
private func performLWWMerge(localVault: String, serverVault: String) throws -> String {
guard let encryptionKey = self.encryptionKey else {
- throw VaultSyncError.unknownError(message: "Encryption key not available for merge")
+ throw AppError.unknownError(message: "Encryption key not available for merge")
}
do {
@@ -494,15 +494,15 @@ extension VaultStore {
return mergedVault
} catch let error as VaultMergeService.VaultMergeError {
print("[VaultSync] Merge error: \(error.localizedDescription)")
- throw VaultSyncError.unknownError(message: "Merge failed: \(error.localizedDescription)")
+ throw AppError.unknownError(message: "Merge failed: \(error.localizedDescription)")
} catch {
print("[VaultSync] Unexpected merge error: \(error)")
- throw VaultSyncError.unknownError(message: "Merge failed: \(error.localizedDescription)")
+ throw AppError.unknownError(message: "Merge failed: \(error.localizedDescription)")
}
}
/// Handle sync errors and return appropriate result
- private func handleSyncError(_ error: VaultSyncError) -> VaultSyncResult {
+ private func handleSyncError(_ error: AppError) -> VaultSyncResult {
switch error {
case .networkError, .serverUnavailable, .timeout:
setOfflineMode(true)
@@ -547,8 +547,8 @@ extension VaultStore {
requiresAuth: true
)
} catch {
- // Network error - convert to VaultSyncError
- throw VaultSyncError.networkError(underlyingError: error)
+ // Network error - convert to AppError
+ throw AppError.networkError(underlyingError: error)
}
// Check response status
@@ -558,18 +558,18 @@ extension VaultStore {
if statusResponse.statusCode == 401 {
// Authentication failed even after token refresh attempt
print("VaultStore: Authentication failed (401) - token refresh also failed")
- throw VaultSyncError.sessionExpired
+ throw AppError.sessionExpired
}
// Other error (5xx, network, etc.) - go offline
setOfflineMode(true)
- throw VaultSyncError.serverUnavailable(statusCode: statusResponse.statusCode)
+ throw AppError.serverUnavailable(statusCode: statusResponse.statusCode)
}
guard let statusData = statusResponse.body.data(using: .utf8) else {
print("VaultStore: Failed to convert status response to data")
print("VaultStore: Response body: '\(statusResponse.body)'")
- throw VaultSyncError.parseError(message: "Failed to convert status response to data")
+ throw AppError.parseError(message: "Failed to convert status response to data")
}
let decoder = JSONDecoder()
@@ -579,17 +579,17 @@ extension VaultStore {
} catch {
print("VaultStore: Failed to decode status response: \(error)")
print("VaultStore: Response body: '\(statusResponse.body)'")
- throw VaultSyncError.parseError(message: "Failed to decode status response: \(error.localizedDescription)")
+ throw AppError.parseError(message: "Failed to decode status response: \(error.localizedDescription)")
}
guard status.clientVersionSupported else {
- throw VaultSyncError.clientVersionNotSupported
+ throw AppError.clientVersionNotSupported
}
// Validate server version meets minimum requirement
guard VersionComparison.isServerVersionSupported(status.serverVersion) else {
print("VaultStore: Server version \(status.serverVersion) does not meet minimum requirement \(AppInfo.minServerVersion)")
- throw VaultSyncError.serverVersionNotSupported
+ throw AppError.serverVersionNotSupported
}
// Store server version in metadata
@@ -608,7 +608,7 @@ extension VaultStore {
}
if !srpSalt.isEmpty && srpSalt != params.salt {
- throw VaultSyncError.passwordChanged
+ throw AppError.passwordChanged
}
}
@@ -624,14 +624,14 @@ extension VaultStore {
requiresAuth: true
)
} catch {
- throw VaultSyncError.networkError(underlyingError: error)
+ throw AppError.networkError(underlyingError: error)
}
guard vaultResponse.statusCode == 200 else {
if vaultResponse.statusCode == 401 {
- throw VaultSyncError.sessionExpired
+ throw AppError.sessionExpired
}
- throw VaultSyncError.serverUnavailable(statusCode: vaultResponse.statusCode)
+ throw AppError.serverUnavailable(statusCode: vaultResponse.statusCode)
}
let vault = try parseVaultResponse(vaultResponse.body)
@@ -658,7 +658,7 @@ extension VaultStore {
let encoder = JSONEncoder()
guard let metadataData = try? encoder.encode(metadata),
let metadataJson = String(data: metadataData, encoding: .utf8) else {
- throw VaultSyncError.parseError(message: "Failed to encode vault metadata")
+ throw AppError.parseError(message: "Failed to encode vault metadata")
}
try storeMetadata(metadataJson)
@@ -667,7 +667,7 @@ extension VaultStore {
/// Parse vault response from JSON
private func parseVaultResponse(_ body: String) throws -> VaultResponse {
guard let vaultData = body.data(using: .utf8) else {
- throw VaultSyncError.parseError(message: "Failed to convert vault response to data")
+ throw AppError.parseError(message: "Failed to convert vault response to data")
}
do {
@@ -675,7 +675,7 @@ extension VaultStore {
} catch {
print("VaultStore: Failed to decode vault response: \(error)")
print("VaultStore: Response body: \(body)")
- throw VaultSyncError.parseError(message: "Failed to decode vault response: \(error.localizedDescription)")
+ throw AppError.parseError(message: "Failed to decode vault response: \(error.localizedDescription)")
}
}
@@ -685,11 +685,11 @@ extension VaultStore {
case 0:
return
case 1:
- throw VaultSyncError.vaultMergeRequired
+ throw AppError.vaultMergeRequired
case 2:
- throw VaultSyncError.vaultOutdated
+ throw AppError.vaultOutdated
default:
- throw VaultSyncError.unknownError(message: "Unknown vault status: \(status)")
+ throw AppError.unknownError(message: "Unknown vault status: \(status)")
}
}
}
diff --git a/apps/mobile-app/utils/types/errors/AppErrorCodes.ts b/apps/mobile-app/utils/types/errors/AppErrorCodes.ts
new file mode 100644
index 000000000..1cc7c065d
--- /dev/null
+++ b/apps/mobile-app/utils/types/errors/AppErrorCodes.ts
@@ -0,0 +1,228 @@
+/**
+ * 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',
+
+ // 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',
+ TIMEOUT = 'E-203',
+
+ // 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',
+
+ // 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
+
+ // Decryption/Encryption errors (E-5xx) - from AppError.kt
+ VAULT_DECRYPT_FAILED = 'E-501',
+ 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
+
+ // Database/Storage errors (E-6xx) - from VaultSync.kt
+ VAULT_STORE_FAILED = 'E-604', // AppError: failed to store vault
+
+ // 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
+
+ // 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
+}
+
+/**
+ * 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;
+}
+
+/**
+ * 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',
+
+ // Authentication errors
+ [AppErrorCode.AUTHENTICATION_FAILED]: 'auth.errors.sessionExpired',
+ [AppErrorCode.SESSION_EXPIRED]: 'auth.errors.sessionExpired',
+ [AppErrorCode.PASSWORD_CHANGED]: 'vault.errors.passwordChanged',
+
+ // Network errors
+ [AppErrorCode.SERVER_UNAVAILABLE]: 'auth.errors.serverError',
+ [AppErrorCode.NETWORK_ERROR]: 'auth.errors.networkError',
+ [AppErrorCode.TIMEOUT]: 'auth.errors.networkError',
+
+ // 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',
+
+ // Vault status errors
+ [AppErrorCode.VAULT_MERGE_REQUIRED]: 'common.errors.unknownErrorTryAgain',
+ [AppErrorCode.VAULT_OUTDATED]: 'vault.errors.vaultOutdated',
+ [AppErrorCode.VAULT_NOT_FOUND]: '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]: 'auth.errors.biometricCancelled',
+ [AppErrorCode.BIOMETRIC_FAILED]: 'auth.errors.biometricFailed',
+ [AppErrorCode.KEYSTORE_KEY_NOT_FOUND]: 'common.errors.unknownErrorTryAgain',
+
+ // Database/Storage errors
+ [AppErrorCode.VAULT_STORE_FAILED]: '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',
+
+ // Native module/retry errors
+ [AppErrorCode.MAX_RETRIES_REACHED]: 'common.errors.unknownErrorTryAgain',
+ [AppErrorCode.NATIVE_UNLOCK_FAILED]: 'common.errors.unknownErrorTryAgain',
+ };
+
+ return codeToKeyMap[code] || 'common.errors.unknownErrorTryAgain';
+}
diff --git a/apps/mobile-app/utils/types/errors/VaultSyncErrorCodes.ts b/apps/mobile-app/utils/types/errors/VaultSyncErrorCodes.ts
deleted file mode 100644
index a3eddb8e8..000000000
--- a/apps/mobile-app/utils/types/errors/VaultSyncErrorCodes.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-/**
- * Error codes for vault sync operations
- * These codes are returned from native layer and should be used instead of parsing error messages
- * This enables multi-language support and robust error handling
- */
-export enum VaultSyncErrorCode {
- // Authentication errors
- AUTHENTICATION_FAILED = 'VAULT_SYNC_AUTH_FAILED',
- SESSION_EXPIRED = 'VAULT_SYNC_SESSION_EXPIRED',
- PASSWORD_CHANGED = 'VAULT_SYNC_PASSWORD_CHANGED',
-
- // Network/connectivity errors
- SERVER_UNAVAILABLE = 'VAULT_SYNC_SERVER_UNAVAILABLE',
- NETWORK_ERROR = 'VAULT_SYNC_NETWORK_ERROR',
- TIMEOUT = 'VAULT_SYNC_TIMEOUT',
-
- // Version/compatibility errors
- CLIENT_VERSION_NOT_SUPPORTED = 'VAULT_SYNC_CLIENT_VERSION_NOT_SUPPORTED',
- SERVER_VERSION_NOT_SUPPORTED = 'VAULT_SYNC_SERVER_VERSION_NOT_SUPPORTED',
- VAULT_VERSION_INCOMPATIBLE = 'VAULT_SYNC_VAULT_VERSION_INCOMPATIBLE',
-
- // Vault status errors
- VAULT_MERGE_REQUIRED = 'VAULT_SYNC_MERGE_REQUIRED',
- VAULT_OUTDATED = 'VAULT_SYNC_OUTDATED',
-
- // Decryption errors
- VAULT_DECRYPT_FAILED = 'VAULT_SYNC_DECRYPT_FAILED',
-
- // Generic errors
- UNKNOWN_ERROR = 'VAULT_SYNC_UNKNOWN_ERROR',
- PARSE_ERROR = 'VAULT_SYNC_PARSE_ERROR',
-}
-
-/**
- * Check if an error is a vault sync error
- */
-export function isVaultSyncError(error: unknown): error is { code: string } {
- return (
- typeof error === 'object' &&
- error !== null &&
- 'code' in error &&
- typeof (error as { code: unknown }).code === 'string' &&
- (error as { code: string }).code.startsWith('VAULT_SYNC_')
- );
-}
-
-/**
- * Get the vault sync error code from an error object
- */
-export function getVaultSyncErrorCode(error: unknown): VaultSyncErrorCode | null {
- if (isVaultSyncError(error)) {
- return error.code as VaultSyncErrorCode;
- }
- return null;
-}