Skip to content

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

Refactor VaultStore kotlin to separate components (#520)

Leendert de Borstb2206cae8f88
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultAuth.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultAuth.kt
new file mode 100644
index 000000000..9f06da94c
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultAuth.kt
@@ -0,0 +1,92 @@
+package net.aliasvault.app.vaultstore
+
+import android.os.Handler
+import android.util.Log
+import net.aliasvault.app.vaultstore.storageprovider.StorageProvider
+
+/**
+ * Handles authentication methods and auto-lock functionality for the vault.
+ */
+class VaultAuth(
+ private val storageProvider: StorageProvider,
+ private val onClearCache: () -> Unit,
+) {
+ companion object {
+ private const val TAG = "VaultAuth"
+ }
+
+ private var autoLockHandler: Handler? = null
+ private var autoLockRunnable: Runnable? = null
+
+ // region Authentication Methods
+
+ /**
+ * Set the auth methods.
+ */
+ fun setAuthMethods(authMethods: String) {
+ storageProvider.setAuthMethods(authMethods)
+ }
+
+ /**
+ * Get the auth methods.
+ */
+ fun getAuthMethods(): String {
+ return storageProvider.getAuthMethods()
+ }
+
+ // endregion
+
+ // region Auto-Lock Timeout
+
+ /**
+ * Set the auto-lock timeout.
+ */
+ fun setAutoLockTimeout(timeout: Int) {
+ storageProvider.setAutoLockTimeout(timeout)
+ }
+
+ /**
+ * Get the auto-lock timeout.
+ */
+ fun getAutoLockTimeout(): Int {
+ return storageProvider.getAutoLockTimeout()
+ }
+
+ // endregion
+
+ // region Background/Foreground Handling
+
+ /**
+ * Called when the app enters the background.
+ */
+ fun onAppBackgrounded() {
+ Log.d(TAG, "App entered background, starting auto-lock timer with ${getAutoLockTimeout()}s")
+ if (getAutoLockTimeout() > 0) {
+ autoLockRunnable?.let { autoLockHandler?.removeCallbacks(it) }
+
+ autoLockRunnable = Runnable {
+ Log.d(TAG, "Auto-lock timer fired, clearing cache")
+ onClearCache()
+ }
+ autoLockHandler?.postDelayed(autoLockRunnable!!, getAutoLockTimeout().toLong() * 1000)
+ }
+ }
+
+ /**
+ * Called when the app enters the foreground.
+ */
+ fun onAppForegrounded() {
+ Log.d(TAG, "App entered foreground, canceling auto-lock timer")
+ autoLockRunnable?.let { autoLockHandler?.removeCallbacks(it) }
+ autoLockRunnable = null
+ }
+
+ /**
+ * Set the auto-lock handler.
+ */
+ fun setAutoLockHandler(handler: Handler) {
+ this.autoLockHandler = handler
+ }
+
+ // endregion
+}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCache.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCache.kt
new file mode 100644
index 000000000..ae83fbd0b
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCache.kt
@@ -0,0 +1,42 @@
+package net.aliasvault.app.vaultstore
+
+import android.util.Log
+import net.aliasvault.app.vaultstore.keystoreprovider.KeystoreProvider
+
+/**
+ * Handles cache management for the vault, including clearing cached data.
+ */
+class VaultCache(
+ private val crypto: VaultCrypto,
+ private val database: VaultDatabase,
+ private val keystoreProvider: KeystoreProvider,
+ private val storageProvider: net.aliasvault.app.vaultstore.storageprovider.StorageProvider,
+) {
+ companion object {
+ private const val TAG = "VaultCache"
+ }
+
+ // region Cache Management
+
+ /**
+ * Clear the memory, removing the encryption key and decrypted database from memory.
+ */
+ fun clearCache() {
+ Log.d(TAG, "Clearing cache - removing encryption key and decrypted database from memory")
+ database.close()
+ crypto.clearKey()
+ }
+
+ /**
+ * Clear all vault data including from persisted storage.
+ */
+ fun clearVault() {
+ clearCache()
+
+ keystoreProvider.clearKeys()
+
+ storageProvider.clearStorage()
+ }
+
+ // endregion
+}
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
new file mode 100644
index 000000000..aaceae810
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt
@@ -0,0 +1,253 @@
+package net.aliasvault.app.vaultstore
+
+import android.util.Base64
+import android.util.Log
+import com.lambdapioneer.argon2kt.Argon2Kt
+import com.lambdapioneer.argon2kt.Argon2Mode
+import com.lambdapioneer.argon2kt.Argon2Version
+import net.aliasvault.app.vaultstore.interfaces.CryptoOperationCallback
+import net.aliasvault.app.vaultstore.keystoreprovider.KeystoreOperationCallback
+import net.aliasvault.app.vaultstore.keystoreprovider.KeystoreProvider
+import net.aliasvault.app.vaultstore.storageprovider.StorageProvider
+import org.json.JSONObject
+import java.security.SecureRandom
+import javax.crypto.Cipher
+import javax.crypto.spec.GCMParameterSpec
+import javax.crypto.spec.SecretKeySpec
+
+/**
+ * Handles encryption, decryption, and key management for the vault.
+ */
+class VaultCrypto(
+ private val keystoreProvider: KeystoreProvider,
+ private val storageProvider: StorageProvider,
+) {
+ companion object {
+ private const val TAG = "VaultCrypto"
+ private const val BIOMETRICS_AUTH_METHOD = "faceid"
+ }
+
+ /**
+ * The encryption key.
+ */
+ internal var encryptionKey: ByteArray? = null
+
+ // region Key Derivation
+
+ /**
+ * Derive a key from a password using Argon2Id.
+ */
+ fun deriveKeyFromPassword(
+ password: String,
+ salt: String,
+ encryptionType: String,
+ encryptionSettings: String,
+ ): ByteArray {
+ require(encryptionType == "Argon2Id") { "Unsupported encryption type: $encryptionType" }
+
+ val settings = JSONObject(encryptionSettings)
+ val iterations = settings.getInt("Iterations")
+ val memorySize = settings.getInt("MemorySize")
+ val parallelism = settings.getInt("DegreeOfParallelism")
+
+ val argon2 = Argon2Kt()
+
+ val hashResult = argon2.hash(
+ mode = Argon2Mode.ARGON2_ID,
+ password = password.toByteArray(Charsets.UTF_8),
+ salt = salt.toByteArray(Charsets.UTF_8),
+ tCostInIterations = iterations,
+ mCostInKibibyte = memorySize,
+ parallelism = parallelism,
+ hashLengthInBytes = 32,
+ version = Argon2Version.V13,
+ )
+
+ return hashResult.rawHashAsByteArray()
+ }
+
+ // endregion
+
+ // region Encryption Key Management
+
+ /**
+ * Store the encryption key.
+ */
+ fun storeEncryptionKey(base64EncryptionKey: String, authMethods: String) {
+ this.encryptionKey = Base64.decode(base64EncryptionKey, Base64.NO_WRAP)
+
+ if (authMethods.contains(BIOMETRICS_AUTH_METHOD) && keystoreProvider.isBiometricAvailable()) {
+ val latch = java.util.concurrent.CountDownLatch(1)
+ var error: Exception? = null
+
+ keystoreProvider.storeKey(
+ key = base64EncryptionKey,
+ object : KeystoreOperationCallback {
+ override fun onSuccess(result: String) {
+ Log.d(TAG, "Encryption key stored successfully with biometric protection")
+ latch.countDown()
+ }
+
+ override fun onError(e: Exception) {
+ Log.e(TAG, "Error storing encryption key with biometric protection", e)
+ error = e
+ latch.countDown()
+ }
+ },
+ )
+
+ latch.await()
+ error?.let { throw it }
+ }
+ }
+
+ /**
+ * Initialize the encryption key.
+ */
+ fun initEncryptionKey(base64EncryptionKey: String) {
+ this.encryptionKey = Base64.decode(base64EncryptionKey, Base64.NO_WRAP)
+ }
+
+ /**
+ * Store the encryption key derivation parameters.
+ */
+ fun storeEncryptionKeyDerivationParams(keyDerivationParams: String) {
+ storageProvider.setKeyDerivationParams(keyDerivationParams)
+ }
+
+ /**
+ * Get the encryption key derivation parameters.
+ */
+ fun getEncryptionKeyDerivationParams(): String {
+ return storageProvider.getKeyDerivationParams()
+ }
+
+ /**
+ * Check if biometric authentication is enabled and available.
+ */
+ fun isBiometricAuthEnabled(authMethods: String): Boolean {
+ return authMethods.contains(BIOMETRICS_AUTH_METHOD) && keystoreProvider.isBiometricAvailable()
+ }
+
+ /**
+ * Get the encryption key.
+ */
+ fun getEncryptionKey(callback: CryptoOperationCallback, authMethods: String) {
+ encryptionKey?.let {
+ callback.onSuccess(Base64.encodeToString(it, Base64.NO_WRAP))
+ return
+ }
+
+ if (isBiometricAuthEnabled(authMethods)) {
+ keystoreProvider.retrieveKey(
+ object : KeystoreOperationCallback {
+ override fun onSuccess(result: String) {
+ try {
+ encryptionKey = Base64.decode(result, Base64.NO_WRAP)
+ callback.onSuccess(result)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error decoding retrieved key", e)
+ callback.onError(e)
+ }
+ }
+
+ override fun onError(e: Exception) {
+ Log.e(TAG, "Error retrieving key", e)
+ callback.onError(e)
+ }
+ },
+ )
+ } else {
+ callback.onError(Exception("No encryption key found"))
+ }
+ }
+
+ /**
+ * Clear the encryption key from memory.
+ */
+ fun clearKey() {
+ encryptionKey = null
+ }
+
+ // endregion
+
+ // region Encryption/Decryption
+
+ /**
+ * Decrypt data.
+ */
+ fun decryptData(encryptedData: String, authMethods: String): String {
+ var decryptedResult: String? = null
+ var error: Exception? = null
+
+ val latch = java.util.concurrent.CountDownLatch(1)
+
+ getEncryptionKey(
+ object : CryptoOperationCallback {
+ override fun onSuccess(result: String) {
+ try {
+ val decoded = Base64.decode(encryptedData, Base64.NO_WRAP)
+
+ val iv = decoded.copyOfRange(0, 12)
+ val encryptedContent = decoded.copyOfRange(12, decoded.size)
+
+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")
+ val keySpec = SecretKeySpec(encryptionKey!!, "AES")
+ val gcmSpec = GCMParameterSpec(128, iv)
+
+ cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmSpec)
+
+ val decrypted = cipher.doFinal(encryptedContent)
+ decryptedResult = String(decrypted, Charsets.UTF_8)
+ } catch (e: Exception) {
+ error = e
+ Log.e(TAG, "Error decrypting data", e)
+ } finally {
+ latch.countDown()
+ }
+ }
+
+ override fun onError(e: Exception) {
+ error = e
+ Log.e(TAG, "Error getting encryption key", e)
+ latch.countDown()
+ }
+ },
+ authMethods,
+ )
+
+ latch.await()
+
+ error?.let { throw it }
+ return decryptedResult ?: error("Decryption failed")
+ }
+
+ /**
+ * Encrypt data.
+ */
+ fun encryptData(data: String): String {
+ try {
+ val iv = ByteArray(12)
+ SecureRandom().nextBytes(iv)
+
+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")
+ val keySpec = SecretKeySpec(encryptionKey!!, "AES")
+ val gcmSpec = GCMParameterSpec(128, iv)
+
+ cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmSpec)
+
+ val encrypted = cipher.doFinal(data.toByteArray(Charsets.UTF_8))
+
+ val result = ByteArray(iv.size + encrypted.size)
+ System.arraycopy(iv, 0, result, 0, iv.size)
+ System.arraycopy(encrypted, 0, result, iv.size, encrypted.size)
+
+ return Base64.encodeToString(result, Base64.NO_WRAP)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error encrypting data", e)
+ throw e
+ }
+ }
+
+ // endregion
+}
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
new file mode 100644
index 000000000..e167af32d
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultDatabase.kt
@@ -0,0 +1,230 @@
+package net.aliasvault.app.vaultstore
+
+import android.database.sqlite.SQLiteDatabase
+import android.util.Base64
+import android.util.Log
+import net.aliasvault.app.vaultstore.storageprovider.StorageProvider
+import java.io.File
+
+/**
+ * Handles database storage, encryption, and decryption operations.
+ */
+class VaultDatabase(
+ private val storageProvider: StorageProvider,
+ private val crypto: VaultCrypto,
+) {
+ companion object {
+ private const val TAG = "VaultDatabase"
+ }
+
+ /**
+ * The database connection.
+ */
+ internal var dbConnection: SQLiteDatabase? = null
+
+ // region Database Storage
+
+ /**
+ * Store the encrypted database in the storage provider.
+ */
+ fun storeEncryptedDatabase(encryptedData: String) {
+ storageProvider.setEncryptedDatabaseFile(encryptedData)
+ }
+
+ /**
+ * Get the encrypted database from the storage provider.
+ */
+ fun getEncryptedDatabase(): String {
+ return storageProvider.getEncryptedDatabaseFile().readText()
+ }
+
+ /**
+ * Check if the encrypted database exists in the storage provider.
+ */
+ fun hasEncryptedDatabase(): Boolean {
+ return storageProvider.getEncryptedDatabaseFile().exists()
+ }
+
+ // endregion
+
+ // region Vault Unlock
+
+ /**
+ * Unlock the vault. This can trigger biometric authentication.
+ */
+ fun unlockVault(authMethods: String) {
+ val encryptedDbBase64 = getEncryptedDatabase()
+ val decryptedDbBase64 = crypto.decryptData(encryptedDbBase64, authMethods)
+
+ try {
+ setupDatabaseWithDecryptedData(decryptedDbBase64)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error unlocking vault", e)
+ throw e
+ }
+ }
+
+ /**
+ * Check if the vault is unlocked.
+ */
+ fun isVaultUnlocked(): Boolean {
+ return crypto.encryptionKey != null
+ }
+
+ // endregion
+
+ // region Database Setup
+
+ /**
+ * Setup the database with decrypted data.
+ */
+ private fun setupDatabaseWithDecryptedData(decryptedDbBase64: String) {
+ var tempDbFile: File? = null
+ try {
+ val decryptedDbData = Base64.decode(decryptedDbBase64, Base64.NO_WRAP)
+
+ tempDbFile = File.createTempFile("temp_db", ".sqlite")
+ tempDbFile.deleteOnExit()
+ tempDbFile.writeBytes(decryptedDbData)
+
+ dbConnection?.close()
+
+ dbConnection = SQLiteDatabase.create(null)
+
+ dbConnection?.beginTransaction()
+
+ try {
+ val attachQuery = "ATTACH DATABASE '${tempDbFile.path}' AS source"
+ dbConnection?.execSQL(attachQuery)
+
+ val verifyCursor = dbConnection?.rawQuery(
+ "SELECT name FROM source.sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'",
+ null,
+ )
+
+ if (verifyCursor == null) {
+ throw android.database.sqlite.SQLiteException("Failed to attach source database")
+ }
+
+ verifyCursor.use {
+ if (!it.moveToFirst()) {
+ throw android.database.sqlite.SQLiteException("No tables found in source database")
+ }
+
+ do {
+ val tableName = it.getString(0)
+ dbConnection?.execSQL(
+ "CREATE TABLE $tableName AS SELECT * FROM source.$tableName",
+ )
+ } while (it.moveToNext())
+ }
+
+ dbConnection?.setTransactionSuccessful()
+ } finally {
+ dbConnection?.endTransaction()
+ }
+
+ dbConnection?.rawQuery("DETACH DATABASE source", null)
+
+ 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, "Error setting up database with decrypted data", e)
+ throw e
+ } finally {
+ tempDbFile?.let {
+ if (it.exists()) {
+ it.setWritable(true, true)
+ it.delete()
+ }
+ }
+ }
+ }
+
+ // endregion
+
+ // region Transaction Management
+
+ /**
+ * Begin a SQL transaction on the vault.
+ */
+ fun beginTransaction() {
+ dbConnection?.beginTransaction()
+ }
+
+ /**
+ * Commit a SQL transaction and persist the encrypted vault.
+ */
+ fun commitTransaction() {
+ dbConnection?.setTransactionSuccessful()
+ dbConnection?.endTransaction()
+
+ val tempDbFile = File.createTempFile("temp_db", ".sqlite")
+ tempDbFile.deleteOnExit()
+
+ try {
+ dbConnection?.execSQL("ATTACH DATABASE '${tempDbFile.path}' AS target")
+
+ dbConnection?.beginTransaction()
+
+ try {
+ val cursor = dbConnection?.rawQuery(
+ "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE 'android_%'",
+ null,
+ )
+
+ cursor?.use {
+ while (it.moveToNext()) {
+ val tableName = it.getString(0)
+ dbConnection?.execSQL(
+ "CREATE TABLE target.$tableName AS SELECT * FROM main.$tableName",
+ )
+ }
+ }
+
+ dbConnection?.setTransactionSuccessful()
+ } finally {
+ dbConnection?.endTransaction()
+ }
+
+ dbConnection?.execSQL("DETACH DATABASE target")
+
+ val rawData = tempDbFile.readBytes()
+
+ val base64String = Base64.encodeToString(rawData, Base64.NO_WRAP)
+ val encryptedBase64Data = crypto.encryptData(base64String)
+
+ storeEncryptedDatabase(encryptedBase64Data)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error exporting and encrypting database", e)
+ throw e
+ } finally {
+ if (tempDbFile.exists()) {
+ tempDbFile.setWritable(true, true)
+ tempDbFile.delete()
+ }
+ }
+ }
+
+ /**
+ * Rollback a SQL transaction on the vault.
+ */
+ fun rollbackTransaction() {
+ dbConnection?.endTransaction()
+ }
+
+ // endregion
+
+ // region Cleanup
+
+ /**
+ * Close the database connection.
+ */
+ fun close() {
+ dbConnection?.close()
+ dbConnection = null
+ }
+
+ // endregion
+}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultMetadataManager.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultMetadataManager.kt
new file mode 100644
index 000000000..971c888ea
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultMetadataManager.kt
@@ -0,0 +1,134 @@
+package net.aliasvault.app.vaultstore
+
+import android.util.Log
+import net.aliasvault.app.vaultstore.models.VaultMetadata
+import net.aliasvault.app.vaultstore.storageprovider.StorageProvider
+import org.json.JSONArray
+import org.json.JSONObject
+
+/**
+ * Handles metadata operations for the vault.
+ */
+class VaultMetadataManager(
+ private val storageProvider: StorageProvider,
+) {
+ companion object {
+ private const val TAG = "VaultMetadata"
+ }
+
+ // region Metadata Storage
+
+ /**
+ * Store the metadata in the storage provider.
+ */
+ fun storeMetadata(metadata: String) {
+ storageProvider.setMetadata(metadata)
+ }
+
+ /**
+ * Get the metadata from the storage provider.
+ */
+ fun getMetadata(): String {
+ return storageProvider.getMetadata()
+ }
+
+ // endregion
+
+ // region Vault Revision Number
+
+ /**
+ * Set the vault revision number.
+ */
+ fun setVaultRevisionNumber(revisionNumber: Int) {
+ val metadata = getVaultMetadataObject() ?: VaultMetadata()
+ val updatedMetadata = metadata.copy(vaultRevisionNumber = revisionNumber)
+ storeMetadata(
+ JSONObject().apply {
+ put("publicEmailDomains", JSONArray(updatedMetadata.publicEmailDomains))
+ put("privateEmailDomains", JSONArray(updatedMetadata.privateEmailDomains))
+ put("vaultRevisionNumber", updatedMetadata.vaultRevisionNumber)
+ }.toString(),
+ )
+ }
+
+ /**
+ * Get the vault revision number.
+ */
+ fun getVaultRevisionNumber(): Int {
+ return getVaultMetadataObject()?.vaultRevisionNumber ?: 0
+ }
+
+ // endregion
+
+ // region Username Management
+
+ /**
+ * Set the username.
+ */
+ fun setUsername(username: String) {
+ storageProvider.setUsername(username)
+ }
+
+ /**
+ * Get the username.
+ */
+ fun getUsername(): String? {
+ return storageProvider.getUsername()
+ }
+
+ /**
+ * Clear the username.
+ */
+ fun clearUsername() {
+ storageProvider.clearUsername()
+ }
+
+ // endregion
+
+ // region Offline Mode Management
+
+ /**
+ * Set offline mode flag.
+ */
+ fun setOfflineMode(isOffline: Boolean) {
+ storageProvider.setOfflineMode(isOffline)
+ }
+
+ /**
+ * Get offline mode flag.
+ */
+ fun getOfflineMode(): Boolean {
+ return storageProvider.getOfflineMode()
+ }
+
+ // endregion
+
+ // region Internal Helpers
+
+ /**
+ * Get the vault metadata object.
+ */
+ fun getVaultMetadataObject(): VaultMetadata? {
+ val metadataJson = getMetadata()
+ if (metadataJson.isBlank()) {
+ return null
+ }
+ return try {
+ val json = JSONObject(metadataJson)
+ VaultMetadata(
+ publicEmailDomains = json.optJSONArray("publicEmailDomains")?.let { array ->
+ List(array.length()) { i -> array.getString(i) }
+ } ?: emptyList(),
+ privateEmailDomains = json.optJSONArray("privateEmailDomains")?.let { array ->
+ List(array.length()) { i -> array.getString(i) }
+ } ?: emptyList(),
+ vaultRevisionNumber = json.optInt("vaultRevisionNumber", 0),
+ )
+ } catch (e: Exception) {
+ Log.e(TAG, "Error parsing vault metadata", e)
+ null
+ }
+ }
+
+ // endregion
+}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultMutate.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultMutate.kt
new file mode 100644
index 000000000..daa253321
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultMutate.kt
@@ -0,0 +1,175 @@
+package net.aliasvault.app.vaultstore
+
+import android.util.Log
+import net.aliasvault.app.exceptions.SerializationException
+import net.aliasvault.app.exceptions.VaultOperationException
+import org.json.JSONArray
+import org.json.JSONObject
+
+/**
+ * Handles vault mutation operations (uploading changes to server).
+ */
+class VaultMutate(
+ private val database: VaultDatabase,
+ private val query: VaultQuery,
+ private val metadata: VaultMetadataManager,
+) {
+ companion object {
+ private const val TAG = "VaultMutate"
+ }
+
+ // region Vault Mutation
+
+ /**
+ * Execute a vault mutation operation.
+ */
+ suspend fun mutateVault(webApiService: net.aliasvault.app.webapi.WebApiService): Boolean {
+ try {
+ val vault = prepareVault()
+
+ val json = JSONObject()
+ json.put("blob", vault.blob)
+ json.put("createdAt", vault.createdAt)
+ json.put("credentialsCount", vault.credentialsCount)
+ json.put("currentRevisionNumber", vault.currentRevisionNumber)
+ json.put("emailAddressList", JSONArray(vault.emailAddressList))
+ json.put("privateEmailDomainList", JSONArray(vault.privateEmailDomainList))
+ json.put("publicEmailDomainList", JSONArray(vault.publicEmailDomainList))
+ json.put("encryptionPublicKey", vault.encryptionPublicKey)
+ json.put("updatedAt", vault.updatedAt)
+ json.put("username", vault.username)
+ json.put("version", vault.version)
+ json.put("client", vault.client)
+
+ val response = webApiService.executeRequest(
+ method = "POST",
+ endpoint = "Vault",
+ body = json.toString(),
+ headers = mapOf("Content-Type" to "application/json"),
+ requiresAuth = true,
+ )
+
+ if (response.statusCode != 200) {
+ Log.e(TAG, "Server rejected vault upload with status ${response.statusCode}")
+ throw VaultOperationException("Server returned error: ${response.statusCode}")
+ }
+
+ val vaultResponse = try {
+ val responseJson = JSONObject(response.body)
+ VaultPostResponse(
+ status = responseJson.getInt("status"),
+ newRevisionNumber = responseJson.getInt("newRevisionNumber"),
+ )
+ } catch (e: Exception) {
+ Log.e(TAG, "Failed to parse vault upload response", e)
+ throw SerializationException("Failed to parse vault upload response: ${e.message}", e)
+ }
+
+ when (vaultResponse.status) {
+ 0 -> {
+ metadata.setVaultRevisionNumber(vaultResponse.newRevisionNumber)
+ metadata.setOfflineMode(false)
+ return true
+ }
+ 1 -> throw VaultOperationException("Vault merge required")
+ 2 -> throw VaultOperationException("Vault is outdated, please sync first")
+ else -> throw VaultOperationException("Failed to upload vault")
+ }
+ } catch (e: Exception) {
+ Log.e(TAG, "Error mutating vault", e)
+ throw e
+ }
+ }
+
+ // endregion
+
+ // region Internal Helpers
+
+ private fun prepareVault(): VaultUpload {
+ val currentRevision = metadata.getVaultRevisionNumber()
+
+ val encryptedDb = database.getEncryptedDatabase()
+
+ val username = metadata.getUsername()
+ ?: throw VaultOperationException("Username not found")
+
+ if (!database.isVaultUnlocked()) {
+ throw VaultOperationException("Vault must be unlocked to prepare for upload")
+ }
+
+ val credentials = query.getAllCredentials()
+
+ val metadataObj = metadata.getVaultMetadataObject()
+ val privateEmailDomains = metadataObj?.privateEmailDomains ?: emptyList()
+
+ val privateEmailAddresses = credentials
+ .mapNotNull { it.alias?.email }
+ .filter { email ->
+ privateEmailDomains.any { domain ->
+ email.lowercase().endsWith("@${domain.lowercase()}")
+ }
+ }
+ .distinct()
+
+ val dbVersion = query.getDatabaseVersion()
+
+ @Suppress("SwallowedException")
+ val version = try {
+ // Try to get version from storage provider context
+ val context = database.javaClass.getDeclaredField("storageProvider")
+ .get(database) as? net.aliasvault.app.vaultstore.storageprovider.AndroidStorageProvider
+ val pm = context?.javaClass?.getDeclaredField("context")?.get(context)
+ as? android.content.Context
+ pm?.packageManager?.getPackageInfo(pm.packageName, 0)?.versionName ?: "0.0.0"
+ } catch (e: Exception) {
+ "0.0.0"
+ }
+ val baseVersion = version.split("-").firstOrNull() ?: "0.0.0"
+ val client = "android-$baseVersion"
+
+ val dateFormat = java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", java.util.Locale.US)
+ dateFormat.timeZone = java.util.TimeZone.getTimeZone("UTC")
+ val now = dateFormat.format(java.util.Date())
+
+ return VaultUpload(
+ blob = encryptedDb,
+ createdAt = now,
+ credentialsCount = credentials.size,
+ currentRevisionNumber = currentRevision,
+ emailAddressList = privateEmailAddresses,
+ privateEmailDomainList = emptyList(),
+ publicEmailDomainList = emptyList(),
+ encryptionPublicKey = "",
+ updatedAt = now,
+ username = username,
+ version = dbVersion,
+ client = client,
+ )
+ }
+
+ // endregion
+
+ // region Data Models
+
+ private data class VaultUpload(
+ val blob: String,
+ val createdAt: String,
+ val credentialsCount: Int,
+ val currentRevisionNumber: Int,
+ val emailAddressList: List<String>,
+ val privateEmailDomainList: List<String>,
+ val publicEmailDomainList: List<String>,
+ val encryptionPublicKey: String,
+ val updatedAt: String,
+ val username: String,
+ val version: String,
+ val client: String,
+ )
+
+ private data class VaultPostResponse(
+ val status: Int,
+ val newRevisionNumber: Int,
+ )
+
+ // endregion
+}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultQuery.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultQuery.kt
new file mode 100644
index 000000000..5679df2ba
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultQuery.kt
@@ -0,0 +1,327 @@
+package net.aliasvault.app.vaultstore
+
+import android.util.Base64
+import android.util.Log
+import net.aliasvault.app.utils.DateHelpers
+import net.aliasvault.app.vaultstore.interfaces.CredentialOperationCallback
+import net.aliasvault.app.vaultstore.models.Alias
+import net.aliasvault.app.vaultstore.models.Credential
+import net.aliasvault.app.vaultstore.models.Password
+import net.aliasvault.app.vaultstore.models.Service
+import java.util.Calendar
+import java.util.Date
+import java.util.TimeZone
+import java.util.UUID
+
+/**
+ * Handles SQL query operations on the vault database.
+ */
+class VaultQuery(
+ private val database: VaultDatabase,
+) {
+ companion object {
+ private const val TAG = "VaultQuery"
+
+ private val MIN_DATE: Date = Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply {
+ set(Calendar.YEAR, 1)
+ set(Calendar.MONTH, Calendar.JANUARY)
+ set(Calendar.DAY_OF_MONTH, 1)
+ set(Calendar.HOUR_OF_DAY, 0)
+ set(Calendar.MINUTE, 0)
+ set(Calendar.SECOND, 0)
+ set(Calendar.MILLISECOND, 0)
+ }.time
+ }
+
+ // region SQL Query Execution
+
+ /**
+ * Execute a read-only SQL query (SELECT) on the vault.
+ */
+ @Suppress("NestedBlockDepth")
+ fun executeQuery(query: String, params: Array<Any?>): List<Map<String, Any?>> {
+ val results = mutableListOf<Map<String, Any?>>()
+
+ database.dbConnection?.let { db ->
+ val convertedParams = params.map { param ->
+ if (param is String && param.startsWith("av-base64-to-blob:")) {
+ val base64 = param.substring("av-base64-to-blob:".length)
+ Base64.decode(base64, Base64.NO_WRAP)
+ } else {
+ param
+ }
+ }.toTypedArray()
+
+ val cursor = db.rawQuery(query, convertedParams.map { it?.toString() }.toTypedArray())
+
+ cursor.use {
+ val columnNames = it.columnNames
+ while (it.moveToNext()) {
+ val row = mutableMapOf<String, Any?>()
+ for (columnName in columnNames) {
+ when (it.getType(it.getColumnIndexOrThrow(columnName))) {
+ android.database.Cursor.FIELD_TYPE_NULL -> row[columnName] = null
+ android.database.Cursor.FIELD_TYPE_INTEGER -> row[columnName] = it.getLong(
+ it.getColumnIndexOrThrow(columnName),
+ )
+ android.database.Cursor.FIELD_TYPE_FLOAT -> row[columnName] = it.getDouble(
+ it.getColumnIndexOrThrow(columnName),
+ )
+ android.database.Cursor.FIELD_TYPE_STRING -> row[columnName] = it.getString(
+ it.getColumnIndexOrThrow(columnName),
+ )
+ android.database.Cursor.FIELD_TYPE_BLOB -> row[columnName] = it.getBlob(
+ it.getColumnIndexOrThrow(columnName),
+ )
+ }
+ }
+ results.add(row)
+ }
+ }
+ }
+
+ return results
+ }
+
+ /**
+ * Execute an SQL update on the vault that mutates it.
+ */
+ fun executeUpdate(query: String, params: Array<Any?>): Int {
+ database.dbConnection?.let { db ->
+ val convertedParams = params.map { param ->
+ if (param is String && param.startsWith("av-base64-to-blob:")) {
+ val base64 = param.substring("av-base64-to-blob:".length)
+ Base64.decode(base64, Base64.NO_WRAP)
+ } else {
+ param
+ }
+ }.toTypedArray()
+
+ db.execSQL(query, convertedParams)
+ val cursor = db.rawQuery("SELECT changes()", null)
+ cursor.use {
+ if (it.moveToFirst()) {
+ return it.getInt(0)
+ }
+ }
+ }
+ return 0
+ }
+
+ /**
+ * Execute a raw SQL command on the vault without parameters.
+ */
+ fun executeRaw(query: String) {
+ database.dbConnection?.let { db ->
+ val statements = query.split(";")
+
+ for (statement in statements) {
+ val trimmedStatement = statement.smartTrim()
+
+ if (trimmedStatement.isEmpty() ||
+ trimmedStatement.uppercase().startsWith("BEGIN") ||
+ trimmedStatement.uppercase().startsWith("COMMIT") ||
+ trimmedStatement.uppercase().startsWith("ROLLBACK")
+ ) {
+ continue
+ }
+
+ db.execSQL(trimmedStatement)
+ }
+ }
+ }
+
+ // endregion
+
+ // region Credential Operations
+
+ /**
+ * Get all credentials from the vault.
+ */
+ fun getAllCredentials(): List<Credential> {
+ if (database.dbConnection == null) {
+ error("Database not initialized")
+ }
+
+ val query = """
+ WITH LatestPasswords AS (
+ SELECT
+ p.Id as password_id,
+ p.CredentialId,
+ p.Value,
+ p.CreatedAt,
+ p.UpdatedAt,
+ p.IsDeleted,
+ ROW_NUMBER() OVER (PARTITION BY p.CredentialId ORDER BY p.CreatedAt DESC) as rn
+ FROM Passwords p
+ WHERE p.IsDeleted = 0
+ )
+ SELECT
+ c.Id,
+ c.AliasId,
+ c.Username,
+ c.Notes,
+ c.CreatedAt,
+ c.UpdatedAt,
+ c.IsDeleted,
+ s.Id as service_id,
+ s.Name as service_name,
+ s.Url as service_url,
+ s.Logo as service_logo,
+ s.CreatedAt as service_created_at,
+ s.UpdatedAt as service_updated_at,
+ s.IsDeleted as service_is_deleted,
+ lp.password_id,
+ lp.Value as password_value,
+ lp.CreatedAt as password_created_at,
+ lp.UpdatedAt as password_updated_at,
+ lp.IsDeleted as password_is_deleted,
+ a.Id as alias_id,
+ a.Gender as alias_gender,
+ a.FirstName as alias_first_name,
+ a.LastName as alias_last_name,
+ a.NickName as alias_nick_name,
+ a.BirthDate as alias_birth_date,
+ a.Email as alias_email,
+ a.CreatedAt as alias_created_at,
+ a.UpdatedAt as alias_updated_at,
+ a.IsDeleted as alias_is_deleted
+ FROM Credentials c
+ LEFT JOIN Services s ON s.Id = c.ServiceId AND s.IsDeleted = 0
+ LEFT JOIN LatestPasswords lp ON lp.CredentialId = c.Id AND lp.rn = 1
+ LEFT JOIN Aliases a ON a.Id = c.AliasId AND a.IsDeleted = 0
+ WHERE c.IsDeleted = 0
+ ORDER BY c.CreatedAt DESC
+ """
+
+ val result = mutableListOf<Credential>()
+ val cursor = database.dbConnection?.rawQuery(query, null)
+
+ cursor?.use {
+ while (it.moveToNext()) {
+ try {
+ val id = UUID.fromString(it.getString(0))
+ val isDeleted = it.getInt(6) == 1
+
+ val serviceId = UUID.fromString(it.getString(7))
+ val service = Service(
+ id = serviceId,
+ name = it.getString(8),
+ url = it.getString(9),
+ logo = it.getBlob(10),
+ createdAt = DateHelpers.parseDateString(it.getString(11)) ?: MIN_DATE,
+ updatedAt = DateHelpers.parseDateString(it.getString(12)) ?: MIN_DATE,
+ isDeleted = it.getInt(13) == 1,
+ )
+
+ var password: Password? = null
+ if (!it.isNull(14)) {
+ password = Password(
+ id = UUID.fromString(it.getString(14)),
+ credentialId = id,
+ value = it.getString(15),
+ createdAt = DateHelpers.parseDateString(it.getString(16)) ?: MIN_DATE,
+ updatedAt = DateHelpers.parseDateString(it.getString(17)) ?: MIN_DATE,
+ isDeleted = it.getInt(18) == 1,
+ )
+ }
+
+ var alias: Alias? = null
+ if (!it.isNull(19)) {
+ alias = Alias(
+ id = UUID.fromString(it.getString(19)),
+ gender = it.getString(20),
+ firstName = it.getString(21),
+ lastName = it.getString(22),
+ nickName = it.getString(23),
+ birthDate = DateHelpers.parseDateString(it.getString(24)) ?: MIN_DATE,
+ email = it.getString(25),
+ createdAt = DateHelpers.parseDateString(it.getString(26)) ?: MIN_DATE,
+ updatedAt = DateHelpers.parseDateString(it.getString(27)) ?: MIN_DATE,
+ isDeleted = it.getInt(28) == 1,
+ )
+ }
+
+ val credential = Credential(
+ id = id,
+ alias = alias,
+ service = service,
+ username = it.getString(2),
+ notes = it.getString(3),
+ password = password,
+ createdAt = DateHelpers.parseDateString(it.getString(4)) ?: MIN_DATE,
+ updatedAt = DateHelpers.parseDateString(it.getString(5)) ?: MIN_DATE,
+ isDeleted = isDeleted,
+ )
+ result.add(credential)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error parsing credential row", e)
+ }
+ }
+ }
+
+ return result
+ }
+
+ /**
+ * Attempts to get all credentials using only the cached encryption key.
+ */
+ fun tryGetAllCredentials(callback: CredentialOperationCallback, crypto: VaultCrypto, unlockVault: () -> Unit): Boolean {
+ if (crypto.encryptionKey == null) {
+ Log.d(TAG, "Encryption key not in memory, authentication required")
+ return false
+ }
+
+ try {
+ if (!database.isVaultUnlocked()) {
+ unlockVault()
+ }
+
+ callback.onSuccess(getAllCredentials())
+ return true
+ } catch (e: Exception) {
+ Log.e(TAG, "Error retrieving credentials", e)
+ callback.onError(e)
+ return false
+ }
+ }
+
+ /**
+ * Get the database version from the __EFMigrationsHistory table.
+ */
+ fun getDatabaseVersion(): String {
+ val query = "SELECT MigrationId FROM __EFMigrationsHistory ORDER BY MigrationId DESC LIMIT 1"
+ val results = executeQuery(query, emptyArray())
+
+ if (results.isEmpty()) {
+ Log.d(TAG, "No migrations found in database, returning default version")
+ return "0.0.0"
+ }
+
+ val migrationId = results[0]["MigrationId"] as? String
+ if (migrationId == null) {
+ return "0.0.0"
+ }
+
+ val versionRegex = Regex("_(\\d+\\.\\d+\\.\\d+)-")
+ val match = versionRegex.find(migrationId)
+
+ return if (match != null && match.groupValues.size > 1) {
+ match.groupValues[1]
+ } else {
+ Log.d(TAG, "Could not extract version from migration ID '$migrationId', returning default")
+ "0.0.0"
+ }
+ }
+
+ // endregion
+
+ // region Helper Functions
+
+ private fun String.smartTrim(): String {
+ val invisible = "[\\uFEFF\\u200B\\u00A0\\u202A-\\u202E\\u2060\\u180E]"
+ return this.replace(Regex("^($invisible)+|($invisible)+$"), "").trim()
+ }
+
+ // endregion
+}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
index 1c0406f35..a196d922a 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
@@ -1,40 +1,28 @@
package net.aliasvault.app.vaultstore
import android.database.sqlite.SQLiteDatabase
-import android.database.sqlite.SQLiteException
import android.os.Handler
import android.os.Looper
-import android.util.Base64
-import android.util.Log
-import com.lambdapioneer.argon2kt.Argon2Kt
-import com.lambdapioneer.argon2kt.Argon2Mode
-import com.lambdapioneer.argon2kt.Argon2Version
-import net.aliasvault.app.exceptions.SerializationException
-import net.aliasvault.app.exceptions.VaultOperationException
-import net.aliasvault.app.utils.DateHelpers
import net.aliasvault.app.vaultstore.interfaces.CredentialOperationCallback
import net.aliasvault.app.vaultstore.interfaces.CryptoOperationCallback
-import net.aliasvault.app.vaultstore.keystoreprovider.KeystoreOperationCallback
import net.aliasvault.app.vaultstore.keystoreprovider.KeystoreProvider
-import net.aliasvault.app.vaultstore.models.Alias
import net.aliasvault.app.vaultstore.models.Credential
-import net.aliasvault.app.vaultstore.models.Password
-import net.aliasvault.app.vaultstore.models.Service
-import net.aliasvault.app.vaultstore.models.VaultMetadata
import net.aliasvault.app.vaultstore.storageprovider.StorageProvider
-import org.json.JSONArray
-import org.json.JSONObject
-import java.io.File
-import java.security.SecureRandom
-import java.util.*
-import javax.crypto.Cipher
-import javax.crypto.spec.GCMParameterSpec
-import javax.crypto.spec.SecretKeySpec
/**
* The vault store that manages the encrypted vault and all input/output operations on it.
* This class is used both by React Native and by the native Android autofill service.
*
+ * This class uses composition to organize functionality into specialized components:
+ * - VaultCrypto: Handles encryption, decryption, and key management
+ * - VaultDatabase: Handles database storage and operations
+ * - VaultQuery: Handles SQL query execution and credential retrieval
+ * - VaultMetadataManager: Handles metadata and settings storage
+ * - VaultAuth: Handles authentication methods and auto-lock
+ * - VaultSync: Handles vault synchronization with server
+ * - VaultMutate: Handles vault mutation (uploading changes)
+ * - VaultCache: Handles cache and storage clearing
+ *
* @param storageProvider The storage provider
* @param keystoreProvider The keystore provider
*/
@@ -43,32 +31,6 @@ class VaultStore(
private val keystoreProvider: KeystoreProvider,
) {
companion object {
- /**
- * The tag for logging.
- */
- private const val TAG = "VaultStore"
-
- /**
- * The biometrics auth method.
- */
- private const val BIOMETRICS_AUTH_METHOD = "faceid"
-
- /**
- * Minimum date definition.
- */
- private val MIN_DATE: Date = Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply {
- set(Calendar.YEAR, 1)
- set(Calendar.MONTH, Calendar.JANUARY)
- set(Calendar.DAY_OF_MONTH, 1)
- set(Calendar.HOUR_OF_DAY, 0)
- set(Calendar.MINUTE, 0)
- set(Calendar.SECOND, 0)
- set(Calendar.MILLISECOND, 0)
- }.time
-
- /**
- * The instance of the vault store.
- */
@Volatile
private var instance: VaultStore? = null
@@ -98,523 +60,255 @@ class VaultStore(
}
}
- /**
- * The encryption key.
- */
- private var encryptionKey: ByteArray? = null
+ // region Composed Components
+
+ private val crypto = VaultCrypto(keystoreProvider, storageProvider)
+ private val databaseComponent = VaultDatabase(storageProvider, crypto)
+ private val query = VaultQuery(databaseComponent)
+ private val metadata = VaultMetadataManager(storageProvider)
+ private val auth = VaultAuth(storageProvider) { cache.clearCache() }
+ private val sync = VaultSync(databaseComponent, metadata, crypto)
+ private val mutate = VaultMutate(databaseComponent, query, metadata)
+ private val cache = VaultCache(crypto, databaseComponent, keystoreProvider, storageProvider)
+
+ // endregion
+
+ // region Internal Accessors for Backwards Compatibility
/**
- * The database connection.
+ * Internal accessor for encryption key.
*/
- private var dbConnection: SQLiteDatabase? = null
+ internal var encryptionKey: ByteArray?
+ get() = crypto.encryptionKey
+ set(value) {
+ crypto.encryptionKey = value
+ }
/**
* Internal accessor for database connection.
- * Used by extension functions to access the database.
*/
internal val database: SQLiteDatabase?
- get() = dbConnection
+ get() = databaseComponent.dbConnection
/**
- * The auto-lock handler.
+ * Internal accessor for database connection (legacy name).
*/
- private var autoLockHandler: Handler? = null
+ internal val dbConnection: SQLiteDatabase?
+ get() = databaseComponent.dbConnection
/**
- * The auto-lock runnable.
+ * Internal accessor for auto-lock handler.
*/
- private var autoLockRunnable: Runnable? = null
+ internal var autoLockHandler: Handler? = null
/**
- * The last unlock time.
+ * Internal accessor for auto-lock runnable.
*/
- private var lastUnlockTime: Long = 0
+ internal var autoLockRunnable: Runnable? = null
+
+ // endregion
init {
- // Initialize the auto-lock handler on the main thread
autoLockHandler = Handler(Looper.getMainLooper())
+ auth.setAutoLockHandler(autoLockHandler!!)
}
+ // region Lifecycle Methods
+
/**
* Called when the app enters the background.
*/
fun onAppBackgrounded() {
- Log.d(TAG, "App entered background, starting auto-lock timer with ${getAutoLockTimeout()}s")
- if (getAutoLockTimeout() > 0) {
- // Cancel any existing auto-lock timer
- autoLockRunnable?.let { autoLockHandler?.removeCallbacks(it) }
-
- // Create and schedule new auto-lock timer
- autoLockRunnable = Runnable {
- Log.d(TAG, "Auto-lock timer fired, clearing cache")
- clearCache()
- }
- autoLockHandler?.postDelayed(autoLockRunnable!!, getAutoLockTimeout().toLong() * 1000)
- }
+ auth.onAppBackgrounded()
}
/**
* Called when the app enters the foreground.
*/
fun onAppForegrounded() {
- Log.d(TAG, "App entered foreground, canceling auto-lock timer")
- // Cancel the auto-lock timer
- autoLockRunnable?.let { autoLockHandler?.removeCallbacks(it) }
- autoLockRunnable = null
+ auth.onAppForegrounded()
}
+ // endregion
+
+ // region Crypto Methods
+
/**
* Store the encryption key.
- * @param base64EncryptionKey The encryption key as a base64 encoded string
*/
fun storeEncryptionKey(base64EncryptionKey: String) {
- this.encryptionKey = Base64.decode(base64EncryptionKey, Base64.NO_WRAP)
-
- // Check if biometric auth is enabled in auth methods
- val authMethods = getAuthMethods()
- if (authMethods.contains(BIOMETRICS_AUTH_METHOD) && keystoreProvider.isBiometricAvailable()) {
- val latch = java.util.concurrent.CountDownLatch(1)
- var error: Exception? = null
-
- keystoreProvider.storeKey(
- key = base64EncryptionKey,
- object : KeystoreOperationCallback {
- override fun onSuccess(result: String) {
- Log.d(TAG, "Encryption key stored successfully with biometric protection")
- latch.countDown()
- }
-
- override fun onError(e: Exception) {
- Log.e(TAG, "Error storing encryption key with biometric protection", e)
- error = e
- latch.countDown()
- }
- },
- )
-
- latch.await()
- error?.let { throw it }
- }
+ crypto.storeEncryptionKey(base64EncryptionKey, auth.getAuthMethods())
}
/**
* Initialize the encryption key.
- * @param encryptionKey The encryption key as a ByteArray
*/
fun initEncryptionKey(base64EncryptionKey: String) {
- this.encryptionKey = Base64.decode(base64EncryptionKey, Base64.NO_WRAP)
+ crypto.initEncryptionKey(base64EncryptionKey)
}
/**
- * Check if biometric authentication is enabled and available.
- * Returns true if biometric auth is enabled in settings AND the device supports biometric authentication.
- * @return True if biometric authentication is enabled and available, false otherwise
+ * Get the encryption key.
*/
- fun isBiometricAuthEnabled(): Boolean {
- val authMethods = getAuthMethods()
- return authMethods.contains(BIOMETRICS_AUTH_METHOD) && keystoreProvider.isBiometricAvailable()
+ fun getEncryptionKey(callback: CryptoOperationCallback) {
+ crypto.getEncryptionKey(callback, auth.getAuthMethods())
}
/**
- * Get the encryption key.
- * @param callback The callback to call when the key is retrieved
+ * Check if biometric authentication is enabled and available.
*/
- fun getEncryptionKey(callback: CryptoOperationCallback) {
- // If key is already in memory, use it
- encryptionKey?.let {
- callback.onSuccess(Base64.encodeToString(it, Base64.NO_WRAP))
- return
- }
-
- // Check if biometric auth is enabled in auth methods
- if (isBiometricAuthEnabled()) {
- keystoreProvider.retrieveKey(
- object : KeystoreOperationCallback {
- override fun onSuccess(result: String) {
- try {
- // Cache the key
- encryptionKey = Base64.decode(result, Base64.NO_WRAP)
- callback.onSuccess(result)
- } catch (e: Exception) {
- Log.e(TAG, "Error decoding retrieved key", e)
- callback.onError(e)
- }
- }
-
- override fun onError(e: Exception) {
- Log.e(TAG, "Error retrieving key", e)
- callback.onError(e)
- }
- },
- )
- } else {
- callback.onError(Exception("No encryption key found"))
- }
+ fun isBiometricAuthEnabled(): Boolean {
+ return crypto.isBiometricAuthEnabled(auth.getAuthMethods())
}
/**
* Store the encryption key derivation parameters.
- * @param keyDerivationParams The encryption key derivation parameters
*/
fun storeEncryptionKeyDerivationParams(keyDerivationParams: String) {
- this.storageProvider.setKeyDerivationParams(keyDerivationParams)
+ crypto.storeEncryptionKeyDerivationParams(keyDerivationParams)
}
/**
* Get the encryption key derivation parameters.
- * @return The encryption key derivation parameters
*/
fun getEncryptionKeyDerivationParams(): String {
- return this.storageProvider.getKeyDerivationParams()
+ return crypto.getEncryptionKeyDerivationParams()
}
/**
* Derive a key from a password using Argon2Id.
- * @param password The password to derive from
- * @param salt The salt to use
- * @param encryptionType The type of encryption (should be "Argon2Id")
- * @param encryptionSettings JSON string with encryption parameters
- * @return The derived key as a ByteArray
*/
- fun deriveKeyFromPassword(password: String, salt: String, encryptionType: String, encryptionSettings: String): ByteArray {
- require(encryptionType == "Argon2Id") { "Unsupported encryption type: $encryptionType" }
-
- // Parse encryption settings JSON
- val settings = JSONObject(encryptionSettings)
- val iterations = settings.getInt("Iterations")
- val memorySize = settings.getInt("MemorySize")
- val parallelism = settings.getInt("DegreeOfParallelism")
-
- // Create Argon2 instance
- val argon2 = Argon2Kt()
-
- // Hash the password using Argon2Id
- val hashResult = argon2.hash(
- mode = Argon2Mode.ARGON2_ID,
- password = password.toByteArray(Charsets.UTF_8),
- salt = salt.toByteArray(Charsets.UTF_8),
- tCostInIterations = iterations,
- mCostInKibibyte = memorySize,
- parallelism = parallelism,
- hashLengthInBytes = 32,
- version = Argon2Version.V13,
- )
-
- return hashResult.rawHashAsByteArray()
+ fun deriveKeyFromPassword(
+ password: String,
+ salt: String,
+ encryptionType: String,
+ encryptionSettings: String,
+ ): ByteArray {
+ return crypto.deriveKeyFromPassword(password, salt, encryptionType, encryptionSettings)
}
+ // endregion
+
+ // region Database Methods
+
/**
- * Store the encrypted database in the storage provider.
- * @param encryptedData The encrypted database as a base64 encoded string
+ * Store the encrypted database.
*/
fun storeEncryptedDatabase(encryptedData: String) {
- // Write the encrypted blob to the filesystem via the supplied file provider
- // which can either be the real Android file system or a mock file system for testing
- storageProvider.setEncryptedDatabaseFile(encryptedData)
+ databaseComponent.storeEncryptedDatabase(encryptedData)
}
/**
- * Get the encrypted database from the storage provider.
- * @return The encrypted database as a base64 encoded string
+ * Get the encrypted database.
*/
fun getEncryptedDatabase(): String {
- val encryptedDbBase64 = storageProvider.getEncryptedDatabaseFile().readText()
- return encryptedDbBase64
+ return databaseComponent.getEncryptedDatabase()
}
/**
- * Check if the encrypted database exists in the storage provider.
- * @return True if the encrypted database exists, false otherwise
+ * Check if the encrypted database exists.
*/
fun hasEncryptedDatabase(): Boolean {
- return storageProvider.getEncryptedDatabaseFile().exists()
+ return databaseComponent.hasEncryptedDatabase()
}
/**
- * Store the metadata in the storage provider.
- * @param metadata The metadata to store
+ * Unlock the vault.
*/
- fun storeMetadata(metadata: String) {
- storageProvider.setMetadata(metadata)
+ fun unlockVault() {
+ databaseComponent.unlockVault(auth.getAuthMethods())
}
/**
- * Get the metadata from the storage provider.
- * @return The metadata as a string
+ * Check if the vault is unlocked.
*/
- fun getMetadata(): String {
- return storageProvider.getMetadata()
+ fun isVaultUnlocked(): Boolean {
+ return databaseComponent.isVaultUnlocked()
}
- /**
- * Unlock the vault. This can trigger biometric authentication.
- */
- fun unlockVault() {
- val encryptedDbBase64 = getEncryptedDatabase()
- val decryptedDbBase64 = decryptData(encryptedDbBase64)
-
- try {
- setupDatabaseWithDecryptedData(decryptedDbBase64)
- } catch (e: Exception) {
- Log.e(TAG, "Error unlocking vault", e)
- throw e
- }
- }
+ // endregion
+
+ // region Query Methods
/**
* Execute a read-only SQL query (SELECT) on the vault.
- * @param query The SQL query
- * @param params The parameters to the query
- * @return The results of the query
*/
- @Suppress("NestedBlockDepth")
- fun executeQuery(query: String, params: Array<Any?>): List<Map<String, Any?>> {
- val results = mutableListOf<Map<String, Any?>>()
-
- dbConnection?.let { db ->
- // Convert any base64 strings with the special flag to blobs
- val convertedParams = params.map { param ->
- if (param is String && param.startsWith("av-base64-to-blob:")) {
- val base64 = param.substring("av-base64-to-blob:".length)
- Base64.decode(base64, Base64.NO_WRAP)
- } else {
- param
- }
- }.toTypedArray()
-
- val cursor = db.rawQuery(query, convertedParams.map { it?.toString() }.toTypedArray())
-
- cursor.use {
- val columnNames = it.columnNames
- while (it.moveToNext()) {
- val row = mutableMapOf<String, Any?>()
- for (columnName in columnNames) {
- when (it.getType(it.getColumnIndexOrThrow(columnName))) {
- android.database.Cursor.FIELD_TYPE_NULL -> row[columnName] = null
- android.database.Cursor.FIELD_TYPE_INTEGER -> row[columnName] = it.getLong(
- it.getColumnIndexOrThrow(columnName),
- )
- android.database.Cursor.FIELD_TYPE_FLOAT -> row[columnName] = it.getDouble(
- it.getColumnIndexOrThrow(columnName),
- )
- android.database.Cursor.FIELD_TYPE_STRING -> row[columnName] = it.getString(
- it.getColumnIndexOrThrow(columnName),
- )
- android.database.Cursor.FIELD_TYPE_BLOB -> row[columnName] = it.getBlob(
- it.getColumnIndexOrThrow(columnName),
- )
- }
- }
- results.add(row)
- }
- }
- }
-
- return results
+ fun executeQuery(queryString: String, params: Array<Any?>): List<Map<String, Any?>> {
+ return query.executeQuery(queryString, params)
}
/**
* Execute an SQL update on the vault that mutates it.
- * @param query The SQL query
- * @param params The parameters to the query
- * @return The number of affected rows
*/
- fun executeUpdate(query: String, params: Array<Any?>): Int {
- dbConnection?.let { db ->
- // Convert any base64 strings with the special flag to blobs
- val convertedParams = params.map { param ->
- if (param is String && param.startsWith("av-base64-to-blob:")) {
- val base64 = param.substring("av-base64-to-blob:".length)
- Base64.decode(base64, Base64.NO_WRAP)
- } else {
- param
- }
- }.toTypedArray()
-
- db.execSQL(query, convertedParams)
- // Get the number of affected rows
- val cursor = db.rawQuery("SELECT changes()", null)
- cursor.use {
- if (it.moveToFirst()) {
- return it.getInt(0)
- }
- }
- }
- return 0
+ fun executeUpdate(queryString: String, params: Array<Any?>): Int {
+ return query.executeUpdate(queryString, params)
}
/**
- * Execute a raw SQL command on the vault without parameters (for DDL operations like CREATE TABLE).
- * @param query The SQL query
+ * Execute a raw SQL command on the vault without parameters.
*/
- fun executeRaw(query: String) {
- dbConnection?.let { db ->
- // Split the query by semicolons to handle multiple statements
- val statements = query.split(";")
-
- for (statement in statements) {
- // Remove problematic invisible characters from string
- val trimmedStatement = statement.smartTrim()
-
- // Skip empty statements and transaction control statements (handled externally)
- if (trimmedStatement.isEmpty() ||
- trimmedStatement.uppercase().startsWith("BEGIN") ||
- trimmedStatement.uppercase().startsWith("COMMIT") ||
- trimmedStatement.uppercase().startsWith("ROLLBACK")
- ) {
- continue
- }
-
- db.execSQL(trimmedStatement)
- }
- }
+ fun executeRaw(queryString: String) {
+ query.executeRaw(queryString)
}
/**
* Begin a SQL transaction on the vault.
*/
fun beginTransaction() {
- dbConnection?.beginTransaction()
+ databaseComponent.beginTransaction()
}
/**
- * Commit a SQL transaction on the vault. This also persists the new version of the encrypted vault from memory to the filesystem.
+ * Commit a SQL transaction on the vault.
*/
fun commitTransaction() {
- dbConnection?.setTransactionSuccessful()
- dbConnection?.endTransaction()
-
- // Create a temporary file in app-specific storage
- val tempDbFile = File.createTempFile("temp_db", ".sqlite")
- tempDbFile.deleteOnExit() // Ensure cleanup on JVM exit
-
- try {
- // Attach the temporary file as target database
- dbConnection?.execSQL("ATTACH DATABASE '${tempDbFile.path}' AS target")
-
- // Begin transaction for copying data
- dbConnection?.beginTransaction()
-
- try {
- // Get all table names from the main database
- val cursor = dbConnection?.rawQuery(
- "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE 'android_%'",
- null,
- )
-
- cursor?.use {
- while (it.moveToNext()) {
- val tableName = it.getString(0)
- // Create table and copy data
- dbConnection?.execSQL(
- "CREATE TABLE target.$tableName AS SELECT * FROM main.$tableName",
- )
- }
- }
-
- // Commit the copy transaction
- dbConnection?.setTransactionSuccessful()
- } finally {
- dbConnection?.endTransaction()
- }
-
- // Detach the target database
- dbConnection?.execSQL("DETACH DATABASE target")
-
- // Read the temporary database file
- val rawData = tempDbFile.readBytes()
-
- // Convert to base64 and encrypt
- val base64String = Base64.encodeToString(rawData, Base64.NO_WRAP)
- val encryptedBase64Data = encryptData(base64String)
-
- // Store the encrypted database
- storeEncryptedDatabase(encryptedBase64Data)
- } catch (e: Exception) {
- Log.e(TAG, "Error exporting and encrypting database", e)
- throw e
- } finally {
- // Securely delete the temporary file
- if (tempDbFile.exists()) {
- tempDbFile.setWritable(true, true) // Temporarily enable write for deletion
- tempDbFile.delete()
- }
- }
+ databaseComponent.commitTransaction()
}
/**
* Rollback a SQL transaction on the vault.
*/
fun rollbackTransaction() {
- dbConnection?.endTransaction()
+ databaseComponent.rollbackTransaction()
}
/**
- * Check if the vault is unlocked.
- * @return True if the vault is unlocked, false otherwise
+ * Get all credentials from the vault.
*/
- fun isVaultUnlocked(): Boolean {
- if (encryptionKey == null) {
- return false
- }
-
- return true
+ fun getAllCredentials(): List<Credential> {
+ return query.getAllCredentials()
}
/**
- * Set the auto-lock timeout.
- * @param timeout The timeout in seconds
+ * Attempts to get all credentials using only the cached encryption key.
*/
- fun setAutoLockTimeout(timeout: Int) {
- storageProvider.setAutoLockTimeout(timeout)
+ fun tryGetAllCredentials(callback: CredentialOperationCallback): Boolean {
+ return query.tryGetAllCredentials(callback, crypto) { unlockVault() }
}
- /**
- * Get the auto-lock timeout.
- * @return The timeout in seconds
- */
- fun getAutoLockTimeout(): Int {
- return storageProvider.getAutoLockTimeout()
- }
+ // endregion
+
+ // region Authentication Methods
/**
* Set the auth methods.
- * @param authMethods The auth methods
*/
fun setAuthMethods(authMethods: String) {
- val previousAuthMethods = getAuthMethods()
- val wasBiometricEnabled = previousAuthMethods.contains(BIOMETRICS_AUTH_METHOD)
- val isBiometricEnabled = authMethods.contains(BIOMETRICS_AUTH_METHOD)
-
- storageProvider.setAuthMethods(authMethods)
-
- // If biometrics were just enabled and we have an encryption key in memory, persist it to the keystore
- if (!wasBiometricEnabled && isBiometricEnabled && encryptionKey != null && keystoreProvider.isBiometricAvailable()) {
- val base64Key = Base64.encodeToString(encryptionKey, Base64.NO_WRAP)
- val latch = java.util.concurrent.CountDownLatch(1)
- var error: Exception? = null
-
- keystoreProvider.storeKey(
- key = base64Key,
- object : KeystoreOperationCallback {
- override fun onSuccess(result: String) {
- Log.d(TAG, "Encryption key persisted to biometric storage after enabling biometrics")
- latch.countDown()
- }
-
- override fun onError(e: Exception) {
- Log.e(TAG, "Error persisting encryption key to biometric storage", e)
- error = e
- latch.countDown()
- }
- },
- )
+ val previousAuthMethods = auth.getAuthMethods()
+ val wasBiometricEnabled = previousAuthMethods.contains("faceid")
+ val isBiometricEnabled = authMethods.contains("faceid")
+
+ auth.setAuthMethods(authMethods)
- latch.await()
- error?.let { throw it }
+ // If biometrics were just enabled and we have an encryption key in memory, persist it
+ if (!wasBiometricEnabled && isBiometricEnabled && crypto.encryptionKey != null && keystoreProvider.isBiometricAvailable()) {
+ crypto.storeEncryptionKey(
+ android.util.Base64.encodeToString(crypto.encryptionKey, android.util.Base64.NO_WRAP),
+ authMethods,
+ )
}
- // If the new auth methods no longer include biometrics, clear the biometric key.
+ // If biometrics were disabled, clear the biometric key
if (wasBiometricEnabled && !isBiometricEnabled) {
keystoreProvider.clearKeys()
}
@@ -622,940 +316,150 @@ class VaultStore(
/**
* Get the auth methods.
- * @return The auth methods
*/
fun getAuthMethods(): String {
- return storageProvider.getAuthMethods()
- }
-
- /**
- * Set the vault revision number.
- * @param revisionNumber The revision number
- */
- fun setVaultRevisionNumber(revisionNumber: Int) {
- val metadata = getVaultMetadataObject() ?: VaultMetadata()
- val updatedMetadata = metadata.copy(vaultRevisionNumber = revisionNumber)
- storeMetadata(
- JSONObject().apply {
- put("publicEmailDomains", JSONArray(updatedMetadata.publicEmailDomains))
- put("privateEmailDomains", JSONArray(updatedMetadata.privateEmailDomains))
- put("vaultRevisionNumber", updatedMetadata.vaultRevisionNumber)
- }.toString(),
- )
- }
-
- /**
- * Get the vault revision number.
- * @return The revision number
- */
- fun getVaultRevisionNumber(): Int {
- return getVaultMetadataObject()?.vaultRevisionNumber ?: 0
+ return auth.getAuthMethods()
}
/**
- * Get the vault metadata object.
- * @return The vault metadata object
- */
- private fun getVaultMetadataObject(): VaultMetadata? {
- val metadataJson = getMetadata()
- if (metadataJson.isBlank()) {
- return null
- }
- return try {
- val json = JSONObject(metadataJson)
- VaultMetadata(
- publicEmailDomains = json.optJSONArray("publicEmailDomains")?.let { array ->
- List(array.length()) { i -> array.getString(i) }
- } ?: emptyList(),
- privateEmailDomains = json.optJSONArray("privateEmailDomains")?.let { array ->
- List(array.length()) { i -> array.getString(i) }
- } ?: emptyList(),
- vaultRevisionNumber = json.optInt("vaultRevisionNumber", 0),
- )
- } catch (e: Exception) {
- Log.e(TAG, "Error parsing vault metadata", e)
- null
- }
- }
-
- /**
- * Clear the memory, removing the encryption key and decrypted database from memory.
- */
- fun clearCache() {
- Log.d(TAG, "Clearing cache - removing encryption key and decrypted database from memory")
- dbConnection?.close()
- encryptionKey = null
- dbConnection = null
- }
-
- /**
- * Clear all vault data including from persisted storage. This removes all data from the local device.
+ * Set the auto-lock timeout.
*/
- fun clearVault() {
- // Remove cached data from memory
- clearCache()
-
- // Remove the encryption key stored in the keystore
- keystoreProvider.clearKeys()
-
- // Remove all data from the storage provider
- storageProvider.clearStorage()
+ fun setAutoLockTimeout(timeout: Int) {
+ auth.setAutoLockTimeout(timeout)
}
/**
- * Attempts to get all credentials using only the cached encryption key.
- * Returns false if the key isn't in memory, which signals the caller to authenticate.
+ * Get the auto-lock timeout.
*/
- fun tryGetAllCredentials(callback: CredentialOperationCallback): Boolean {
- // Check if the encryption key is already in memory
- if (encryptionKey == null) {
- Log.d(TAG, "Encryption key not in memory, authentication required")
- return false
- }
-
- try {
- // Unlock vault if it's locked
- if (!isVaultUnlocked()) {
- unlockVault()
- }
-
- // Return all credentials
- callback.onSuccess(getAllCredentials())
- return true
- } catch (e: Exception) {
- Log.e(TAG, "Error retrieving credentials", e)
- callback.onError(e)
- return false
- }
+ fun getAutoLockTimeout(): Int {
+ return auth.getAutoLockTimeout()
}
- /**
- * Decrypt data.
- * @param encryptedData The encrypted data
- * @return The decrypted data
- */
- private fun decryptData(encryptedData: String): String {
- var decryptedResult: String? = null
- var error: Exception? = null
-
- // Create a latch to wait for the callback
- val latch = java.util.concurrent.CountDownLatch(1)
-
- getEncryptionKey(object : CryptoOperationCallback {
- override fun onSuccess(result: String) {
- try {
- val decoded = Base64.decode(encryptedData, Base64.NO_WRAP)
-
- // Extract IV from the first 12 bytes
- val iv = decoded.copyOfRange(0, 12)
- val encryptedContent = decoded.copyOfRange(12, decoded.size)
-
- // Create cipher
- val cipher = Cipher.getInstance("AES/GCM/NoPadding")
- val keySpec = SecretKeySpec(encryptionKey!!, "AES")
- val gcmSpec = GCMParameterSpec(128, iv)
-
- // Initialize cipher for decryption
- cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmSpec)
-
- // Decrypt
- val decrypted = cipher.doFinal(encryptedContent)
- decryptedResult = String(decrypted, Charsets.UTF_8)
- } catch (e: Exception) {
- error = e
- Log.e(TAG, "Error decrypting data", e)
- } finally {
- latch.countDown()
- }
- }
+ // endregion
- override fun onError(e: Exception) {
- error = e
- Log.e(TAG, "Error getting encryption key", e)
- latch.countDown()
- }
- })
-
- // Wait for the callback to complete
- latch.await()
-
- // Throw any error that occurred or return the result
- error?.let { throw it }
- return decryptedResult ?: error("Decryption failed")
- }
+ // region Metadata Methods
/**
- * Get all credentials from the vault.
- * @return The list of credentials
+ * Store the metadata.
*/
- fun getAllCredentials(): List<Credential> {
- if (dbConnection == null) {
- error("Database not initialized")
- }
-
- val query = """
- WITH LatestPasswords AS (
- SELECT
- p.Id as password_id,
- p.CredentialId,
- p.Value,
- p.CreatedAt,
- p.UpdatedAt,
- p.IsDeleted,
- ROW_NUMBER() OVER (PARTITION BY p.CredentialId ORDER BY p.CreatedAt DESC) as rn
- FROM Passwords p
- WHERE p.IsDeleted = 0
- )
- SELECT
- c.Id,
- c.AliasId,
- c.Username,
- c.Notes,
- c.CreatedAt,
- c.UpdatedAt,
- c.IsDeleted,
- s.Id as service_id,
- s.Name as service_name,
- s.Url as service_url,
- s.Logo as service_logo,
- s.CreatedAt as service_created_at,
- s.UpdatedAt as service_updated_at,
- s.IsDeleted as service_is_deleted,
- lp.password_id,
- lp.Value as password_value,
- lp.CreatedAt as password_created_at,
- lp.UpdatedAt as password_updated_at,
- lp.IsDeleted as password_is_deleted,
- a.Id as alias_id,
- a.Gender as alias_gender,
- a.FirstName as alias_first_name,
- a.LastName as alias_last_name,
- a.NickName as alias_nick_name,
- a.BirthDate as alias_birth_date,
- a.Email as alias_email,
- a.CreatedAt as alias_created_at,
- a.UpdatedAt as alias_updated_at,
- a.IsDeleted as alias_is_deleted
- FROM Credentials c
- LEFT JOIN Services s ON s.Id = c.ServiceId AND s.IsDeleted = 0
- LEFT JOIN LatestPasswords lp ON lp.CredentialId = c.Id AND lp.rn = 1
- LEFT JOIN Aliases a ON a.Id = c.AliasId AND a.IsDeleted = 0
- WHERE c.IsDeleted = 0
- ORDER BY c.CreatedAt DESC
- """
-
- val result = mutableListOf<Credential>()
- val cursor = dbConnection?.rawQuery(query, null)
-
- cursor?.use {
- while (it.moveToNext()) {
- try {
- val id = UUID.fromString(it.getString(0))
- val isDeleted = it.getInt(6) == 1
-
- // Service
- val serviceId = UUID.fromString(it.getString(7))
- val service = Service(
- id = serviceId,
- name = it.getString(8),
- url = it.getString(9),
- logo = it.getBlob(10),
- createdAt = DateHelpers.parseDateString(it.getString(11)) ?: MIN_DATE,
- updatedAt = DateHelpers.parseDateString(it.getString(12)) ?: MIN_DATE,
- isDeleted = it.getInt(13) == 1,
- )
-
- // Password
- var password: Password? = null
- if (!it.isNull(14)) {
- password = Password(
- id = UUID.fromString(it.getString(14)),
- credentialId = id,
- value = it.getString(15),
- createdAt = DateHelpers.parseDateString(it.getString(16)) ?: MIN_DATE,
- updatedAt = DateHelpers.parseDateString(it.getString(17)) ?: MIN_DATE,
- isDeleted = it.getInt(18) == 1,
- )
- }
-
- // Alias
- var alias: Alias? = null
- if (!it.isNull(19)) {
- alias = Alias(
- id = UUID.fromString(it.getString(19)),
- gender = it.getString(20),
- firstName = it.getString(21),
- lastName = it.getString(22),
- nickName = it.getString(23),
- birthDate = DateHelpers.parseDateString(it.getString(24)) ?: MIN_DATE,
- email = it.getString(25),
- createdAt = DateHelpers.parseDateString(it.getString(26)) ?: MIN_DATE,
- updatedAt = DateHelpers.parseDateString(it.getString(27)) ?: MIN_DATE,
- isDeleted = it.getInt(28) == 1,
- )
- }
-
- val credential = Credential(
- id = id,
- alias = alias,
- service = service,
- username = it.getString(2),
- notes = it.getString(3),
- password = password,
- createdAt = DateHelpers.parseDateString(it.getString(4)) ?: MIN_DATE,
- updatedAt = DateHelpers.parseDateString(it.getString(5)) ?: MIN_DATE,
- isDeleted = isDeleted,
- )
- result.add(credential)
- } catch (e: Exception) {
- Log.e(TAG, "Error parsing credential row", e)
- }
- }
- }
-
- return result
+ fun storeMetadata(metadataString: String) {
+ metadata.storeMetadata(metadataString)
}
/**
- * Encrypt data.
- * @param data The data to encrypt
- * @return The encrypted data
+ * Get the metadata.
*/
- private fun encryptData(data: String): String {
- try {
- // Generate random IV
- val iv = ByteArray(12)
- SecureRandom().nextBytes(iv)
-
- // Create cipher
- val cipher = Cipher.getInstance("AES/GCM/NoPadding")
- val keySpec = SecretKeySpec(encryptionKey!!, "AES")
- val gcmSpec = GCMParameterSpec(128, iv)
-
- // Initialize cipher for encryption
- cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmSpec)
-
- // Encrypt
- val encrypted = cipher.doFinal(data.toByteArray(Charsets.UTF_8))
-
- // Combine IV and encrypted content
- val result = ByteArray(iv.size + encrypted.size)
- System.arraycopy(iv, 0, result, 0, iv.size)
- System.arraycopy(encrypted, 0, result, iv.size, encrypted.size)
-
- return Base64.encodeToString(result, Base64.NO_WRAP)
- } catch (e: Exception) {
- Log.e(TAG, "Error encrypting data", e)
- throw e
- }
+ fun getMetadata(): String {
+ return metadata.getMetadata()
}
/**
- * Setup the database with decrypted data. This initializes the decrypted database in memory.
- * @param decryptedDbBase64 The decrypted database as a base64 encoded string
+ * Set the vault revision number.
*/
- private fun setupDatabaseWithDecryptedData(decryptedDbBase64: String) {
- var tempDbFile: File? = null
- try {
- // Decode the base64 data
- val decryptedDbData = Base64.decode(decryptedDbBase64, Base64.NO_WRAP)
-
- // Create a temporary file in app-specific storage
- tempDbFile = File.createTempFile("temp_db", ".sqlite")
- tempDbFile.deleteOnExit() // Ensure cleanup on JVM exit
- tempDbFile.writeBytes(decryptedDbData)
-
- // Close any existing connection if it exists
- dbConnection?.close()
-
- // Create an in-memory database
- dbConnection = SQLiteDatabase.create(null)
-
- // Begin transaction
- dbConnection?.beginTransaction()
-
- try {
- // Attach the temporary database
- val attachQuery = "ATTACH DATABASE '${tempDbFile.path}' AS source"
- dbConnection?.execSQL(attachQuery)
-
- // Verify the attachment worked by checking if we can access the source database
- val verifyCursor = dbConnection?.rawQuery(
- "SELECT name FROM source.sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'",
- null,
- )
-
- if (verifyCursor == null) {
- throw SQLiteException("Failed to attach source database")
- }
-
- verifyCursor.use {
- if (!it.moveToFirst()) {
- throw SQLiteException("No tables found in source database")
- }
-
- do {
- val tableName = it.getString(0)
- // Create table and copy data using rawQuery
- dbConnection?.execSQL(
- "CREATE TABLE $tableName AS SELECT * FROM source.$tableName",
- )
- } while (it.moveToNext())
- }
-
- // Commit transaction
- dbConnection?.setTransactionSuccessful()
- } finally {
- dbConnection?.endTransaction()
- }
-
- // Detach the source database
- dbConnection?.rawQuery("DETACH DATABASE source", null)
-
- // Set database pragmas using rawQuery
- dbConnection?.rawQuery("PRAGMA journal_mode = WAL", null)
- dbConnection?.rawQuery("PRAGMA synchronous = NORMAL", null)
- dbConnection?.rawQuery("PRAGMA foreign_keys = ON", null)
-
- lastUnlockTime = System.currentTimeMillis()
- } catch (e: Exception) {
- Log.e(TAG, "Error setting up database with decrypted data", e)
- throw e
- } finally {
- // Securely delete the temporary file
- tempDbFile?.let {
- if (it.exists()) {
- it.setWritable(true, true) // Temporarily enable write for deletion
- it.delete()
- }
- }
- }
+ fun setVaultRevisionNumber(revisionNumber: Int) {
+ metadata.setVaultRevisionNumber(revisionNumber)
}
/**
- * Remove problematic invisible characters from string.
- * @return The trimmed string
+ * Get the vault revision number.
*/
- private fun String.smartTrim(): String {
- val invisible = "[\\uFEFF\\u200B\\u00A0\\u202A-\\u202E\\u2060\\u180E]"
- return this.replace(Regex("^($invisible)+|($invisible)+$"), "").trim()
+ fun getVaultRevisionNumber(): Int {
+ return metadata.getVaultRevisionNumber()
}
- // MARK: - Username Management
-
/**
* Set the username.
- * @param username The username to store
*/
fun setUsername(username: String) {
- storageProvider.setUsername(username)
+ metadata.setUsername(username)
}
/**
* Get the username.
- * @return The username or null if not set
*/
fun getUsername(): String? {
- return storageProvider.getUsername()
+ return metadata.getUsername()
}
/**
* Clear the username.
*/
fun clearUsername() {
- storageProvider.clearUsername()
+ metadata.clearUsername()
}
- // MARK: - Offline Mode Management
-
/**
* Set offline mode flag.
- * @param isOffline Whether the app is in offline mode
*/
fun setOfflineMode(isOffline: Boolean) {
- storageProvider.setOfflineMode(isOffline)
+ metadata.setOfflineMode(isOffline)
}
/**
* Get offline mode flag.
- * @return True if app is in offline mode, false otherwise
*/
fun getOfflineMode(): Boolean {
- return storageProvider.getOfflineMode()
+ return metadata.getOfflineMode()
}
- // MARK: - Vault Sync Methods
+ // endregion
+
+ // region Sync Methods
/**
* Check if a new vault version is available on the server.
- * Returns a map with isNewVersionAvailable and newRevision keys.
- *
- * @param webApiService The WebApiService to use for the request
- * @return Map with "isNewVersionAvailable" (Boolean) and "newRevision" (Int?) keys
*/
suspend fun isNewVaultVersionAvailable(webApiService: net.aliasvault.app.webapi.WebApiService): Map<String, Any?> {
- val status = fetchAndValidateStatus(webApiService)
- setOfflineMode(false)
-
- val currentRevision = getVaultRevisionNumber()
- return if (status.vaultRevision > currentRevision) {
- mapOf(
- "isNewVersionAvailable" to true,
- "newRevision" to status.vaultRevision,
- )
- } else {
- mapOf(
- "isNewVersionAvailable" to false,
- "newRevision" to null,
- )
- }
+ return sync.isNewVaultVersionAvailable(webApiService)
}
/**
* Download and store the vault from the server.
- * This method assumes a version check has already been performed.
- *
- * @param webApiService The WebApiService to use for the request
- * @param newRevision The new revision number to download
- * @return True if successful
*/
suspend fun downloadVault(webApiService: net.aliasvault.app.webapi.WebApiService, newRevision: Int): Boolean {
- try {
- downloadAndStoreVault(webApiService, newRevision)
- setOfflineMode(false)
- return true
- } catch (e: Exception) {
- Log.e(TAG, "Error downloading vault", e)
- throw e
+ val result = sync.downloadVault(webApiService, newRevision)
+ // Re-unlock vault if it was unlocked before download
+ if (result && isVaultUnlocked()) {
+ unlockVault()
}
+ return result
}
/**
* Sync the vault with the server.
- * Returns true if a new vault was downloaded, false if vault is already up to date.
- * NOTE: This is a convenience method that combines isNewVaultVersionAvailable and downloadVault
- * For better UX control, use isNewVaultVersionAvailable() and downloadVault() separately
*/
suspend fun syncVault(webApiService: net.aliasvault.app.webapi.WebApiService): Boolean {
- // Check if new version is available
- val versionCheck = isNewVaultVersionAvailable(webApiService)
- val isNewVersionAvailable = versionCheck["isNewVersionAvailable"] as? Boolean ?: false
- val newRevision = versionCheck["newRevision"] as? Int
-
- if (isNewVersionAvailable && newRevision != null) {
- // Download the new vault
- downloadVault(webApiService, newRevision)
- return true
- }
-
- return false
- }
-
- /**
- * Fetch and validate server status.
- */
- private suspend fun fetchAndValidateStatus(webApiService: net.aliasvault.app.webapi.WebApiService): StatusResponse {
- val statusResponse = try {
- webApiService.executeRequest(
- method = "GET",
- endpoint = "Auth/status",
- body = null,
- headers = emptyMap(),
- requiresAuth = true,
- )
- } catch (e: Exception) {
- // Network error - convert to VaultSyncError
- throw VaultSyncError.NetworkError(e)
- }
-
- // Check response status
- // Note: WebApiService already handles 401 with automatic token refresh and retry
- // If we still get a 401 here, it means the refresh failed and we should logout
- if (statusResponse.statusCode != 200) {
- if (statusResponse.statusCode == 401) {
- // Authentication failed even after token refresh attempt
- Log.e(TAG, "Authentication failed (401) - token refresh also failed")
- throw VaultSyncError.SessionExpired()
- }
- // Other error (5xx, network, etc.) - go offline
- setOfflineMode(true)
- throw VaultSyncError.ServerUnavailable(statusResponse.statusCode)
- }
-
- val status = try {
- val json = org.json.JSONObject(statusResponse.body)
- StatusResponse(
- clientVersionSupported = json.getBoolean("clientVersionSupported"),
- serverVersion = json.getString("serverVersion"),
- vaultRevision = json.getInt("vaultRevision"),
- srpSalt = json.getString("srpSalt"),
- )
- } 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)
- }
-
- if (!status.clientVersionSupported) {
- throw VaultSyncError.ClientVersionNotSupported()
- }
-
- // Validate server version meets minimum requirement
- if (!VersionComparison.isServerVersionSupported(status.serverVersion)) {
- Log.e(TAG, "Server version ${status.serverVersion} does not meet minimum requirement ${AppInfo.MIN_SERVER_VERSION}")
- throw VaultSyncError.ServerVersionNotSupported()
- }
-
- validateSrpSalt(status.srpSalt)
- return status
+ return sync.syncVault(webApiService)
}
- /**
- * Validate SRP salt hasn't changed (password change detection).
- */
- private fun validateSrpSalt(srpSalt: String) {
- val keyDerivationParams = storageProvider.getKeyDerivationParams()
- if (keyDerivationParams.isEmpty()) {
- return
- }
+ // endregion
- @Suppress("SwallowedException")
- try {
- val json = org.json.JSONObject(keyDerivationParams)
- val salt = json.optString("salt", "")
- if (srpSalt.isNotEmpty() && srpSalt != salt) {
- throw VaultSyncError.PasswordChanged()
- }
- } catch (e: VaultSyncError.PasswordChanged) {
- throw e
- } catch (e: Exception) {
- // Ignore generic parsing errors
- }
- }
-
- /**
- * Download vault from server and store it locally.
- */
- private suspend fun downloadAndStoreVault(webApiService: net.aliasvault.app.webapi.WebApiService, newRevision: Int) {
- val vaultResponse = try {
- webApiService.executeRequest(
- method = "GET",
- endpoint = "Vault",
- body = null,
- headers = emptyMap(),
- requiresAuth = true,
- )
- } catch (e: Exception) {
- throw VaultOperationException("Network error: ${e.message}", e)
- }
-
- if (vaultResponse.statusCode != 200) {
- if (vaultResponse.statusCode == 401) {
- throw VaultOperationException("Session expired")
- }
- throw VaultOperationException("Server unavailable: ${vaultResponse.statusCode}")
- }
-
- val vault = parseVaultResponse(vaultResponse.body)
- validateVaultStatus(vault.status)
- storeEncryptedDatabase(vault.vault.blob)
- setVaultRevisionNumber(newRevision)
-
- if (isVaultUnlocked()) {
- unlockVault()
- }
- }
-
- /**
- * Parse vault response from JSON.
- */
- private fun parseVaultResponse(body: String): VaultResponse {
- return try {
- val json = org.json.JSONObject(body)
- val vaultJson = json.getJSONObject("vault")
-
- val emailList = mutableListOf<String>()
- val emailArray = vaultJson.getJSONArray("emailAddressList")
- for (i in 0 until emailArray.length()) {
- emailList.add(emailArray.getString(i))
- }
-
- val privateList = mutableListOf<String>()
- val privateArray = vaultJson.getJSONArray("privateEmailDomainList")
- for (i in 0 until privateArray.length()) {
- privateList.add(privateArray.getString(i))
- }
-
- val publicList = mutableListOf<String>()
- val publicArray = vaultJson.getJSONArray("publicEmailDomainList")
- for (i in 0 until publicArray.length()) {
- publicList.add(publicArray.getString(i))
- }
-
- VaultResponse(
- status = json.getInt("status"),
- vault = VaultData(
- username = vaultJson.getString("username"),
- blob = vaultJson.getString("blob"),
- version = vaultJson.getString("version"),
- currentRevisionNumber = vaultJson.getInt("currentRevisionNumber"),
- encryptionPublicKey = vaultJson.getString("encryptionPublicKey"),
- credentialsCount = vaultJson.getInt("credentialsCount"),
- emailAddressList = emailList,
- privateEmailDomainList = privateList,
- publicEmailDomainList = publicList,
- createdAt = vaultJson.getString("createdAt"),
- updatedAt = vaultJson.getString("updatedAt"),
- ),
- )
- } catch (e: Exception) {
- Log.e(TAG, "Failed to decode vault response", e)
- throw SerializationException("Failed to decode vault response: ${e.message}", e)
- }
- }
-
- /**
- * Validate vault response status.
- */
- private fun validateVaultStatus(status: Int) {
- when (status) {
- 0 -> return
- 1 -> throw VaultOperationException("Vault merge required")
- 2 -> throw VaultOperationException("Vault outdated")
- else -> throw VaultOperationException("Unknown vault status: $status")
- }
- }
-
- // MARK: - Vault Mutate Methods
-
- /**
- * Prepare the vault for upload by assembling all metadata.
- * Returns a VaultUpload object ready to be sent to the server.
- */
- private fun prepareVault(): VaultUpload {
- val currentRevision = getVaultRevisionNumber()
-
- val encryptedDb = getEncryptedDatabase()
-
- val username = getUsername()
- ?: throw VaultOperationException("Username not found")
-
- if (!isVaultUnlocked()) {
- throw VaultOperationException("Vault must be unlocked to prepare for upload")
- }
-
- // Get all credentials
- val credentials = getAllCredentials()
-
- // Get private email domains from metadata
- val metadata = getVaultMetadataObject()
- val privateEmailDomains = metadata?.privateEmailDomains ?: emptyList()
-
- // Extract private email addresses from credentials
- val privateEmailAddresses = credentials
- .mapNotNull { it.alias?.email }
- .filter { email ->
- privateEmailDomains.any { domain ->
- email.lowercase().endsWith("@${domain.lowercase()}")
- }
- }
- .distinct()
-
- // Get database version
- val dbVersion = getDatabaseVersion()
-
- // Get app version
- @Suppress("SwallowedException")
- val version = try {
- val context = storageProvider as? net.aliasvault.app.vaultstore.storageprovider.AndroidStorageProvider
- val pm = context?.javaClass?.getDeclaredField("context")?.get(context) as? android.content.Context
- pm?.packageManager?.getPackageInfo(pm.packageName, 0)?.versionName ?: "0.0.0"
- } catch (e: Exception) {
- "0.0.0"
- }
- val baseVersion = version.split("-").firstOrNull() ?: "0.0.0"
- val client = "android-$baseVersion"
-
- val dateFormat = java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", java.util.Locale.US)
- dateFormat.timeZone = java.util.TimeZone.getTimeZone("UTC")
- val now = dateFormat.format(java.util.Date())
-
- return VaultUpload(
- blob = encryptedDb,
- createdAt = now,
- credentialsCount = credentials.size,
- currentRevisionNumber = currentRevision,
- emailAddressList = privateEmailAddresses,
- privateEmailDomainList = emptyList(), // Empty on purpose
- publicEmailDomainList = emptyList(), // Empty on purpose
- encryptionPublicKey = "", // Empty on purpose
- updatedAt = now,
- username = username,
- version = dbVersion,
- client = client,
- )
- }
+ // region Mutate Methods
/**
* Execute a vault mutation operation.
- * This method uploads the vault to the server and updates the local revision number.
- *
- * @param webApiService The WebApiService to use for the request
- * @return True if successful
*/
suspend fun mutateVault(webApiService: net.aliasvault.app.webapi.WebApiService): Boolean {
- try {
- // Prepare vault for upload
- val vault = prepareVault()
-
- // Convert to JSON
- val json = org.json.JSONObject()
- json.put("blob", vault.blob)
- json.put("createdAt", vault.createdAt)
- json.put("credentialsCount", vault.credentialsCount)
- json.put("currentRevisionNumber", vault.currentRevisionNumber)
- json.put("emailAddressList", org.json.JSONArray(vault.emailAddressList))
- json.put("privateEmailDomainList", org.json.JSONArray(vault.privateEmailDomainList))
- json.put("publicEmailDomainList", org.json.JSONArray(vault.publicEmailDomainList))
- json.put("encryptionPublicKey", vault.encryptionPublicKey)
- json.put("updatedAt", vault.updatedAt)
- json.put("username", vault.username)
- json.put("version", vault.version)
- json.put("client", vault.client)
-
- // Upload to server
- val response = webApiService.executeRequest(
- method = "POST",
- endpoint = "Vault",
- body = json.toString(),
- headers = mapOf("Content-Type" to "application/json"),
- requiresAuth = true,
- )
-
- if (response.statusCode != 200) {
- Log.e(TAG, "Server rejected vault upload with status ${response.statusCode}")
- throw VaultOperationException("Server returned error: ${response.statusCode}")
- }
-
- // Parse response
- val vaultResponse = try {
- val responseJson = org.json.JSONObject(response.body)
- VaultPostResponse(
- status = responseJson.getInt("status"),
- newRevisionNumber = responseJson.getInt("newRevisionNumber"),
- )
- } catch (e: Exception) {
- Log.e(TAG, "Failed to parse vault upload response", e)
- throw SerializationException("Failed to parse vault upload response: ${e.message}", e)
- }
-
- // Check vault response status
- when (vaultResponse.status) {
- 0 -> {
- // Success - update local revision number
- setVaultRevisionNumber(vaultResponse.newRevisionNumber)
- setOfflineMode(false)
- return true
- }
- 1 -> throw VaultOperationException("Vault merge required")
- 2 -> throw VaultOperationException("Vault is outdated, please sync first")
- else -> throw VaultOperationException("Failed to upload vault")
- }
- } catch (e: Exception) {
- Log.e(TAG, "Error mutating vault", e)
- throw e
- }
+ return mutate.mutateVault(webApiService)
}
- /**
- * Get the database version from the __EFMigrationsHistory table.
- */
- private fun getDatabaseVersion(): String {
- val query = "SELECT MigrationId FROM __EFMigrationsHistory ORDER BY MigrationId DESC LIMIT 1"
- val results = executeQuery(query, emptyArray())
-
- if (results.isEmpty()) {
- Log.d(TAG, "No migrations found in database, returning default version")
- return "0.0.0"
- }
+ // endregion
- val migrationId = results[0]["MigrationId"] as? String
- if (migrationId == null) {
- return "0.0.0"
- }
-
- // Extract version using regex - matches patterns like "_1.4.1-"
- val versionRegex = Regex("_(\\d+\\.\\d+\\.\\d+)-")
- val match = versionRegex.find(migrationId)
-
- return if (match != null && match.groupValues.size > 1) {
- match.groupValues[1]
- } else {
- Log.d(TAG, "Could not extract version from migration ID '$migrationId', returning default")
- "0.0.0"
- }
- }
-
- // MARK: - Data Models for Sync/Mutate
-
- /**
- * Status response from Auth/status endpoint.
- */
- private data class StatusResponse(
- val clientVersionSupported: Boolean,
- val serverVersion: String,
- val vaultRevision: Int,
- val srpSalt: String,
- )
-
- /**
- * Vault data from API.
- */
- private data class VaultData(
- val username: String,
- val blob: String,
- val version: String,
- val currentRevisionNumber: Int,
- val encryptionPublicKey: String,
- val credentialsCount: Int,
- val emailAddressList: List<String>,
- val privateEmailDomainList: List<String>,
- val publicEmailDomainList: List<String>,
- val createdAt: String,
- val updatedAt: String,
- )
+ // region Cache Methods
/**
- * Vault response from Vault GET endpoint.
+ * Clear the memory, removing the encryption key and decrypted database from memory.
*/
- private data class VaultResponse(
- val status: Int,
- val vault: VaultData,
- )
+ fun clearCache() {
+ cache.clearCache()
+ }
/**
- * Vault upload model that matches the API contract.
+ * Clear all vault data including from persisted storage.
*/
- private data class VaultUpload(
- val blob: String,
- val createdAt: String,
- val credentialsCount: Int,
- val currentRevisionNumber: Int,
- val emailAddressList: List<String>,
- val privateEmailDomainList: List<String>,
- val publicEmailDomainList: List<String>,
- val encryptionPublicKey: String,
- val updatedAt: String,
- val username: String,
- val version: String,
- val client: String,
- )
+ fun clearVault() {
+ cache.clearVault()
+ }
- /**
- * Vault POST response from API.
- */
- private data class VaultPostResponse(
- val status: Int,
- val newRevisionNumber: Int,
- )
+ // endregion
}
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
new file mode 100644
index 000000000..eb7ee1f71
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt
@@ -0,0 +1,262 @@
+package net.aliasvault.app.vaultstore
+
+import android.util.Log
+import net.aliasvault.app.exceptions.SerializationException
+import net.aliasvault.app.exceptions.VaultOperationException
+import org.json.JSONObject
+
+/**
+ * Handles vault synchronization with the server.
+ */
+class VaultSync(
+ private val database: VaultDatabase,
+ private val metadata: VaultMetadataManager,
+ private val crypto: VaultCrypto,
+) {
+ companion object {
+ private const val TAG = "VaultSync"
+ }
+
+ // region Sync Methods
+
+ /**
+ * Check if a new vault version is available on the server.
+ */
+ suspend fun isNewVaultVersionAvailable(webApiService: net.aliasvault.app.webapi.WebApiService): Map<String, Any?> {
+ val status = fetchAndValidateStatus(webApiService)
+ metadata.setOfflineMode(false)
+
+ val currentRevision = metadata.getVaultRevisionNumber()
+ return if (status.vaultRevision > currentRevision) {
+ mapOf(
+ "isNewVersionAvailable" to true,
+ "newRevision" to status.vaultRevision,
+ )
+ } else {
+ mapOf(
+ "isNewVersionAvailable" to false,
+ "newRevision" to null,
+ )
+ }
+ }
+
+ /**
+ * Download and store the vault from the server.
+ */
+ suspend fun downloadVault(webApiService: net.aliasvault.app.webapi.WebApiService, newRevision: Int): Boolean {
+ try {
+ downloadAndStoreVault(webApiService, newRevision)
+ metadata.setOfflineMode(false)
+ return true
+ } catch (e: Exception) {
+ Log.e(TAG, "Error downloading vault", e)
+ throw e
+ }
+ }
+
+ /**
+ * Sync the vault with the server.
+ */
+ suspend fun syncVault(webApiService: net.aliasvault.app.webapi.WebApiService): Boolean {
+ val versionCheck = isNewVaultVersionAvailable(webApiService)
+ val isNewVersionAvailable = versionCheck["isNewVersionAvailable"] as? Boolean ?: false
+ val newRevision = versionCheck["newRevision"] as? Int
+
+ if (isNewVersionAvailable && newRevision != null) {
+ downloadVault(webApiService, newRevision)
+ return true
+ }
+
+ return false
+ }
+
+ // endregion
+
+ // region Internal Helpers
+
+ private suspend fun fetchAndValidateStatus(webApiService: net.aliasvault.app.webapi.WebApiService): StatusResponse {
+ val statusResponse = try {
+ webApiService.executeRequest(
+ method = "GET",
+ endpoint = "Auth/status",
+ body = null,
+ headers = emptyMap(),
+ requiresAuth = true,
+ )
+ } catch (e: Exception) {
+ throw VaultSyncError.NetworkError(e)
+ }
+
+ if (statusResponse.statusCode != 200) {
+ if (statusResponse.statusCode == 401) {
+ Log.e(TAG, "Authentication failed (401) - token refresh also failed")
+ throw VaultSyncError.SessionExpired()
+ }
+ metadata.setOfflineMode(true)
+ throw VaultSyncError.ServerUnavailable(statusResponse.statusCode)
+ }
+
+ val status = try {
+ val json = JSONObject(statusResponse.body)
+ StatusResponse(
+ clientVersionSupported = json.getBoolean("clientVersionSupported"),
+ serverVersion = json.getString("serverVersion"),
+ vaultRevision = json.getInt("vaultRevision"),
+ srpSalt = json.getString("srpSalt"),
+ )
+ } 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)
+ }
+
+ if (!status.clientVersionSupported) {
+ throw VaultSyncError.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()
+ }
+
+ validateSrpSalt(status.srpSalt)
+ return status
+ }
+
+ private fun validateSrpSalt(srpSalt: String) {
+ val keyDerivationParams = crypto.getEncryptionKeyDerivationParams()
+ if (keyDerivationParams.isEmpty()) {
+ return
+ }
+
+ @Suppress("SwallowedException")
+ try {
+ val json = JSONObject(keyDerivationParams)
+ val salt = json.optString("salt", "")
+ if (srpSalt.isNotEmpty() && srpSalt != salt) {
+ throw VaultSyncError.PasswordChanged()
+ }
+ } catch (e: VaultSyncError.PasswordChanged) {
+ throw e
+ } catch (e: Exception) {
+ // Ignore generic parsing errors
+ }
+ }
+
+ private suspend fun downloadAndStoreVault(webApiService: net.aliasvault.app.webapi.WebApiService, newRevision: Int) {
+ val vaultResponse = try {
+ webApiService.executeRequest(
+ method = "GET",
+ endpoint = "Vault",
+ body = null,
+ headers = emptyMap(),
+ requiresAuth = true,
+ )
+ } catch (e: Exception) {
+ throw VaultOperationException("Network error: ${e.message}", e)
+ }
+
+ if (vaultResponse.statusCode != 200) {
+ if (vaultResponse.statusCode == 401) {
+ throw VaultOperationException("Session expired")
+ }
+ throw VaultOperationException("Server unavailable: ${vaultResponse.statusCode}")
+ }
+
+ val vault = parseVaultResponse(vaultResponse.body)
+ validateVaultStatus(vault.status)
+ database.storeEncryptedDatabase(vault.vault.blob)
+ metadata.setVaultRevisionNumber(newRevision)
+
+ if (database.isVaultUnlocked()) {
+ // Re-unlock with new data
+ // Note: This requires auth methods to be passed, handled by VaultStore
+ }
+ }
+
+ private fun parseVaultResponse(body: String): VaultResponse {
+ return try {
+ val json = JSONObject(body)
+ val vaultJson = json.getJSONObject("vault")
+
+ val emailList = mutableListOf<String>()
+ val emailArray = vaultJson.getJSONArray("emailAddressList")
+ for (i in 0 until emailArray.length()) {
+ emailList.add(emailArray.getString(i))
+ }
+
+ val privateList = mutableListOf<String>()
+ val privateArray = vaultJson.getJSONArray("privateEmailDomainList")
+ for (i in 0 until privateArray.length()) {
+ privateList.add(privateArray.getString(i))
+ }
+
+ val publicList = mutableListOf<String>()
+ val publicArray = vaultJson.getJSONArray("publicEmailDomainList")
+ for (i in 0 until publicArray.length()) {
+ publicList.add(publicArray.getString(i))
+ }
+
+ VaultResponse(
+ status = json.getInt("status"),
+ vault = VaultData(
+ username = vaultJson.getString("username"),
+ blob = vaultJson.getString("blob"),
+ version = vaultJson.getString("version"),
+ currentRevisionNumber = vaultJson.getInt("currentRevisionNumber"),
+ encryptionPublicKey = vaultJson.getString("encryptionPublicKey"),
+ credentialsCount = vaultJson.getInt("credentialsCount"),
+ emailAddressList = emailList,
+ privateEmailDomainList = privateList,
+ publicEmailDomainList = publicList,
+ createdAt = vaultJson.getString("createdAt"),
+ updatedAt = vaultJson.getString("updatedAt"),
+ ),
+ )
+ } catch (e: Exception) {
+ Log.e(TAG, "Failed to decode vault response", e)
+ throw SerializationException("Failed to decode vault response: ${e.message}", e)
+ }
+ }
+
+ private fun validateVaultStatus(status: Int) {
+ when (status) {
+ 0 -> return
+ 1 -> throw VaultOperationException("Vault merge required")
+ 2 -> throw VaultOperationException("Vault outdated")
+ else -> throw VaultOperationException("Unknown vault status: $status")
+ }
+ }
+
+ // endregion
+
+ // region Data Models
+
+ private data class StatusResponse(
+ val clientVersionSupported: Boolean,
+ val serverVersion: String,
+ val vaultRevision: Int,
+ val srpSalt: String,
+ )
+
+ private data class VaultData(
+ val username: String,
+ val blob: String,
+ val version: String,
+ val currentRevisionNumber: Int,
+ val encryptionPublicKey: String,
+ val credentialsCount: Int,
+ val emailAddressList: List<String>,
+ val privateEmailDomainList: List<String>,
+ val publicEmailDomainList: List<String>,
+ val createdAt: String,
+ val updatedAt: String,
+ )
+
+ private data class VaultResponse(
+ val status: Int,
+ val vault: VaultData,
+ )
+
+ // endregion
+}