Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Implement separate databucket push to mobile app (#2159)
Leendert de Borst904d1af472a9
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.ktindex fb4762b24..2880ba19d 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt@@ -27,6 +27,7 @@ import net.aliasvault.app.vaultstore.AppErrorimport net.aliasvault.app.vaultstore.VaultStoreimport net.aliasvault.app.vaultstore.interfaces.CryptoOperationCallbackimport net.aliasvault.app.vaultstore.keystoreprovider.AndroidKeystoreProvider+import net.aliasvault.app.vaultstore.models.VaultMutationScopeimport net.aliasvault.app.vaultstore.storageprovider.AndroidStorageProviderimport net.aliasvault.app.webapi.WebApiServiceimport org.json.JSONArray@@ -546,9 +547,9 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :* @param promise The promise to resolve*/@ReactMethod- override fun commitTransaction(promise: Promise) {+ override fun commitTransaction(scope: String, promise: Promise) {try {- vaultStore.commitTransaction()+ vaultStore.commitTransaction(VaultMutationScope.known(scope))promise.resolve(null)} catch (e: Exception) {Log.e(TAG, "Error committing transaction", e)@@ -585,9 +586,9 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :* @param promise The promise to resolve*/@ReactMethod- override fun persistAndMarkDirty(promise: Promise) {+ override fun persistAndMarkDirty(scope: String, promise: Promise) {try {- vaultStore.persistAndMarkDirty()+ vaultStore.persistAndMarkDirty(VaultMutationScope.known(scope))promise.resolve(null)} catch (e: Exception) {Log.e(TAG, "Error persisting and marking dirty", e)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.ktindex 8434cc29e..a9bffcbce 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultDatabase.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultDatabase.kt@@ -3,6 +3,7 @@ package net.aliasvault.app.vaultstoreimport android.util.Base64import android.util.Logimport net.aliasvault.app.rustcore.JnaInitializer+import net.aliasvault.app.vaultstore.models.VaultMutationScopeimport net.aliasvault.app.vaultstore.storageprovider.StorageProviderimport uniffi.aliasvault_core.SqlValueimport uniffi.aliasvault_core.SqliteMemoryDatabase@@ -169,11 +170,12 @@ class VaultDatabase(/*** Commit a SQL transaction, persist the encrypted vault and mark it as changed locally.+ * @param scope What the mutation touched, so the next sync can push only that scope*/- fun commitTransaction() {+ fun commitTransaction(scope: String = VaultMutationScope.MAIN) {connection().executeBatch("COMMIT")persistDatabaseToEncryptedStorage()- markMutated()+ markMutated(scope)}/**@@ -186,10 +188,11 @@ class VaultDatabase(/*** Persist the in-memory database and mark it as changed locally, without committing a SQL transaction.* Used after migrations, whose scripts manage their own transactions.+ * @param scope What the mutation touched, so the next sync can push only that scope*/- fun persistAndMarkDirty() {+ fun persistAndMarkDirty(scope: String = VaultMutationScope.MAIN) {persistDatabaseToEncryptedStorage()- markMutated()+ markMutated(scope)}/**@@ -212,8 +215,8 @@ class VaultDatabase(* Mark the vault dirty and bump the mutation sequence, atomically from the sync engine's point of view,* so the next sync pushes the local change instead of reporting the vault in sync.*/- private fun markMutated() {- metadata.setIsDirty(true)+ private fun markMutated(scope: String) {+ metadata.markDirty(scope)metadata.incrementMutationSequence()}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.ktindex 91552ea4c..ea3c082b3 100644--- 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@@ -3,6 +3,7 @@ package net.aliasvault.app.vaultstoreimport android.util.Logimport net.aliasvault.app.vaultstore.models.SyncStateimport net.aliasvault.app.vaultstore.models.VaultMetadata+import net.aliasvault.app.vaultstore.models.VaultMutationScopeimport net.aliasvault.app.vaultstore.storageprovider.StorageProviderimport net.aliasvault.app.vaultstore.utils.VersionComparisonimport org.json.JSONArray@@ -158,10 +159,43 @@ class VaultMetadataManager(// region Sync State Management/**- * Set the dirty flag indicating local changes need to be synced.+ * Set the dirty flag indicating local changes need to be synced. Clearing it forgets the pending scopes+ * with it, since a clean vault has nothing left to push.*/fun setIsDirty(isDirty: Boolean) {storageProvider.setIsDirty(isDirty)+ if (!isDirty) {+ storageProvider.setDirtyScopes(emptyList())+ }+ }++ /**+ * Mark the vault dirty and record what the mutation touched, so the next sync can push only that scope.+ * @param scope The mutation scope, defaulting to a full-manifest change+ */+ fun markDirty(scope: String = VaultMutationScope.MAIN) {+ setIsDirty(true)+ addDirtyScope(scope)+ }++ /**+ * The mutation scopes that have pending changes.+ */+ fun getDirtyScopes(): List<String> {+ return storageProvider.getDirtyScopes()+ }++ /**+ * Record one scope as having pending changes.+ * @param scope The mutation scope; an unknown one counts as a full-manifest change+ */+ fun addDirtyScope(scope: String) {+ val known = VaultMutationScope.known(scope)+ val scopes = getDirtyScopes()+ if (scopes.contains(known)) {+ return+ }+ storageProvider.setDirtyScopes(scopes + known)}/**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.ktindex f6d41fdbe..64da5ac0c 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@@ -10,6 +10,7 @@ import net.aliasvault.app.vaultstore.keystoreprovider.KeystoreProviderimport net.aliasvault.app.vaultstore.models.Itemimport net.aliasvault.app.vaultstore.models.StoreVaultResultimport net.aliasvault.app.vaultstore.models.TotpCode+import net.aliasvault.app.vaultstore.models.VaultMutationScopeimport net.aliasvault.app.vaultstore.storageprovider.StorageProviderimport kotlin.coroutines.resume@@ -410,9 +411,10 @@ class VaultStore(/*** Commit a SQL transaction on the vault. The commit persists the vault and marks it dirty for the sync.+ * @param scope What the mutation touched, so the next sync can push only that scope*/- fun commitTransaction() {- database.commitTransaction()+ fun commitTransaction(scope: String = VaultMutationScope.MAIN) {+ database.commitTransaction(scope)}/**@@ -425,9 +427,10 @@ class VaultStore(/*** Persist the in-memory database to encrypted storage and mark as dirty, without committing a SQL* transaction. Used after migrations whose scripts manage their own transactions.+ * @param scope What the mutation touched, so the next sync can push only that scope*/- fun persistAndMarkDirty() {- database.persistAndMarkDirty()+ fun persistAndMarkDirty(scope: String = VaultMutationScope.MAIN) {+ database.persistAndMarkDirty(scope)}/**@@ -644,6 +647,7 @@ class VaultStore(markDirty: Boolean = false,serverRevision: Int? = null,expectedMutationSeq: Int? = null,+ scope: String = VaultMutationScope.MAIN,): StoreVaultResult {var mutationSequence = metadata.getMutationSequence()@@ -661,7 +665,7 @@ class VaultStore(if (markDirty) {metadata.setMutationSequence(mutationSequence)- metadata.setIsDirty(true)+ metadata.markDirty(scope)}if (serverRevision != null) {diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.ktindex 233890161..687396013 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt@@ -4,6 +4,7 @@ import android.util.Base64import android.util.Logimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.withContext+import net.aliasvault.app.Rimport net.aliasvault.app.rustcore.JnaInitializerimport net.aliasvault.app.utils.AppInfoimport net.aliasvault.app.vaultstore.models.VaultSql@@ -41,6 +42,9 @@ class VaultSyncEngine(/** The engine staging database used for internal sync and merge operations. */private var staging: SqliteMemoryDatabase? = null++ /** Whether the live vault was written to since the last store went through. */+ private var localMutated = falseprivate var runLog = VaultSyncRunLog("")/**@@ -71,6 +75,7 @@ class VaultSyncEngine(}} finally {closeStaging()+ discardLocalDatabaseIfNeeded()session.destroy()log.finish(success, storageProvider)}@@ -86,12 +91,12 @@ class VaultSyncEngine(put("username", vaultStore.getUsername() ?: "")put("isDirty", syncState.isDirty)put("mutationSequence", syncState.mutationSequence)- put("dirtyScopes", JSONArray(if (syncState.isDirty) listOf("Main") else emptyList<String>()))+ put("dirtyScopes", JSONArray(if (syncState.isDirty) vaultStore.metadata.getDirtyScopes() else emptyList<String>()))put("privateEmailDomains", JSONArray(metadata?.privateEmailDomains ?: emptyList<String>()))put("forcePull", forcePull)put("minServerVersion", AppInfo.MIN_SERVER_VERSION)put("isOfflineMode", vaultStore.getOfflineMode())- put("unnamedSharedVaultName", "Shared vault")+ put("unnamedSharedVaultName", storageProvider.getAppContext()?.getString(R.string.unnamed_shared_vault) ?: "Shared vault")}(encryptionKey ?: vaultStore.getEncryptionKeyBase64())?.let { request.put("encryptionKey", it) }(state("accountPublicKey") as? String)?.let { request.put("accountPublicKey", it) }@@ -127,7 +132,11 @@ class VaultSyncEngine(JSONObject().put("rows", JSONArray(database(command.optString("db")).query(command.optString("sql"), params)))}"dbExec" -> {- database(command.optString("db")).exec((command.optJSONArray("statements") ?: JSONArray()).toString())+ val name = command.optString("db")+ database(name).exec((command.optJSONArray("statements") ?: JSONArray()).toString())+ if (name == "local") {+ localMutated = true+ }JSONObject()}"dbExport" -> {@@ -170,6 +179,7 @@ class VaultSyncEngine(body = body,headers = headers,requiresAuth = command.optBoolean("auth", true),+ largeTransfer = command.optBoolean("largeTransfer", false),)JSONObject().put("status", response.statusCode).put("body", response.body)} catch (e: SocketTimeoutException) {@@ -234,6 +244,10 @@ class VaultSyncEngine(serverRevision = optionalInt(command, "revision"),expectedMutationSeq = optionalInt(command, "expectedMutationSeq"),)+ if (result.success) {+ // The stored vault is now what the live database holds, so nothing is left to discard.+ localMutated = false+ }if (result.success && vaultStore.isVaultUnlocked()) {// The contract: after a store, the live database is the vault just stored.val reloadStartNanos = System.nanoTime()@@ -279,5 +293,26 @@ class VaultSyncEngine(staging = null}+ /**+ * Reload the stored vault when the run left changes in the live database that no store persisted, so the+ * vault the app reads from is the one on disk rather than a half-finished sync.+ */+ @Suppress("TooGenericExceptionCaught")+ private fun discardLocalDatabaseIfNeeded() {+ if (!localMutated) {+ return+ }+ localMutated = false+ if (!vaultStore.isVaultUnlocked()) {+ return+ }+ try {+ vaultStore.unlockVault()+ runLog.note("Discarded unpersisted local vault changes; reloaded the stored vault")+ } catch (e: Exception) {+ Log.w(TAG, "Failed to reload the stored vault after discarding unpersisted changes", e)+ }+ }+// endregion}diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/VaultMutationScope.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/VaultMutationScope.ktnew file mode 100644index 000000000..11b0f6355--- /dev/null+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/VaultMutationScope.kt@@ -0,0 +1,22 @@+package net.aliasvault.app.vaultstore.models++/**+ * Scope of a local vault mutation: what actually changed, so the sync engine can push only the data bucket a+ * mutation touched instead of a full manifest. Mirrors VaultMutationScope in core/client.+ */+object VaultMutationScope {+ /**+ * A change to the vault content itself, which needs a full manifest push.+ */+ const val MAIN = "Main"++ /**+ * Every scope the sync engine understands: the manifest scope plus one per data bucket category.+ */+ val all = listOf(MAIN) + VaultDataBucketCategory.all++ /**+ * The given scope when the engine knows it, else the manifest scope, which is always safe to push.+ */+ fun known(scope: String?): String = if (scope != null && all.contains(scope)) scope else MAIN+}diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/PasskeyQueries.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/PasskeyQueries.ktindex b67ff0efe..d95b02a76 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/PasskeyQueries.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/PasskeyQueries.kt@@ -139,13 +139,6 @@ object PasskeyQueries {?7, ?8, ?9, ?10)"""- /**- * Update an item's UpdatedAt timestamp. Binds (now, id, manifestId).- */- const val UPDATE_ITEM_TIMESTAMP = """- UPDATE Items SET UpdatedAt = ? WHERE Id = ? AND ManifestId = ?- """-/*** Get the logo ID of an item. Binds (id, manifestId).*/@@ -179,11 +172,11 @@ object LogoQueries {"""/**- * The kind and key of an existing logo. Binds (id, manifestId).+ * The kind and key of an existing logo. Binds (id).*/const val GET_BY_ID = """SELECT Id, Kind, Source, Name FROM Logos- WHERE Id = ? AND ManifestId = ? AND IsDeleted = 0+ WHERE Id = ? AND IsDeleted = 0LIMIT 1"""diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/BaseRepository.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/BaseRepository.ktindex ecad7b4c3..1463f1deb 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/BaseRepository.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/BaseRepository.kt@@ -3,6 +3,7 @@ package net.aliasvault.app.vaultstore.repositoriesimport net.aliasvault.app.utils.DateHelpersimport net.aliasvault.app.vaultstore.AppErrorimport net.aliasvault.app.vaultstore.VaultDatabase+import net.aliasvault.app.vaultstore.models.VaultMutationScopeimport java.util.UUID/**@@ -33,14 +34,15 @@ open class BaseRepository(/*** Execute a function within a transaction. The commit persists the vault and marks it dirty, so every* repository write reaches the next sync.+ * @param scope What the mutation touched, so the next sync can push only that scope* @param operation The function to execute within the transaction* @return The result of the function*/- fun <T> withTransaction(operation: () -> T): T {+ fun <T> withTransaction(scope: String = VaultMutationScope.MAIN, operation: () -> T): T {database.beginTransaction()return try {val result = operation()- database.commitTransaction()+ database.commitTransaction(scope)result} catch (e: Exception) {database.rollbackTransaction()diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/ItemStatsRepository.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/ItemStatsRepository.ktindex 987dfcb8b..9bb334712 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/ItemStatsRepository.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/ItemStatsRepository.kt@@ -1,6 +1,7 @@package net.aliasvault.app.vaultstore.repositoriesimport net.aliasvault.app.vaultstore.VaultDatabase+import net.aliasvault.app.vaultstore.models.VaultDataBucketCategoryimport net.aliasvault.app.vaultstore.queries.ItemStatsQueries/**@@ -33,7 +34,8 @@ class ItemStatsRepository(database: VaultDatabase) : BaseRepository(database) {* @param action What the user did with it*/fun recordUsage(itemId: String, manifestId: String, action: ItemUsageAction) {- withTransaction {+ // Usage statistics live in their own data bucket which should be pushed without a full manifest write.+ withTransaction(VaultDataBucketCategory.STATS) {val now = now()val id = itemId.lowercase()executeUpdate(ItemStatsQueries.INSERT_ROW, arrayOf(manifestId, id, now, now))diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/PasskeyRepository.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/PasskeyRepository.ktindex 8de811a4f..4ea0ad13d 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/PasskeyRepository.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/PasskeyRepository.kt@@ -211,7 +211,6 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {val manifestId = oldPasskey.manifestId ?: error("Passkey has no manifest: $oldPasskeyId")val itemId = oldPasskey.parentItemId.toString().lowercase()- executeUpdate(PasskeyQueries.UPDATE_ITEM_TIMESTAMP, arrayOf(timestamp, itemId, manifestId))updateItemLogo(itemId, manifestId, url, logo, timestamp)// Soft delete the old passkey@@ -253,7 +252,6 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {val id = itemId.toString().lowercase()updateItemLogo(id, manifestId, url, logo, timestamp)- executeUpdate(PasskeyQueries.UPDATE_ITEM_TIMESTAMP, arrayOf(timestamp, id, manifestId))insert(passkey.copy(@@ -455,7 +453,7 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {* @return The logo id, or null when the item should keep what it has (update) or get none (create)*/private fun resolveLogoId(scope: String, existingLogoId: String?, url: String, logo: ByteArray?, timestamp: String): String? {- val existing = existingLogoId?.let { getLogoById(it, scope) }+ val existing = existingLogoId?.let { getLogoById(it) }if (existing != null && existing.kind != LOGO_KIND_FAVICON) {return adoptIntoScope(scope, existing.kind, existing.source, timestamp)}@@ -478,10 +476,10 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {}/**- * The kind and key of a logo row inside one manifest, or null when it no longer exists.+ * The kind and key of a logo row, in whichever manifest holds it, or null when it no longer exists.*/- private fun getLogoById(logoId: String, manifestId: String): LogoRef? {- val row = executeQuery(LogoQueries.GET_BY_ID, arrayOf(logoId, manifestId)).firstOrNull() ?: return null+ private fun getLogoById(logoId: String): LogoRef? {+ val row = executeQuery(LogoQueries.GET_BY_ID, arrayOf(logoId)).firstOrNull() ?: return nullval source = row["Source"] as? String ?: return nullreturn LogoRef(row["Kind"] as? String ?: LOGO_KIND_FAVICON, source)}diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/AndroidStorageProvider.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/AndroidStorageProvider.ktindex b006acd43..2b410bb6a 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/AndroidStorageProvider.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/AndroidStorageProvider.kt@@ -10,6 +10,8 @@ import java.io.Fileclass AndroidStorageProvider(private val context: Context) : StorageProvider {private var defaultAutoLockTimeout = 3600 // 1 hour default+ override fun getAppContext(): Context = context+override fun getEncryptedDatabaseFile(): File {return File(context.filesDir, "encrypted_database.db")}@@ -183,6 +185,22 @@ class AndroidStorageProvider(private val context: Context) : StorageProvider {return sharedPreferences.getBoolean("is_dirty", false)}+ override fun getDirtyScopes(): List<String> {+ val sharedPreferences = context.getSharedPreferences("aliasvault", Context.MODE_PRIVATE)+ return sharedPreferences.getStringSet("dirty_scopes", emptySet())?.toList() ?: emptyList()+ }++ override fun setDirtyScopes(scopes: List<String>) {+ val sharedPreferences = context.getSharedPreferences("aliasvault", Context.MODE_PRIVATE)+ sharedPreferences.edit {+ if (scopes.isEmpty()) {+ remove("dirty_scopes")+ } else {+ putStringSet("dirty_scopes", scopes.toSet())+ }+ }+ }+override fun getMutationSequence(): Int {val sharedPreferences = context.getSharedPreferences("aliasvault", Context.MODE_PRIVATE)return sharedPreferences.getInt("mutation_sequence", 0)@@ -211,6 +229,7 @@ class AndroidStorageProvider(private val context: Context) : StorageProvider {val sharedPreferences = context.getSharedPreferences("aliasvault", Context.MODE_PRIVATE)sharedPreferences.edit {remove("is_dirty")+ remove("dirty_scopes")remove("mutation_sequence")remove("is_syncing")}diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/StorageProvider.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/StorageProvider.ktindex 2e575852a..de2d8acba 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/StorageProvider.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/StorageProvider.kt@@ -1,5 +1,6 @@package net.aliasvault.app.vaultstore.storageprovider+import android.content.Contextimport java.io.File/**@@ -7,6 +8,13 @@ import java.io.File* This allows for different implementations for real devices and testing.*/interface StorageProvider {+ /**+ * The application context, for the string resources the native layer renders. Null outside an Android app+ * (unit tests), where callers fall back to their untranslated default.+ * @return The application context, or null when there is none+ */+ fun getAppContext(): Context?+/*** Get the encrypted database file.* @return The encrypted database file@@ -156,6 +164,18 @@ interface StorageProvider {*/fun getIsDirty(): Boolean+ /**+ * Get the mutation scopes that have pending changes.+ * @return The recorded scopes, empty when nothing is pending+ */+ fun getDirtyScopes(): List<String>++ /**+ * Set the mutation scopes that have pending changes.+ * @param scopes The scopes to record; an empty list forgets them+ */+ fun setDirtyScopes(scopes: List<String>)+/*** Get the mutation sequence number.* @return The current mutation sequencediff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/TestStorageProvider.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/TestStorageProvider.ktindex a70819649..2c0442bef 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/TestStorageProvider.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/TestStorageProvider.kt@@ -1,5 +1,6 @@package net.aliasvault.app.vaultstore.storageprovider+import android.content.Contextimport java.io.File/**@@ -19,9 +20,12 @@ class TestStorageProvider : StorageProvider {private var serverVersion: String? = nullprivate var capabilities: String? = nullprivate var isDirty: Boolean = false+ private var dirtyScopes: List<String> = emptyList()private var mutationSequence: Int = 0private var isSyncing: Boolean = false+ override fun getAppContext(): Context? = null+override fun getEncryptedDatabaseFile(): File = tempFileoverride fun setEncryptedDatabaseFile(encryptedData: String) {@@ -127,6 +131,14 @@ class TestStorageProvider : StorageProvider {return isDirty}+ override fun getDirtyScopes(): List<String> {+ return dirtyScopes+ }++ override fun setDirtyScopes(scopes: List<String>) {+ dirtyScopes = scopes+ }+override fun getMutationSequence(): Int {return mutationSequence}@@ -145,6 +157,7 @@ class TestStorageProvider : StorageProvider {override fun clearSyncState() {isDirty = false+ dirtyScopes = emptyList()mutationSequence = 0isSyncing = false}diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/webapi/WebApiService.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/webapi/WebApiService.ktindex bcc55ea15..a692fa1de 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/webapi/WebApiService.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/webapi/WebApiService.kt@@ -55,6 +55,11 @@ class WebApiService(private val context: Context) {* Read timeout. This is an inactivity timeout between successive reads.*/private const val READ_TIMEOUT_MS = 15000++ /**+ * Read timeout of a request that carries vault ciphertext which can be larger and therefore can take longer to transfer.+ */+ private const val VAULT_TRANSFER_READ_TIMEOUT_MS = 180000}private val sharedPreferences = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE)@@ -162,7 +167,7 @@ class WebApiService(private val context: Context) {}/**- * Turn an endpoint into a full URL. If the endpoint starts with "v1/" or "v2/" etc,+ * Turn an endpoint into a full URL. If the endpoint starts with "v1/" or "v2/" etc,* resolve it against the API root, otherwise resolve it against the base URL.*/private fun resolveUrl(endpoint: String): String {@@ -210,13 +215,16 @@ class WebApiService(private val context: Context) {/*** Execute a WebAPI request with support for authentication and token refresh.+ * Pass largeTransfer for a request that carries vault ciphertext, which gets the longer transfer timeout.*/+ @Suppress("LongParameterList") // One argument per part of the request the callers varysuspend fun executeRequest(method: String,endpoint: String,body: String?,headers: Map<String, String>,requiresAuth: Boolean,+ largeTransfer: Boolean = false,): WebApiResponse = withContext(Dispatchers.IO) {val requestHeaders = headers.toMutableMap()@@ -237,6 +245,7 @@ class WebApiService(private val context: Context) {endpoint = endpoint,body = body,headers = requestHeaders,+ largeTransfer = largeTransfer,)// Handle 401 Unauthorized - attempt token refresh@@ -256,6 +265,7 @@ class WebApiService(private val context: Context) {endpoint = endpoint,body = body,headers = retryHeaders,+ largeTransfer = largeTransfer,)return@withContext retryResponse@@ -277,6 +287,7 @@ class WebApiService(private val context: Context) {endpoint: String,body: String?,headers: Map<String, String>,+ largeTransfer: Boolean = false,): WebApiResponse = withContext(Dispatchers.IO) {val urlString = resolveUrl(endpoint)@@ -286,7 +297,7 @@ class WebApiService(private val context: Context) {connection = url.openConnection() as HttpURLConnectionconnection.requestMethod = method.uppercase()connection.connectTimeout = CONNECT_TIMEOUT_MS- connection.readTimeout = READ_TIMEOUT_MS+ connection.readTimeout = if (largeTransfer) VAULT_TRANSFER_READ_TIMEOUT_MS else READ_TIMEOUT_MSconnection.doInput = true// Add any custom proxy headersdiff --git a/apps/mobile-app/android/app/src/main/res/values/strings.xml b/apps/mobile-app/android/app/src/main/res/values/strings.xmlindex ea172c57c..32a59e5d6 100644--- a/apps/mobile-app/android/app/src/main/res/values/strings.xml+++ b/apps/mobile-app/android/app/src/main/res/values/strings.xml@@ -88,4 +88,5 @@<string name="password_unlock_error">Failed to verify password</string><string name="password_unlock_attempts_warning">Incorrect password. You will be logged out if you enter the wrong password %d more times.</string><string name="password_unlock_max_attempts_reached">Too many failed unlock attempts. You have been logged out for security reasons.</string>+ <string name="unnamed_shared_vault">Shared vault</string></resources>\ No newline at end of filediff --git a/apps/mobile-app/app/upgrade.tsx b/apps/mobile-app/app/upgrade.tsxindex 468d25a14..15178a03a 100644--- a/apps/mobile-app/app/upgrade.tsx+++ b/apps/mobile-app/app/upgrade.tsx@@ -1,5 +1,6 @@import { VaultVersionIncompatibleError } from '@aliasvault/client/api/errors/VaultVersionIncompatibleError';import { AppInfo } from '@aliasvault/client/platform/AppInfo';+import { DEFAULT_VAULT_MUTATION_SCOPE } from '@aliasvault/client/sync/VaultMutationScope';import { VaultSqlGenerator } from '@aliasvault/vault';import { MaterialIcons } from '@expo/vector-icons';import { LinearGradient } from 'expo-linear-gradient';@@ -252,7 +253,7 @@ export default function UpgradeScreen() : React.ReactNode {if (upgradeResult.sqlCommands.length > 0) {// Persist the upgraded database as a pending change; the manifest migration push that follows carries it.setUpgradeStatus(t('upgrade.status.committingChanges'));- await NativeVaultManager.persistAndMarkDirty();+ await NativeVaultManager.persistAndMarkDirty(DEFAULT_VAULT_MUTATION_SCOPE);await dbContext.unlockVault();}diff --git a/apps/mobile-app/hooks/useVaultMutate.ts b/apps/mobile-app/hooks/useVaultMutate.tsindex 2b758c0ba..c26cee85a 100644--- a/apps/mobile-app/hooks/useVaultMutate.ts+++ b/apps/mobile-app/hooks/useVaultMutate.ts@@ -9,6 +9,7 @@ import type { PasswordChangeInitiateResponse, Vault, VaultPasswordChangeRequestimport { FieldKey, getFieldValue } from '@aliasvault/models/vault';import EncryptionUtility from '@/utils/EncryptionUtility';import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';+import { DEFAULT_VAULT_MUTATION_SCOPE } from '@aliasvault/client/sync/VaultMutationScope';import { useVaultSync } from '@/hooks/useVaultSync';@@ -232,7 +233,7 @@ export function useVaultMutate() : {* locally which can then be uploaded to the server.*/await NativeVaultManager.beginTransaction();- await NativeVaultManager.commitTransaction();+ await NativeVaultManager.commitTransaction(DEFAULT_VAULT_MUTATION_SCOPE);// Unlock the newly persisted database to ensure it works and the new encryption key will be persisted in the keychain.await NativeVaultManager.unlockVault();diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mmindex fca853be4..e1df698c8 100644--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm@@ -53,16 +53,16 @@[vaultManager beginTransaction:resolve rejecter:reject];}-- (void)commitTransaction:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {- [vaultManager commitTransaction:resolve rejecter:reject];+- (void)commitTransaction:(NSString *)scope resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {+ [vaultManager commitTransaction:scope resolver:resolve rejecter:reject];}- (void)rollbackTransaction:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {[vaultManager rollbackTransaction:resolve rejecter:reject];}-- (void)persistAndMarkDirty:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {- [vaultManager persistAndMarkDirty:resolve rejecter:reject];+- (void)persistAndMarkDirty:(NSString *)scope resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {+ [vaultManager persistAndMarkDirty:scope resolver:resolve rejecter:reject];}- (void)getAuthMethods:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swiftindex a374bd18d..acceb0a27 100644--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift@@ -343,10 +343,11 @@ public class VaultManager: NSObject {}@objc- func commitTransaction(_ resolve: @escaping RCTPromiseResolveBlock,+ func commitTransaction(_ scope: String,+ resolver resolve: @escaping RCTPromiseResolveBlock,rejecter reject: @escaping RCTPromiseRejectBlock) {do {- try vaultStore.commitTransaction()+ try vaultStore.commitTransaction(scope: VaultMutationScope.known(scope))resolve(nil)} catch {reject("TRANSACTION_ERROR", "Failed to commit transaction: \(error.localizedDescription)", error)@@ -365,10 +366,11 @@ public class VaultManager: NSObject {}@objc- func persistAndMarkDirty(_ resolve: @escaping RCTPromiseResolveBlock,+ func persistAndMarkDirty(_ scope: String,+ resolver resolve: @escaping RCTPromiseResolveBlock,rejecter reject: @escaping RCTPromiseRejectBlock) {do {- try vaultStore.persistAndMarkDirty()+ try vaultStore.persistAndMarkDirty(scope: VaultMutationScope.known(scope))resolve(nil)} catch {reject("PERSIST_ERROR", "Failed to persist and mark dirty: \(error.localizedDescription)", error)diff --git a/apps/mobile-app/ios/VaultModels/Passkey.swift b/apps/mobile-app/ios/VaultModels/Passkey.swiftindex 2ff898cc7..22c852e94 100644--- a/apps/mobile-app/ios/VaultModels/Passkey.swift+++ b/apps/mobile-app/ios/VaultModels/Passkey.swift@@ -18,7 +18,7 @@ public struct Passkey: Codable, Hashable, Equatable {public let updatedAt: Datepublic let isDeleted: Boolpublic let manifestId: String?- public let additionalData: String?+ public let additionalData: Data?public init(id: UUID,@@ -34,7 +34,7 @@ public struct Passkey: Codable, Hashable, Equatable {updatedAt: Date,isDeleted: Bool,manifestId: String? = nil,- additionalData: String? = nil+ additionalData: Data? = nil) {self.id = idself.parentItemId = parentItemIddiff --git a/apps/mobile-app/ios/VaultModels/VaultMutationScope.swift b/apps/mobile-app/ios/VaultModels/VaultMutationScope.swiftnew file mode 100644index 000000000..1941805d4--- /dev/null+++ b/apps/mobile-app/ios/VaultModels/VaultMutationScope.swift@@ -0,0 +1,19 @@+import Foundation++/// Scope of a local vault mutation: what actually changed, so the sync engine can push only the data bucket a+/// mutation touched instead of a full manifest. Mirrors VaultMutationScope in core/client.+public struct VaultMutationScope {+ /// A change to the vault content itself, which needs a full manifest push.+ public static let main = "Main"++ /// Every scope the sync engine understands: the manifest scope plus one per data bucket category.+ public static let all = [main] + VaultDataBucketCategory.all++ /// The given scope when the engine knows it, else the manifest scope, which is always safe to push.+ public static func known(_ scope: String?) -> String {+ guard let scope = scope, all.contains(scope) else {+ return main+ }+ return scope+ }+}diff --git a/apps/mobile-app/ios/VaultStoreKit/Bundle+VaultStoreKit.swift b/apps/mobile-app/ios/VaultStoreKit/Bundle+VaultStoreKit.swiftnew file mode 100644index 000000000..b8166c760--- /dev/null+++ b/apps/mobile-app/ios/VaultStoreKit/Bundle+VaultStoreKit.swift@@ -0,0 +1,10 @@+import Foundation++private final class VaultStoreKitBundleToken {}++public extension Bundle {+ /// The bundle that contains VaultStoreKit's localized resources.+ static var vaultStoreKit: Bundle {+ return Bundle(for: VaultStoreKitBundleToken.self)+ }+}diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/BaseRepository.swift b/apps/mobile-app/ios/VaultStoreKit/Database/BaseRepository.swiftindex 30a40844c..430972519 100644--- a/apps/mobile-app/ios/VaultStoreKit/Database/BaseRepository.swift+++ b/apps/mobile-app/ios/VaultStoreKit/Database/BaseRepository.swift@@ -1,4 +1,5 @@import Foundation+import VaultModelsimport VaultUtils/// The grouping key of a manifest-scoped row (same id can exist in several manifests by design).@@ -31,13 +32,15 @@ public class BaseRepository {/// Execute a function within a transaction./// Automatically handles begin, commit, and rollback.- /// - Parameter operation: The function to execute within the transaction+ /// - Parameters:+ /// - scope: What the mutation touched, so the next sync can push only that scope+ /// - operation: The function to execute within the transaction/// - Returns: The result of the function- public func withTransaction<T>(_ operation: () throws -> T) throws -> T {+ public func withTransaction<T>(scope: String = VaultMutationScope.main, _ operation: () throws -> T) throws -> T {try client.beginTransaction()do {let result = try operation()- try client.commitTransaction()+ try client.commitTransaction(scope: scope)return result} catch {try? client.rollbackTransaction()diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/DatabaseClient.swift b/apps/mobile-app/ios/VaultStoreKit/Database/DatabaseClient.swiftindex 029ac9794..eb784775a 100644--- a/apps/mobile-app/ios/VaultStoreKit/Database/DatabaseClient.swift+++ b/apps/mobile-app/ios/VaultStoreKit/Database/DatabaseClient.swift@@ -25,7 +25,8 @@ public protocol DatabaseClient: AnyObject {func beginTransaction() throws/// Commit a database transaction.- func commitTransaction() throws+ /// - Parameter scope: What the mutation touched, so the next sync can push only that scope+ func commitTransaction(scope: String) throws/// Rollback a database transaction.func rollbackTransaction() throwsdiff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Mappers/PasskeyMapper.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Mappers/PasskeyMapper.swiftindex 1f38c4113..8a9ed9df6 100644--- a/apps/mobile-app/ios/VaultStoreKit/Database/Mappers/PasskeyMapper.swift+++ b/apps/mobile-app/ios/VaultStoreKit/Database/Mappers/PasskeyMapper.swift@@ -13,7 +13,7 @@ public struct PasskeyRow {public let privateKey: Stringpublic let prfKey: Data?public let displayName: String- public let additionalData: String?+ public let additionalData: Data?public let createdAt: Stringpublic let updatedAt: Stringpublic let isDeleted: Int64@@ -40,7 +40,6 @@ public struct PasskeyRow {self.publicKey = publicKeyself.privateKey = privateKeyself.displayName = displayName- self.additionalData = row["AdditionalData"] as? Stringself.createdAt = createdAtself.updatedAt = updatedAtself.isDeleted = isDeleted@@ -57,6 +56,12 @@ public struct PasskeyRow {} else {self.prfKey = nil}++ if let additionalDataBase64 = row["AdditionalData"] as? String {+ self.additionalData = Data(base64Encoded: additionalDataBase64, options: .ignoreUnknownCharacters)+ } else {+ self.additionalData = nil+ }}}diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Queries/ItemQueries.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Queries/ItemQueries.swiftindex 2035cc5ff..37924622d 100644--- a/apps/mobile-app/ios/VaultStoreKit/Database/Queries/ItemQueries.swift+++ b/apps/mobile-app/ios/VaultStoreKit/Database/Queries/ItemQueries.swift@@ -64,11 +64,6 @@ public struct ItemQueries {INSERT INTO Items (Id, Name, ItemType, LogoId, FolderId, CreatedAt, UpdatedAt, IsDeleted, ManifestId)VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"""-- /// Bump an item's UpdatedAt so a child-row change is picked up by sync.- public static let touchItem = """- UPDATE Items SET UpdatedAt = ? WHERE Id = ? AND ManifestId = ?- """}/// SQL query constants for FieldValue operations.diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/ItemRepository.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/ItemRepository.swiftindex c50c28b6f..d9cecbf26 100644--- a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/ItemRepository.swift+++ b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/ItemRepository.swift@@ -66,16 +66,13 @@ public class ItemRepository: BaseRepository {/// - fieldKey: The system FieldKey to append under (e.g. `FieldKey.loginUrl`)/// - value: The value to append/// - manifestId: The manifest the item belongs to- /// - Returns: The number of rows affected by the parent Item's UpdatedAt bump, 0 when no such item exists+ /// - Returns: The number of rows inserted@discardableResultpublic func appendFieldValue(itemId: String, manifestId: String, fieldKey: String, value: String) throws -> Int {return try withTransaction {let now = self.now()let weight = FieldValueQueries.defaultWeight(forFieldKey: fieldKey)- try client.executeUpdate(FieldValueQueries.insert, params: [generateId(), itemId, nil, fieldKey, value, weight, now, now, 0, manifestId])-- // Bump the parent Item's UpdatedAt so the change is picked up by the sync layer.- return try client.executeUpdate(ItemQueries.touchItem, params: [now, itemId, manifestId])+ return try client.executeUpdate(FieldValueQueries.insert, params: [generateId(), itemId, nil, fieldKey, value, weight, now, now, 0, manifestId])}}}diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/ItemStatsRepository.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/ItemStatsRepository.swiftindex 722b0f3f6..1bc363443 100644--- a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/ItemStatsRepository.swift+++ b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/ItemStatsRepository.swift@@ -1,4 +1,5 @@import Foundation+import VaultModels/// The actions whose use of an item is recorded. Each maps to its own timestamp + counter pair alongside the/// aggregate `LastUsedAt` / `UseCount`.@@ -31,7 +32,8 @@ public class ItemStatsRepository: BaseRepository {/// - manifestId: The manifest the item belongs to/// - action: What the user did with itpublic func recordUsage(itemId: String, manifestId: String, action: ItemUsageAction) throws {- try withTransaction {+ // Usage statistics live in their own data bucket which should be pushed without a full manifest write.+ try withTransaction(scope: VaultDataBucketCategory.stats) {let now = self.now()let columns = action.columnstry client.executeUpdate(ItemStatsQueries.insertRow, params: [manifestId, itemId, now, now])diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/PasskeyRepository.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/PasskeyRepository.swiftindex 99968cd7c..54744fa41 100644--- a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/PasskeyRepository.swift+++ b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/PasskeyRepository.swift@@ -73,29 +73,6 @@ public class PasskeyRepository: BaseRepository {return mappedResults}- /// Get Items that match an rpId but don't have a passkey yet using legacy SQL LIKE matching.- /// Note: The public API now uses getAllItemsWithoutPasskey + Rust credential matcher for consistent cross-platform matching.- /// This method is kept for potential fallback scenarios.- /// - Parameters:- /// - rpId: The relying party identifier (domain)- /// - userName: Optional username to filter by- /// - Returns: Array of ItemWithCredentialInfoData objects- func getItemsWithoutPasskeyLegacy(forRpId rpId: String, userName: String? = nil) throws -> [ItemWithCredentialInfoData] {- let rpIdLower = rpId.lowercased()- let urlPattern1 = "%\(rpIdLower)%"- let urlPattern2 = "%\(rpIdLower.replacingOccurrences(of: "www.", with: ""))%"-- let results = try client.executeQuery(PasskeyQueries.getItemsWithoutPasskeyForRpId, params: [urlPattern1, urlPattern2])-- return results.compactMap { row -> ItemWithCredentialInfoData? in- let item = mapItemWithCredentialInfo(row, urls: (row["Url"] as? String).map { [$0] } ?? [])- if let userName = userName, item?.username != userName {- return nil- }- return item- }- }-/// Get ALL Login items that don't have a passkey yet (no URL filtering)./// Used with RustItemMatcher for intelligent, cross-platform consistent filtering./// - Returns: Array of ItemWithCredentialInfoData objects with all URLs@@ -263,7 +240,7 @@ public class PasskeyRepository: BaseRepository {privateKeyString,blobParam(passkey.prfKey),displayName,- passkey.additionalData as SqliteBindValue,+ blobParam(passkey.additionalData),now,now,0diff --git a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swiftindex 834c4b532..ef43f4a8a 100644--- a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift+++ b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift@@ -27,6 +27,8 @@ public final class VaultSyncEngine {private let webApiService: WebApiService/// The engine's staging database, held in the Rust core's memory.private var staging: SqliteMemoryDatabase?+ /// Whether the live vault was written to since the last store went through.+ private var localMutated = falseprivate var runLog = VaultSyncRunLog(operation: "")public init(vaultStore: VaultStore, webApiService: WebApiService) {@@ -47,6 +49,7 @@ public final class VaultSyncEngine {let session = try VaultSyncSession(requestJson: try buildRequest(operation: operation, forcePull: forcePull, encryptionKey: encryptionKey, sharing: sharing))defer {closeStaging()+ discardLocalDatabaseIfNeeded()log.finish(result: finalResult, userDefaults: vaultStore.userDefaults)}@@ -77,12 +80,12 @@ public final class VaultSyncEngine {"username": vaultStore.getUsername() ?? "","isDirty": syncState.isDirty,"mutationSequence": syncState.mutationSequence,- "dirtyScopes": syncState.isDirty ? ["Main"] : [],+ "dirtyScopes": syncState.isDirty ? vaultStore.getDirtyScopes() : [],"privateEmailDomains": metadata?.privateEmailDomains ?? [],"forcePull": forcePull,"minServerVersion": AppInfo.minServerVersion,"isOfflineMode": vaultStore.getOfflineMode(),- "unnamedSharedVaultName": NSLocalizedString("unnamed_shared_vault", value: "Shared vault", comment: "Name of a shared vault without a name")+ "unnamedSharedVaultName": NSLocalizedString("unnamed_shared_vault", bundle: .vaultStoreKit, value: "Shared vault", comment: "Name of a shared vault without a name")]if let key = encryptionKey ?? (try? vaultStore.getEncryptionKeyBase64()) {request["encryptionKey"] = key@@ -122,8 +125,11 @@ public final class VaultSyncEngine {let rowsJson = try db.query(sql: command["sql"] as? String ?? "", paramsJson: try Self.serializeJson(command["params"] ?? []))return ["rows": try Self.parseJsonArray(rowsJson)]case "dbExec":- let db = try database(named: command["db"] as? String ?? "")- try db.exec(statementsJson: try Self.serializeJson(command["statements"] ?? []))+ let name = command["db"] as? String ?? ""+ try database(named: name).exec(statementsJson: try Self.serializeJson(command["statements"] ?? []))+ if name == "local" {+ localMutated = true+ }return [:]case "dbExport":let bytes: Data@@ -161,12 +167,13 @@ public final class VaultSyncEngine {let path = command["path"] as? String ?? ""let body = command["body"] as? Stringlet auth = command["auth"] as? Bool ?? true+ let largeTransfer = command["largeTransfer"] as? Bool ?? falsevar headers: [String: String] = ["Accept": "application/json"]if body != nil {headers["Content-Type"] = "application/json"}do {- let response = try await webApiService.executeRequest(method: method, endpoint: path, body: body, headers: headers, requiresAuth: auth)+ let response = try await webApiService.executeRequest(method: method, endpoint: path, body: body, headers: headers, requiresAuth: auth, largeTransfer: largeTransfer)return ["status": response.statusCode, "body": response.body]} catch {let timedOut = (error as? URLError)?.code == .timedOut@@ -241,6 +248,10 @@ public final class VaultSyncEngine {serverRevision: command["revision"] as? Int,expectedMutationSeq: command["expectedMutationSeq"] as? Int)+ if result.success {+ // The stored vault is now what the live database holds, so nothing is left to discard.+ localMutated = false+ }if result.success && vaultStore.isVaultUnlocked {// The contract: after a store, the live database is the vault just stored.let reloadStartedAt = Date()@@ -287,6 +298,20 @@ public final class VaultSyncEngine {staging = nil}+ /// Reload the stored vault when the run left changes in the live database that no store persisted, so the+ /// vault the app reads from is the one on disk rather than a half-finished sync.+ private func discardLocalDatabaseIfNeeded() {+ guard localMutated else { return }+ localMutated = false+ guard vaultStore.isVaultUnlocked else { return }+ do {+ try vaultStore.unlockVault()+ runLog.note("Discarded unpersisted local vault changes; reloaded the stored vault")+ } catch {+ runLog.note("Failed to reload the stored vault after discarding unpersisted changes: \(error)")+ }+ }+// MARK: - JSONprivate static func parseJson(_ json: String) throws -> [String: Any] {diff --git a/apps/mobile-app/ios/VaultStoreKit/Services/WebApiService.swift b/apps/mobile-app/ios/VaultStoreKit/Services/WebApiService.swiftindex 3eb10d0e0..7524cf2cd 100644--- a/apps/mobile-app/ios/VaultStoreKit/Services/WebApiService.swift+++ b/apps/mobile-app/ios/VaultStoreKit/Services/WebApiService.swift@@ -8,14 +8,32 @@ import VaultUtilspublic class WebApiService {private let vaultStore = VaultStore.shared+ /// Timeout of an ordinary API call, in seconds.+ private static let defaultRequestTimeout: TimeInterval = 8++ /// Upper bound on an ordinary API call, in seconds.+ private static let defaultResourceTimeout: TimeInterval = 120++ /// Timeout of a vault transfer, in seconds. A vault moves far more data than a status call, so the sync engine marks those requests as large.+ private static let vaultTransferTimeout: TimeInterval = 180+/*** URLSession configured with explicit timeouts to avoid blocking the main thread for too long* when the server is not responding in a suitable time.*/private lazy var urlSession: URLSession = {let config = URLSessionConfiguration.default- config.timeoutIntervalForRequest = 8- config.timeoutIntervalForResource = 120+ config.timeoutIntervalForRequest = Self.defaultRequestTimeout+ config.timeoutIntervalForResource = Self.defaultResourceTimeout+ config.waitsForConnectivity = false+ return URLSession(configuration: config)+ }()++ /// URLSession for the requests that carry vault ciphertext.+ private lazy var vaultTransferSession: URLSession = {+ let config = URLSessionConfiguration.default+ config.timeoutIntervalForRequest = Self.vaultTransferTimeout+ config.timeoutIntervalForResource = Self.vaultTransferTimeoutconfig.waitsForConnectivity = falsereturn URLSession(configuration: config)}()@@ -164,14 +182,16 @@ public class WebApiService {// MARK: - HTTP Request Execution/**- * Execute a WebAPI request with support for authentication and token refresh+ * Execute a WebAPI request with support for authentication and token refresh.+ * Pass largeTransfer for a request that carries vault ciphertext, which gets the longer transfer timeout.*/public func executeRequest(method: String,endpoint: String,body: String?,headers: [String: String],- requiresAuth: Bool+ requiresAuth: Bool,+ largeTransfer: Bool = false) async throws -> WebApiResponse {var requestHeaders = headers@@ -188,7 +208,8 @@ public class WebApiService {method: method,endpoint: endpoint,body: body,- headers: requestHeaders+ headers: requestHeaders,+ largeTransfer: largeTransfer)// Handle 401 Unauthorized - attempt token refresh@@ -204,7 +225,8 @@ public class WebApiService {method: method,endpoint: endpoint,body: body,- headers: retryHeaders+ headers: retryHeaders,+ largeTransfer: largeTransfer)return retryResponse@@ -225,7 +247,8 @@ public class WebApiService {method: String,endpoint: String,body: String?,- headers: [String: String]+ headers: [String: String],+ largeTransfer: Bool = false) async throws -> WebApiResponse {let urlString = resolveUrl(endpoint)@@ -257,7 +280,8 @@ public class WebApiService {}// Execute the request- let (data, urlResponse) = try await urlSession.data(for: request)+ let session = largeTransfer ? vaultTransferSession : urlSession+ let (data, urlResponse) = try await session.data(for: request)guard let httpResponse = urlResponse as? HTTPURLResponse else {throw NSError(diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Metadata.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Metadata.swiftindex bcdaccb94..0f4f5f2a3 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Metadata.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Metadata.swift@@ -136,9 +136,38 @@ extension VaultStore {// MARK: - Sync State Storage (isDirty, mutationSequence, isSyncing)- /// Set the dirty flag indicating local changes need to be synced+ /// Set the dirty flag indicating local changes need to be synced. Clearing it forgets the pending scopes+ /// with it, since a clean vault has nothing left to push.public func setIsDirty(_ isDirty: Bool) {userDefaults.set(isDirty, forKey: VaultConstants.isDirtyKey)+ if !isDirty {+ userDefaults.removeObject(forKey: VaultConstants.dirtyScopesKey)+ }+ userDefaults.synchronize()+ }++ /// Mark the vault dirty and record what the mutation touched, so the next sync can push only that scope.+ /// - Parameter scope: The mutation scope, defaulting to a full-manifest change+ public func markDirty(scope: String = VaultMutationScope.main) {+ setIsDirty(true)+ addDirtyScope(scope)+ }++ /// The mutation scopes that have pending changes.+ public func getDirtyScopes() -> [String] {+ return userDefaults.stringArray(forKey: VaultConstants.dirtyScopesKey) ?? []+ }++ /// Record one scope as having pending changes.+ /// - Parameter scope: The mutation scope; an unknown one counts as a full-manifest change+ public func addDirtyScope(_ scope: String) {+ let known = VaultMutationScope.known(scope)+ var scopes = getDirtyScopes()+ guard !scopes.contains(known) else {+ return+ }+ scopes.append(known)+ userDefaults.set(scopes, forKey: VaultConstants.dirtyScopesKey)userDefaults.synchronize()}@@ -197,12 +226,14 @@ extension VaultStore {/// - markDirty: If true, marks vault as dirty and increments mutation sequence/// - serverRevision: Optional server revision to set/// - expectedMutationSeq: If provided, only store if current sequence matches+ /// - scope: What the mutation touched, when it marks the vault dirty/// - Returns: (success, mutationSequence) - success=false if expectedMutationSeq didn't matchpublic func storeEncryptedVaultWithSyncState(encryptedVault: String,markDirty: Bool = false,serverRevision: Int? = nil,- expectedMutationSeq: Int? = nil+ expectedMutationSeq: Int? = nil,+ scope: String = VaultMutationScope.main) throws -> (success: Bool, mutationSequence: Int) {var mutationSequence = getMutationSequence()@@ -220,7 +251,7 @@ extension VaultStore {if markDirty {setMutationSequence(mutationSequence)- setIsDirty(true)+ self.markDirty(scope: scope)}if let revision = serverRevision {@@ -256,6 +287,7 @@ extension VaultStore {/// Clear all sync state (used on logout)public func clearSyncState() {userDefaults.removeObject(forKey: VaultConstants.isDirtyKey)+ userDefaults.removeObject(forKey: VaultConstants.dirtyScopesKey)userDefaults.removeObject(forKey: VaultConstants.mutationSequenceKey)userDefaults.removeObject(forKey: VaultConstants.isSyncingKey)userDefaults.synchronize()diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swiftindex 44af29915..a44bfd462 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift@@ -61,13 +61,14 @@ extension VaultStore {}/// Commit a transaction on the database. This is required for all database operations that modify the database.- public func commitTransaction() throws {+ /// - Parameter scope: What the mutation touched, so the next sync can push only that scope+ public func commitTransaction(scope: String = VaultMutationScope.main) throws {try requireDatabase().executeBatch(sql: "COMMIT")try persistDatabaseToEncryptedStorage()// Atomically mark vault as dirty and increment mutation sequence// This ensures sync can properly detect local changes- setIsDirty(true)+ markDirty(scope: scope)_ = incrementMutationSequence()}@@ -77,12 +78,13 @@ extension VaultStore {}/// Persist the in-memory database to encrypted storage and mark as dirty.- public func persistAndMarkDirty() throws {+ /// - Parameter scope: What the mutation touched, so the next sync can push only that scope+ public func persistAndMarkDirty(scope: String = VaultMutationScope.main) throws {try persistDatabaseToEncryptedStorage()// Atomically mark vault as dirty and increment mutation sequence// This ensures sync can properly detect local changes- setIsDirty(true)+ markDirty(scope: scope)_ = incrementMutationSequence()}diff --git a/apps/mobile-app/ios/VaultStoreKit/en.lproj/Localizable.strings b/apps/mobile-app/ios/VaultStoreKit/en.lproj/Localizable.stringsnew file mode 100644index 000000000..0afe3f38b--- /dev/null+++ b/apps/mobile-app/ios/VaultStoreKit/en.lproj/Localizable.strings@@ -0,0 +1,2 @@+/* English localization strings for VaultStoreKit */+"unnamed_shared_vault" = "Shared vault";diff --git a/apps/mobile-app/ios/VaultUtils/VaultConstants.swift b/apps/mobile-app/ios/VaultUtils/VaultConstants.swiftindex 818d5dca5..fff068d18 100644--- a/apps/mobile-app/ios/VaultUtils/VaultConstants.swift+++ b/apps/mobile-app/ios/VaultUtils/VaultConstants.swift@@ -23,6 +23,7 @@ public struct VaultConstants {public static let isDirtyKey = "aliasvault_is_dirty"public static let mutationSequenceKey = "aliasvault_mutation_sequence"public static let isSyncingKey = "aliasvault_is_syncing"+ public static let dirtyScopesKey = "aliasvault_dirty_scopes"public static let syncLogsKey = "aliasvault_sync_logs"public static let defaultAutoLockTimeout: Int = 3600 // 1 hour in secondsdiff --git a/apps/mobile-app/platform/NativeDatabaseClient.ts b/apps/mobile-app/platform/NativeDatabaseClient.tsindex 4576adbdb..9fb545055 100644--- a/apps/mobile-app/platform/NativeDatabaseClient.ts+++ b/apps/mobile-app/platform/NativeDatabaseClient.ts@@ -1,6 +1,7 @@import { Buffer } from 'buffer';import type { IDatabaseClient, SqliteBindValue } from '@aliasvault/client/database/BaseRepository';+import { DEFAULT_VAULT_MUTATION_SCOPE, type VaultMutationScope } from '@aliasvault/client/sync/VaultMutationScope';import NativeVaultManager from '@/specs/NativeVaultManager';@@ -53,10 +54,11 @@ export class NativeDatabaseClient implements IDatabaseClient {}/**- * Commit the transaction, which persists the vault and marks it dirty.+ * Commit the transaction, which persists the vault and marks it dirty for the given scope.+ * @param scope - what the mutation touched; a full-manifest change when omitted*/- public async commitTransaction(): Promise<void> {- await NativeVaultManager.commitTransaction();+ public async commitTransaction(scope?: VaultMutationScope): Promise<void> {+ await NativeVaultManager.commitTransaction(scope ?? DEFAULT_VAULT_MUTATION_SCOPE);this.transactionOpen = false;}diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.tsindex 8e7077431..56a1fa1b0 100644--- a/apps/mobile-app/specs/NativeVaultManager.ts+++ b/apps/mobile-app/specs/NativeVaultManager.ts@@ -57,9 +57,9 @@ export interface Spec extends TurboModule {executeUpdate(query: string, params:(string | number | null)[]): Promise<number>;executeRaw(query: string): Promise<void>;beginTransaction(): Promise<void>;- commitTransaction(): Promise<void>;+ commitTransaction(scope: string): Promise<void>;rollbackTransaction(): Promise<void>;- persistAndMarkDirty(): Promise<void>;+ persistAndMarkDirty(scope: string): Promise<void>;// Cryptography operationsderiveKeyFromPassword(password: string, salt: string, encryptionType: string, encryptionSettings: string): Promise<string>;diff --git a/apps/mobile-app/utils/SqliteClient.ts b/apps/mobile-app/utils/SqliteClient.tsindex 9a94a07fe..87462055e 100644--- a/apps/mobile-app/utils/SqliteClient.ts+++ b/apps/mobile-app/utils/SqliteClient.ts@@ -1,4 +1,5 @@import type { UnlockKeyDerivationParams, VaultMetadata } from '@aliasvault/models/metadata';+import { VaultDataBucketCategory } from '@aliasvault/models/vault';import { asyncRepository } from '@aliasvault/client/database/DbOp';import { EncryptionKeyRepository } from '@aliasvault/client/database/repositories/EncryptionKeyRepository';import { FolderRepository } from '@aliasvault/client/database/repositories/FolderRepository';@@ -53,7 +54,7 @@ class SqliteClient {/*** Repository for the vault's user preferences.*/- public readonly settings = asyncRepository(new SettingsRepository(this.database), this.database);+ public readonly settings = asyncRepository(new SettingsRepository(this.database), this.database, VaultDataBucketCategory.Settings);/*** Repository for the per-manifest keypairs that receive mail.@@ -63,7 +64,7 @@ class SqliteClient {/*** Repository for per-item usage statistics.*/- public readonly itemStats = asyncRepository(new ItemStatsRepository(this.database), this.database);+ public readonly itemStats = asyncRepository(new ItemStatsRepository(this.database), this.database, VaultDataBucketCategory.Stats);/*** The id of the user's personal manifest, or null when no pull has recorded one yet.diff --git a/core/client/src/database/BaseRepository.ts b/core/client/src/database/BaseRepository.tsindex 417eef20f..7f408106e 100644--- a/core/client/src/database/BaseRepository.ts+++ b/core/client/src/database/BaseRepository.ts@@ -5,6 +5,7 @@ import { BaseQueries } from './queries/BaseQueries';import type { DbOp, ManifestScope } from './DbOp';import type { ISqliteDatabase } from '../platform/SqliteEngine';+import type { VaultMutationScope } from '../sync/VaultMutationScope';export type SqliteBindValue = string | number | null | Uint8Array;@@ -18,7 +19,7 @@ export interface IDatabaseClient {executeQuery<T>(query: string, params?: SqliteBindValue[]): T[] | Promise<T[]>;executeUpdate(query: string, params?: SqliteBindValue[]): number | Promise<number>;beginTransaction(): void | Promise<void>;- commitTransaction(): Promise<void>;+ commitTransaction(scope?: VaultMutationScope): Promise<void>;rollbackTransaction(): void | Promise<void>;isInTransaction(): boolean;getActiveManifestId(): string | null;diff --git a/core/client/src/database/DbOp.ts b/core/client/src/database/DbOp.tsindex c1afea2fc..4c5992544 100644--- a/core/client/src/database/DbOp.ts+++ b/core/client/src/database/DbOp.ts@@ -1,4 +1,5 @@import type { IDatabaseClient, ISyncDatabaseClient, SqliteBindValue } from './BaseRepository';+import type { VaultMutationScope } from '../sync/VaultMutationScope';/** Repository methods are written once and can run on two kinds of host: synchronous and@@ -66,9 +67,10 @@ export function runSync<T>(op: DbOp<T>, client: ISyncDatabaseClient): T {* outside a transaction runs in one of its own.* @param op - The op to run* @param client - The client that performs its steps+ * @param scope - What the op's writes touch, for a host that marks the vault dirty per scope* @returns The op's result*/-export async function runAsync<T>(op: DbOp<T>, client: IDatabaseClient): Promise<T> {+export async function runAsync<T>(op: DbOp<T>, client: IDatabaseClient, scope?: VaultMutationScope): Promise<T> {let ownsTransaction = false;try {let step = op.next();@@ -88,7 +90,7 @@ export async function runAsync<T>(op: DbOp<T>, client: IDatabaseClient): Promise}if (ownsTransaction) {- await client.commitTransaction();+ await client.commitTransaction(scope);ownsTransaction = false;}return step.value;@@ -118,10 +120,12 @@ export function syncRepository<R extends object>(repository: R, client: ISyncDat* Wrap a repository for an asynchronous client.* @param repository - The repository* @param client - The client its ops run on+ * @param scope - What this repository's writes touch; a bucket-scoped repository lets the sync push just that+ * data bucket instead of the full vault manifest. Defaults to a full-manifest change.* @returns The repository with its DbOp methods returning Promises*/-export function asyncRepository<R extends object>(repository: R, client: IDatabaseClient): AsyncRepository<R> {- return bindRepository(repository, (op) => runAsync(op, client)) as AsyncRepository<R>;+export function asyncRepository<R extends object>(repository: R, client: IDatabaseClient, scope?: VaultMutationScope): AsyncRepository<R> {+ return bindRepository(repository, (op) => runAsync(op, client, scope)) as AsyncRepository<R>;}/**diff --git a/core/client/src/database/__tests__/LogoScoping.test.ts b/core/client/src/database/__tests__/LogoScoping.test.tsindex ac1c2d81a..b4dd875e3 100644--- a/core/client/src/database/__tests__/LogoScoping.test.ts+++ b/core/client/src/database/__tests__/LogoScoping.test.ts@@ -55,36 +55,17 @@ describe('logo manifest scoping', () => {expect(rows(db, LogoQueries.GET_BEST_FOR_KEY, ['favicon', 'github.com'])[0].Name).toBe('real');});- it('finds an item whose logo lives in another manifest, and only that item', async () => {+ it('GET_BY_ID answers for an item whose logo lives in another manifest', async () => {const db = await makeDb();- db.run(`INSERT INTO Logos VALUES ('${PERSONAL}','L-PERSONAL','favicon','github.com',X'0102',NULL,NULL,'t','t',0)`);- db.run(`INSERT INTO Logos VALUES ('${SHARED}','L-SHARED','favicon','gitlab.com',X'0304',NULL,NULL,'t','t',0)`);+ db.run(`INSERT INTO Logos VALUES ('${PERSONAL}','L-PERSONAL','builtin','shopping',NULL,NULL,NULL,'t','t',0)`);// Moved into the shared folder by a restamp, still pointing at the personal logo row.db.run(`INSERT INTO Items VALUES ('${SHARED}','ITEM-MOVED','L-PERSONAL','FOLDER-SHARED',0)`);- // Correctly scoped rows of both kinds, plus one with no logo at all.- db.run(`INSERT INTO Items VALUES ('${PERSONAL}','ITEM-MINE','L-PERSONAL','FOLDER-MINE',0)`);- db.run(`INSERT INTO Items VALUES ('${SHARED}','ITEM-THEIRS','L-SHARED','FOLDER-SHARED',0)`);- db.run(`INSERT INTO Items VALUES ('${PERSONAL}','ITEM-BARE',NULL,NULL,0)`);- const found = rows(db, LogoQueries.FIND_ITEMS_WITH_FOREIGN_LOGO);- expect(found).toEqual([{ Id: 'ITEM-MOVED', ManifestId: SHARED, Kind: 'favicon', Source: 'github.com' }]);- });-- it('repointing clears the defect and leaves the origin manifest its own copy', async () => {- const db = await makeDb();- db.run(`INSERT INTO Logos VALUES ('${PERSONAL}','L-PERSONAL','favicon','github.com',X'0102',NULL,NULL,'t','t',0)`);- db.run(`INSERT INTO Items VALUES ('${SHARED}','ITEM-MOVED','L-PERSONAL','FOLDER-SHARED',0)`);- db.run(`INSERT INTO Items VALUES ('${PERSONAL}','ITEM-MINE','L-PERSONAL','FOLDER-MINE',0)`);-- // What adoptIntoScope does: clone under the target manifest's own derived id, then repoint.- const clonedId = 'L-SHARED-DERIVED';- db.run(`INSERT INTO Logos VALUES ('${SHARED}','${clonedId}','favicon','github.com',X'0102',NULL,NULL,'t','t',0)`);- db.run(LogoQueries.REPOINT_ITEM_LOGO, [clonedId, 'ITEM-MOVED', SHARED]);-- expect(rows(db, LogoQueries.FIND_ITEMS_WITH_FOREIGN_LOGO)).toEqual([]);- // The personal item is untouched and its own copy still exists.- expect(rows(db, `SELECT LogoId FROM Items WHERE Id = 'ITEM-MINE'`)[0].LogoId).toBe('L-PERSONAL');- expect(rows(db, LogoQueries.GET_ID_FOR_KEY, [PERSONAL, 'favicon', 'github.com'])[0].Id).toBe('L-PERSONAL');+ /*+ * The write path reads the item's current logo by id alone, so the built-in logo the user picked is+ * still found and kept instead of being replaced by the domain's favicon.+ */+ expect(rows(db, LogoQueries.GET_BY_ID, ['L-PERSONAL'])[0]).toMatchObject({ Kind: 'builtin', Source: 'shopping' });});it('GET_ID_FOR_KEY will not hand one manifest another manifest row', async () => {