Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add new vault sync scaffolding and repository pattern DB access to mobile app (#1404)
Leendert de Borstd45d66ee0fc4
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 f93aa8724..a8eb2765d 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@@ -1527,4 +1527,253 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :}}}++ // MARK: - Sync State Management++ /**+ * Get the sync state (isDirty, mutationSequence, serverRevision, isSyncing).+ * @param promise The promise to resolve.+ */+ @ReactMethod+ fun getSyncState(promise: Promise) {+ try {+ val syncState = vaultStore.getSyncState()+ val result = Arguments.createMap()+ result.putBoolean("isDirty", syncState.isDirty)+ result.putInt("mutationSequence", syncState.mutationSequence)+ result.putInt("serverRevision", syncState.serverRevision)+ result.putBoolean("isSyncing", syncState.isSyncing)+ promise.resolve(result)+ } catch (e: Exception) {+ Log.e(TAG, "Error getting sync state", e)+ promise.reject("ERR_GET_SYNC_STATE", "Failed to get sync state: ${e.message}", e)+ }+ }++ /**+ * Set the isDirty flag.+ * @param isDirty Whether the vault has unsynced changes.+ * @param promise The promise to resolve.+ */+ @ReactMethod+ fun setIsDirty(isDirty: Boolean, promise: Promise) {+ try {+ vaultStore.setIsDirty(isDirty)+ promise.resolve(null)+ } catch (e: Exception) {+ Log.e(TAG, "Error setting isDirty", e)+ promise.reject("ERR_SET_IS_DIRTY", "Failed to set isDirty: ${e.message}", e)+ }+ }++ /**+ * Set the isSyncing flag.+ * @param isSyncing Whether a sync operation is in progress.+ * @param promise The promise to resolve.+ */+ @ReactMethod+ fun setIsSyncing(isSyncing: Boolean, promise: Promise) {+ try {+ vaultStore.setIsSyncing(isSyncing)+ promise.resolve(null)+ } catch (e: Exception) {+ Log.e(TAG, "Error setting isSyncing", e)+ promise.reject("ERR_SET_IS_SYNCING", "Failed to set isSyncing: ${e.message}", e)+ }+ }++ /**+ * Store encrypted vault with sync state atomically.+ * Two modes:+ * 1. markDirty=true: Local mutation - always succeeds, increments mutation sequence+ * 2. expectedMutationSeq provided: Sync operation - only succeeds if no mutations happened+ *+ * @param encryptedVault The encrypted vault blob.+ * @param markDirty If true, marks vault as dirty and increments mutation sequence.+ * @param serverRevision Optional server revision to set.+ * @param expectedMutationSeq If provided, only store if current sequence matches.+ * @param promise The promise to resolve with { success: boolean, mutationSequence: number }.+ */+ @ReactMethod+ fun storeEncryptedVaultWithSyncState(+ encryptedVault: String,+ markDirty: Boolean,+ serverRevision: Double?,+ expectedMutationSeq: Double?,+ promise: Promise,+ ) {+ try {+ val result = vaultStore.storeEncryptedVaultWithSyncState(+ encryptedVault = encryptedVault,+ markDirty = markDirty,+ serverRevision = serverRevision?.toInt(),+ expectedMutationSeq = expectedMutationSeq?.toInt(),+ )+ val response = Arguments.createMap()+ response.putBoolean("success", result.success)+ response.putInt("mutationSequence", result.mutationSequence)+ promise.resolve(response)+ } catch (e: Exception) {+ Log.e(TAG, "Error storing vault with sync state", e)+ promise.reject("ERR_STORE_VAULT_SYNC", "Failed to store vault with sync state: ${e.message}", e)+ }+ }++ /**+ * Mark the vault as clean after successful sync.+ * Only clears dirty flag if no mutations happened during sync.+ *+ * @param mutationSeqAtStart The mutation sequence when sync started.+ * @param newServerRevision The new server revision after successful upload.+ * @param promise The promise to resolve with boolean indicating if dirty flag was cleared.+ */+ @ReactMethod+ fun markVaultClean(mutationSeqAtStart: Double, newServerRevision: Double, promise: Promise) {+ try {+ val cleared = vaultStore.markVaultClean(+ mutationSeqAtStart = mutationSeqAtStart.toInt(),+ newServerRevision = newServerRevision.toInt(),+ )+ promise.resolve(cleared)+ } catch (e: Exception) {+ Log.e(TAG, "Error marking vault clean", e)+ promise.reject("ERR_MARK_VAULT_CLEAN", "Failed to mark vault clean: ${e.message}", e)+ }+ }++ /**+ * Upload the vault to the server.+ * This is used for sync operations where race detection is needed.+ *+ * @param promise The promise to resolve with upload result.+ */+ @ReactMethod+ fun uploadVault(promise: Promise) {+ CoroutineScope(Dispatchers.IO).launch {+ try {+ val result = vaultStore.uploadVault(webApiService)+ withContext(Dispatchers.Main) {+ val response = Arguments.createMap()+ response.putBoolean("success", result.success)+ response.putInt("status", result.status)+ response.putInt("newRevisionNumber", result.newRevisionNumber)+ response.putInt("mutationSeqAtStart", result.mutationSeqAtStart)+ if (result.error != null) {+ response.putString("error", result.error)+ } else {+ response.putNull("error")+ }+ promise.resolve(response)+ }+ } catch (e: Exception) {+ withContext(Dispatchers.Main) {+ Log.e(TAG, "Error uploading vault", e)+ promise.reject("ERR_UPLOAD_VAULT", "Failed to upload vault: ${e.message}", e)+ }+ }+ }+ }++ /**+ * Fetch the server vault (encrypted blob).+ * Use this for merge operations where you need both local and server vaults.+ *+ * @param promise The promise to resolve with VaultResponse.+ */+ @ReactMethod+ fun fetchServerVault(promise: Promise) {+ CoroutineScope(Dispatchers.IO).launch {+ try {+ val vaultResponse = vaultStore.fetchServerVault(webApiService)+ withContext(Dispatchers.Main) {+ val vaultDict = Arguments.createMap()+ vaultDict.putInt("status", vaultResponse.status)++ val vaultData = Arguments.createMap()+ vaultData.putString("username", vaultResponse.vault.username)+ vaultData.putString("blob", vaultResponse.vault.blob)+ vaultData.putString("version", vaultResponse.vault.version)+ vaultData.putInt("currentRevisionNumber", vaultResponse.vault.currentRevisionNumber)+ vaultData.putString("encryptionPublicKey", vaultResponse.vault.encryptionPublicKey)+ vaultData.putInt("credentialsCount", vaultResponse.vault.credentialsCount)++ val emailList = Arguments.createArray()+ vaultResponse.vault.emailAddressList.forEach { emailList.pushString(it) }+ vaultData.putArray("emailAddressList", emailList)++ val privateEmailList = Arguments.createArray()+ vaultResponse.vault.privateEmailDomainList.forEach { privateEmailList.pushString(it) }+ vaultData.putArray("privateEmailDomainList", privateEmailList)++ val hiddenPrivateEmailList = Arguments.createArray()+ vaultResponse.vault.hiddenPrivateEmailDomainList.forEach { hiddenPrivateEmailList.pushString(it) }+ vaultData.putArray("hiddenPrivateEmailDomainList", hiddenPrivateEmailList)++ val publicEmailList = Arguments.createArray()+ vaultResponse.vault.publicEmailDomainList.forEach { publicEmailList.pushString(it) }+ vaultData.putArray("publicEmailDomainList", publicEmailList)++ vaultData.putString("createdAt", vaultResponse.vault.createdAt)+ vaultData.putString("updatedAt", vaultResponse.vault.updatedAt)++ vaultDict.putMap("vault", vaultData)+ promise.resolve(vaultDict)+ }+ } catch (e: VaultSyncError) {+ withContext(Dispatchers.Main) {+ Log.e(TAG, "Vault sync error fetching vault", e)+ promise.reject(e.code, e.message, e)+ }+ } catch (e: Exception) {+ withContext(Dispatchers.Main) {+ Log.e(TAG, "Error fetching vault", e)+ promise.reject("ERR_FETCH_VAULT", "Failed to fetch vault: ${e.message}", e)+ }+ }+ }+ }++ /**+ * Check if a new vault version is available, including sync state for merge decision.+ * This enhanced version returns sync state so the caller can decide whether to merge.+ *+ * @param promise The promise to resolve with VaultVersionCheckResult.+ */+ @ReactMethod+ fun checkVaultVersion(promise: Promise) {+ CoroutineScope(Dispatchers.IO).launch {+ try {+ val result = vaultStore.checkVaultVersion(webApiService)+ withContext(Dispatchers.Main) {+ val response = Arguments.createMap()+ response.putBoolean("isNewVersionAvailable", result.isNewVersionAvailable)+ if (result.newRevision != null) {+ response.putInt("newRevision", result.newRevision)+ } else {+ response.putNull("newRevision")+ }+ response.putInt("serverRevision", result.serverRevision)++ val syncStateMap = Arguments.createMap()+ syncStateMap.putBoolean("isDirty", result.syncState.isDirty)+ syncStateMap.putInt("mutationSequence", result.syncState.mutationSequence)+ syncStateMap.putInt("serverRevision", result.syncState.serverRevision)+ syncStateMap.putBoolean("isSyncing", result.syncState.isSyncing)+ response.putMap("syncState", syncStateMap)++ promise.resolve(response)+ }+ } catch (e: VaultSyncError) {+ withContext(Dispatchers.Main) {+ Log.e(TAG, "Vault sync error checking version", e)+ promise.reject(e.code, e.message, e)+ }+ } catch (e: Exception) {+ withContext(Dispatchers.Main) {+ Log.e(TAG, "Error checking vault version", e)+ promise.reject("ERR_CHECK_VERSION", "Failed to check vault version: ${e.message}", e)+ }+ }+ }+ }}diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultData.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultData.ktnew file mode 100644index 000000000..344342586--- /dev/null+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultData.kt@@ -0,0 +1,48 @@+package net.aliasvault.app.vaultstore++/**+ * Vault data from API.+ */+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 hiddenPrivateEmailDomainList: List<String>,+ val publicEmailDomainList: List<String>,+ val createdAt: String,+ val updatedAt: String,+)++/**+ * Vault response from Vault GET endpoint.+ */+data class VaultResponse(+ val status: Int,+ val vault: VaultData,+)++/**+ * Result of checking for new vault version.+ */+data class VaultVersionCheckResult(+ val isNewVersionAvailable: Boolean,+ val newRevision: Int?,+ val serverRevision: Int,+ val syncState: net.aliasvault.app.vaultstore.models.SyncState,+)++/**+ * Result of vault upload.+ */+data class VaultUploadResult(+ val success: Boolean,+ val status: Int,+ val newRevisionNumber: Int,+ val mutationSeqAtStart: Int,+ val error: String? = null,+)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 baad47edf..dddd3c0a8 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@@ -140,6 +140,105 @@ class VaultMetadataManager(// endregion+ // region Sync State Management++ /**+ * Set the dirty flag indicating local changes need to be synced.+ */+ fun setIsDirty(isDirty: Boolean) {+ storageProvider.setIsDirty(isDirty)+ }++ /**+ * Get the dirty flag.+ */+ fun getIsDirty(): Boolean {+ return storageProvider.getIsDirty()+ }++ /**+ * Get the current mutation sequence number.+ */+ fun getMutationSequence(): Int {+ return storageProvider.getMutationSequence()+ }++ /**+ * Set the mutation sequence number.+ */+ fun setMutationSequence(sequence: Int) {+ storageProvider.setMutationSequence(sequence)+ }++ /**+ * Increment the mutation sequence and return the new value.+ */+ fun incrementMutationSequence(): Int {+ val current = getMutationSequence()+ val newValue = current + 1+ setMutationSequence(newValue)+ return newValue+ }++ /**+ * Set the syncing flag.+ */+ fun setIsSyncing(isSyncing: Boolean) {+ storageProvider.setIsSyncing(isSyncing)+ }++ /**+ * Get the syncing flag.+ */+ fun getIsSyncing(): Boolean {+ return storageProvider.getIsSyncing()+ }++ /**+ * Get the complete sync state.+ */+ fun getSyncState(): SyncState {+ return SyncState(+ isDirty = getIsDirty(),+ mutationSequence = getMutationSequence(),+ serverRevision = getVaultRevisionNumber(),+ isSyncing = getIsSyncing(),+ )+ }++ /**+ * Mark the vault as clean after successful sync.+ * Only clears dirty flag if no mutations happened during sync.+ *+ * @param mutationSeqAtStart The mutation sequence when sync started+ * @param newServerRevision The new server revision after successful upload+ * @return Whether the dirty flag was cleared+ */+ fun markVaultClean(mutationSeqAtStart: Int, newServerRevision: Int): Boolean {+ val currentMutationSeq = getMutationSequence()++ // Always update server revision+ setVaultRevisionNumber(newServerRevision)++ if (currentMutationSeq == mutationSeqAtStart) {+ // No mutations during sync - safe to mark as clean+ setIsDirty(false)+ return true+ }++ // Mutations happened during sync - keep dirty+ return false+ }++ /**+ * Clear all sync state (used on logout).+ */+ fun clearSyncState() {+ storageProvider.clearSyncState()+ }++ // endregion+// region Internal Helpers/**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.ktindex 2c0bdd133..b7ca69b0d 100644--- 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@@ -3,6 +3,7 @@ package net.aliasvault.app.vaultstoreimport android.util.Logimport net.aliasvault.app.exceptions.SerializationExceptionimport net.aliasvault.app.exceptions.VaultOperationException+import net.aliasvault.app.vaultstore.models.FieldKeyimport org.json.JSONArrayimport org.json.JSONObject@@ -78,6 +79,96 @@ class VaultMutate(}}+ /**+ * Upload the vault to the server and return detailed result.+ * This is used for sync operations where race detection is needed.+ */+ suspend fun uploadVault(webApiService: net.aliasvault.app.webapi.WebApiService): VaultUploadResult {+ val mutationSeqAtStart = metadata.getMutationSequence()++ return 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("encryptionPublicKey", vault.encryptionPublicKey)+ json.put("updatedAt", vault.updatedAt)+ json.put("username", vault.username)+ json.put("version", vault.version)++ val response = try {+ webApiService.executeRequest(+ method = "POST",+ endpoint = "Vault",+ body = json.toString(),+ headers = mapOf("Content-Type" to "application/json"),+ requiresAuth = true,+ )+ } catch (e: Exception) {+ return VaultUploadResult(+ success = false,+ status = -1,+ newRevisionNumber = 0,+ mutationSeqAtStart = mutationSeqAtStart,+ error = "Network error: ${e.message}",+ )+ }++ if (response.statusCode != 200) {+ return VaultUploadResult(+ success = false,+ status = -1,+ newRevisionNumber = 0,+ mutationSeqAtStart = mutationSeqAtStart,+ error = "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) {+ return VaultUploadResult(+ success = false,+ status = -1,+ newRevisionNumber = 0,+ mutationSeqAtStart = mutationSeqAtStart,+ error = "Failed to parse response: ${e.message}",+ )+ }++ if (vaultResponse.status == 0) {+ // Success - update local revision number and clear offline mode+ metadata.setVaultRevisionNumber(vaultResponse.newRevisionNumber)+ metadata.setOfflineMode(false)+ }++ VaultUploadResult(+ success = vaultResponse.status == 0,+ status = vaultResponse.status,+ newRevisionNumber = vaultResponse.newRevisionNumber,+ mutationSeqAtStart = mutationSeqAtStart,+ error = if (vaultResponse.status != 0) "Vault upload returned status ${vaultResponse.status}" else null,+ )+ } catch (e: Exception) {+ Log.e(TAG, "Error uploading vault", e)+ VaultUploadResult(+ success = false,+ status = -1,+ newRevisionNumber = 0,+ mutationSeqAtStart = mutationSeqAtStart,+ error = "Error uploading vault: ${e.message}",+ )+ }+ }+// endregion// region Internal Helpers@@ -94,13 +185,15 @@ class VaultMutate(throw VaultOperationException("Vault must be unlocked to prepare for upload")}- val credentials = query.getAllCredentials()+ // Get all items to count them and extract private email addresses+ val items = query.getAllItems()val metadataObj = metadata.getVaultMetadataObject()val privateEmailDomains = metadataObj?.privateEmailDomains ?: emptyList()- val privateEmailAddresses = credentials- .mapNotNull { it.alias?.email }+ // Extract private email addresses from items using the email field+ val privateEmailAddresses = items+ .mapNotNull { it.email }.filter { email ->privateEmailDomains.any { domain ->email.lowercase().endsWith("@${domain.lowercase()}")@@ -129,7 +222,7 @@ class VaultMutate(return VaultUpload(blob = encryptedDb,createdAt = now,- credentialsCount = credentials.size,+ credentialsCount = items.size,currentRevisionNumber = currentRevision,emailAddressList = privateEmailAddresses,// TODO: add public RSA encryption key to payload when implementing vault creation from mobile app. Currently only web app does this.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.ktindex 74cfeee52..e9fb70f16 100644--- 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@@ -6,6 +6,10 @@ import net.aliasvault.app.utils.DateHelpersimport net.aliasvault.app.vaultstore.interfaces.CredentialOperationCallbackimport net.aliasvault.app.vaultstore.models.Aliasimport net.aliasvault.app.vaultstore.models.Credential+import net.aliasvault.app.vaultstore.models.FieldKey+import net.aliasvault.app.vaultstore.models.FieldType+import net.aliasvault.app.vaultstore.models.Item+import net.aliasvault.app.vaultstore.models.ItemFieldimport net.aliasvault.app.vaultstore.models.Passwordimport net.aliasvault.app.vaultstore.models.Serviceimport java.util.Calendar@@ -157,134 +161,280 @@ class VaultQuery(// endregion- // region Credential Operations+ // region Item Operations (New Field-Based Model)/**- * Get all credentials from the vault.+ * Get all items from the vault using the new field-based model.*/- fun getAllCredentials(): List<Credential> {+ @Suppress("LongMethod", "NestedBlockDepth")+ fun getAllItems(): List<Item> {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 itemQuery = """+ SELECT DISTINCT+ i.Id,+ i.Name,+ i.ItemType,+ i.FolderId,+ f.Name as FolderPath,+ l.FileData as Logo,+ CASE WHEN EXISTS (SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.IsDeleted = 0) THEN 1 ELSE 0 END as HasPasskey,+ CASE WHEN EXISTS (SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.IsDeleted = 0) THEN 1 ELSE 0 END as HasAttachment,+ CASE WHEN EXISTS (SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.IsDeleted = 0) THEN 1 ELSE 0 END as HasTotp,+ i.CreatedAt,+ i.UpdatedAt+ FROM Items i+ LEFT JOIN Logos l ON i.LogoId = l.Id+ LEFT JOIN Folders f ON i.FolderId = f.Id+ WHERE i.IsDeleted = 0 AND i.DeletedAt IS NULL+ ORDER BY i.CreatedAt DESC"""- val result = mutableListOf<Credential>()- val cursor = database.dbConnection?.query(query)+ val items = mutableListOf<Item>()+ val itemIds = mutableListOf<String>()- cursor?.use {- while (it.moveToNext()) {+ database.dbConnection?.query(itemQuery)?.use { cursor ->+ while (cursor.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,+ val idString = cursor.getString(0)+ val name = if (cursor.isNull(1)) null else cursor.getString(1)+ val itemType = cursor.getString(2)+ val folderId = if (cursor.isNull(3)) null else cursor.getString(3)+ val folderPath = if (cursor.isNull(4)) null else cursor.getString(4)+ val logo = if (cursor.isNull(5)) null else cursor.getBlob(5)+ val hasPasskey = cursor.getInt(6) == 1+ val hasAttachment = cursor.getInt(7) == 1+ val hasTotp = cursor.getInt(8) == 1+ val createdAt = DateHelpers.parseDateString(cursor.getString(9)) ?: MIN_DATE+ val updatedAt = DateHelpers.parseDateString(cursor.getString(10)) ?: MIN_DATE++ val item = Item(+ id = UUID.fromString(idString),+ name = name,+ itemType = itemType,+ logo = logo,+ folderId = folderId?.let { UUID.fromString(it) },+ folderPath = folderPath,+ fields = emptyList(), // Will be populated below+ hasPasskey = hasPasskey,+ hasAttachment = hasAttachment,+ hasTotp = hasTotp,+ createdAt = createdAt,+ updatedAt = updatedAt)+ items.add(item)+ itemIds.add(idString)+ } catch (e: Exception) {+ Log.e(TAG, "Error parsing item row", e)+ }+ }+ }- 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,- )- }+ // If no items, return empty list+ if (items.isEmpty()) {+ return emptyList()+ }- 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,- )- }+ // Get all field values for these items+ val placeholders = itemIds.joinToString(",") { "?" }+ val fieldQuery = """+ SELECT+ fv.ItemId,+ fv.FieldKey,+ fv.FieldDefinitionId,+ fd.Label as CustomLabel,+ fd.FieldType as CustomFieldType,+ fd.IsHidden as CustomIsHidden,+ fd.EnableHistory as CustomEnableHistory,+ fv.Value,+ fv.Weight as DisplayOrder+ FROM FieldValues fv+ LEFT JOIN FieldDefinitions fd ON fv.FieldDefinitionId = fd.Id+ WHERE fv.ItemId IN ($placeholders)+ AND fv.IsDeleted = 0+ ORDER BY fv.ItemId, fv.Weight+ """- 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,+ // Build a map of itemId -> [ItemField]+ val fieldsByItemId = mutableMapOf<String, MutableList<ItemField>>()++ database.dbConnection?.query(fieldQuery, itemIds.toTypedArray())?.use { cursor ->+ while (cursor.moveToNext()) {+ try {+ val itemIdString = cursor.getString(0)+ val fieldKey = if (cursor.isNull(1)) null else cursor.getString(1)+ val fieldDefinitionId = if (cursor.isNull(2)) null else cursor.getString(2)+ val customLabel = if (cursor.isNull(3)) null else cursor.getString(3)+ val customFieldType = if (cursor.isNull(4)) null else cursor.getString(4)+ val customIsHidden = if (cursor.isNull(5)) false else cursor.getInt(5) == 1+ val customEnableHistory = if (cursor.isNull(6)) false else cursor.getInt(6) == 1+ val value = if (cursor.isNull(7)) "" else cursor.getString(7)+ val displayOrder = if (cursor.isNull(8)) 0 else cursor.getInt(8)++ // Determine if this is a custom field+ val isCustomField = fieldDefinitionId != null && fieldKey == null++ // Resolve the effective field key+ val effectiveFieldKey = fieldKey ?: fieldDefinitionId ?: ""++ // Resolve field metadata+ val metadata = resolveFieldMetadata(+ fieldKey = effectiveFieldKey,+ customLabel = customLabel,+ customFieldType = customFieldType,+ customIsHidden = customIsHidden,+ customEnableHistory = customEnableHistory,+ isCustomField = isCustomField+ )++ val field = ItemField(+ fieldKey = effectiveFieldKey,+ label = metadata.label,+ fieldType = metadata.fieldType,+ value = value,+ isHidden = metadata.isHidden,+ displayOrder = displayOrder,+ isCustomField = isCustomField,+ enableHistory = metadata.enableHistory)- result.add(credential)++ fieldsByItemId.getOrPut(itemIdString) { mutableListOf() }.add(field)} catch (e: Exception) {- Log.e(TAG, "Error parsing credential row", e)+ Log.e(TAG, "Error parsing field row", e)}}}- return result+ // Assign fields to items+ return items.map { item ->+ val fields = fieldsByItemId[item.id.toString().uppercase()] ?: emptyList()+ item.copy(fields = fields)+ }+ }++ /**+ * Helper class to hold resolved field metadata.+ */+ private data class FieldMetadata(+ val label: String,+ val fieldType: String,+ val isHidden: Boolean,+ val enableHistory: Boolean+ )++ /**+ * Resolve field metadata for system fields and custom fields.+ */+ @Suppress("CyclomaticComplexMethod")+ private fun resolveFieldMetadata(+ fieldKey: String,+ customLabel: String?,+ customFieldType: String?,+ customIsHidden: Boolean,+ customEnableHistory: Boolean,+ isCustomField: Boolean+ ): FieldMetadata {+ if (isCustomField) {+ return FieldMetadata(+ label = customLabel ?: fieldKey,+ fieldType = customFieldType ?: FieldType.TEXT,+ isHidden = customIsHidden,+ enableHistory = customEnableHistory+ )+ }++ // System field metadata based on FieldKey constants+ return when (fieldKey) {+ FieldKey.LOGIN_USERNAME -> FieldMetadata("Username", FieldType.TEXT, false, false)+ FieldKey.LOGIN_PASSWORD -> FieldMetadata("Password", FieldType.PASSWORD, true, true)+ FieldKey.LOGIN_EMAIL -> FieldMetadata("Email", FieldType.EMAIL, false, false)+ FieldKey.LOGIN_URL -> FieldMetadata("URL", FieldType.URL, false, false)+ FieldKey.CARD_NUMBER -> FieldMetadata("Card Number", FieldType.TEXT, true, false)+ FieldKey.CARD_CARDHOLDER_NAME -> FieldMetadata("Cardholder Name", FieldType.TEXT, false, false)+ FieldKey.CARD_EXPIRY_MONTH -> FieldMetadata("Expiry Month", FieldType.TEXT, false, false)+ FieldKey.CARD_EXPIRY_YEAR -> FieldMetadata("Expiry Year", FieldType.TEXT, false, false)+ FieldKey.CARD_CVV -> FieldMetadata("CVV", FieldType.PASSWORD, true, false)+ FieldKey.CARD_PIN -> FieldMetadata("PIN", FieldType.PASSWORD, true, false)+ FieldKey.ALIAS_FIRST_NAME -> FieldMetadata("First Name", FieldType.TEXT, false, false)+ FieldKey.ALIAS_LAST_NAME -> FieldMetadata("Last Name", FieldType.TEXT, false, false)+ FieldKey.ALIAS_GENDER -> FieldMetadata("Gender", FieldType.TEXT, false, false)+ FieldKey.ALIAS_BIRTHDATE -> FieldMetadata("Birth Date", FieldType.DATE, false, false)+ FieldKey.NOTES_CONTENT -> FieldMetadata("Notes", FieldType.TEXT_AREA, false, false)+ else -> FieldMetadata(fieldKey, FieldType.TEXT, false, false)+ }+ }++ // endregion++ // region Legacy Credential Operations (Compatibility Layer)++ /**+ * Get all credentials from the vault.+ * This method converts the new Items model back to the legacy Credential model for compatibility.+ */+ fun getAllCredentials(): List<Credential> {+ val items = getAllItems()+ return items.mapNotNull { convertItemToCredential(it) }+ }++ /**+ * Convert an Item to the legacy Credential format.+ */+ private fun convertItemToCredential(item: Item): Credential? {+ // Create a Service from the item+ val service = Service(+ id = item.id,+ name = item.name,+ url = item.url,+ logo = item.logo,+ createdAt = item.createdAt,+ updatedAt = item.updatedAt,+ isDeleted = false+ )++ // Create an Alias if the item has alias fields+ var alias: Alias? = null+ if (item.firstName != null || item.lastName != null || item.email != null) {+ alias = Alias(+ id = item.id,+ gender = item.getFieldValue(FieldKey.ALIAS_GENDER),+ firstName = item.firstName,+ lastName = item.lastName,+ nickName = null,+ birthDate = MIN_DATE, // TODO: Parse birthdate from field value+ email = item.email,+ createdAt = item.createdAt,+ updatedAt = item.updatedAt,+ isDeleted = false+ )+ }++ // Create a Password if the item has a password field+ var password: Password? = null+ item.password?.let { passwordValue ->+ password = Password(+ id = UUID.randomUUID(),+ credentialId = item.id,+ value = passwordValue,+ createdAt = item.createdAt,+ updatedAt = item.updatedAt,+ isDeleted = false+ )+ }++ return Credential(+ id = item.id,+ alias = alias,+ service = service,+ username = item.username,+ notes = item.getFieldValue("login.notes"),+ password = password,+ createdAt = item.createdAt,+ updatedAt = item.updatedAt,+ isDeleted = false+ )}/**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 89fec195d..13363cfde 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@@ -452,6 +452,93 @@ class VaultStore(return sync.syncVault(webApiService)}+ /**+ * Get the sync state.+ */+ fun getSyncState(): net.aliasvault.app.vaultstore.models.SyncState {+ return metadata.getSyncState()+ }++ /**+ * Set the isDirty flag.+ */+ fun setIsDirty(isDirty: Boolean) {+ metadata.setIsDirty(isDirty)+ }++ /**+ * Set the isSyncing flag.+ */+ fun setIsSyncing(isSyncing: Boolean) {+ metadata.setIsSyncing(isSyncing)+ }++ /**+ * Store encrypted vault with sync state atomically.+ * Two modes:+ * 1. markDirty=true: Local mutation - always succeeds, increments mutation sequence+ * 2. expectedMutationSeq provided: Sync operation - only succeeds if no mutations happened+ */+ fun storeEncryptedVaultWithSyncState(+ encryptedVault: String,+ markDirty: Boolean = false,+ serverRevision: Int? = null,+ expectedMutationSeq: Int? = null,+ ): StoreVaultResult {+ var mutationSequence = metadata.getMutationSequence()++ // Race detection for sync operations+ if (expectedMutationSeq != null && expectedMutationSeq != mutationSequence) {+ return StoreVaultResult(success = false, mutationSequence = mutationSequence)+ }++ if (markDirty) {+ mutationSequence += 1+ }++ // Store vault+ databaseComponent.storeEncryptedDatabase(encryptedVault)++ if (markDirty) {+ metadata.setMutationSequence(mutationSequence)+ metadata.setIsDirty(true)+ }++ if (serverRevision != null) {+ metadata.setVaultRevisionNumber(serverRevision)+ }++ return StoreVaultResult(success = true, mutationSequence = mutationSequence)+ }++ /**+ * Mark the vault as clean after successful sync.+ */+ fun markVaultClean(mutationSeqAtStart: Int, newServerRevision: Int): Boolean {+ return metadata.markVaultClean(mutationSeqAtStart, newServerRevision)+ }++ /**+ * Upload the vault to the server.+ */+ suspend fun uploadVault(webApiService: net.aliasvault.app.webapi.WebApiService): VaultUploadResult {+ return mutate.uploadVault(webApiService)+ }++ /**+ * Fetch the server vault (encrypted blob).+ */+ suspend fun fetchServerVault(webApiService: net.aliasvault.app.webapi.WebApiService): VaultResponse {+ return sync.fetchServerVault(webApiService)+ }++ /**+ * Check vault version including sync state.+ */+ suspend fun checkVaultVersion(webApiService: net.aliasvault.app.webapi.WebApiService): VaultVersionCheckResult {+ return sync.checkVaultVersion(webApiService)+ }+// endregion// region Mutate Methodsdiff --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.ktindex 5facc7726..f7566436c 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt@@ -72,6 +72,52 @@ class VaultSync(return false}+ /**+ * Check if a new vault version is available, including sync state for merge decision.+ * This enhanced version returns sync state so the caller can decide whether to merge.+ */+ suspend fun checkVaultVersion(webApiService: net.aliasvault.app.webapi.WebApiService): VaultVersionCheckResult {+ val status = fetchAndValidateStatus(webApiService)+ metadata.setOfflineMode(false)++ val syncState = metadata.getSyncState()+ val isNewVersionAvailable = status.vaultRevision > syncState.serverRevision++ return VaultVersionCheckResult(+ isNewVersionAvailable = isNewVersionAvailable,+ newRevision = if (isNewVersionAvailable) status.vaultRevision else null,+ serverRevision = status.vaultRevision,+ syncState = syncState,+ )+ }++ /**+ * Fetch the server vault (encrypted blob).+ * Use this for merge operations where you need both local and server vaults.+ */+ suspend fun fetchServerVault(webApiService: net.aliasvault.app.webapi.WebApiService): VaultResponse {+ val vaultResponse = try {+ webApiService.executeRequest(+ method = "GET",+ endpoint = "Vault",+ body = null,+ headers = emptyMap(),+ requiresAuth = true,+ )+ } catch (e: Exception) {+ throw VaultSyncError.NetworkError(e)+ }++ if (vaultResponse.statusCode != 200) {+ if (vaultResponse.statusCode == 401) {+ throw VaultSyncError.SessionExpired()+ }+ throw VaultSyncError.ServerUnavailable(vaultResponse.statusCode)+ }++ return parseVaultResponsePublic(vaultResponse.body)+ }+// endregion// region Internal Helpers@@ -201,7 +247,7 @@ class VaultSync(metadata.storeMetadata(json.toString())}- private fun parseVaultResponse(body: String): VaultResponse {+ private fun parseVaultResponse(body: String): InternalVaultResponse {return try {val json = JSONObject(body)val vaultJson = json.getJSONObject("vault")@@ -230,9 +276,9 @@ class VaultSync(publicList.add(publicArray.getString(i))}- VaultResponse(+ InternalVaultResponse(status = json.getInt("status"),- vault = VaultData(+ vault = InternalVaultData(username = vaultJson.getString("username"),blob = vaultJson.getString("blob"),version = vaultJson.getString("version"),@@ -253,6 +299,27 @@ class VaultSync(}}+ private fun parseVaultResponsePublic(body: String): VaultResponse {+ val internal = parseVaultResponse(body)+ return VaultResponse(+ status = internal.status,+ vault = VaultData(+ username = internal.vault.username,+ blob = internal.vault.blob,+ version = internal.vault.version,+ currentRevisionNumber = internal.vault.currentRevisionNumber,+ encryptionPublicKey = internal.vault.encryptionPublicKey,+ credentialsCount = internal.vault.credentialsCount,+ emailAddressList = internal.vault.emailAddressList,+ privateEmailDomainList = internal.vault.privateEmailDomainList,+ hiddenPrivateEmailDomainList = internal.vault.hiddenPrivateEmailDomainList,+ publicEmailDomainList = internal.vault.publicEmailDomainList,+ createdAt = internal.vault.createdAt,+ updatedAt = internal.vault.updatedAt,+ ),+ )+ }+private fun validateVaultStatus(status: Int) {when (status) {0 -> return@@ -273,7 +340,7 @@ class VaultSync(val srpSalt: String,)- private data class VaultData(+ private data class InternalVaultData(val username: String,val blob: String,val version: String,@@ -288,9 +355,9 @@ class VaultSync(val updatedAt: String,)- private data class VaultResponse(+ private data class InternalVaultResponse(val status: Int,- val vault: VaultData,+ val vault: InternalVaultData,)// endregiondiff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/Item.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/Item.ktnew file mode 100644index 000000000..8ba6c7f58--- /dev/null+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/Item.kt@@ -0,0 +1,90 @@+package net.aliasvault.app.vaultstore.models++import java.util.Date+import java.util.UUID++/**+ * Item model representing vault entries in the new field-based data model.+ */+data class Item(+ val id: UUID,+ val name: String?,+ val itemType: String,+ val logo: ByteArray?,+ val folderId: UUID?,+ val folderPath: String?,+ val fields: List<ItemField>,+ val hasPasskey: Boolean,+ val hasAttachment: Boolean,+ val hasTotp: Boolean,+ val createdAt: Date,+ val updatedAt: Date+) {+ /**+ * Get the value of a field by its key.+ */+ fun getFieldValue(fieldKey: String): String? {+ return fields.find { it.fieldKey == fieldKey }?.value+ }++ /**+ * Get the URL field value (login.url).+ */+ val url: String?+ get() = getFieldValue(FieldKey.LOGIN_URL)++ /**+ * Get the username field value (login.username).+ */+ val username: String?+ get() = getFieldValue(FieldKey.LOGIN_USERNAME)++ /**+ * Get the password field value (login.password).+ */+ val password: String?+ get() = getFieldValue(FieldKey.LOGIN_PASSWORD)++ /**+ * Get the email field value (login.email).+ */+ val email: String?+ get() = getFieldValue(FieldKey.LOGIN_EMAIL)++ /**+ * Get the first name field value (alias.first_name).+ */+ val firstName: String?+ get() = getFieldValue(FieldKey.ALIAS_FIRST_NAME)++ /**+ * Get the last name field value (alias.last_name).+ */+ val lastName: String?+ get() = getFieldValue(FieldKey.ALIAS_LAST_NAME)++ override fun equals(other: Any?): Boolean {+ if (this === other) return true+ if (javaClass != other?.javaClass) return false+ other as Item+ return id == other.id+ }++ override fun hashCode(): Int {+ return id.hashCode()+ }+}++/**+ * Field value within an item.+ */+data class ItemField(+ val fieldKey: String,+ val label: String,+ val fieldType: String,+ val value: String,+ val isHidden: Boolean,+ val displayOrder: Int,+ val isCustomField: Boolean,+ val enableHistory: Boolean+)diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/StoreVaultResult.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/StoreVaultResult.ktnew file mode 100644index 000000000..f66ef18ed--- /dev/null+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/StoreVaultResult.kt@@ -0,0 +1,17 @@+package net.aliasvault.app.vaultstore.models++/**+ * Result of storing vault with sync state.+ */+data class StoreVaultResult(+ /**+ * Whether the store operation succeeded.+ * Can be false if expectedMutationSeq was provided and didn't match.+ */+ val success: Boolean,++ /**+ * The current mutation sequence after the operation.+ */+ val mutationSequence: Int,+)diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/SyncState.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/SyncState.ktnew file mode 100644index 000000000..5a2412fc7--- /dev/null+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/SyncState.kt@@ -0,0 +1,27 @@+package net.aliasvault.app.vaultstore.models++/**+ * Sync state for offline sync and race detection.+ */+data class SyncState(+ /**+ * True if local vault has unsynced changes.+ */+ val isDirty: Boolean = false,++ /**+ * Counter that increments on each local mutation.+ * Used for race detection during sync operations.+ */+ val mutationSequence: Int = 0,++ /**+ * The last synced server revision number.+ */+ val serverRevision: Int = 0,++ /**+ * True if a sync operation is currently in progress.+ */+ val isSyncing: Boolean = false,+)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 92a9dff99..b2df63e93 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@@ -150,4 +150,53 @@ class AndroidStorageProvider(private val context: Context) : StorageProvider {remove("server_version")}}++ // region Sync State++ override fun setIsDirty(isDirty: Boolean) {+ val sharedPreferences = context.getSharedPreferences("aliasvault", Context.MODE_PRIVATE)+ sharedPreferences.edit {+ putBoolean("is_dirty", isDirty)+ }+ }++ override fun getIsDirty(): Boolean {+ val sharedPreferences = context.getSharedPreferences("aliasvault", Context.MODE_PRIVATE)+ return sharedPreferences.getBoolean("is_dirty", false)+ }++ override fun getMutationSequence(): Int {+ val sharedPreferences = context.getSharedPreferences("aliasvault", Context.MODE_PRIVATE)+ return sharedPreferences.getInt("mutation_sequence", 0)+ }++ override fun setMutationSequence(sequence: Int) {+ val sharedPreferences = context.getSharedPreferences("aliasvault", Context.MODE_PRIVATE)+ sharedPreferences.edit {+ putInt("mutation_sequence", sequence)+ }+ }++ override fun setIsSyncing(isSyncing: Boolean) {+ val sharedPreferences = context.getSharedPreferences("aliasvault", Context.MODE_PRIVATE)+ sharedPreferences.edit {+ putBoolean("is_syncing", isSyncing)+ }+ }++ override fun getIsSyncing(): Boolean {+ val sharedPreferences = context.getSharedPreferences("aliasvault", Context.MODE_PRIVATE)+ return sharedPreferences.getBoolean("is_syncing", false)+ }++ override fun clearSyncState() {+ val sharedPreferences = context.getSharedPreferences("aliasvault", Context.MODE_PRIVATE)+ sharedPreferences.edit {+ remove("is_dirty")+ remove("mutation_sequence")+ remove("is_syncing")+ }+ }++ // endregion}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 8bf1dc7fd..299a92623 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@@ -123,4 +123,49 @@ interface StorageProvider {* Clear the server version.*/fun clearServerVersion()++ // region Sync State++ /**+ * Set the dirty flag indicating local changes need to be synced.+ * @param isDirty Whether the vault has unsynced changes+ */+ fun setIsDirty(isDirty: Boolean)++ /**+ * Get the dirty flag.+ * @return True if vault has unsynced changes+ */+ fun getIsDirty(): Boolean++ /**+ * Get the mutation sequence number.+ * @return The current mutation sequence+ */+ fun getMutationSequence(): Int++ /**+ * Set the mutation sequence number.+ * @param sequence The new mutation sequence value+ */+ fun setMutationSequence(sequence: Int)++ /**+ * Set the syncing flag.+ * @param isSyncing Whether a sync operation is in progress+ */+ fun setIsSyncing(isSyncing: Boolean)++ /**+ * Get the syncing flag.+ * @return True if a sync operation is in progress+ */+ fun getIsSyncing(): Boolean++ /**+ * Clear all sync state (isDirty, mutationSequence, isSyncing).+ */+ fun clearSyncState()++ // endregion}diff --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 9ea027b5c..a011a75fa 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@@ -16,6 +16,9 @@ class TestStorageProvider : StorageProvider {private var username: String? = nullprivate var offlineMode: Boolean = falseprivate var serverVersion: String? = null+ private var isDirty: Boolean = false+ private var mutationSequence: Int = 0+ private var isSyncing: Boolean = falseoverride fun getEncryptedDatabaseFile(): File = tempFile@@ -100,4 +103,38 @@ class TestStorageProvider : StorageProvider {override fun clearServerVersion() {serverVersion = null}++ // region Sync State++ override fun setIsDirty(isDirty: Boolean) {+ this.isDirty = isDirty+ }++ override fun getIsDirty(): Boolean {+ return isDirty+ }++ override fun getMutationSequence(): Int {+ return mutationSequence+ }++ override fun setMutationSequence(sequence: Int) {+ mutationSequence = sequence+ }++ override fun setIsSyncing(isSyncing: Boolean) {+ this.isSyncing = isSyncing+ }++ override fun getIsSyncing(): Boolean {+ return isSyncing+ }++ override fun clearSyncState() {+ isDirty = false+ mutationSequence = 0+ isSyncing = false+ }++ // endregion}diff --git a/apps/mobile-app/app/(tabs)/emails/[id].tsx b/apps/mobile-app/app/(tabs)/emails/[id].tsxindex be8c77c9a..45a199643 100644--- a/apps/mobile-app/app/(tabs)/emails/[id].tsx+++ b/apps/mobile-app/app/(tabs)/emails/[id].tsx@@ -8,7 +8,7 @@ import { useTranslation } from 'react-i18next';import { StyleSheet, View, ActivityIndicator, Alert, Share, useColorScheme, Linking, Text, TextInput, Platform } from 'react-native';import { WebView } from 'react-native-webview';-import type { Credential } from '@/utils/dist/core/models/vault';+import type { Item } from '@/utils/dist/core/models/vault';import type { Email } from '@/utils/dist/core/models/webapi';import EncryptionUtility from '@/utils/EncryptionUtility';import emitter from '@/utils/EventEmitter';@@ -40,7 +40,7 @@ export default function EmailDetailsScreen() : React.ReactNode {const [isMetadataMaximized, setMetadataMaximized] = useState(false);const [isHtmlView, setHtmlView] = useState(true);const isDarkMode = useColorScheme() === 'dark';- const [associatedCredential, setAssociatedCredential] = useState<Credential | null>(null);+ const [associatedItem, setAssociatedItem] = useState<Item | null>(null);/*** Load the email.@@ -61,11 +61,11 @@ export default function EmailDetailsScreen() : React.ReactNode {const decryptedEmail = await EncryptionUtility.decryptEmail(response, encryptionKeys);setEmail(decryptedEmail);- // Look up associated credential+ // Look up associated itemif (decryptedEmail.toLocal && decryptedEmail.toDomain) {const emailAddress = `${decryptedEmail.toLocal}@${decryptedEmail.toDomain}`;- const credential = await dbContext.sqliteClient.getCredentialByEmail(emailAddress);- setAssociatedCredential(credential);+ const item = await dbContext.sqliteClient.getItemByEmail(emailAddress);+ setAssociatedItem(item);}// Set initial view mode based on content@@ -171,8 +171,8 @@ export default function EmailDetailsScreen() : React.ReactNode {* Handle the open item button press.*/const handleOpenItem = () : void => {- if (associatedCredential) {- router.push(`/(tabs)/items/${associatedCredential.Id}`);+ if (associatedItem) {+ router.push(`/(tabs)/items/${associatedItem.Id}`);}};@@ -405,7 +405,7 @@ export default function EmailDetailsScreen() : React.ReactNode {<View style={styles.metadataRow}><View style={styles.metadataValue}><ThemedText style={[styles.metadataText, styles.metadataSubject]}>{email.subject}</ThemedText>- {associatedCredential && (+ {associatedItem && (<View><RobustPressableonPress={handleOpenItem}@@ -413,7 +413,7 @@ export default function EmailDetailsScreen() : React.ReactNode {><IconSymbol size={16} name={IconSymbolName.Key} color={colors.primary} style={styles.metadataItemIcon} /><ThemedText style={[styles.metadataText, { color: colors.primary }]}>- {associatedCredential.ServiceName}+ {associatedItem.Name}</ThemedText></RobustPressable></View>diff --git a/apps/mobile-app/app/(tabs)/emails/index.tsx b/apps/mobile-app/app/(tabs)/emails/index.tsxindex cf3288f3b..f39ce1763 100644--- a/apps/mobile-app/app/(tabs)/emails/index.tsx+++ b/apps/mobile-app/app/(tabs)/emails/index.tsx@@ -60,8 +60,8 @@ export default function EmailsScreen() : React.ReactNode {return;}- // Get unique email addresses from all credentials- const emailAddresses = await dbContext.sqliteClient.getAllEmailAddresses();+ // Get unique email addresses from all items+ const emailAddresses = await dbContext.sqliteClient.getAllItemEmailAddresses();try {// For now we only show the latest 50 emails. No pagination.diff --git a/apps/mobile-app/app/(tabs)/settings/import-export.tsx b/apps/mobile-app/app/(tabs)/settings/import-export.tsxindex e79246d86..3eb0ed49a 100644--- a/apps/mobile-app/app/(tabs)/settings/import-export.tsx+++ b/apps/mobile-app/app/(tabs)/settings/import-export.tsx@@ -4,7 +4,8 @@ import * as Sharing from 'expo-sharing';import { useState } from 'react';import { StyleSheet, View, TouchableOpacity, Alert } from 'react-native';-import type { Credential } from '@/utils/dist/core/models/vault';+import type { Item } from '@/utils/dist/core/models/vault';+import { FieldKey, getFieldValue, itemToCredential } from '@/utils/dist/core/models/vault';import { useColors } from '@/hooks/useColorScheme';import { useTranslation } from '@/hooks/useTranslation';@@ -80,34 +81,33 @@ export default function ImportExportScreen(): React.ReactNode {};/**- * Convert credentials to CSV format.+ * Convert items to CSV format.*/- const credentialsToCsv = async (credentials: Credential[]): Promise<string> => {+ const itemsToCsv = async (items: Item[]): Promise<string> => {const records: ICredentialCsvRecord[] = [];- // Get all credentials with their TOTP codes- for (const credential of credentials) {- // Get TOTP codes for this credential- const totpCodes = await dbContext.sqliteClient?.getTotpCodesForCredential(credential.Id) ?? [];+ // Get all items with their TOTP codes+ for (const item of items) {+ // Get TOTP codes for this item+ const totpCodes = await dbContext.sqliteClient?.getTotpCodesForItem(item.Id) ?? [];const totpSecret = totpCodes.length > 0 ? totpCodes[0].SecretKey : '';- /*- * For now, we'll use current date for CreatedAt/UpdatedAt since they're not available- * in the Credential type. In a production scenario, we'd want to extend the- * SqliteClient to fetch these fields.- */- const currentDate = formatDate(new Date().toISOString());+ // Convert item to credential format for backward compatibility with CSV export+ const credential = itemToCredential(item);++ // Get nickname from item fields (not in Credential type but needed for CSV)+ const nickName = getFieldValue(item, FieldKey.AliasNickname) ?? '';const record: ICredentialCsvRecord = {Version: '1.5.0',Username: credential.Username ?? '',Notes: credential.Notes ?? '',- CreatedAt: currentDate,- UpdatedAt: currentDate,+ CreatedAt: formatDate(item.CreatedAt),+ UpdatedAt: formatDate(item.UpdatedAt),AliasGender: credential.Alias?.Gender ?? '',AliasFirstName: credential.Alias?.FirstName ?? '',AliasLastName: credential.Alias?.LastName ?? '',- AliasNickName: credential.Alias?.NickName ?? '',+ AliasNickName: nickName,AliasBirthDate: credential.Alias?.BirthDate ? formatDate(credential.Alias.BirthDate) : '01/01/0001 00:00:00',AliasEmail: credential.Alias?.Email ?? '',ServiceName: credential.ServiceName ?? '',@@ -223,8 +223,8 @@ export default function ImportExportScreen(): React.ReactNode {const dateStr = new Date().toISOString().split('T')[0];// Export as CSV- const credentials = await dbContext.sqliteClient?.getAllCredentials() ?? [];- const csvContent = await credentialsToCsv(credentials);+ const items = await dbContext.sqliteClient?.getAllItems() ?? [];+ const csvContent = await itemsToCsv(items);const filename = `aliasvault-export-${dateStr}.csv`;const downloadsDir = FileSystem.documentDirectory + 'Exports/';diff --git a/apps/mobile-app/components/EmailCard.tsx b/apps/mobile-app/components/EmailCard.tsxindex c9cd42529..f8ac94c2f 100644--- a/apps/mobile-app/components/EmailCard.tsx+++ b/apps/mobile-app/components/EmailCard.tsx@@ -2,7 +2,7 @@ import { router } from 'expo-router';import { useEffect, useState } from 'react';import { StyleSheet, View } from 'react-native';-import type { Credential } from '@/utils/dist/core/models/vault';+import type { Item } from '@/utils/dist/core/models/vault';import type { MailboxEmail } from '@/utils/dist/core/models/webapi';import { useColors } from '@/hooks/useColorScheme';@@ -25,26 +25,26 @@ export function EmailCard({ email }: EmailCardProps) : React.ReactNode {const colors = useColors();const { t } = useTranslation();const dbContext = useDb();- const [associatedCredential, setAssociatedCredential] = useState<Credential | null>(null);+ const [associatedItem, setAssociatedItem] = useState<Item | null>(null);/**- * Load the associated credential for this email.+ * Load the associated item for this email.*/useEffect(() => {/**- * Load the credential associated with the email's recipient address.+ * Load the item associated with the email's recipient address.*/- const loadCredential = async (): Promise<void> => {+ const loadItem = async (): Promise<void> => {if (!dbContext?.sqliteClient || !email.toLocal || !email.toDomain) {return;}const emailAddress = `${email.toLocal}@${email.toDomain}`;- const credential = await dbContext.sqliteClient.getCredentialByEmail(emailAddress);- setAssociatedCredential(credential);+ const item = await dbContext.sqliteClient.getItemByEmail(emailAddress);+ setAssociatedItem(item);};- loadCredential();+ loadItem();}, [dbContext?.sqliteClient, email.toLocal, email.toDomain]);/**@@ -149,11 +149,11 @@ export function EmailCard({ email }: EmailCardProps) : React.ReactNode {<ThemedText style={styles.emailPreview} numberOfLines={2}>{email.messagePreview}</ThemedText>- {associatedCredential && (+ {associatedItem && (<View style={styles.serviceContainer}><IconSymbol size={14} name={IconSymbolName.Key} color={colors.primary} style={styles.serviceIcon} /><ThemedText style={styles.serviceName}>- {associatedCredential.ServiceName}+ {associatedItem.Name}</ThemedText></View>)}diff --git a/apps/mobile-app/hooks/useVaultMutate.ts b/apps/mobile-app/hooks/useVaultMutate.tsindex bf8b90861..5e958dcb8 100644--- a/apps/mobile-app/hooks/useVaultMutate.ts+++ b/apps/mobile-app/hooks/useVaultMutate.ts@@ -7,6 +7,7 @@ import srp from 'secure-remote-password/client';import type { EncryptionKeyDerivationParams } from '@/utils/dist/core/models/metadata';import type { PasswordChangeInitiateResponse, Vault, VaultPasswordChangeRequest } from '@/utils/dist/core/models/webapi';+import { FieldKey, getFieldValue } from '@/utils/dist/core/models/vault';import EncryptionUtility from '@/utils/EncryptionUtility';import { useVaultSync } from '@/hooks/useVaultSync';@@ -55,10 +56,10 @@ export function useVaultMutate() : {}const privateEmailDomains = await dbContext.sqliteClient!.getPrivateEmailDomains();- const credentials = await dbContext.sqliteClient!.getAllCredentials();- const privateEmailAddresses = credentials- .filter(cred => cred.Alias?.Email != null)- .map(cred => cred.Alias!.Email!)+ const items = await dbContext.sqliteClient!.items.getAll();+ const privateEmailAddresses = items+ .map(item => getFieldValue(item, FieldKey.LoginEmail))+ .filter((email): email is string => email != null && email !== '').filter((email, index, self) => self.indexOf(email) === index).filter(email => {return privateEmailDomains.some(domain => email.toLowerCase().endsWith(`@${domain.toLowerCase()}`));@@ -72,7 +73,7 @@ export function useVaultMutate() : {return {blob: encryptedDb,createdAt: new Date().toISOString(),- credentialsCount: credentials.length,+ credentialsCount: items.length,currentRevisionNumber: currentRevision,emailAddressList: privateEmailAddresses,privateEmailDomainList: [],@@ -88,65 +89,94 @@ export function useVaultMutate() : {/*** Execute the provided operation (e.g. create/update/delete credential)- * Now delegates to native layer for vault upload.+ *+ * Implements the mutation pattern from OFFLINE_MODE.md:+ * 1. Apply mutation to local database+ * 2. Export and encrypt+ * 3. Store locally with dirty flag (ATOMIC!)+ * 4. Sync in background (or immediately if blocking)*/const executeMutateOperation = useCallback(async (operation: () => Promise<void>,options: VaultMutationOptions- ) : Promise<void> => {+ ): Promise<void> => {setSyncStatus(t('vault.savingChangesToVault'));// Execute the provided operation (e.g. create/update/delete credential)// The operation should wrap its changes in beginTransaction/commitTransactionawait operation();+ // After the operation completes, the native layer has the updated encrypted database.+ // We need to store it with the isDirty flag set atomically.+ const encryptedDb = await NativeVaultManager.getEncryptedDatabase();+ if (!encryptedDb) {+ throw new Error(t('vault.errors.failedToGetEncryptedDatabase'));+ }++ // Store locally with dirty flag (atomic operation)+ await NativeVaultManager.storeEncryptedVaultWithSyncState(+ encryptedDb,+ true, // markDirty - increments mutation sequence and sets isDirty+ null, // serverRevision - don't change+ null // expectedMutationSeq - not checking for race (local mutation)+ );+setSyncStatus(t('vault.uploadingVaultToServer'));+ // Upload to servertry {- // Call native mutateVault which handles:- // - Preparing vault metadata (credentials count, email addresses, etc.)- // - Uploading to server- // - Updating revision number- // - Clearing offline mode on success- const result = await NativeVaultManager.mutateVault();-- // Verify success- if (result !== true) {- console.error('VaultMutate: Native mutateVault did not return true, result:', result);- throw new Error('Vault mutation did not complete successfully');- }+ const uploadResult = await NativeVaultManager.uploadVault();++ if (uploadResult.success) {+ // Mark vault clean only if no mutations happened during upload+ await NativeVaultManager.markVaultClean(+ uploadResult.mutationSeqAtStart,+ uploadResult.newRevisionNumber+ );++ // Register credential identities after successful mutation+ try {+ await NativeVaultManager.registerCredentialIdentities();+ } catch (error) {+ console.warn('VaultMutate: Failed to register credential identities:', error);+ }- // Register credential identities after successful mutation- try {- await NativeVaultManager.registerCredentialIdentities();- } catch (error) {- console.warn('VaultMutate: Failed to register credential identities:', error);- // Don't fail the mutation if credential registration fails+ options.onSuccess?.();+ } else if (uploadResult.status === 2) {+ // Vault outdated - need to sync first+ // The sync will handle merging our local changes+ console.log('[VaultMutate] Vault outdated, triggering sync');+ await syncVault({+ onSuccess: () => options.onSuccess?.(),+ onError: (error) => options.onError?.(new Error(error)),+ });+ } else {+ // Other error - keep isDirty true for next sync+ console.warn('[VaultMutate] Failed to upload vault:', uploadResult.error);++ // Check if it's a network error+ if (uploadResult.error?.includes('Network') || uploadResult.error?.includes('network')) {+ await NativeVaultManager.setOfflineMode(true);+ // Still call success - the local change is saved+ options.onSuccess?.();+ } else {+ options.onError?.(new Error(uploadResult.error ?? t('common.errors.unknownError')));+ }}-- // Success- options.onSuccess?.();} catch (error) {- console.error('VaultMutate: Error during vault mutation:', error);+ console.error('VaultMutate: Error during vault upload:', error);// Check if it's a network errorif (error instanceof Error && (error.message.includes('network') || error.message.includes('timeout'))) {- // Network error, mark as offline and track pending changesawait NativeVaultManager.setOfflineMode(true);+ // Still call success - the local change is saved and isDirty is setoptions.onSuccess?.();return;}- // Check for vault outdated error- if (error instanceof Error && error.message.includes('Vault is outdated')) {- options.onError?.(new Error(t('vault.errors.vaultOutdated')));- return;- }-- // Re-throw the error so it's handled by the calleroptions.onError?.(new Error(t('common.errors.unknownError')));}- }, [t]);+ }, [t, syncVault]);/*** Execute the provided operation (e.g. create/update/delete credential)diff --git a/apps/mobile-app/hooks/useVaultSync.ts b/apps/mobile-app/hooks/useVaultSync.tsindex d72042045..957acb826 100644--- a/apps/mobile-app/hooks/useVaultSync.ts+++ b/apps/mobile-app/hooks/useVaultSync.ts@@ -1,17 +1,24 @@-import { useCallback } from 'react';+import { useCallback, useRef } from 'react';-import { AppInfo } from '@/utils/AppInfo';-import type { VaultResponse } from '@/utils/dist/core/models/webapi';import { VaultAuthenticationError } from '@/utils/types/errors/VaultAuthenticationError';-import { useTranslation } from '@/hooks/useTranslation';import { useApp } from '@/context/AppContext';import { useDb } from '@/context/DbContext';-import { useWebApi } from '@/context/WebApiContext';import NativeVaultManager from '@/specs/NativeVaultManager';import { VaultVersionIncompatibleError } from '@/utils/types/errors/VaultVersionIncompatibleError';import { VaultSyncErrorCode, getVaultSyncErrorCode } from '@/utils/types/errors/VaultSyncErrorCodes';+import { VaultMergeService } from '@/utils/VaultMergeService';++/**+ * Sync state tracking for race detection and offline support.+ */+export type SyncState = {+ isDirty: boolean;+ mutationSequence: number;+ serverRevision: number;+ isSyncing: boolean;+};/*** Utility function to ensure a minimum time has elapsed for an operation@@ -35,21 +42,56 @@ type VaultSyncOptions = {onOffline?: () => void;onUpgradeRequired?: () => void;abortSignal?: AbortSignal;-}+ /** Internal retry count for race detection */+ _retryCount?: number;+};++/**+ * Maximum number of sync retries for race detection.+ */+const MAX_SYNC_RETRIES = 3;/*** Hook to sync the vault with the server.- * Now delegates core sync logic to native layer while keeping UI orchestration in React Native.+ *+ * Implements the offline sync pattern from OFFLINE_MODE.md:+ * 1. Check isDirty before overwriting local vault+ * 2. Upload pending changes - sync is responsible for uploading, not just downloading+ * 3. Race detection - use mutation sequence to detect concurrent edits+ * 4. Recursive retry - if race detected, restart sync*/-export const useVaultSync = () : {+export const useVaultSync = (): {syncVault: (options?: VaultSyncOptions) => Promise<boolean>;+ getSyncState: () => Promise<SyncState>;} => {const { t } = useTranslation();const app = useApp();const dbContext = useDb();+ const syncInProgressRef = useRef(false);++ const getSyncState = useCallback(async (): Promise<SyncState> => {+ return await NativeVaultManager.getSyncState();+ }, []);++ const syncVault = useCallback(async (options: VaultSyncOptions = {}): Promise<boolean> => {+ const { onSuccess, onError, onStatus, onOffline, onUpgradeRequired, abortSignal, _retryCount = 0 } = options;- const syncVault = useCallback(async (options: VaultSyncOptions = {}) => {- const { onSuccess, onError, onStatus, onOffline, onUpgradeRequired, abortSignal } = options;+ // Prevent infinite recursion+ if (_retryCount >= MAX_SYNC_RETRIES) {+ console.error('[useVaultSync] Max sync retries reached, aborting');+ onError?.('Sync failed after multiple retries');+ return false;+ }++ // Prevent concurrent syncs (only for the first call, not retries)+ if (_retryCount === 0 && syncInProgressRef.current) {+ console.log('[useVaultSync] Sync already in progress, skipping');+ return false;+ }++ if (_retryCount === 0) {+ syncInProgressRef.current = true;+ }try {// Check if operation was aborted@@ -61,101 +103,149 @@ export const useVaultSync = () : {const { isLoggedIn } = await app.initializeAuth();if (!isLoggedIn) {- // Not authenticated, return false immediatelyreturn false;}- // Check if operation was abortedif (abortSignal?.aborted) {console.debug('VaultSync: Operation aborted after auth check');return false;}- // Update status+ // Mark as syncing+ await NativeVaultManager.setIsSyncing(true);+onStatus?.(t('vault.checkingVaultUpdates'));- // Check if operation was aborted- if (abortSignal?.aborted) {- console.debug('VaultSync: Operation aborted after status update');- return false;+ // Capture sync state at start for race detection+ let versionCheck;+ try {+ versionCheck = await NativeVaultManager.checkVaultVersion();+ } catch (err) {+ const errorCode = getVaultSyncErrorCode(err);+ return await handleSyncError(err, errorCode, app, t, onError, onOffline);}- // Step 1: Check if a new vault version is available- // This calls Auth/status endpoint and compares vault revisions- let hasNewVault = false;- let newRevision: number | null = null;+ const { isNewVersionAvailable, serverRevision, syncState } = versionCheck;+ const mutationSeqAtStart = syncState.mutationSequence;+ const isDirty = syncState.isDirty;- try {- const versionCheckResult = await NativeVaultManager.isNewVaultVersionAvailable();-- // Check if operation was aborted after version check- if (abortSignal?.aborted) {- console.debug('VaultSync: Operation aborted after version check');- return false;- }+ if (abortSignal?.aborted) {+ console.debug('VaultSync: Operation aborted after version check');+ return false;+ }- hasNewVault = versionCheckResult.isNewVersionAvailable;- newRevision = versionCheckResult.newRevision;+ if (serverRevision > syncState.serverRevision) {+ // Server has newer vault - download it+ onStatus?.(t('vault.syncingUpdatedVault'));- // Step 2: If a new version is available, download it- if (hasNewVault && newRevision != null) {- // Check if operation was aborted before download- if (abortSignal?.aborted) {- console.debug('VaultSync: Operation aborted before download');- return false;+ try {+ const serverVaultResponse = await NativeVaultManager.fetchServerVault();++ if (isDirty) {+ // CRITICAL: We have local changes - must merge!+ console.log('[useVaultSync] Local changes detected, merging with server vault');+ onStatus?.(t('vault.mergingVault'));++ const localVault = await NativeVaultManager.getEncryptedDatabase();+ if (!localVault) {+ throw new Error('No local vault available for merge');+ }++ // Perform LWW merge+ // Note: For now, VaultMergeService returns localVault as placeholder.+ // Full merge implementation will use Rust core library via native bindings.+ const mergedVault = await VaultMergeService.mergeVaults(+ localVault,+ serverVaultResponse.vault.blob,+ null // Encryption key not needed for current placeholder implementation+ );++ // Store merged vault with race detection+ const storeResult = await NativeVaultManager.storeEncryptedVaultWithSyncState(+ mergedVault,+ false, // Not marking dirty - this is a sync operation+ null, // Server revision will be updated after upload+ mutationSeqAtStart+ );++ if (!storeResult.success) {+ // Race detected - concurrent mutation happened during sync+ console.log('[useVaultSync] Race detected during merge, retrying sync');+ await NativeVaultManager.setIsSyncing(false);+ return syncVault({ ...options, _retryCount: _retryCount + 1 });+ }++ // Upload merged vault to server+ const uploadResult = await NativeVaultManager.uploadVault();++ if (uploadResult.success) {+ // Mark vault clean only if no mutations happened during upload+ await NativeVaultManager.markVaultClean(mutationSeqAtStart, uploadResult.newRevisionNumber);+ } else if (uploadResult.status === 2) {+ // Vault outdated - server moved forward, retry sync+ console.log('[useVaultSync] Vault outdated during upload, retrying sync');+ await NativeVaultManager.setIsSyncing(false);+ return syncVault({ ...options, _retryCount: _retryCount + 1 });+ } else {+ console.warn('[useVaultSync] Failed to upload merged vault:', uploadResult.error);+ // Keep isDirty true for next sync attempt+ }+ } else {+ // No local changes - safe to overwrite with server vault+ const storeResult = await NativeVaultManager.storeEncryptedVaultWithSyncState(+ serverVaultResponse.vault.blob,+ false,+ serverRevision,+ mutationSeqAtStart+ );++ if (!storeResult.success) {+ // Race detected - mutation happened during download+ console.log('[useVaultSync] Race detected during download, retrying sync');+ await NativeVaultManager.setIsSyncing(false);+ return syncVault({ ...options, _retryCount: _retryCount + 1 });+ }}-- onStatus?.(t('vault.syncingUpdatedVault'));-- // Run downloadVault with a min delay for UX purposes- await withMinimumDelay(- () => NativeVaultManager.downloadVault(newRevision!),- 300- );+ } catch (err) {+ console.error('[useVaultSync] Error during vault download/merge:', err);+ const errorCode = getVaultSyncErrorCode(err);+ await NativeVaultManager.setIsSyncing(false);+ return await handleSyncError(err, errorCode, app, t, onError, onOffline);}- } catch (err) {- console.error('VaultSync: syncVault error:', err);-- // Get the error code from the native layer- const errorCode = getVaultSyncErrorCode(err);+ } else if (serverRevision === syncState.serverRevision && isDirty) {+ // Local changes at same revision - upload them!+ console.log('[useVaultSync] Uploading local changes to server');+ onStatus?.(t('vault.uploadingChanges'));- // Handle specific error codes- switch (errorCode) {- case VaultSyncErrorCode.SESSION_EXPIRED:- case VaultSyncErrorCode.AUTHENTICATION_FAILED:- await app.logout('Your session has expired. Please login again.');- return false;-- case VaultSyncErrorCode.PASSWORD_CHANGED:- await app.logout(t('vault.errors.passwordChanged'));- return false;-- case VaultSyncErrorCode.CLIENT_VERSION_NOT_SUPPORTED:- onError?.(t('vault.errors.versionNotSupported'));- return false;-- case VaultSyncErrorCode.SERVER_VERSION_NOT_SUPPORTED:- await app.logout(t('vault.errors.serverVersionNotSupported'));- return false;-- case VaultSyncErrorCode.SERVER_UNAVAILABLE:- onOffline?.();- return false;-- case VaultSyncErrorCode.NETWORK_ERROR:- case VaultSyncErrorCode.TIMEOUT:- onOffline?.();- return false;-- default:- // Unknown error or no error code - rethrow- throw err;+ try {+ const uploadResult = await NativeVaultManager.uploadVault();++ if (uploadResult.success) {+ // Mark vault clean only if no mutations happened during upload+ await NativeVaultManager.markVaultClean(mutationSeqAtStart, uploadResult.newRevisionNumber);+ } else if (uploadResult.status === 2) {+ // Vault outdated - another device uploaded, retry to merge+ console.log('[useVaultSync] Vault outdated, another device uploaded, retrying sync');+ await NativeVaultManager.setIsSyncing(false);+ return syncVault({ ...options, _retryCount: _retryCount + 1 });+ } else {+ console.warn('[useVaultSync] Failed to upload vault:', uploadResult.error);+ // Keep isDirty true for next sync attempt+ }+ } catch (err) {+ console.error('[useVaultSync] Error during vault upload:', err);+ const errorCode = getVaultSyncErrorCode(err);+ await NativeVaultManager.setIsSyncing(false);+ return await handleSyncError(err, errorCode, app, t, onError, onOffline);}}+ // else: Already in sync - nothing to do+ // Mark syncing as complete+ await NativeVaultManager.setIsSyncing(false);++ // Unlock vault to refresh database connectiontry {- // We always re-unlock the vault to force reload of database connection- // This ensures React Native's SQLite connection sees changes made by native layerawait NativeVaultManager.unlockVault();// Check if the vault needs migration@@ -164,36 +254,35 @@ export const useVaultSync = () : {return false;}- onSuccess?.(hasNewVault);+ onSuccess?.(isNewVersionAvailable);// Register credential identities after synctry {await NativeVaultManager.registerCredentialIdentities();} catch (error) {console.warn('Vault sync: Failed to register credential identities:', error);- // Don't fail the sync if credential registration fails}- return hasNewVault;- } catch (err: any) {+ return isNewVersionAvailable;+ } catch (err) {if (err instanceof VaultVersionIncompatibleError) {await app.logout(t(err.message));return false;}- // Log detailed error information for database setup failures- if (err?.code === 'DATABASE_SETUP_ERROR') {- console.error('Database setup error during unlock:', err.message);- throw new Error(t('common.errors.unknownErrorTryAgain'));- }-- // Vault could not be unlockedconsole.error('Failed to unlock vault:', err);throw new Error(t('common.errors.unknownErrorTryAgain'));}} catch (err) {console.error('Vault sync error:', err);+ // Ensure syncing flag is cleared on error+ try {+ await NativeVaultManager.setIsSyncing(false);+ } catch {+ // Ignore+ }+// Handle authentication errorsif (err instanceof VaultAuthenticationError) {await app.logout(err.message);@@ -208,44 +297,63 @@ export const useVaultSync = () : {// Check if it's a vault sync error with error codeconst errorCode = getVaultSyncErrorCode(err);if (errorCode) {- switch (errorCode) {- case VaultSyncErrorCode.SESSION_EXPIRED:- case VaultSyncErrorCode.AUTHENTICATION_FAILED:- await app.logout('Your session has expired. Please login again.');- return false;-- case VaultSyncErrorCode.PASSWORD_CHANGED:- await app.logout(t('vault.errors.passwordChanged'));- return false;-- case VaultSyncErrorCode.CLIENT_VERSION_NOT_SUPPORTED:- onError?.(t('vault.errors.versionNotSupported'));- return false;-- case VaultSyncErrorCode.SERVER_VERSION_NOT_SUPPORTED:- await app.logout(t('vault.errors.serverVersionNotSupported'));- return false;-- case VaultSyncErrorCode.SERVER_UNAVAILABLE:- await NativeVaultManager.setOfflineMode(true);- return true;-- case VaultSyncErrorCode.NETWORK_ERROR:- case VaultSyncErrorCode.TIMEOUT:- await NativeVaultManager.setOfflineMode(true);- return true;-- default:- // Let the error be handled below- break;- }+ return await handleSyncError(err, errorCode, app, t, onError, onOffline);}const errorMessage = err instanceof Error ? err.message : t('common.errors.unknownError');onError?.(errorMessage);return false;+ } finally {+ if (_retryCount === 0) {+ syncInProgressRef.current = false;+ }}}, [app, dbContext, t]);- return { syncVault };-};\ No newline at end of file+ return { syncVault, getSyncState };+};++/**+ * Handle sync errors by mapping error codes to appropriate actions.+ */+async function handleSyncError(+ err: unknown,+ errorCode: VaultSyncErrorCode | null,+ app: ReturnType<typeof useApp>,+ t: (key: string) => string,+ onError?: (error: string) => void,+ onOffline?: () => void+): Promise<boolean> {+ switch (errorCode) {+ case VaultSyncErrorCode.SESSION_EXPIRED:+ case VaultSyncErrorCode.AUTHENTICATION_FAILED:+ await app.logout('Your session has expired. Please login again.');+ return false;++ case VaultSyncErrorCode.PASSWORD_CHANGED:+ await app.logout(t('vault.errors.passwordChanged'));+ return false;++ case VaultSyncErrorCode.CLIENT_VERSION_NOT_SUPPORTED:+ onError?.(t('vault.errors.versionNotSupported'));+ return false;++ case VaultSyncErrorCode.SERVER_VERSION_NOT_SUPPORTED:+ await app.logout(t('vault.errors.serverVersionNotSupported'));+ return false;++ case VaultSyncErrorCode.SERVER_UNAVAILABLE:+ case VaultSyncErrorCode.NETWORK_ERROR:+ case VaultSyncErrorCode.TIMEOUT:+ await NativeVaultManager.setOfflineMode(true);+ onOffline?.();+ // Return true to continue with local vault+ return true;++ default:+ // Unknown error+ const errorMessage = err instanceof Error ? err.message : t('common.errors.unknownError');+ onError?.(errorMessage);+ return false;+ }+}diff --git a/apps/mobile-app/i18n/locales/en.json b/apps/mobile-app/i18n/locales/en.jsonindex cea88108d..99d06d147 100644--- a/apps/mobile-app/i18n/locales/en.json+++ b/apps/mobile-app/i18n/locales/en.json@@ -82,6 +82,8 @@"executingOperation": "Executing operation...","checkingVaultUpdates": "Checking vault updates","syncingUpdatedVault": "Syncing updated vault",+ "mergingVault": "Merging vault changes",+ "uploadingChanges": "Uploading changes","errors": {"failedToGetEncryptedDatabase": "Failed to get encrypted database","usernameNotFound": "Username not found",diff --git a/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj b/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxprojindex 35b0ea342..a33439843 100644--- a/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj+++ b/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj@@ -3,7 +3,7 @@archiveVersion = 1;classes = {};- objectVersion = 60;+ objectVersion = 70;objects = {/* Begin PBXBuildFile section */@@ -212,7 +212,7 @@/* End PBXFileReference section *//* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */- CEE9098F2DA548C7008D568F /* Exceptions for "Autofill" folder in "Autofill" target */ = {+ CEE9098F2DA548C7008D568F /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {isa = PBXFileSystemSynchronizedBuildFileExceptionSet;membershipExceptions = (Info.plist,@@ -222,84 +222,13 @@/* End PBXFileSystemSynchronizedBuildFileExceptionSet section *//* Begin PBXFileSystemSynchronizedRootGroup section */- CE59C7602E4F47FD0024A246 /* VaultUITests */ = {- isa = PBXFileSystemSynchronizedRootGroup;- exceptions = (- );- explicitFileTypes = {- };- explicitFolders = (- );- path = VaultUITests;- sourceTree = "<group>";- };- CE77825E2EA1822400A75E6F /* VaultUtils */ = {- isa = PBXFileSystemSynchronizedRootGroup;- exceptions = (- );- explicitFileTypes = {- };- explicitFolders = (- );- path = VaultUtils;- sourceTree = "<group>";- };- CEE480882DBE86DC00F4A367 /* VaultStoreKit */ = {- isa = PBXFileSystemSynchronizedRootGroup;- exceptions = (- );- explicitFileTypes = {- };- explicitFolders = (- );- path = VaultStoreKit;- sourceTree = "<group>";- };- CEE480972DBE86DD00F4A367 /* VaultStoreKitTests */ = {- isa = PBXFileSystemSynchronizedRootGroup;- exceptions = (- );- explicitFileTypes = {- };- explicitFolders = (- );- path = VaultStoreKitTests;- sourceTree = "<group>";- };- CEE4816B2DBE8AC800F4A367 /* VaultUI */ = {- isa = PBXFileSystemSynchronizedRootGroup;- exceptions = (- );- explicitFileTypes = {- };- explicitFolders = (- );- path = VaultUI;- sourceTree = "<group>";- };- CEE482AB2DBE8EFE00F4A367 /* VaultModels */ = {- isa = PBXFileSystemSynchronizedRootGroup;- exceptions = (- );- explicitFileTypes = {- };- explicitFolders = (- );- path = VaultModels;- sourceTree = "<group>";- };- CEE909812DA548C7008D568F /* Autofill */ = {- isa = PBXFileSystemSynchronizedRootGroup;- exceptions = (- CEE9098F2DA548C7008D568F /* Exceptions for "Autofill" folder in "Autofill" target */,- );- explicitFileTypes = {- };- explicitFolders = (- );- path = Autofill;- sourceTree = "<group>";- };+ CE59C7602E4F47FD0024A246 /* VaultUITests */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultUITests; sourceTree = "<group>"; };+ CE77825E2EA1822400A75E6F /* VaultUtils */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultUtils; sourceTree = "<group>"; };+ CEE480882DBE86DC00F4A367 /* VaultStoreKit */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultStoreKit; sourceTree = "<group>"; };+ CEE480972DBE86DD00F4A367 /* VaultStoreKitTests */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultStoreKitTests; sourceTree = "<group>"; };+ CEE4816B2DBE8AC800F4A367 /* VaultUI */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultUI; sourceTree = "<group>"; };+ CEE482AB2DBE8EFE00F4A367 /* VaultModels */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultModels; sourceTree = "<group>"; };+ CEE909812DA548C7008D568F /* Autofill */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (CEE9098F2DA548C7008D568F /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = Autofill; sourceTree = "<group>"; };/* End PBXFileSystemSynchronizedRootGroup section *//* Begin PBXFrameworksBuildPhase section */@@ -1420,10 +1349,7 @@LIBRARY_SEARCH_PATHS = "$(SDKROOT)/usr/lib/swift\"$(inherited)\"";MTL_ENABLE_DEBUG_INFO = YES;ONLY_ACTIVE_ARCH = YES;- OTHER_LDFLAGS = (- "$(inherited)",- " ",- );+ OTHER_LDFLAGS = "$(inherited) ";REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native";SDKROOT = iphoneos;SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) DEBUG";@@ -1477,10 +1403,7 @@);LIBRARY_SEARCH_PATHS = "$(SDKROOT)/usr/lib/swift\"$(inherited)\"";MTL_ENABLE_DEBUG_INFO = NO;- OTHER_LDFLAGS = (- "$(inherited)",- " ",- );+ OTHER_LDFLAGS = "$(inherited) ";REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native";SDKROOT = iphoneos;USE_HERMES = true;diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mmindex 7152e3128..122a56972 100644--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm@@ -261,6 +261,40 @@[vaultManager mutateVault:resolve rejecter:reject];}+// MARK: - Sync State Management++- (void)getSyncState:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {+ [vaultManager getSyncState:resolve rejecter:reject];+}++- (void)setIsDirty:(BOOL)isDirty resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {+ [vaultManager setIsDirty:isDirty resolver:resolve rejecter:reject];+}++- (void)setIsSyncing:(BOOL)isSyncing resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {+ [vaultManager setIsSyncing:isSyncing resolver:resolve rejecter:reject];+}++- (void)storeEncryptedVaultWithSyncState:(NSString *)encryptedVault markDirty:(BOOL)markDirty serverRevision:(NSNumber *)serverRevision expectedMutationSeq:(NSNumber *)expectedMutationSeq resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {+ [vaultManager storeEncryptedVaultWithSyncState:encryptedVault markDirty:markDirty serverRevision:serverRevision expectedMutationSeq:expectedMutationSeq resolver:resolve rejecter:reject];+}++- (void)markVaultClean:(double)mutationSeqAtStart newServerRevision:(double)newServerRevision resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {+ [vaultManager markVaultClean:(NSInteger)mutationSeqAtStart newServerRevision:(NSInteger)newServerRevision resolver:resolve rejecter:reject];+}++- (void)uploadVault:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {+ [vaultManager uploadVault:resolve rejecter:reject];+}++- (void)fetchServerVault:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {+ [vaultManager fetchServerVault:resolve rejecter:reject];+}++- (void)checkVaultVersion:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {+ [vaultManager checkVaultVersion:resolve rejecter:reject];+}+// MARK: - PIN Unlock- (void)isPinEnabled:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swiftindex 535b7a4c7..717d35c59 100644--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift@@ -1017,6 +1017,167 @@ public class VaultManager: NSObject {}}+ // MARK: - Sync State Management++ @objc+ func getSyncState(_ resolve: @escaping RCTPromiseResolveBlock,+ rejecter reject: @escaping RCTPromiseRejectBlock) {+ let syncState = vaultStore.getSyncState()+ let result: [String: Any] = [+ "isDirty": syncState.isDirty,+ "mutationSequence": syncState.mutationSequence,+ "serverRevision": syncState.serverRevision,+ "isSyncing": syncState.isSyncing+ ]+ resolve(result)+ }++ @objc+ func setIsDirty(_ isDirty: Bool,+ resolver resolve: @escaping RCTPromiseResolveBlock,+ rejecter reject: @escaping RCTPromiseRejectBlock) {+ vaultStore.setIsDirty(isDirty)+ resolve(nil)+ }++ @objc+ func setIsSyncing(_ isSyncing: Bool,+ resolver resolve: @escaping RCTPromiseResolveBlock,+ rejecter reject: @escaping RCTPromiseRejectBlock) {+ vaultStore.setIsSyncing(isSyncing)+ resolve(nil)+ }++ @objc+ func storeEncryptedVaultWithSyncState(_ encryptedVault: String,+ markDirty: Bool,+ serverRevision: NSNumber?,+ expectedMutationSeq: NSNumber?,+ resolver resolve: @escaping RCTPromiseResolveBlock,+ rejecter reject: @escaping RCTPromiseRejectBlock) {+ do {+ let result = try vaultStore.storeEncryptedVaultWithSyncState(+ encryptedVault: encryptedVault,+ markDirty: markDirty,+ serverRevision: serverRevision?.intValue,+ expectedMutationSeq: expectedMutationSeq?.intValue+ )+ let response: [String: Any] = [+ "success": result.success,+ "mutationSequence": result.mutationSequence+ ]+ resolve(response)+ } catch {+ reject("STORE_VAULT_ERROR", "Failed to store vault: \(error.localizedDescription)", error)+ }+ }++ @objc+ func markVaultClean(_ mutationSeqAtStart: Int,+ newServerRevision: Int,+ resolver resolve: @escaping RCTPromiseResolveBlock,+ rejecter reject: @escaping RCTPromiseRejectBlock) {+ let cleared = vaultStore.markVaultClean(mutationSeqAtStart: mutationSeqAtStart, newServerRevision: newServerRevision)+ resolve(cleared)+ }++ @objc+ func uploadVault(_ resolve: @escaping RCTPromiseResolveBlock,+ rejecter reject: @escaping RCTPromiseRejectBlock) {+ Task {+ do {+ let result = try await vaultStore.uploadVault(using: webApiService)+ await MainActor.run {+ let response: [String: Any] = [+ "success": result.success,+ "status": result.status,+ "newRevisionNumber": result.newRevisionNumber,+ "mutationSeqAtStart": result.mutationSeqAtStart,+ "error": result.error as Any+ ]+ resolve(response)+ }+ } catch {+ await MainActor.run {+ reject("UPLOAD_VAULT_ERROR", "Failed to upload vault: \(error.localizedDescription)", error)+ }+ }+ }+ }++ @objc+ func fetchServerVault(_ resolve: @escaping RCTPromiseResolveBlock,+ rejecter reject: @escaping RCTPromiseRejectBlock) {+ Task {+ do {+ let vaultResponse = try await vaultStore.fetchServerVault(using: webApiService)++ // Convert VaultResponse to dictionary for React Native+ let vaultDict: [String: Any] = [+ "status": vaultResponse.status,+ "vault": [+ "username": vaultResponse.vault.username,+ "blob": vaultResponse.vault.blob,+ "version": vaultResponse.vault.version,+ "currentRevisionNumber": vaultResponse.vault.currentRevisionNumber,+ "encryptionPublicKey": vaultResponse.vault.encryptionPublicKey,+ "credentialsCount": vaultResponse.vault.credentialsCount,+ "emailAddressList": vaultResponse.vault.emailAddressList,+ "privateEmailDomainList": vaultResponse.vault.privateEmailDomainList,+ "hiddenPrivateEmailDomainList": vaultResponse.vault.hiddenPrivateEmailDomainList,+ "publicEmailDomainList": vaultResponse.vault.publicEmailDomainList,+ "createdAt": vaultResponse.vault.createdAt,+ "updatedAt": vaultResponse.vault.updatedAt+ ]+ ]++ await MainActor.run {+ resolve(vaultDict)+ }+ } catch {+ await MainActor.run {+ if let syncError = error as? VaultSyncError {+ reject(syncError.code, syncError.message, error)+ } else {+ reject("FETCH_VAULT_ERROR", "Failed to fetch vault: \(error.localizedDescription)", error)+ }+ }+ }+ }+ }++ @objc+ func checkVaultVersion(_ resolve: @escaping RCTPromiseResolveBlock,+ rejecter reject: @escaping RCTPromiseRejectBlock) {+ Task {+ do {+ let result = try await vaultStore.checkVaultVersion(using: webApiService)+ await MainActor.run {+ let response: [String: Any] = [+ "isNewVersionAvailable": result.isNewVersionAvailable,+ "newRevision": result.newRevision as Any,+ "serverRevision": result.serverRevision,+ "syncState": [+ "isDirty": result.syncState.isDirty,+ "mutationSequence": result.syncState.mutationSequence,+ "serverRevision": result.syncState.serverRevision,+ "isSyncing": result.syncState.isSyncing+ ]+ ]+ resolve(response)+ }+ } catch {+ await MainActor.run {+ if let syncError = error as? VaultSyncError {+ reject(syncError.code, syncError.message, error)+ } else {+ reject("CHECK_VERSION_ERROR", "Failed to check vault version: \(error.localizedDescription)", error)+ }+ }+ }+ }+ }+@objcfunc requiresMainQueueSetup() -> Bool {return falsediff --git a/apps/mobile-app/ios/VaultModels/Item.swift b/apps/mobile-app/ios/VaultModels/Item.swiftnew file mode 100644index 000000000..22b8598e1--- /dev/null+++ b/apps/mobile-app/ios/VaultModels/Item.swift@@ -0,0 +1,122 @@+import Foundation++/// Item type representing vault entries in the new field-based data model.+public struct Item: Codable, Hashable, Equatable {+ public let id: UUID+ public let name: String?+ public let itemType: String+ public let logo: Data?+ public let folderId: UUID?+ public let folderPath: String?+ public let fields: [ItemField]+ public let hasPasskey: Bool+ public let hasAttachment: Bool+ public let hasTotp: Bool+ public let createdAt: Date+ public let updatedAt: Date++ public init(+ id: UUID,+ name: String?,+ itemType: String,+ logo: Data?,+ folderId: UUID?,+ folderPath: String?,+ fields: [ItemField],+ hasPasskey: Bool,+ hasAttachment: Bool,+ hasTotp: Bool,+ createdAt: Date,+ updatedAt: Date+ ) {+ self.id = id+ self.name = name+ self.itemType = itemType+ self.logo = logo+ self.folderId = folderId+ self.folderPath = folderPath+ self.fields = fields+ self.hasPasskey = hasPasskey+ self.hasAttachment = hasAttachment+ self.hasTotp = hasTotp+ self.createdAt = createdAt+ self.updatedAt = updatedAt+ }++ public static func == (lhs: Item, rhs: Item) -> Bool {+ return lhs.id == rhs.id+ }++ public func hash(into hasher: inout Hasher) {+ hasher.combine(id)+ }++ // MARK: - Field Accessors++ /// Get the value of a field by its key.+ public func getFieldValue(_ fieldKey: String) -> String? {+ return fields.first { $0.fieldKey == fieldKey }?.value+ }++ /// Get the URL field value (login.url).+ public var url: String? {+ return getFieldValue(FieldKey.loginUrl)+ }++ /// Get the username field value (login.username).+ public var username: String? {+ return getFieldValue(FieldKey.loginUsername)+ }++ /// Get the password field value (login.password).+ public var password: String? {+ return getFieldValue(FieldKey.loginPassword)+ }++ /// Get the email field value (login.email).+ public var email: String? {+ return getFieldValue(FieldKey.loginEmail)+ }++ /// Get the first name field value (alias.first_name).+ public var firstName: String? {+ return getFieldValue(FieldKey.aliasFirstName)+ }++ /// Get the last name field value (alias.last_name).+ public var lastName: String? {+ return getFieldValue(FieldKey.aliasLastName)+ }+}++/// Field value within an item.+public struct ItemField: Codable, Hashable {+ public let fieldKey: String+ public let label: String+ public let fieldType: String+ public let value: String+ public let isHidden: Bool+ public let displayOrder: Int+ public let isCustomField: Bool+ public let enableHistory: Bool++ public init(+ fieldKey: String,+ label: String,+ fieldType: String,+ value: String,+ isHidden: Bool,+ displayOrder: Int,+ isCustomField: Bool,+ enableHistory: Bool+ ) {+ self.fieldKey = fieldKey+ self.label = label+ self.fieldType = fieldType+ self.value = value+ self.isHidden = isHidden+ self.displayOrder = displayOrder+ self.isCustomField = isCustomField+ self.enableHistory = enableHistory+ }+}diff --git a/apps/mobile-app/ios/VaultStoreKit/Constants/VaultConstants.swift b/apps/mobile-app/ios/VaultStoreKit/Constants/VaultConstants.swiftindex febfc9082..7b66fde5f 100644--- a/apps/mobile-app/ios/VaultStoreKit/Constants/VaultConstants.swift+++ b/apps/mobile-app/ios/VaultStoreKit/Constants/VaultConstants.swift@@ -18,5 +18,10 @@ public struct VaultConstants {static let pinEnabledKey = "aliasvault_pin_enabled"static let serverVersionKey = "aliasvault_server_version"+ // Sync state keys (for offline sync and race detection)+ static let isDirtyKey = "aliasvault_is_dirty"+ static let mutationSequenceKey = "aliasvault_mutation_sequence"+ static let isSyncingKey = "aliasvault_is_syncing"+static let defaultAutoLockTimeout: Int = 3600 // 1 hour in seconds}diff --git a/apps/mobile-app/ios/VaultStoreKit/Repository/BaseRepository.swift b/apps/mobile-app/ios/VaultStoreKit/Repository/BaseRepository.swiftnew file mode 100644index 000000000..63723ad03--- /dev/null+++ b/apps/mobile-app/ios/VaultStoreKit/Repository/BaseRepository.swift@@ -0,0 +1,126 @@+import Foundation+import VaultUtils++/// Base repository class with common database operations.+/// Provides transaction handling, soft delete, and other shared functionality.+public class BaseRepository {+ /// The database client used for executing queries.+ internal let client: DatabaseClient++ /// Initialize the repository with a database client.+ /// - Parameter client: The database client to use+ public init(client: DatabaseClient) {+ self.client = client+ }++ // MARK: - Transaction Helpers++ /// Execute a function within a transaction.+ /// Automatically handles begin, commit, and rollback.+ /// - Parameter operation: The function to execute within the transaction+ /// - Returns: The result of the function+ public func withTransaction<T>(_ operation: () throws -> T) throws -> T {+ try client.beginTransaction()+ do {+ let result = try operation()+ try client.commitTransaction()+ return result+ } catch {+ try? client.rollbackTransaction()+ throw error+ }+ }++ // MARK: - Soft Delete Helpers++ /// Soft delete a record by setting IsDeleted = 1.+ /// - Parameters:+ /// - table: The table name+ /// - id: The record ID+ /// - Returns: Number of rows affected+ @discardableResult+ public func softDelete(table: String, id: String) throws -> Int {+ let timestamp = DateHelpers.now()+ return try client.executeUpdate(+ "UPDATE \(table) SET IsDeleted = 1, UpdatedAt = ? WHERE Id = ?",+ params: [timestamp, id]+ )+ }++ /// Soft delete records by a foreign key.+ /// - Parameters:+ /// - table: The table name+ /// - foreignKey: The foreign key column name+ /// - foreignKeyValue: The foreign key value+ /// - Returns: Number of rows affected+ @discardableResult+ public func softDeleteByForeignKey(table: String, foreignKey: String, foreignKeyValue: String) throws -> Int {+ let timestamp = DateHelpers.now()+ return try client.executeUpdate(+ "UPDATE \(table) SET IsDeleted = 1, UpdatedAt = ? WHERE \(foreignKey) = ?",+ params: [timestamp, foreignKeyValue]+ )+ }++ // MARK: - Hard Delete Helpers++ /// Hard delete a record permanently.+ /// - Parameters:+ /// - table: The table name+ /// - id: The record ID+ /// - Returns: Number of rows affected+ @discardableResult+ public func hardDelete(table: String, id: String) throws -> Int {+ return try client.executeUpdate(+ "DELETE FROM \(table) WHERE Id = ?",+ params: [id]+ )+ }++ /// Hard delete records by a foreign key.+ /// - Parameters:+ /// - table: The table name+ /// - foreignKey: The foreign key column name+ /// - foreignKeyValue: The foreign key value+ /// - Returns: Number of rows affected+ @discardableResult+ public func hardDeleteByForeignKey(table: String, foreignKey: String, foreignKeyValue: String) throws -> Int {+ return try client.executeUpdate(+ "DELETE FROM \(table) WHERE \(foreignKey) = ?",+ params: [foreignKeyValue]+ )+ }++ // MARK: - Utility Methods++ /// Check if a table exists in the database.+ /// - Parameter tableName: The name of the table to check+ /// - Returns: True if the table exists+ public func tableExists(_ tableName: String) throws -> Bool {+ let results = try client.executeQuery(+ "SELECT name FROM sqlite_master WHERE type='table' AND name=?",+ params: [tableName]+ )+ return !results.isEmpty+ }++ /// Generate a new UUID in uppercase format.+ /// - Returns: A new UUID string+ public func generateId() -> String {+ return UUID().uuidString.uppercased()+ }++ /// Get the current timestamp in the standard format.+ /// - Returns: Current timestamp string+ public func now() -> String {+ return DateHelpers.now()+ }++ /// Build a parameterized IN clause for SQL queries.+ /// - Parameter values: Array of values for the IN clause+ /// - Returns: Tuple with placeholders string and values array+ public func buildInClause(_ values: [String]) -> (placeholders: String, values: [String]) {+ let placeholders = values.map { _ in "?" }.joined(separator: ",")+ return (placeholders, values)+ }+}diff --git a/apps/mobile-app/ios/VaultStoreKit/Repository/DatabaseClient.swift b/apps/mobile-app/ios/VaultStoreKit/Repository/DatabaseClient.swiftnew file mode 100644index 000000000..f168c670d--- /dev/null+++ b/apps/mobile-app/ios/VaultStoreKit/Repository/DatabaseClient.swift@@ -0,0 +1,32 @@+import Foundation+import SQLite++/// Type alias for SQLite bind values.+public typealias SqliteBindValue = Binding?++/// Protocol for core database operations needed by repositories.+/// Abstracts the SQLite database connection to allow for testing and flexibility.+public protocol DatabaseClient: AnyObject {+ /// Execute a SELECT query and return results as an array of dictionaries.+ /// - Parameters:+ /// - query: The SQL query to execute+ /// - params: The parameters to bind to the query+ /// - Returns: Array of dictionaries representing the result rows+ func executeQuery(_ query: String, params: [SqliteBindValue]) throws -> [[String: Any]]++ /// Execute an UPDATE, INSERT, or DELETE query.+ /// - Parameters:+ /// - query: The SQL query to execute+ /// - params: The parameters to bind to the query+ /// - Returns: Number of rows affected+ func executeUpdate(_ query: String, params: [SqliteBindValue]) throws -> Int++ /// Begin a database transaction.+ func beginTransaction() throws++ /// Commit a database transaction.+ func commitTransaction() throws++ /// Rollback a database transaction.+ func rollbackTransaction() throws+}diff --git a/apps/mobile-app/ios/VaultStoreKit/Repository/ItemRepository.swift b/apps/mobile-app/ios/VaultStoreKit/Repository/ItemRepository.swiftnew file mode 100644index 000000000..04649c507--- /dev/null+++ b/apps/mobile-app/ios/VaultStoreKit/Repository/ItemRepository.swift@@ -0,0 +1,297 @@+import Foundation+import VaultModels++/// Repository for Item CRUD operations.+/// Handles fetching, creating, updating, and deleting items with their related data.+public class ItemRepository: BaseRepository {++ // MARK: - Read Operations++ /// Fetch all active items (not deleted, not in trash) with their fields.+ /// - Returns: Array of Item objects+ public func getAll() throws -> [Item] {+ // 1. Fetch all item rows+ let itemResults = try client.executeQuery(ItemQueries.getAllActive, params: [])+ let itemRows = itemResults.compactMap { ItemRow(from: $0) }++ if itemRows.isEmpty {+ return []+ }++ // 2. Fetch field values for all items+ let itemIds = itemRows.map { $0.id }+ let fieldQuery = ItemQueries.getFieldValuesForItems(itemIds.count)+ let fieldResults = try client.executeQuery(fieldQuery, params: itemIds.map { $0 as SqliteBindValue })+ let fieldRows = fieldResults.compactMap { FieldRow(from: $0) }++ // 3. Process fields into a dictionary by ItemId+ let fieldsByItem = FieldMapper.processFieldRows(fieldRows)++ // 4. Map rows to Item objects+ return ItemMapper.mapRows(itemRows, fieldsByItem: fieldsByItem)+ }++ /// Fetch a single item by ID with its fields.+ /// - Parameter itemId: The ID of the item to fetch+ /// - Returns: Item object or nil if not found+ public func getById(_ itemId: String) throws -> Item? {+ // 1. Fetch item row+ let itemResults = try client.executeQuery(ItemQueries.getById, params: [itemId])+ guard let itemRow = itemResults.first.flatMap({ ItemRow(from: $0) }) else {+ return nil+ }++ // 2. Fetch field values+ let fieldResults = try client.executeQuery(ItemQueries.getFieldValuesForItem, params: [itemId])+ let fieldRows = fieldResults.compactMap { SingleItemFieldRow(from: $0) }+ let fields = FieldMapper.processFieldRowsForSingleItem(fieldRows)++ // 3. Map to Item object+ return ItemMapper.mapRow(itemRow, fields: fields)+ }++ /// Fetch all unique email addresses from field values.+ /// - Returns: Array of email addresses+ public func getAllEmailAddresses() throws -> [String] {+ let results = try client.executeQuery(+ ItemQueries.getAllEmailAddresses,+ params: [FieldKey.loginEmail]+ )+ return results.compactMap { $0["Email"] as? String }+ }++ /// Get recently deleted items (in trash).+ /// - Returns: Array of items+ public func getRecentlyDeleted() throws -> [Item] {+ let itemResults = try client.executeQuery(ItemQueries.getRecentlyDeleted, params: [])+ let itemRows = itemResults.compactMap { ItemRow(from: $0) }++ if itemRows.isEmpty {+ return []+ }++ // Fetch fields for deleted items+ let itemIds = itemRows.map { $0.id }+ let fieldQuery = ItemQueries.getFieldValuesForItems(itemIds.count)+ let fieldResults = try client.executeQuery(fieldQuery, params: itemIds.map { $0 as SqliteBindValue })+ let fieldRows = fieldResults.compactMap { FieldRow(from: $0) }+ let fieldsByItem = FieldMapper.processFieldRows(fieldRows)++ return itemRows.compactMap { row in+ ItemMapper.mapDeletedItemRow(row, fields: fieldsByItem[row.id] ?? [])+ }+ }++ /// Get count of items in trash.+ /// - Returns: Number of items in trash+ public func getRecentlyDeletedCount() throws -> Int {+ let results = try client.executeQuery(ItemQueries.countRecentlyDeleted, params: [])+ return Int(results.first?["count"] as? Int64 ?? 0)+ }++ // MARK: - Write Operations++ /// Move an item to trash (set DeletedAt timestamp).+ /// - Parameter itemId: The ID of the item to trash+ /// - Returns: Number of rows affected+ @discardableResult+ public func trash(_ itemId: String) throws -> Int {+ let now = self.now()+ return try withTransaction {+ try client.executeUpdate(ItemQueries.trashItem, params: [now, now, itemId])+ }+ }++ /// Restore an item from trash (clear DeletedAt).+ /// - Parameter itemId: The ID of the item to restore+ /// - Returns: Number of rows affected+ @discardableResult+ public func restore(_ itemId: String) throws -> Int {+ let now = self.now()+ return try withTransaction {+ try client.executeUpdate(ItemQueries.restoreItem, params: [now, itemId])+ }+ }++ /// Permanently delete an item (tombstone).+ /// Converts item to tombstone and soft deletes all related data.+ /// - Parameter itemId: The ID of the item to permanently delete+ /// - Returns: Number of rows affected+ @discardableResult+ public func permanentlyDelete(_ itemId: String) throws -> Int {+ return try withTransaction {+ let now = self.now()++ // Soft delete related FieldValues+ try softDeleteByForeignKey(table: "FieldValues", foreignKey: "ItemId", foreignKeyValue: itemId)++ // Soft delete related data+ try softDeleteByForeignKey(table: "TotpCodes", foreignKey: "ItemId", foreignKeyValue: itemId)+ try softDeleteByForeignKey(table: "Attachments", foreignKey: "ItemId", foreignKeyValue: itemId)+ try softDeleteByForeignKey(table: "Passkeys", foreignKey: "ItemId", foreignKeyValue: itemId)++ if try tableExists("ItemTags") {+ try softDeleteByForeignKey(table: "ItemTags", foreignKey: "ItemId", foreignKeyValue: itemId)+ }+ if try tableExists("FieldHistories") {+ try softDeleteByForeignKey(table: "FieldHistories", foreignKey: "ItemId", foreignKeyValue: itemId)+ }++ // Convert item to tombstone+ return try client.executeUpdate(ItemQueries.tombstoneItem, params: [now, itemId])+ }+ }++ /// Create a new item with its fields.+ /// - Parameter item: The item to create+ /// - Returns: The ID of the created item+ @discardableResult+ public func create(_ item: Item) throws -> String {+ return try withTransaction {+ let now = self.now()+ let itemId = item.id.uuidString.uppercased()++ // 1. Insert Item+ try client.executeUpdate(ItemQueries.insertItem, params: [+ itemId,+ item.name as SqliteBindValue,+ item.itemType,+ nil, // LogoId - handled separately if needed+ item.folderId?.uuidString.uppercased() as SqliteBindValue,+ now,+ now,+ 0+ ])++ // 2. Insert FieldValues+ try insertFieldValues(itemId: itemId, fields: item.fields, now: now)++ return itemId+ }+ }++ /// Update an existing item with its fields.+ /// - Parameter item: The item to update+ /// - Returns: Number of rows affected+ @discardableResult+ public func update(_ item: Item) throws -> Int {+ return try withTransaction {+ let now = self.now()+ let itemId = item.id.uuidString.uppercased()++ // 1. Update Item+ try client.executeUpdate(ItemQueries.updateItem, params: [+ item.name as SqliteBindValue,+ item.itemType,+ item.folderId?.uuidString.uppercased() as SqliteBindValue,+ nil, // LogoId update handled separately if needed+ now,+ itemId+ ])++ // 2. Update FieldValues using preserve-and-track strategy+ try updateFieldValues(itemId: itemId, fields: item.fields, now: now)++ return 1+ }+ }++ // MARK: - Private Helpers++ /// Insert field values for an item.+ private func insertFieldValues(itemId: String, fields: [ItemField], now: String) throws {+ for (index, field) in fields.enumerated() {+ if field.value.isEmpty { continue }++ try client.executeUpdate(FieldValueQueries.insert, params: [+ generateId(),+ itemId,+ field.isCustomField ? field.fieldKey : nil, // FieldDefinitionId for custom+ field.isCustomField ? nil : field.fieldKey, // FieldKey for system+ field.value,+ index * 100, // Weight for ordering+ now,+ now,+ 0+ ])+ }+ }++ /// Update field values using preserve-and-track strategy.+ /// Preserves existing field value IDs when possible for stable merge behavior.+ private func updateFieldValues(itemId: String, fields: [ItemField], now: String) throws {+ // 1. Get existing field values+ let existingResults = try client.executeQuery(FieldValueQueries.getExistingForItem, params: [itemId])++ struct ExistingField {+ let id: String+ let fieldKey: String?+ let fieldDefinitionId: String?+ let value: String+ }++ let existingFields = existingResults.compactMap { row -> ExistingField? in+ guard let id = row["Id"] as? String else { return nil }+ return ExistingField(+ id: id,+ fieldKey: row["FieldKey"] as? String,+ fieldDefinitionId: row["FieldDefinitionId"] as? String,+ value: row["Value"] as? String ?? ""+ )+ }++ // 2. Build lookup by composite key (FieldKey or FieldDefinitionId)+ var existingByKey: [String: [ExistingField]] = [:]+ for existing in existingFields {+ let key = existing.fieldKey ?? existing.fieldDefinitionId ?? ""+ if existingByKey[key] == nil {+ existingByKey[key] = []+ }+ existingByKey[key]!.append(existing)+ }++ // 3. Track which existing IDs we've processed+ var processedIds = Set<String>()++ // 4. Process each field+ for (index, field) in fields.enumerated() {+ if field.value.isEmpty { continue }++ let existingForKey = existingByKey[field.fieldKey] ?? []+ let existingEntry = existingForKey.first++ if let existing = existingEntry {+ // Update existing if value changed+ processedIds.insert(existing.id)+ if existing.value != field.value {+ try client.executeUpdate(FieldValueQueries.update, params: [+ field.value,+ index * 100,+ now,+ existing.id+ ])+ }+ } else {+ // Insert new field value+ try client.executeUpdate(FieldValueQueries.insert, params: [+ generateId(),+ itemId,+ field.isCustomField ? field.fieldKey : nil,+ field.isCustomField ? nil : field.fieldKey,+ field.value,+ index * 100,+ now,+ now,+ 0+ ])+ }+ }++ // 5. Soft delete removed fields+ for existing in existingFields {+ if !processedIds.contains(existing.id) {+ try client.executeUpdate(FieldValueQueries.softDelete, params: [now, existing.id])+ }+ }+ }+}diff --git a/apps/mobile-app/ios/VaultStoreKit/Repository/Mappers/FieldMapper.swift b/apps/mobile-app/ios/VaultStoreKit/Repository/Mappers/FieldMapper.swiftnew file mode 100644index 000000000..a4620cc4b--- /dev/null+++ b/apps/mobile-app/ios/VaultStoreKit/Repository/Mappers/FieldMapper.swift@@ -0,0 +1,357 @@+import Foundation+import VaultModels++/// Raw field row from database query.+public struct FieldRow {+ public let itemId: String+ public let fieldKey: String?+ public let fieldDefinitionId: String?+ public let customLabel: String?+ public let customFieldType: String?+ public let customIsHidden: Int64?+ public let customEnableHistory: Int64?+ public let value: String+ public let displayOrder: Int++ public init(+ itemId: String,+ fieldKey: String?,+ fieldDefinitionId: String?,+ customLabel: String?,+ customFieldType: String?,+ customIsHidden: Int64?,+ customEnableHistory: Int64?,+ value: String,+ displayOrder: Int+ ) {+ self.itemId = itemId+ self.fieldKey = fieldKey+ self.fieldDefinitionId = fieldDefinitionId+ self.customLabel = customLabel+ self.customFieldType = customFieldType+ self.customIsHidden = customIsHidden+ self.customEnableHistory = customEnableHistory+ self.value = value+ self.displayOrder = displayOrder+ }++ /// Initialize from a database row dictionary.+ public init?(from row: [String: Any]) {+ guard let itemId = row["ItemId"] as? String else { return nil }++ self.itemId = itemId+ self.fieldKey = row["FieldKey"] as? String+ self.fieldDefinitionId = row["FieldDefinitionId"] as? String+ self.customLabel = row["CustomLabel"] as? String+ self.customFieldType = row["CustomFieldType"] as? String+ self.customIsHidden = row["CustomIsHidden"] as? Int64+ self.customEnableHistory = row["CustomEnableHistory"] as? Int64+ self.value = row["Value"] as? String ?? ""+ self.displayOrder = Int(row["DisplayOrder"] as? Int64 ?? 0)+ }+}++/// Raw field row for single item queries (without ItemId).+public struct SingleItemFieldRow {+ public let fieldKey: String?+ public let fieldDefinitionId: String?+ public let customLabel: String?+ public let customFieldType: String?+ public let customIsHidden: Int64?+ public let customEnableHistory: Int64?+ public let value: String+ public let displayOrder: Int++ /// Initialize from a database row dictionary.+ public init?(from row: [String: Any]) {+ self.fieldKey = row["FieldKey"] as? String+ self.fieldDefinitionId = row["FieldDefinitionId"] as? String+ self.customLabel = row["CustomLabel"] as? String+ self.customFieldType = row["CustomFieldType"] as? String+ self.customIsHidden = row["CustomIsHidden"] as? Int64+ self.customEnableHistory = row["CustomEnableHistory"] as? Int64+ self.value = row["Value"] as? String ?? ""+ self.displayOrder = Int(row["DisplayOrder"] as? Int64 ?? 0)+ }+}++/// Intermediate field representation before grouping.+public struct ProcessedField {+ public let itemId: String+ public let fieldKey: String+ public let label: String+ public let fieldType: String+ public let isHidden: Bool+ public let value: String+ public let displayOrder: Int+ public let isCustomField: Bool+ public let enableHistory: Bool+}++/// Mapper class for processing database field rows into ItemField objects.+/// Handles both system fields (with FieldKey) and custom fields (with FieldDefinitionId).+public struct FieldMapper {+ /// Process raw field rows from database into a map of ItemId -> [ItemField].+ /// Handles system vs custom fields and multi-value field grouping.+ /// - Parameter rows: Raw field rows from database+ /// - Returns: Dictionary of ItemId to array of ItemField objects+ public static func processFieldRows(_ rows: [FieldRow]) -> [String: [ItemField]] {+ // First, convert rows to processed fields with proper metadata+ let processedFields = rows.map { processFieldRow($0) }++ // Group by ItemId and FieldKey (to handle multi-value fields)+ var fieldsByItem: [String: [ItemField]] = [:]+ var fieldValuesByKey: [String: [String]] = [:]++ for field in processedFields {+ let key = "\(field.itemId)_\(field.fieldKey)"++ // Accumulate values for the same field+ if fieldValuesByKey[key] == nil {+ fieldValuesByKey[key] = []+ }+ fieldValuesByKey[key]!.append(field.value)++ // Create ItemField entry only once per unique FieldKey per item+ if fieldsByItem[field.itemId] == nil {+ fieldsByItem[field.itemId] = []+ }++ let itemFields = fieldsByItem[field.itemId]!+ let existingField = itemFields.first { $0.fieldKey == field.fieldKey }++ if existingField == nil {+ let itemField = ItemField(+ fieldKey: field.fieldKey,+ label: field.label,+ fieldType: field.fieldType,+ value: "", // Will be set below+ isHidden: field.isHidden,+ displayOrder: field.displayOrder,+ isCustomField: field.isCustomField,+ enableHistory: field.enableHistory+ )+ fieldsByItem[field.itemId]!.append(itemField)+ }+ }++ // Set Values (using first value for single value or concatenated for multi-value)+ for (itemId, fields) in fieldsByItem {+ var updatedFields: [ItemField] = []+ for field in fields {+ let key = "\(itemId)_\(field.fieldKey)"+ let values = fieldValuesByKey[key] ?? []++ // Use first value (multi-value fields would need different handling in the model)+ let value = values.first ?? ""++ let updatedField = ItemField(+ fieldKey: field.fieldKey,+ label: field.label,+ fieldType: field.fieldType,+ value: value,+ isHidden: field.isHidden,+ displayOrder: field.displayOrder,+ isCustomField: field.isCustomField,+ enableHistory: field.enableHistory+ )+ updatedFields.append(updatedField)+ }+ fieldsByItem[itemId] = updatedFields+ }++ return fieldsByItem+ }++ /// Process a single field row to extract proper metadata.+ /// System fields use FieldKey and get metadata from SystemFieldRegistry.+ /// Custom fields use FieldDefinitionId and get metadata from the row.+ /// - Parameter row: Raw field row+ /// - Returns: Processed field with proper metadata+ private static func processFieldRow(_ row: FieldRow) -> ProcessedField {+ if let fieldKey = row.fieldKey, !fieldKey.isEmpty {+ // System field: has FieldKey, get metadata from field metadata resolver+ let metadata = resolveFieldMetadata(+ fieldKey: fieldKey,+ customLabel: nil,+ customFieldType: nil,+ customIsHidden: false,+ customEnableHistory: false,+ isCustomField: false+ )+ return ProcessedField(+ itemId: row.itemId,+ fieldKey: fieldKey,+ label: metadata.label,+ fieldType: metadata.fieldType,+ isHidden: metadata.isHidden,+ value: row.value,+ displayOrder: row.displayOrder,+ isCustomField: false,+ enableHistory: metadata.enableHistory+ )+ } else {+ // Custom field: has FieldDefinitionId, get metadata from FieldDefinitions+ let fieldKey = row.fieldDefinitionId ?? ""+ return ProcessedField(+ itemId: row.itemId,+ fieldKey: fieldKey,+ label: row.customLabel ?? "",+ fieldType: row.customFieldType ?? FieldType.text,+ isHidden: row.customIsHidden == 1,+ value: row.value,+ displayOrder: row.displayOrder,+ isCustomField: true,+ enableHistory: row.customEnableHistory == 1+ )+ }+ }++ /// Process field rows for a single item (without ItemId in result).+ /// Used when fetching a single item by ID.+ /// - Parameter rows: Raw field rows for a single item+ /// - Returns: Array of ItemField objects+ public static func processFieldRowsForSingleItem(_ rows: [SingleItemFieldRow]) -> [ItemField] {+ var fieldValuesByKey: [String: [String]] = [:]+ var uniqueFields: [String: UniqueFieldData] = [:]++ for row in rows {+ let fieldKey = row.fieldKey ?? row.fieldDefinitionId ?? ""++ // Accumulate values+ if fieldValuesByKey[fieldKey] == nil {+ fieldValuesByKey[fieldKey] = []+ }+ fieldValuesByKey[fieldKey]!.append(row.value)++ // Store field metadata (only once per FieldKey)+ if uniqueFields[fieldKey] == nil {+ if let rowFieldKey = row.fieldKey, !rowFieldKey.isEmpty {+ // System field+ let metadata = resolveFieldMetadata(+ fieldKey: rowFieldKey,+ customLabel: nil,+ customFieldType: nil,+ customIsHidden: false,+ customEnableHistory: false,+ isCustomField: false+ )+ uniqueFields[fieldKey] = UniqueFieldData(+ fieldKey: rowFieldKey,+ label: metadata.label,+ fieldType: metadata.fieldType,+ isHidden: metadata.isHidden,+ displayOrder: row.displayOrder,+ isCustomField: false,+ enableHistory: metadata.enableHistory+ )+ } else {+ // Custom field+ uniqueFields[fieldKey] = UniqueFieldData(+ fieldKey: fieldKey,+ label: row.customLabel ?? "",+ fieldType: row.customFieldType ?? FieldType.text,+ isHidden: row.customIsHidden == 1,+ displayOrder: row.displayOrder,+ isCustomField: true,+ enableHistory: row.customEnableHistory == 1+ )+ }+ }+ }++ // Build fields array with proper single/multi values+ return uniqueFields.map { (fieldKey, fieldData) in+ let values = fieldValuesByKey[fieldKey] ?? []+ let value = values.first ?? ""++ return ItemField(+ fieldKey: fieldData.fieldKey,+ label: fieldData.label,+ fieldType: fieldData.fieldType,+ value: value,+ isHidden: fieldData.isHidden,+ displayOrder: fieldData.displayOrder,+ isCustomField: fieldData.isCustomField,+ enableHistory: fieldData.enableHistory+ )+ }.sorted { $0.displayOrder < $1.displayOrder }+ }++ // MARK: - Field Metadata Resolution++ /// Helper struct to hold resolved field metadata.+ private struct FieldMetadata {+ let label: String+ let fieldType: String+ let isHidden: Bool+ let enableHistory: Bool+ }++ /// Helper struct to hold unique field data for single item processing.+ private struct UniqueFieldData {+ let fieldKey: String+ let label: String+ let fieldType: String+ let isHidden: Bool+ let displayOrder: Int+ let isCustomField: Bool+ let enableHistory: Bool+ }++ /// Resolve field metadata for system fields and custom fields.+ private static func resolveFieldMetadata(+ fieldKey: String,+ customLabel: String?,+ customFieldType: String?,+ customIsHidden: Bool,+ customEnableHistory: Bool,+ isCustomField: Bool+ ) -> FieldMetadata {+ if isCustomField {+ return FieldMetadata(+ label: customLabel ?? fieldKey,+ fieldType: customFieldType ?? FieldType.text,+ isHidden: customIsHidden,+ enableHistory: customEnableHistory+ )+ }++ // System field metadata based on FieldKey constants+ switch fieldKey {+ case FieldKey.loginUsername:+ return FieldMetadata(label: "Username", fieldType: FieldType.text, isHidden: false, enableHistory: false)+ case FieldKey.loginPassword:+ return FieldMetadata(label: "Password", fieldType: FieldType.password, isHidden: true, enableHistory: true)+ case FieldKey.loginEmail:+ return FieldMetadata(label: "Email", fieldType: FieldType.email, isHidden: false, enableHistory: false)+ case FieldKey.loginUrl:+ return FieldMetadata(label: "URL", fieldType: FieldType.uRL, isHidden: false, enableHistory: false)+ case FieldKey.cardNumber:+ return FieldMetadata(label: "Card Number", fieldType: FieldType.text, isHidden: true, enableHistory: false)+ case FieldKey.cardCardholderName:+ return FieldMetadata(label: "Cardholder Name", fieldType: FieldType.text, isHidden: false, enableHistory: false)+ case FieldKey.cardExpiryMonth:+ return FieldMetadata(label: "Expiry Month", fieldType: FieldType.text, isHidden: false, enableHistory: false)+ case FieldKey.cardExpiryYear:+ return FieldMetadata(label: "Expiry Year", fieldType: FieldType.text, isHidden: false, enableHistory: false)+ case FieldKey.cardCvv:+ return FieldMetadata(label: "CVV", fieldType: FieldType.password, isHidden: true, enableHistory: false)+ case FieldKey.cardPin:+ return FieldMetadata(label: "PIN", fieldType: FieldType.password, isHidden: true, enableHistory: false)+ case FieldKey.aliasFirstName:+ return FieldMetadata(label: "First Name", fieldType: FieldType.text, isHidden: false, enableHistory: false)+ case FieldKey.aliasLastName:+ return FieldMetadata(label: "Last Name", fieldType: FieldType.text, isHidden: false, enableHistory: false)+ case FieldKey.aliasGender:+ return FieldMetadata(label: "Gender", fieldType: FieldType.text, isHidden: false, enableHistory: false)+ case FieldKey.aliasBirthdate:+ return FieldMetadata(label: "Birth Date", fieldType: FieldType.date, isHidden: false, enableHistory: false)+ case FieldKey.notesContent:+ return FieldMetadata(label: "Notes", fieldType: FieldType.textArea, isHidden: false, enableHistory: false)+ default:+ // Unknown system field - use field key as label+ return FieldMetadata(label: fieldKey, fieldType: FieldType.text, isHidden: false, enableHistory: false)+ }+ }+}diff --git a/apps/mobile-app/ios/VaultStoreKit/Repository/Mappers/ItemMapper.swift b/apps/mobile-app/ios/VaultStoreKit/Repository/Mappers/ItemMapper.swiftnew file mode 100644index 000000000..acb975039--- /dev/null+++ b/apps/mobile-app/ios/VaultStoreKit/Repository/Mappers/ItemMapper.swift@@ -0,0 +1,147 @@+import Foundation+import SQLite+import VaultModels+import VaultUtils++/// Raw item row from database query.+public struct ItemRow {+ public let id: String+ public let name: String?+ public let itemType: String+ public let folderId: String?+ public let folderPath: String?+ public let logo: Data?+ public let hasPasskey: Bool+ public let hasAttachment: Bool+ public let hasTotp: Bool+ public let createdAt: String+ public let updatedAt: String+ public let deletedAt: String?++ /// Initialize from a database row dictionary.+ public init?(from row: [String: Any]) {+ guard let id = row["Id"] as? String,+ let itemType = row["ItemType"] as? String,+ let createdAt = row["CreatedAt"] as? String,+ let updatedAt = row["UpdatedAt"] as? String else {+ return nil+ }++ self.id = id+ self.name = row["Name"] as? String+ self.itemType = itemType+ self.folderId = row["FolderId"] as? String+ self.folderPath = row["FolderPath"] as? String++ // Handle logo data - can be base64 string or Blob+ if let logoBase64 = row["Logo"] as? String {+ self.logo = Data(base64Encoded: logoBase64)+ } else if let logoBlob = row["Logo"] as? SQLite.Blob {+ self.logo = Data(logoBlob.bytes)+ } else {+ self.logo = nil+ }++ self.hasPasskey = (row["HasPasskey"] as? Int64 ?? 0) == 1+ self.hasAttachment = (row["HasAttachment"] as? Int64 ?? 0) == 1+ self.hasTotp = (row["HasTotp"] as? Int64 ?? 0) == 1+ self.createdAt = createdAt+ self.updatedAt = updatedAt+ self.deletedAt = row["DeletedAt"] as? String+ }+}++/// Raw tag row from database query.+public struct TagRow {+ public let itemId: String+ public let id: String+ public let name: String+ public let color: String?++ /// Initialize from a database row dictionary.+ public init?(from row: [String: Any]) {+ guard let itemId = row["ItemId"] as? String,+ let id = row["Id"] as? String,+ let name = row["Name"] as? String else {+ return nil+ }++ self.itemId = itemId+ self.id = id+ self.name = name+ self.color = row["Color"] as? String+ }+}++/// Tag reference for single item queries (without ItemId).+public struct SingleItemTagRow {+ public let id: String+ public let name: String+ public let color: String?++ /// Initialize from a database row dictionary.+ public init?(from row: [String: Any]) {+ guard let id = row["Id"] as? String,+ let name = row["Name"] as? String else {+ return nil+ }++ self.id = id+ self.name = name+ self.color = row["Color"] as? String+ }+}++/// Mapper class for converting database rows to Item objects.+public struct ItemMapper {+ /// Map a single database row to an Item object.+ /// - Parameters:+ /// - row: Raw item row from database+ /// - fields: Processed fields for this item+ /// - Returns: Item object+ public static func mapRow(_ row: ItemRow, fields: [ItemField] = []) -> Item? {+ guard let createdAt = DateHelpers.parseDateString(row.createdAt),+ let updatedAt = DateHelpers.parseDateString(row.updatedAt) else {+ return nil+ }++ return Item(+ id: UUID(uuidString: row.id) ?? UUID(),+ name: row.name,+ itemType: row.itemType,+ logo: row.logo,+ folderId: row.folderId.flatMap { UUID(uuidString: $0) },+ folderPath: row.folderPath,+ fields: fields,+ hasPasskey: row.hasPasskey,+ hasAttachment: row.hasAttachment,+ hasTotp: row.hasTotp,+ createdAt: createdAt,+ updatedAt: updatedAt+ )+ }++ /// Map multiple database rows to Item objects with their fields.+ /// - Parameters:+ /// - rows: Raw item rows from database+ /// - fieldsByItem: Dictionary of ItemId to array of fields+ /// - Returns: Array of Item objects+ public static func mapRows(+ _ rows: [ItemRow],+ fieldsByItem: [String: [ItemField]]+ ) -> [Item] {+ return rows.compactMap { row in+ let fields = fieldsByItem[row.id] ?? []+ return mapRow(row, fields: fields)+ }+ }++ /// Map a single item row for recently deleted items (includes DeletedAt).+ /// - Parameters:+ /// - row: Raw item row with DeletedAt+ /// - fields: Processed fields for this item+ /// - Returns: Item object (deletedAt stored as extension or separate property if needed)+ public static func mapDeletedItemRow(_ row: ItemRow, fields: [ItemField] = []) -> Item? {+ return mapRow(row, fields: fields)+ }+}diff --git a/apps/mobile-app/ios/VaultStoreKit/Repository/Queries/ItemQueries.swift b/apps/mobile-app/ios/VaultStoreKit/Repository/Queries/ItemQueries.swiftnew file mode 100644index 000000000..0687be476--- /dev/null+++ b/apps/mobile-app/ios/VaultStoreKit/Repository/Queries/ItemQueries.swift@@ -0,0 +1,243 @@+import Foundation++/// SQL query constants for Item operations.+/// Centralizes all item-related queries to avoid duplication.+/// Mirrors the React Native implementation.+public struct ItemQueries {+ /// Base SELECT for items with common fields.+ /// Includes LEFT JOIN to Logos and Folders, and subqueries for HasPasskey/HasAttachment/HasTotp.+ public static let baseSelect = """+ SELECT DISTINCT+ i.Id,+ i.Name,+ i.ItemType,+ i.FolderId,+ f.Name as FolderPath,+ l.FileData as Logo,+ CASE WHEN EXISTS (SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.IsDeleted = 0) THEN 1 ELSE 0 END as HasPasskey,+ CASE WHEN EXISTS (SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.IsDeleted = 0) THEN 1 ELSE 0 END as HasAttachment,+ CASE WHEN EXISTS (SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.IsDeleted = 0) THEN 1 ELSE 0 END as HasTotp,+ i.CreatedAt,+ i.UpdatedAt+ FROM Items i+ LEFT JOIN Logos l ON i.LogoId = l.Id+ LEFT JOIN Folders f ON i.FolderId = f.Id+ """++ /// Get all active items (not deleted, not in trash).+ public static let getAllActive = """+ \(baseSelect)+ WHERE i.IsDeleted = 0 AND i.DeletedAt IS NULL+ ORDER BY i.CreatedAt DESC+ """++ /// Get a single item by ID.+ public static let getById = """+ SELECT+ i.Id,+ i.Name,+ i.ItemType,+ i.FolderId,+ f.Name as FolderPath,+ l.FileData as Logo,+ CASE WHEN EXISTS (SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.IsDeleted = 0) THEN 1 ELSE 0 END as HasPasskey,+ CASE WHEN EXISTS (SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.IsDeleted = 0) THEN 1 ELSE 0 END as HasAttachment,+ CASE WHEN EXISTS (SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.IsDeleted = 0) THEN 1 ELSE 0 END as HasTotp,+ i.CreatedAt,+ i.UpdatedAt+ FROM Items i+ LEFT JOIN Logos l ON i.LogoId = l.Id+ LEFT JOIN Folders f ON i.FolderId = f.Id+ WHERE i.Id = ? AND i.IsDeleted = 0+ """++ /// Get field values for multiple items.+ /// - Parameter itemCount: Number of items (for placeholder generation)+ /// - Returns: Query with placeholders+ public static func getFieldValuesForItems(_ itemCount: Int) -> String {+ let placeholders = Array(repeating: "?", count: itemCount).joined(separator: ",")+ return """+ SELECT+ fv.ItemId,+ fv.FieldKey,+ fv.FieldDefinitionId,+ fd.Label as CustomLabel,+ fd.FieldType as CustomFieldType,+ fd.IsHidden as CustomIsHidden,+ fd.EnableHistory as CustomEnableHistory,+ fv.Value,+ fv.Weight as DisplayOrder+ FROM FieldValues fv+ LEFT JOIN FieldDefinitions fd ON fv.FieldDefinitionId = fd.Id+ WHERE fv.ItemId IN (\(placeholders))+ AND fv.IsDeleted = 0+ ORDER BY fv.ItemId, fv.Weight+ """+ }++ /// Get field values for a single item.+ public static let getFieldValuesForItem = """+ SELECT+ fv.FieldKey,+ fv.FieldDefinitionId,+ fd.Label as CustomLabel,+ fd.FieldType as CustomFieldType,+ fd.IsHidden as CustomIsHidden,+ fd.EnableHistory as CustomEnableHistory,+ fv.Value,+ fv.Weight as DisplayOrder+ FROM FieldValues fv+ LEFT JOIN FieldDefinitions fd ON fv.FieldDefinitionId = fd.Id+ WHERE fv.ItemId = ? AND fv.IsDeleted = 0+ ORDER BY fv.Weight+ """++ /// Get all unique email addresses from field values.+ public static let getAllEmailAddresses = """+ SELECT DISTINCT fv.Value as Email+ FROM FieldValues fv+ INNER JOIN Items i ON fv.ItemId = i.Id+ WHERE fv.FieldKey = ?+ AND fv.Value IS NOT NULL+ AND fv.Value != ''+ AND fv.IsDeleted = 0+ AND i.IsDeleted = 0+ AND i.DeletedAt IS NULL+ """++ /// Get all recently deleted items (in trash).+ public static let getRecentlyDeleted = """+ SELECT DISTINCT+ i.Id,+ i.Name,+ i.ItemType,+ i.FolderId,+ f.Name as FolderPath,+ l.FileData as Logo,+ CASE WHEN EXISTS (SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.IsDeleted = 0) THEN 1 ELSE 0 END as HasPasskey,+ CASE WHEN EXISTS (SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.IsDeleted = 0) THEN 1 ELSE 0 END as HasAttachment,+ CASE WHEN EXISTS (SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.IsDeleted = 0) THEN 1 ELSE 0 END as HasTotp,+ i.CreatedAt,+ i.UpdatedAt,+ i.DeletedAt+ FROM Items i+ LEFT JOIN Logos l ON i.LogoId = l.Id+ LEFT JOIN Folders f ON i.FolderId = f.Id+ WHERE i.IsDeleted = 0 AND i.DeletedAt IS NOT NULL+ ORDER BY i.DeletedAt DESC+ """++ /// Count of recently deleted items.+ public static let countRecentlyDeleted = """+ SELECT COUNT(*) as count+ FROM Items+ WHERE IsDeleted = 0 AND DeletedAt IS NOT NULL+ """++ /// Insert a new item.+ public static let insertItem = """+ INSERT INTO Items (Id, Name, ItemType, LogoId, FolderId, CreatedAt, UpdatedAt, IsDeleted)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)+ """++ /// Update an existing item.+ public static let updateItem = """+ UPDATE Items+ SET Name = ?,+ ItemType = ?,+ FolderId = ?,+ LogoId = COALESCE(?, LogoId),+ UpdatedAt = ?+ WHERE Id = ?+ """++ /// Move item to trash (set DeletedAt).+ public static let trashItem = """+ UPDATE Items+ SET DeletedAt = ?,+ UpdatedAt = ?+ WHERE Id = ? AND IsDeleted = 0+ """++ /// Restore item from trash (clear DeletedAt).+ public static let restoreItem = """+ UPDATE Items+ SET DeletedAt = NULL,+ UpdatedAt = ?+ WHERE Id = ? AND IsDeleted = 0 AND DeletedAt IS NOT NULL+ """++ /// Convert item to tombstone for permanent deletion.+ public static let tombstoneItem = """+ UPDATE Items+ SET IsDeleted = 1,+ Name = NULL,+ LogoId = NULL,+ FolderId = NULL,+ UpdatedAt = ?+ WHERE Id = ?+ """+}++/// SQL query constants for FieldValue operations.+public struct FieldValueQueries {+ /// Get existing field values for an item.+ public static let getExistingForItem = """+ SELECT Id, FieldKey, FieldDefinitionId, Value+ FROM FieldValues+ WHERE ItemId = ? AND IsDeleted = 0+ """++ /// Insert a new field value.+ public static let insert = """+ INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)+ """++ /// Update an existing field value.+ public static let update = """+ UPDATE FieldValues+ SET Value = ?,+ Weight = ?,+ UpdatedAt = ?+ WHERE Id = ?+ """++ /// Soft delete a field value.+ public static let softDelete = """+ UPDATE FieldValues+ SET IsDeleted = 1,+ UpdatedAt = ?+ WHERE Id = ?+ """+}++/// SQL query constants for Tag operations.+public struct TagQueries {+ /// Get tags for multiple items.+ /// - Parameter itemCount: Number of items (for placeholder generation)+ /// - Returns: Query with placeholders+ public static func getTagsForItems(_ itemCount: Int) -> String {+ let placeholders = Array(repeating: "?", count: itemCount).joined(separator: ",")+ return """+ SELECT it.ItemId, t.Id, t.Name, t.Color+ FROM ItemTags it+ INNER JOIN Tags t ON it.TagId = t.Id+ WHERE it.ItemId IN (\(placeholders))+ AND it.IsDeleted = 0+ AND t.IsDeleted = 0+ ORDER BY t.DisplayOrder+ """+ }++ /// Get tags for a single item.+ public static let getTagsForItem = """+ SELECT t.Id, t.Name, t.Color+ FROM ItemTags it+ INNER JOIN Tags t ON it.TagId = t.Id+ WHERE it.ItemId = ?+ AND it.IsDeleted = 0+ AND t.IsDeleted = 0+ ORDER BY t.DisplayOrder+ """+}diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swiftindex d73c0fd32..74cc8d49b 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift@@ -34,6 +34,12 @@ extension VaultStore {self.userDefaults.removeObject(forKey: VaultConstants.authMethodsKey)self.userDefaults.removeObject(forKey: VaultConstants.autoLockTimeoutKey)self.userDefaults.removeObject(forKey: VaultConstants.encryptionKeyDerivationParamsKey)++ // Clear sync state+ self.userDefaults.removeObject(forKey: VaultConstants.isDirtyKey)+ self.userDefaults.removeObject(forKey: VaultConstants.mutationSequenceKey)+ self.userDefaults.removeObject(forKey: VaultConstants.isSyncingKey)+self.userDefaults.synchronize()print("Cleared UserDefaults")diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+DatabaseClient.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+DatabaseClient.swiftnew file mode 100644index 000000000..c6eaed69c--- /dev/null+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+DatabaseClient.swift@@ -0,0 +1,12 @@+import Foundation+import SQLite++/// Extension to make VaultStore conform to DatabaseClient protocol.+/// This allows VaultStore to be used with the repository pattern.+extension VaultStore: DatabaseClient {+ /// The ItemRepository instance for this VaultStore.+ /// Lazily initialized to use self as the database client.+ public var itemRepository: ItemRepository {+ return ItemRepository(client: self)+ }+}diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Metadata.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Metadata.swiftindex 3d02d00f7..9a874daf4 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Metadata.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Metadata.swift@@ -115,4 +115,131 @@ extension VaultStore {}return VersionComparison.isGreaterThanOrEqualTo(serverVersion, targetVersion)}++ // MARK: - Sync State Storage (isDirty, mutationSequence, isSyncing)++ /// Set the dirty flag indicating local changes need to be synced+ public func setIsDirty(_ isDirty: Bool) {+ userDefaults.set(isDirty, forKey: VaultConstants.isDirtyKey)+ userDefaults.synchronize()+ }++ /// Get the dirty flag+ public func getIsDirty() -> Bool {+ return userDefaults.bool(forKey: VaultConstants.isDirtyKey)+ }++ /// Get the current mutation sequence number+ public func getMutationSequence() -> Int {+ return userDefaults.integer(forKey: VaultConstants.mutationSequenceKey)+ }++ /// Set the mutation sequence number+ public func setMutationSequence(_ sequence: Int) {+ userDefaults.set(sequence, forKey: VaultConstants.mutationSequenceKey)+ userDefaults.synchronize()+ }++ /// Increment the mutation sequence and return the new value+ public func incrementMutationSequence() -> Int {+ let current = getMutationSequence()+ let newValue = current + 1+ setMutationSequence(newValue)+ return newValue+ }++ /// Set the syncing flag+ public func setIsSyncing(_ isSyncing: Bool) {+ userDefaults.set(isSyncing, forKey: VaultConstants.isSyncingKey)+ userDefaults.synchronize()+ }++ /// Get the syncing flag+ public func getIsSyncing() -> Bool {+ return userDefaults.bool(forKey: VaultConstants.isSyncingKey)+ }++ /// Get the complete sync state+ public func getSyncState() -> SyncStateResult {+ return SyncStateResult(+ isDirty: getIsDirty(),+ mutationSequence: getMutationSequence(),+ serverRevision: getCurrentVaultRevisionNumber(),+ isSyncing: getIsSyncing()+ )+ }++ /// Store encrypted vault with sync state atomically.+ /// Two modes:+ /// 1. markDirty=true: Local mutation - always succeeds, increments mutation sequence+ /// 2. expectedMutationSeq provided: Sync operation - only succeeds if no mutations happened+ ///+ /// - Parameters:+ /// - encryptedVault: The encrypted vault blob+ /// - 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+ /// - Returns: (success, mutationSequence) - success=false if expectedMutationSeq didn't match+ public func storeEncryptedVaultWithSyncState(+ encryptedVault: String,+ markDirty: Bool = false,+ serverRevision: Int? = nil,+ expectedMutationSeq: Int? = nil+ ) throws -> (success: Bool, mutationSequence: Int) {+ var mutationSequence = getMutationSequence()++ // Race detection for sync operations+ if let expectedSeq = expectedMutationSeq, expectedSeq != mutationSequence {+ return (success: false, mutationSequence: mutationSequence)+ }++ if markDirty {+ mutationSequence += 1+ }++ // Store vault and sync state atomically+ try storeEncryptedDatabase(encryptedVault)++ if markDirty {+ setMutationSequence(mutationSequence)+ setIsDirty(true)+ }++ if let revision = serverRevision {+ setCurrentVaultRevisionNumber(revision)+ }++ return (success: true, mutationSequence: mutationSequence)+ }++ /// Mark the vault as clean after successful sync.+ /// Only clears dirty flag if no mutations happened during sync.+ ///+ /// - Parameters:+ /// - mutationSeqAtStart: The mutation sequence when sync started+ /// - newServerRevision: The new server revision after successful upload+ /// - Returns: Whether the dirty flag was cleared+ public func markVaultClean(mutationSeqAtStart: Int, newServerRevision: Int) -> Bool {+ let currentMutationSeq = getMutationSequence()++ // Always update server revision+ setCurrentVaultRevisionNumber(newServerRevision)++ if currentMutationSeq == mutationSeqAtStart {+ // No mutations during sync - safe to mark as clean+ setIsDirty(false)+ return true+ }++ // Mutations happened during sync - keep dirty+ return false+ }++ /// Clear all sync state (used on logout)+ public func clearSyncState() {+ userDefaults.removeObject(forKey: VaultConstants.isDirtyKey)+ userDefaults.removeObject(forKey: VaultConstants.mutationSequenceKey)+ userDefaults.removeObject(forKey: VaultConstants.isSyncingKey)+ userDefaults.synchronize()+ }}diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Mutate.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Mutate.swiftindex 8df2b6790..e5b3f2a9c 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Mutate.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Mutate.swift@@ -57,16 +57,16 @@ extension VaultStore {)}- // Get all credentials to count them and extract private email addresses- let credentials = try getAllCredentials()+ // Get all items to count them and extract private email addresses+ let items = try getAllItems()// Get private email domains from metadatalet metadata = getVaultMetadataObject()let privateEmailDomains = metadata?.privateEmailDomains ?? []- // Extract private email addresses from credentials- let privateEmailAddresses = credentials- .compactMap { $0.alias?.email }+ // Extract private email addresses from items using the email field+ let privateEmailAddresses = items+ .compactMap { $0.email } // Get email from login.email field.filter { email in// Check if email belongs to any private domainprivateEmailDomains.contains { domain in@@ -90,14 +90,14 @@ extension VaultStore {return VaultUpload(blob: encryptedDb,createdAt: now,- credentialsCount: credentials.count,+ credentialsCount: items.count,currentRevisionNumber: currentRevision,emailAddressList: privateEmailAddresses,// TODO: add public RSA encryption key to payload when implementing vault creation from mobile app. Currently only web app does this.encryptionPublicKey: "",updatedAt: now,username: username,- version: dbVersion,+ version: dbVersion)}@@ -211,6 +211,99 @@ extension VaultStore {}}+ /// Upload the vault to the server and return detailed result+ /// This is used for sync operations where race detection is needed+ /// The caller captures mutationSeqAtStart before calling this method+ public func uploadVault(using webApiService: WebApiService) async throws -> VaultUploadResult {+ let mutationSeqAtStart = getMutationSequence()++ // Prepare vault for upload+ let vault = try prepareVault()++ // Convert to JSON+ let encoder = JSONEncoder()+ let jsonData = try encoder.encode(vault)+ guard let jsonString = String(data: jsonData, encoding: .utf8) else {+ return VaultUploadResult(+ success: false,+ status: -1,+ newRevisionNumber: 0,+ mutationSeqAtStart: mutationSeqAtStart,+ error: "Failed to encode vault to JSON"+ )+ }++ // Upload to server+ let response: WebApiResponse+ do {+ response = try await webApiService.executeRequest(+ method: "POST",+ endpoint: "Vault",+ body: jsonString,+ headers: ["Content-Type": "application/json"],+ requiresAuth: true+ )+ } catch {+ return VaultUploadResult(+ success: false,+ status: -1,+ newRevisionNumber: 0,+ mutationSeqAtStart: mutationSeqAtStart,+ error: "Network error: \(error.localizedDescription)"+ )+ }++ // Check response status+ guard response.statusCode == 200 else {+ return VaultUploadResult(+ success: false,+ status: -1,+ newRevisionNumber: 0,+ mutationSeqAtStart: mutationSeqAtStart,+ error: "Server returned error: \(response.statusCode)"+ )+ }++ // Parse response+ guard let responseData = response.body.data(using: .utf8) else {+ return VaultUploadResult(+ success: false,+ status: -1,+ newRevisionNumber: 0,+ mutationSeqAtStart: mutationSeqAtStart,+ error: "Failed to convert response body to data"+ )+ }++ let vaultResponse: VaultPostResponse+ do {+ vaultResponse = try JSONDecoder().decode(VaultPostResponse.self, from: responseData)+ } catch {+ return VaultUploadResult(+ success: false,+ status: -1,+ newRevisionNumber: 0,+ mutationSeqAtStart: mutationSeqAtStart,+ error: "Failed to parse vault upload response: \(error.localizedDescription)"+ )+ }++ // Return upload result (let caller decide how to handle status)+ if vaultResponse.status == 0 {+ // Success - update local revision number and clear offline mode+ setCurrentVaultRevisionNumber(vaultResponse.newRevisionNumber)+ setOfflineMode(false)+ }++ return VaultUploadResult(+ success: vaultResponse.status == 0,+ status: vaultResponse.status,+ newRevisionNumber: vaultResponse.newRevisionNumber,+ mutationSeqAtStart: mutationSeqAtStart,+ error: vaultResponse.status != 0 ? "Vault upload returned status \(vaultResponse.status)" : nil+ )+ }+// MARK: - Helper Methods/// Get the database version from the __EFMigrationsHistory tablediff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swiftindex ff8c96398..e020c3ea2 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swift@@ -14,7 +14,7 @@ extension VaultStore {private static let passkeysTable = Table("Passkeys")private static let colId = Expression<String>("Id")- private static let colCredentialId = Expression<String>("CredentialId")+ private static let colItemId = Expression<String>("ItemId")private static let colRpId = Expression<String>("RpId")private static let colUserHandle = Expression<Blob?>("UserHandle")private static let colPublicKey = Expression<String>("PublicKey")@@ -57,15 +57,15 @@ extension VaultStore {}/**- * Get all passkeys for a credential+ * Get all passkeys for an item (new model)*/- public func getPasskeys(forCredentialId credentialId: UUID) throws -> [Passkey] {+ public func getPasskeys(forItemId itemId: UUID) throws -> [Passkey] {guard let dbConn = dbConnection else {throw VaultStoreError.vaultNotUnlocked}let query = Self.passkeysTable- .filter(Self.colCredentialId == credentialId.uuidString)+ .filter(Self.colItemId == itemId.uuidString).filter(Self.colIsDeleted == 0).order(Self.colCreatedAt.desc)@@ -79,6 +79,13 @@ extension VaultStore {return passkeys}+ /**+ * Get all passkeys for a credential (legacy alias for backwards compatibility)+ */+ public func getPasskeys(forCredentialId credentialId: UUID) throws -> [Passkey] {+ return try getPasskeys(forItemId: credentialId)+ }+/*** Get all passkeys for a specific relying party identifier (RP ID)*/@@ -103,7 +110,7 @@ extension VaultStore {}/**- * Get passkeys with credential info for a specific rpId and optionally username+ * Get passkeys with item info for a specific rpId and optionally username* Used for finding existing passkeys that might be replaced during registration*/public func getPasskeysWithCredentialInfo(forRpId rpId: String, userName: String? = nil, userId: Data? = nil) throws -> [(passkey: Passkey, serviceName: String?, username: String?)] {@@ -111,27 +118,38 @@ extension VaultStore {throw VaultStoreError.vaultNotUnlocked}- // Join passkeys with credentials and services to get display info+ // Join passkeys with items and field values to get display infolet passkeysTable = Table("Passkeys")- let credentialsTable = Table("Credentials")- let servicesTable = Table("Services")+ let itemsTable = Table("Items")+ let fieldValuesTable = Table("FieldValues")+ // First get passkeys joined with itemslet query = passkeysTable- .select(passkeysTable[*], credentialsTable[Expression<String?>("Username")], servicesTable[Expression<String?>("Name")])- .join(credentialsTable, on: passkeysTable[Expression<String>("CredentialId")] == credentialsTable[Expression<String>("Id")])- .join(servicesTable, on: credentialsTable[Expression<String>("ServiceId")] == servicesTable[Expression<String>("Id")])+ .select(passkeysTable[*], itemsTable[Expression<String?>("Name")])+ .join(itemsTable, on: passkeysTable[Expression<String>("ItemId")] == itemsTable[Expression<String>("Id")]).filter(passkeysTable[Expression<String>("RpId")] == rpId).filter(passkeysTable[Expression<Int64>("IsDeleted")] == 0)- .filter(credentialsTable[Expression<Int64>("IsDeleted")] == 0)+ .filter(itemsTable[Expression<Int64>("IsDeleted")] == 0).order(passkeysTable[Expression<String>("CreatedAt")].desc)var results: [(passkey: Passkey, serviceName: String?, username: String?)] = []for row in try dbConn.prepare(query) {if let passkey = try parsePasskeyRow(row) {- let credUsername = try? row.get(Expression<String?>("Username"))let serviceName = try? row.get(Expression<String?>("Name"))+ // Get username from field values (login.username)+ let usernameQuery = fieldValuesTable+ .filter(Expression<String>("ItemId") == passkey.parentCredentialId.uuidString)+ .filter(Expression<String?>("FieldKey") == FieldKey.loginUsername)+ .filter(Expression<Int64>("IsDeleted") == 0)+ .limit(1)++ var credUsername: String?+ if let usernameRow = try? dbConn.pluck(usernameQuery) {+ credUsername = try? usernameRow.get(Expression<String?>("Value"))+ }+// Filter by username or userId if providedvar matches = trueif let userName = userName {@@ -162,7 +180,7 @@ extension VaultStore {private func parsePasskeyRow(_ row: Row) throws -> Passkey? {// Extract required fields using column expressionslet idString = try row.get(Self.colId)- let parentCredentialIdString = try row.get(Self.colCredentialId)+ let parentCredentialIdString = try row.get(Self.colItemId)let rpId = try row.get(Self.colRpId)let userHandleBlob = try? row.get(Self.colUserHandle)let publicKeyString = try row.get(Self.colPublicKey)@@ -238,8 +256,8 @@ extension VaultStore {}/**- * Create a credential with a passkey (proof of concept for passkey registration)- * This creates a minimal credential record and links the passkey to it+ * Create an item with a passkey (for passkey registration)+ * This creates an Item record with field values and links the passkey to it*/public func createCredentialWithPasskey(rpId: String,@@ -252,67 +270,90 @@ extension VaultStore {throw VaultStoreError.vaultNotUnlocked}- let credentialId = passkey.parentCredentialId+ let itemId = passkey.parentCredentialIdlet now = Date()let timestamp = formatDateForDatabase(now)- // Create a minimal service for the RP- let serviceId = UUID()- let serviceTable = Table("Services")+ // Create logo if provided+ var logoId: UUID?+ if let logo = logo {+ logoId = UUID()+ let logosTable = Table("Logos")+ let logoBlob = Blob(bytes: [UInt8](logo))- // Convert logo Data to SQLite Blob if present- let logoBlob = logo.map { Blob(bytes: [UInt8]($0)) }+ // Extract normalized domain from rpId for source+ let source = rpId.lowercased().replacingOccurrences(of: "www.", with: "")++ let logoInsert = logosTable.insert(+ Expression<String>("Id") <- logoId!.uuidString,+ Expression<String>("Source") <- source,+ Expression<SQLite.Blob?>("FileData") <- logoBlob,+ Expression<String?>("MimeType") <- "image/png",+ Expression<String?>("FetchedAt") <- nil,+ Expression<String>("CreatedAt") <- timestamp,+ Expression<String>("UpdatedAt") <- timestamp,+ Expression<Int64>("IsDeleted") <- 0+ )+ try dbConn.run(logoInsert)+ }- let serviceInsert = serviceTable.insert(- Expression<String>("Id") <- serviceId.uuidString,- Expression<String?>("Name") <- displayName, // Use displayName as the service name (title)- Expression<String?>("Url") <- "https://\(rpId)",- Expression<SQLite.Blob?>("Logo") <- logoBlob,- Expression<String>("CreatedAt") <- timestamp,- Expression<String>("UpdatedAt") <- timestamp,- Expression<Int64>("IsDeleted") <- 0- )- try dbConn.run(serviceInsert)-- // Create a minimal alias with empty fields and default birthdate- // TODO: once birthdate is made nullable in datamodel refactor, remove this.- let aliasId = UUID()- let aliasesTable = Table("Aliases")- let aliasInsert = aliasesTable.insert(- Expression<String>("Id") <- aliasId.uuidString,- Expression<String?>("FirstName") <- "",- Expression<String?>("LastName") <- "",- Expression<String?>("NickName") <- "",- Expression<String?>("BirthDate") <- "0001-01-01 00:00:00",- Expression<String?>("Gender") <- "",- Expression<String?>("Email") <- "",+ // Create the Item+ let itemsTable = Table("Items")+ let itemInsert = itemsTable.insert(+ Expression<String>("Id") <- itemId.uuidString,+ Expression<String?>("Name") <- displayName,+ Expression<String>("ItemType") <- ItemType.login,+ Expression<String?>("LogoId") <- logoId?.uuidString,+ Expression<String?>("FolderId") <- nil,+ Expression<String?>("DeletedAt") <- nil,Expression<String>("CreatedAt") <- timestamp,Expression<String>("UpdatedAt") <- timestamp,Expression<Int64>("IsDeleted") <- 0)- try dbConn.run(aliasInsert)-- // Create the credential with the alias- let credentialsTable = Table("Credentials")- let credentialInsert = credentialsTable.insert(- Expression<String>("Id") <- credentialId.uuidString,- Expression<String>("ServiceId") <- serviceId.uuidString,- Expression<String?>("AliasId") <- aliasId.uuidString,- Expression<String?>("Username") <- userName,- Expression<String?>("Notes") <- nil,+ try dbConn.run(itemInsert)++ // Create field values+ let fieldValuesTable = Table("FieldValues")++ // Add login.url field+ let urlFieldId = UUID()+ let urlFieldInsert = fieldValuesTable.insert(+ Expression<String>("Id") <- urlFieldId.uuidString,+ Expression<String>("ItemId") <- itemId.uuidString,+ Expression<String?>("FieldDefinitionId") <- nil,+ Expression<String?>("FieldKey") <- FieldKey.loginUrl,+ Expression<String?>("Value") <- "https://\(rpId)",+ Expression<Int64>("Weight") <- 0,Expression<String>("CreatedAt") <- timestamp,Expression<String>("UpdatedAt") <- timestamp,Expression<Int64>("IsDeleted") <- 0)- try dbConn.run(credentialInsert)+ try dbConn.run(urlFieldInsert)++ // Add login.username field if provided+ if let userName = userName, !userName.isEmpty {+ let usernameFieldId = UUID()+ let usernameFieldInsert = fieldValuesTable.insert(+ Expression<String>("Id") <- usernameFieldId.uuidString,+ Expression<String>("ItemId") <- itemId.uuidString,+ Expression<String?>("FieldDefinitionId") <- nil,+ Expression<String?>("FieldKey") <- FieldKey.loginUsername,+ Expression<String?>("Value") <- userName,+ Expression<Int64>("Weight") <- 0,+ Expression<String>("CreatedAt") <- timestamp,+ Expression<String>("UpdatedAt") <- timestamp,+ Expression<Int64>("IsDeleted") <- 0+ )+ try dbConn.run(usernameFieldInsert)+ }// Insert the passkeytry insertPasskey(passkey)- // Return the credential+ // Return the credential (legacy format for backwards compatibility)let service = Service(- id: serviceId,- name: rpId,+ id: itemId,+ name: displayName,url: "https://\(rpId)",logo: logo,createdAt: now,@@ -320,29 +361,9 @@ extension VaultStore {isDeleted: false)- // Create default birthdate (0001-01-01)- var defaultBirthDateComponents = DateComponents()- defaultBirthDateComponents.year = 1- defaultBirthDateComponents.month = 1- defaultBirthDateComponents.day = 1- let defaultBirthDate = Calendar(identifier: .gregorian).date(from: defaultBirthDateComponents)!-- let alias = Alias(- id: aliasId,- gender: "",- firstName: "",- lastName: "",- nickName: "",- birthDate: defaultBirthDate,- email: "",- createdAt: now,- updatedAt: now,- isDeleted: false- )-return Credential(- id: credentialId,- alias: alias,+ id: itemId,+ alias: nil,service: service,username: userName,notes: nil,@@ -364,7 +385,7 @@ extension VaultStore {let insert = Self.passkeysTable.insert(Self.colId <- passkey.id.uuidString,- Self.colCredentialId <- passkey.parentCredentialId.uuidString,+ Self.colItemId <- passkey.parentCredentialId.uuidString,Self.colRpId <- passkey.rpId,Self.colUserHandle <- passkey.userHandle.map { Blob(bytes: [UInt8]($0)) },Self.colPublicKey <- String(data: passkey.publicKey, encoding: .utf8)!,@@ -381,14 +402,14 @@ extension VaultStore {/*** Replace an existing passkey with a new one- * This deletes the old passkey and creates a new one with the same credential+ * This deletes the old passkey and creates a new one with the same item*/public func replacePasskey(oldPasskeyId: UUID, newPasskey: Passkey, displayName: String, logo: Data? = nil) throws {guard let dbConn = dbConnection else {throw VaultStoreError.vaultNotUnlocked}- // Get the old passkey to find its credential+ // Get the old passkey to find its itemlet oldPasskeyQuery = Self.passkeysTable.filter(Self.colId == oldPasskeyId.uuidString).filter(Self.colIsDeleted == 0)@@ -399,34 +420,68 @@ extension VaultStore {throw VaultStoreError.databaseError("Passkey not found")}- let credentialId = oldPasskey.parentCredentialId+ let itemId = oldPasskey.parentCredentialIdlet now = Date()let timestamp = formatDateForDatabase(now)- // Update the credential's service with new logo if provided+ // Update the item's logo if providedif let logo = logo {- let logoBlob = Blob(bytes: [UInt8](logo))- let credentialsTable = Table("Credentials")- let servicesTable = Table("Services")+ let itemsTable = Table("Items")+ let logosTable = Table("Logos")- // Get the service ID from the credential- let credQuery = credentialsTable- .filter(Expression<String>("Id") == credentialId.uuidString)+ // Get the current logo ID from the item+ let itemQuery = itemsTable+ .filter(Expression<String>("Id") == itemId.uuidString).limit(1)- if let credRow = try dbConn.pluck(credQuery) {- let serviceId = try credRow.get(Expression<String>("ServiceId"))+ if let itemRow = try dbConn.pluck(itemQuery) {+ let existingLogoId = try? itemRow.get(Expression<String?>("LogoId"))++ let logoBlob = Blob(bytes: [UInt8](logo))++ if let logoIdString = existingLogoId, let logoId = UUID(uuidString: logoIdString) {+ // Update existing logo+ let logoUpdate = logosTable+ .filter(Expression<String>("Id") == logoId.uuidString)+ .update(+ Expression<SQLite.Blob?>("FileData") <- logoBlob,+ Expression<String>("UpdatedAt") <- timestamp+ )+ try dbConn.run(logoUpdate)+ } else {+ // Create new logo+ let newLogoId = UUID()+ let source = newPasskey.rpId.lowercased().replacingOccurrences(of: "www.", with: "")+ let logoInsert = logosTable.insert(+ Expression<String>("Id") <- newLogoId.uuidString,+ Expression<String>("Source") <- source,+ Expression<SQLite.Blob?>("FileData") <- logoBlob,+ Expression<String?>("MimeType") <- "image/png",+ Expression<String?>("FetchedAt") <- nil,+ Expression<String>("CreatedAt") <- timestamp,+ Expression<String>("UpdatedAt") <- timestamp,+ Expression<Int64>("IsDeleted") <- 0+ )+ try dbConn.run(logoInsert)++ // Update item with new logo ID+ let itemUpdate = itemsTable+ .filter(Expression<String>("Id") == itemId.uuidString)+ .update(+ Expression<String?>("LogoId") <- newLogoId.uuidString,+ Expression<String>("UpdatedAt") <- timestamp+ )+ try dbConn.run(itemUpdate)+ }- // Update the service with new logo and displayName- let serviceUpdate = servicesTable- .filter(Expression<String>("Id") == serviceId)+ // Update item name with displayName+ let nameUpdate = itemsTable+ .filter(Expression<String>("Id") == itemId.uuidString).update(- Expression<SQLite.Blob?>("Logo") <- logoBlob,Expression<String?>("Name") <- displayName,Expression<String>("UpdatedAt") <- timestamp)-- try dbConn.run(serviceUpdate)+ try dbConn.run(nameUpdate)}}@@ -440,11 +495,10 @@ extension VaultStore {try dbConn.run(deleteQuery)- // Create the new passkey with the same credential ID- var updatedPasskey = newPasskey- updatedPasskey = Passkey(+ // Create the new passkey with the same item ID+ let updatedPasskey = Passkey(id: newPasskey.id,- parentCredentialId: credentialId, // Use the old credential ID+ parentCredentialId: itemId, // Use the old item IDrpId: newPasskey.rpId,userHandle: newPasskey.userHandle,userName: newPasskey.userName,diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swiftindex 9e6ae1c55..b5a2dd84d 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift@@ -5,6 +5,8 @@ import VaultUtils/// Extension for the VaultStore class to handle query managementextension VaultStore {+ // MARK: - Core Database Operations (DatabaseClient Protocol)+/// Execute a SELECT query on the databasepublic func executeQuery(_ query: String, params: [Binding?]) throws -> [[String: Any]] {guard let dbConnection = self.dbConnection else {@@ -118,7 +120,7 @@ extension VaultStore {// If you have your own transaction management, ensure it's committed before calling this.// Optional: give SQLite time to resolve lockstry? dbConnection.execute("PRAGMA busy_timeout=5000")-+// End any lingering transaction (no-op if none)._ = try? dbConnection.execute("END")@@ -135,7 +137,7 @@ extension VaultStore {// Run VACUUM INTO to create a compact, faithful copy of the current DB.// Must be executed with no active transaction and no attached target needed.// This preserves schema, indexes, triggers, views, pragmas like page_size, auto_vacuum, encoding, user_version, etc.- // Retry VACUUM INTO a few times if we hit “statements in progress”+ // Retry VACUUM INTO a few times if we hit "statements in progress"var lastError: Error?for attempt in 1...5 {do {@@ -190,189 +192,161 @@ extension VaultStore {try dbConnection.execute("ROLLBACK")}- // swiftlint:disable function_body_length- /// Get all credentials from the database.- public func getAllCredentials() throws -> [Credential] {- guard let dbConnection = self.dbConnection else {- throw NSError(domain: "VaultStore", code: 4, userInfo: [NSLocalizedDescriptionKey: "Database not initialized"])- }+ // MARK: - Items (Using Repository Pattern)- let 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- """-- var result: [Credential] = []- for row in try dbConnection.prepare(query) {- guard let idString = row[0] as? String else {- continue- }+ /// Get all items from the database using the new field-based model.+ /// Delegates to ItemRepository for the actual query logic.+ public func getAllItems() throws -> [Item] {+ return try itemRepository.getAll()+ }- let createdAtString = row[4] as? String- let updatedAtString = row[5] as? String+ /// Get a single item by ID.+ /// - Parameter itemId: The UUID of the item to fetch+ /// - Returns: Item object or nil if not found+ public func getItemById(_ itemId: UUID) throws -> Item? {+ return try itemRepository.getById(itemId.uuidString.uppercased())+ }- guard let createdAtString = createdAtString,- let updatedAtString = updatedAtString else {- continue- }+ /// Get all items that have passkeys.+ public func getAllItemsWithPasskeys() throws -> [Item] {+ return try getAllItems().filter { $0.hasPasskey }+ }- guard let createdAt = DateHelpers.parseDateString(createdAtString),- let updatedAt = DateHelpers.parseDateString(updatedAtString) else {- continue- }+ /// Get all unique email addresses from items.+ /// - Returns: Array of email addresses+ public func getAllItemEmailAddresses() throws -> [String] {+ return try itemRepository.getAllEmailAddresses()+ }++ /// Get recently deleted items (in trash).+ /// - Returns: Array of items+ public func getRecentlyDeletedItems() throws -> [Item] {+ return try itemRepository.getRecentlyDeleted()+ }- guard let isDeletedInt64 = row[6] as? Int64 else { continue }- let isDeleted = isDeletedInt64 == 1+ /// Get count of items in trash.+ /// - Returns: Number of items in trash+ public func getRecentlyDeletedCount() throws -> Int {+ return try itemRepository.getRecentlyDeletedCount()+ }- guard let serviceId = row[7] as? String,- let serviceCreatedAtString = row[11] as? String,- let serviceUpdatedAtString = row[12] as? String,- let serviceIsDeletedInt64 = row[13] as? Int64,- let serviceCreatedAt = DateHelpers.parseDateString(serviceCreatedAtString),- let serviceUpdatedAt = DateHelpers.parseDateString(serviceUpdatedAtString) else {- continue- }+ /// Move an item to trash.+ /// - Parameter itemId: The UUID of the item to trash+ /// - Returns: Number of rows affected+ @discardableResult+ public func trashItem(_ itemId: UUID) throws -> Int {+ return try itemRepository.trash(itemId.uuidString.uppercased())+ }- let serviceIsDeleted = serviceIsDeletedInt64 == 1+ /// Restore an item from trash.+ /// - Parameter itemId: The UUID of the item to restore+ /// - Returns: Number of rows affected+ @discardableResult+ public func restoreItem(_ itemId: UUID) throws -> Int {+ return try itemRepository.restore(itemId.uuidString.uppercased())+ }- let service = Service(- id: UUID(uuidString: serviceId)!,- name: row[8] as? String,- url: row[9] as? String,- logo: (row[10] as? SQLite.Blob).map { Data($0.bytes) },- createdAt: serviceCreatedAt,- updatedAt: serviceUpdatedAt,- isDeleted: serviceIsDeleted- )+ /// Permanently delete an item.+ /// - Parameter itemId: The UUID of the item to permanently delete+ /// - Returns: Number of rows affected+ @discardableResult+ public func permanentlyDeleteItem(_ itemId: UUID) throws -> Int {+ return try itemRepository.permanentlyDelete(itemId.uuidString.uppercased())+ }- var alias: Alias?- if let aliasIdString = row[19] as? String,- let aliasCreatedAtString = row[26] as? String,- let aliasUpdatedAtString = row[27] as? String,- let aliasIsDeletedInt64 = row[28] as? Int64,- let aliasCreatedAt = DateHelpers.parseDateString(aliasCreatedAtString),- let aliasUpdatedAt = DateHelpers.parseDateString(aliasUpdatedAtString) {+ /// Create a new item.+ /// - Parameter item: The item to create+ /// - Returns: The ID of the created item+ @discardableResult+ public func createItem(_ item: Item) throws -> String {+ return try itemRepository.create(item)+ }- let aliasIsDeleted = aliasIsDeletedInt64 == 1+ /// Update an existing item.+ /// - Parameter item: The item to update+ /// - Returns: Number of rows affected+ @discardableResult+ public func updateItem(_ item: Item) throws -> Int {+ return try itemRepository.update(item)+ }- let aliasBirthDate: Date- if let aliasBirthDateString = row[24] as? String,- let parsedBirthDate = DateHelpers.parseDateString(aliasBirthDateString) {- aliasBirthDate = parsedBirthDate- } else {- // Use 0001-01-01 00:00 as the default date if birthDate is null- var dateComponents = DateComponents()- dateComponents.year = 1- dateComponents.month = 1- dateComponents.day = 1- dateComponents.hour = 0- dateComponents.minute = 0- dateComponents.second = 0- aliasBirthDate = Calendar(identifier: .gregorian).date(from: dateComponents)!- }+ // MARK: - Legacy Credentials (Compatibility Layer)- alias = Alias(- id: UUID(uuidString: aliasIdString)!,- gender: row[20] as? String,- firstName: row[21] as? String,- lastName: row[22] as? String,- nickName: row[23] as? String,- birthDate: aliasBirthDate,- email: row[25] as? String,- createdAt: aliasCreatedAt,- updatedAt: aliasUpdatedAt,- isDeleted: aliasIsDeleted- )- }+ /// Get all credentials from the database.+ /// This method converts the new Items model back to the legacy Credential model for compatibility.+ /// Used by iOS Autofill extension which expects the old Credential structure.+ public func getAllCredentials() throws -> [Credential] {+ let items = try getAllItems()+ return items.compactMap { convertItemToCredential($0) }+ }- var password: Password?- if let passwordIdString = row[14] as? String,- let passwordValue = row[15] as? String,- let passwordCreatedAtString = row[16] as? String,- let passwordUpdatedAtString = row[17] as? String,- let passwordIsDeletedInt64 = row[18] as? Int64,- let passwordCreatedAt = DateHelpers.parseDateString(passwordCreatedAtString),- let passwordUpdatedAt = DateHelpers.parseDateString(passwordUpdatedAtString) {-- let passwordIsDeleted = passwordIsDeletedInt64 == 1-- password = Password(- id: UUID(uuidString: passwordIdString)!,- credentialId: UUID(uuidString: idString)!,- value: passwordValue,- createdAt: passwordCreatedAt,- updatedAt: passwordUpdatedAt,- isDeleted: passwordIsDeleted- )- }+ /// Convert an Item to the legacy Credential format.+ /// Used to maintain backwards compatibility with iOS Autofill extension.+ private func convertItemToCredential(_ item: Item) -> Credential? {+ // Create a Service from the item+ let service = Service(+ id: item.id, // Use item ID as service ID (they're now the same entity)+ name: item.name,+ url: item.url,+ logo: item.logo,+ createdAt: item.createdAt,+ updatedAt: item.updatedAt,+ isDeleted: false+ )++ // Create an Alias if the item has alias fields+ var alias: Alias?+ if item.firstName != nil || item.lastName != nil || item.email != nil {+ // Default birth date for backwards compatibility+ var dateComponents = DateComponents()+ dateComponents.year = 1+ dateComponents.month = 1+ dateComponents.day = 1+ let defaultBirthDate = Calendar(identifier: .gregorian).date(from: dateComponents)!++ alias = Alias(+ id: item.id, // Use item ID as alias ID+ gender: item.getFieldValue(FieldKey.aliasGender),+ firstName: item.firstName,+ lastName: item.lastName,+ nickName: nil,+ birthDate: defaultBirthDate, // TODO: Parse birthdate from field value+ email: item.email,+ createdAt: item.createdAt,+ updatedAt: item.updatedAt,+ isDeleted: false+ )+ }- // Load passkeys for this credential- let passkeys = try getPasskeys(forCredentialId: UUID(uuidString: idString)!)-- let credential = Credential(- id: UUID(uuidString: idString)!,- alias: alias,- service: service,- username: row[2] as? String,- notes: row[3] as? String,- password: password,- passkeys: passkeys,- createdAt: createdAt,- updatedAt: updatedAt,- isDeleted: isDeleted+ // Create a Password if the item has a password field+ var password: Password?+ if let passwordValue = item.password {+ password = Password(+ id: UUID(), // Generate a new ID for the password+ credentialId: item.id,+ value: passwordValue,+ createdAt: item.createdAt,+ updatedAt: item.updatedAt,+ isDeleted: false)- result.append(credential)}- return result+ // Load passkeys for this item+ let passkeys = try? getPasskeys(forItemId: item.id)++ return Credential(+ id: item.id,+ alias: alias,+ service: service,+ username: item.username,+ notes: item.getFieldValue("login.notes"),+ password: password,+ passkeys: passkeys,+ createdAt: item.createdAt,+ updatedAt: item.updatedAt,+ isDeleted: false+ )}- // swiftlint:enable function_body_length/// Get all credentials that have passkeys by filtering the result of getAllCredentials.public func getAllCredentialsWithPasskeys() throws -> [Credential] {diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swiftindex d18187cd6..01da13bb8 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift@@ -31,6 +31,46 @@ public struct VaultResponse: Codable {public let vault: VaultData}+/// Sync state result+public struct SyncStateResult {+ public let isDirty: Bool+ public let mutationSequence: Int+ public let serverRevision: Int+ public let isSyncing: Bool++ public init(isDirty: Bool, mutationSequence: Int, serverRevision: Int, isSyncing: Bool) {+ self.isDirty = isDirty+ self.mutationSequence = mutationSequence+ self.serverRevision = serverRevision+ self.isSyncing = isSyncing+ }+}++/// Result of checking for new vault version+public struct VaultVersionCheckResult {+ public let isNewVersionAvailable: Bool+ public let newRevision: Int?+ public let serverRevision: Int+ public let syncState: SyncStateResult+}++/// Result of vault upload+public struct VaultUploadResult {+ public let success: Bool+ public let status: Int+ public let newRevisionNumber: Int+ public let mutationSeqAtStart: Int+ public let error: String?++ public init(success: Bool, status: Int, newRevisionNumber: Int, mutationSeqAtStart: Int, error: String? = nil) {+ self.success = success+ self.status = status+ self.newRevisionNumber = newRevisionNumber+ self.mutationSeqAtStart = mutationSeqAtStart+ self.error = error+ }+}+/// Extension for the VaultStore class to handle vault sync operationsextension VaultStore {// MARK: - Vault Sync@@ -49,6 +89,49 @@ extension VaultStore {return nil}+ /// Check if a new vault version is available, including sync state for merge decision+ /// This enhanced version returns sync state so the caller can decide whether to merge+ public func checkVaultVersion(using webApiService: WebApiService) async throws -> VaultVersionCheckResult {+ let status = try await fetchAndValidateStatus(using: webApiService)+ setOfflineMode(false)++ let syncState = getSyncState()+ let isNewVersionAvailable = status.vaultRevision > syncState.serverRevision++ return VaultVersionCheckResult(+ isNewVersionAvailable: isNewVersionAvailable,+ newRevision: isNewVersionAvailable ? status.vaultRevision : nil,+ serverRevision: status.vaultRevision,+ syncState: syncState+ )+ }++ /// Fetch the server vault (encrypted blob)+ /// Use this for merge operations where you need both local and server vaults+ public func fetchServerVault(using webApiService: WebApiService) async throws -> VaultResponse {+ let vaultResponse: WebApiResponse+ do {+ vaultResponse = try await webApiService.executeRequest(+ method: "GET",+ endpoint: "Vault",+ body: nil,+ headers: [:],+ requiresAuth: true+ )+ } catch {+ throw VaultSyncError.networkError(underlyingError: error)+ }++ guard vaultResponse.statusCode == 200 else {+ if vaultResponse.statusCode == 401 {+ throw VaultSyncError.sessionExpired+ }+ throw VaultSyncError.serverUnavailable(statusCode: vaultResponse.statusCode)+ }++ return try parseVaultResponse(vaultResponse.body)+ }+/// Download and store the vault from the server/// This method assumes a version check has already been performed/// Use this after calling isNewVaultVersionAvailable() to download the vaultdiff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.tsindex 86fa6d072..c16031485 100644--- a/apps/mobile-app/specs/NativeVaultManager.ts+++ b/apps/mobile-app/specs/NativeVaultManager.ts@@ -93,6 +93,58 @@ export interface Spec extends TurboModule {downloadVault(newRevision: number): Promise<boolean>;mutateVault(): Promise<boolean>;+ // Sync state management+ getSyncState(): Promise<{+ isDirty: boolean;+ mutationSequence: number;+ serverRevision: number;+ isSyncing: boolean;+ }>;+ setIsDirty(isDirty: boolean): Promise<void>;+ setIsSyncing(isSyncing: boolean): Promise<void>;+ storeEncryptedVaultWithSyncState(+ encryptedVault: string,+ markDirty: boolean,+ serverRevision: number | null,+ expectedMutationSeq: number | null+ ): Promise<{ success: boolean; mutationSequence: number }>;+ markVaultClean(mutationSeqAtStart: number, newServerRevision: number): Promise<boolean>;+ uploadVault(): Promise<{+ success: boolean;+ status: number;+ newRevisionNumber: number;+ mutationSeqAtStart: number;+ error: string | null;+ }>;+ fetchServerVault(): Promise<{+ status: number;+ vault: {+ username: string;+ blob: string;+ version: string;+ currentRevisionNumber: number;+ encryptionPublicKey: string;+ credentialsCount: number;+ emailAddressList: string[];+ privateEmailDomainList: string[];+ hiddenPrivateEmailDomainList: string[];+ publicEmailDomainList: string[];+ createdAt: string;+ updatedAt: string;+ };+ }>;+ checkVaultVersion(): Promise<{+ isNewVersionAvailable: boolean;+ newRevision: number | null;+ serverRevision: number;+ syncState: {+ isDirty: boolean;+ mutationSequence: number;+ serverRevision: number;+ isSyncing: boolean;+ };+ }>;+// PIN unlock methodsisPinEnabled(): Promise<boolean>;removeAndDisablePin(): Promise<void>;diff --git a/apps/mobile-app/utils/SqliteClient.tsx b/apps/mobile-app/utils/SqliteClient.tsxindex 91689e7eb..4fc90fb81 100644--- a/apps/mobile-app/utils/SqliteClient.tsx+++ b/apps/mobile-app/utils/SqliteClient.tsx@@ -1,16 +1,16 @@import { Buffer } from 'buffer';import type { EncryptionKeyDerivationParams, VaultMetadata } from '@/utils/dist/core/models/metadata';-import type { Attachment, Credential, EncryptionKey, PasswordSettings, TotpCode, Passkey, Item } from '@/utils/dist/core/models/vault';+import type { Attachment, EncryptionKey, PasswordSettings, TotpCode, Passkey, Item } from '@/utils/dist/core/models/vault';import { VaultSqlGenerator, VaultVersion, checkVersionCompatibility, extractVersionFromMigrationId } from '@/utils/dist/core/vault';import { VaultVersionIncompatibleError } from '@/utils/types/errors/VaultVersionIncompatibleError';import NativeVaultManager from '@/specs/NativeVaultManager';-import * as dateFormatter from '@/utils/dateFormatter';import { ItemRepository } from '@/utils/db/repositories/ItemRepository';import { SettingsRepository } from '@/utils/db/repositories/SettingsRepository';import { LogoRepository } from '@/utils/db/repositories/LogoRepository';import { FolderRepository, type Folder } from '@/utils/db/repositories/FolderRepository';+import { PasskeyRepository, type PasskeyWithItemInfo } from '@/utils/db/repositories/PasskeyRepository';import type { IDatabaseClient, SqliteBindValue } from '@/utils/db/BaseRepository';import type { ItemWithDeletedAt } from '@/utils/db/mappers/ItemMapper';@@ -21,90 +21,65 @@ type SQLiteBindValue = string | number | null | Uint8Array;* Implements IDatabaseClient interface for repository pattern.*/class SqliteClient implements IDatabaseClient {- // Repositories for Item-based access (lazy initialized)- private _itemRepository: ItemRepository | null = null;- private _settingsRepository: SettingsRepository | null = null;- private _logoRepository: LogoRepository | null = null;- private _folderRepository: FolderRepository | null = null;+ // Lazy-initialized repositories+ private _items: ItemRepository | null = null;+ private _passkeys: PasskeyRepository | null = null;+ private _folders: FolderRepository | null = null;+ private _settings: SettingsRepository | null = null;+ private _logos: LogoRepository | null = null;/**- * Get the ItemRepository instance (lazy initialization).+ * Repository for Item CRUD operations.*/- public get itemRepository(): ItemRepository {- if (!this._itemRepository) {- // Use a factory function to create the repository with 'this' as the client- this._itemRepository = Object.setPrototypeOf(- { client: this as IDatabaseClient },- ItemRepository.prototype- ) as ItemRepository;- // Manually bind 'this' context to all repository methods- Object.getOwnPropertyNames(ItemRepository.prototype).forEach(name => {- const method = ItemRepository.prototype[name as keyof typeof ItemRepository.prototype];- if (typeof method === 'function' && name !== 'constructor') {- (this._itemRepository as unknown as Record<string, unknown>)[name] = method.bind(this._itemRepository);- }- });+ public get items(): ItemRepository {+ if (!this._items) {+ this._items = new ItemRepository(this);}- return this._itemRepository;+ return this._items;}/**- * Get the SettingsRepository instance (lazy initialization).+ * Repository for Passkey operations.*/- public get settingsRepository(): SettingsRepository {- if (!this._settingsRepository) {- this._settingsRepository = Object.setPrototypeOf(- { client: this as IDatabaseClient },- SettingsRepository.prototype- ) as SettingsRepository;- Object.getOwnPropertyNames(SettingsRepository.prototype).forEach(name => {- const method = SettingsRepository.prototype[name as keyof typeof SettingsRepository.prototype];- if (typeof method === 'function' && name !== 'constructor') {- (this._settingsRepository as unknown as Record<string, unknown>)[name] = method.bind(this._settingsRepository);- }- });+ public get passkeys(): PasskeyRepository {+ if (!this._passkeys) {+ this._passkeys = new PasskeyRepository(this);}- return this._settingsRepository;+ return this._passkeys;}/**- * Get the LogoRepository instance (lazy initialization).+ * Repository for Folder operations.*/- public get logoRepository(): LogoRepository {- if (!this._logoRepository) {- this._logoRepository = Object.setPrototypeOf(- { client: this as IDatabaseClient },- LogoRepository.prototype- ) as LogoRepository;- Object.getOwnPropertyNames(LogoRepository.prototype).forEach(name => {- const method = LogoRepository.prototype[name as keyof typeof LogoRepository.prototype];- if (typeof method === 'function' && name !== 'constructor') {- (this._logoRepository as unknown as Record<string, unknown>)[name] = method.bind(this._logoRepository);- }- });+ public get folders(): FolderRepository {+ if (!this._folders) {+ this._folders = new FolderRepository(this);}- return this._logoRepository;+ return this._folders;}/**- * Get the FolderRepository instance (lazy initialization).+ * Repository for Settings and auxiliary data operations.*/- public get folderRepository(): FolderRepository {- if (!this._folderRepository) {- this._folderRepository = Object.setPrototypeOf(- { client: this as IDatabaseClient },- FolderRepository.prototype- ) as FolderRepository;- Object.getOwnPropertyNames(FolderRepository.prototype).forEach(name => {- const method = FolderRepository.prototype[name as keyof typeof FolderRepository.prototype];- if (typeof method === 'function' && name !== 'constructor') {- (this._folderRepository as unknown as Record<string, unknown>)[name] = method.bind(this._folderRepository);- }- });+ public get settings(): SettingsRepository {+ if (!this._settings) {+ this._settings = new SettingsRepository(this);}- return this._folderRepository;+ return this._settings;}+ /**+ * Repository for Logo management operations.+ */+ public get logos(): LogoRepository {+ if (!this._logos) {+ this._logos = new LogoRepository(this);+ }+ return this._logos;+ }++ // ===== Core Database Operations =====+/*** Store the encrypted database via the native code implementation.*/@@ -306,23 +281,12 @@ class SqliteClient implements IDatabaseClient {}}- /**- * Close the database connection and free resources.- */- public close(): void {- // No-op since the native code handles connection lifecycle- }-- // ============================================================================- // NEW: Item-based methods using repository pattern- // ============================================================================-/*** Fetch all items (new V5 schema).* @returns Array of Item objects*/public async getAllItems(): Promise<Item[]> {- return this.itemRepository.getAll();+ return this.items.getAll();}/**@@ -331,7 +295,7 @@ class SqliteClient implements IDatabaseClient {* @returns Item object or null if not found*/public async getItemById(itemId: string): Promise<Item | null> {- return this.itemRepository.getById(itemId);+ return this.items.getById(itemId);}/**@@ -339,7 +303,16 @@ class SqliteClient implements IDatabaseClient {* @returns Array of email addresses*/public async getAllItemEmailAddresses(): Promise<string[]> {- return this.itemRepository.getAllEmailAddresses();+ return this.items.getAllEmailAddresses();+ }++ /**+ * Fetch an item by its email address (case-insensitive).+ * @param email - The email address to search for+ * @returns Item object or null if not found+ */+ public async getItemByEmail(email: string): Promise<Item | null> {+ return this.items.getByEmail(email);}/**@@ -347,7 +320,7 @@ class SqliteClient implements IDatabaseClient {* @returns Array of items with DeletedAt field*/public async getRecentlyDeletedItems(): Promise<ItemWithDeletedAt[]> {- return this.itemRepository.getRecentlyDeleted();+ return this.items.getRecentlyDeleted();}/**@@ -355,7 +328,7 @@ class SqliteClient implements IDatabaseClient {* @returns Number of items in trash*/public async getRecentlyDeletedCount(): Promise<number> {- return this.itemRepository.getRecentlyDeletedCount();+ return this.items.getRecentlyDeletedCount();}/**@@ -366,7 +339,7 @@ class SqliteClient implements IDatabaseClient {* @returns The ID of the created item*/public async createItem(item: Item, attachments: Attachment[] = [], totpCodes: TotpCode[] = []): Promise<string> {- return this.itemRepository.create(item, attachments, totpCodes);+ return this.items.create(item, attachments, totpCodes);}/**@@ -385,7 +358,7 @@ class SqliteClient implements IDatabaseClient {originalTotpCodeIds: string[],totpCodes: TotpCode[]): Promise<number> {- return this.itemRepository.update(item, originalAttachmentIds, attachments, originalTotpCodeIds, totpCodes);+ return this.items.update(item, originalAttachmentIds, attachments, originalTotpCodeIds, totpCodes);}/**@@ -394,7 +367,7 @@ class SqliteClient implements IDatabaseClient {* @returns Number of rows affected*/public async trashItem(itemId: string): Promise<number> {- return this.itemRepository.trash(itemId);+ return this.items.trash(itemId);}/**@@ -403,7 +376,7 @@ class SqliteClient implements IDatabaseClient {* @returns Number of rows affected*/public async restoreItem(itemId: string): Promise<number> {- return this.itemRepository.restore(itemId);+ return this.items.restore(itemId);}/**@@ -412,7 +385,7 @@ class SqliteClient implements IDatabaseClient {* @returns Number of rows affected*/public async permanentlyDeleteItem(itemId: string): Promise<number> {- return this.itemRepository.permanentlyDelete(itemId);+ return this.items.permanentlyDelete(itemId);}/**@@ -421,7 +394,7 @@ class SqliteClient implements IDatabaseClient {* @returns Array of TotpCode objects*/public async getTotpCodesForItem(itemId: string): Promise<TotpCode[]> {- return this.settingsRepository.getTotpCodesForItem(itemId);+ return this.settings.getTotpCodesForItem(itemId);}/**@@ -430,19 +403,15 @@ class SqliteClient implements IDatabaseClient {* @returns Array of attachments*/public async getAttachmentsForItem(itemId: string): Promise<Attachment[]> {- return this.settingsRepository.getAttachmentsForItem(itemId);+ return this.settings.getAttachmentsForItem(itemId);}- // ============================================================================- // NEW: Folder-based methods using repository pattern- // ============================================================================-/*** Get all folders.* @returns Array of Folder objects*/public async getAllFolders(): Promise<Folder[]> {- return this.folderRepository.getAll();+ return this.folders.getAll();}/**@@ -451,7 +420,7 @@ class SqliteClient implements IDatabaseClient {* @returns Folder object or null if not found*/public async getFolderById(folderId: string): Promise<Omit<Folder, 'Weight'> | null> {- return this.folderRepository.getById(folderId);+ return this.folders.getById(folderId);}/**@@ -461,7 +430,7 @@ class SqliteClient implements IDatabaseClient {* @returns The ID of the created folder*/public async createFolder(name: string, parentFolderId?: string | null): Promise<string> {- return this.folderRepository.create(name, parentFolderId);+ return this.folders.create(name, parentFolderId);}/**@@ -471,7 +440,7 @@ class SqliteClient implements IDatabaseClient {* @returns The number of rows updated*/public async updateFolder(folderId: string, name: string): Promise<number> {- return this.folderRepository.update(folderId, name);+ return this.folders.update(folderId, name);}/**@@ -480,7 +449,7 @@ class SqliteClient implements IDatabaseClient {* @returns The number of rows updated*/public async deleteFolder(folderId: string): Promise<number> {- return this.folderRepository.delete(folderId);+ return this.folders.delete(folderId);}/**@@ -489,7 +458,7 @@ class SqliteClient implements IDatabaseClient {* @returns The number of items trashed*/public async deleteFolderWithContents(folderId: string): Promise<number> {- return this.folderRepository.deleteWithContents(folderId);+ return this.folders.deleteWithContents(folderId);}/**@@ -499,229 +468,13 @@ class SqliteClient implements IDatabaseClient {* @returns The number of rows updated*/public async moveItemToFolder(itemId: string, folderId: string | null): Promise<number> {- return this.folderRepository.moveItem(itemId, folderId);+ return this.folders.moveItem(itemId, folderId);}// ============================================================================- // LEGACY: Credential-based methods (kept for backward compatibility)+ // Utility methods// ============================================================================- /**- * Fetch a single credential with its associated service information.- * @param credentialId - The ID of the credential to fetch.- * @returns Credential object with service details or null if not found.- */- public async getCredentialById(credentialId: string): Promise<Credential | null> {- const query = `- SELECT DISTINCT- c.Id,- c.Username,- c.Notes,- c.ServiceId,- s.Name as ServiceName,- s.Url as ServiceUrl,- s.Logo as Logo,- a.FirstName,- a.LastName,- a.NickName,- a.BirthDate,- a.Gender,- a.Email,- p.Value as Password,- CASE- WHEN EXISTS (- SELECT 1 FROM Passkeys pk- WHERE pk.CredentialId = c.Id AND pk.IsDeleted = 0- ) THEN 1- ELSE 0- END as HasPasskey,- (SELECT pk.RpId FROM Passkeys pk WHERE pk.CredentialId = c.Id AND pk.IsDeleted = 0 LIMIT 1) as PasskeyRpId,- (SELECT pk.DisplayName FROM Passkeys pk WHERE pk.CredentialId = c.Id AND pk.IsDeleted = 0 LIMIT 1) as PasskeyDisplayName- FROM Credentials c- LEFT JOIN Services s ON c.ServiceId = s.Id- LEFT JOIN Aliases a ON c.AliasId = a.Id- LEFT JOIN Passwords p ON p.CredentialId = c.Id- WHERE c.IsDeleted = 0- AND c.Id = ?`;-- const results = await this.executeQuery(query, [credentialId]);-- if (results.length === 0) {- return null;- }-- // Convert the first row to a Credential object- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const row = results[0] as any;- return {- Id: row.Id,- Username: row.Username,- Password: row.Password,- ServiceName: row.ServiceName,- ServiceUrl: row.ServiceUrl,- Logo: row.Logo,- Notes: row.Notes,- HasPasskey: row.HasPasskey === 1,- PasskeyRpId: row.PasskeyRpId,- PasskeyDisplayName: row.PasskeyDisplayName,- Alias: {- FirstName: row.FirstName,- LastName: row.LastName,- NickName: row.NickName,- BirthDate: row.BirthDate,- Gender: row.Gender,- Email: row.Email- }- };- }-- /**- * Fetch all credentials with their associated service information.- * @returns Array of Credential objects with service details.- */- public async getAllCredentials(): Promise<Credential[]> {- const query = `- SELECT DISTINCT- c.Id,- c.Username,- c.Notes,- c.ServiceId,- s.Name as ServiceName,- s.Url as ServiceUrl,- s.Logo as Logo,- a.FirstName,- a.LastName,- a.NickName,- a.BirthDate,- a.Gender,- a.Email,- p.Value as Password,- CASE- WHEN EXISTS (- SELECT 1 FROM Passkeys pk- WHERE pk.CredentialId = c.Id AND pk.IsDeleted = 0- ) THEN 1- ELSE 0- END as HasPasskey,- (SELECT pk.RpId FROM Passkeys pk WHERE pk.CredentialId = c.Id AND pk.IsDeleted = 0 LIMIT 1) as PasskeyRpId,- (SELECT pk.DisplayName FROM Passkeys pk WHERE pk.CredentialId = c.Id AND pk.IsDeleted = 0 LIMIT 1) as PasskeyDisplayName,- CASE- WHEN EXISTS (- SELECT 1 FROM Attachments att- WHERE att.CredentialId = c.Id AND att.IsDeleted = 0- ) THEN 1- ELSE 0- END as HasAttachment- FROM Credentials c- LEFT JOIN Services s ON c.ServiceId = s.Id- LEFT JOIN Aliases a ON c.AliasId = a.Id- LEFT JOIN Passwords p ON p.CredentialId = c.Id- WHERE c.IsDeleted = 0- ORDER BY c.CreatedAt DESC`;-- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const results = await this.executeQuery<any>(query);-- return results.map((row) => ({- Id: row.Id,- Username: row.Username,- Password: row.Password,- ServiceName: row.ServiceName,- ServiceUrl: row.ServiceUrl,- Logo: row.Logo,- Notes: row.Notes,- HasPasskey: row.HasPasskey === 1,- PasskeyRpId: row.PasskeyRpId,- PasskeyDisplayName: row.PasskeyDisplayName,- HasAttachment: row.HasAttachment === 1,- Alias: {- FirstName: row.FirstName,- LastName: row.LastName,- NickName: row.NickName,- BirthDate: row.BirthDate,- Gender: row.Gender,- Email: row.Email- }- }));- }-- /**- * Delete a credential by ID- * @param credentialId - The ID of the credential to delete- * @returns The number of rows deleted- */- public async deleteCredentialById(credentialId: string): Promise<number> {- try {- await NativeVaultManager.beginTransaction();-- const currentDateTime = dateFormatter.now();-- // Update the credential, alias, and service to be deleted- const query = `- UPDATE Credentials- SET IsDeleted = 1,- UpdatedAt = ?- WHERE Id = ?`;-- const aliasQuery = `- UPDATE Aliases- SET IsDeleted = 1,- UpdatedAt = ?- WHERE Id = (- SELECT AliasId- FROM Credentials- WHERE Id = ?- )`;-- const serviceQuery = `- UPDATE Services- SET IsDeleted = 1,- UpdatedAt = ?- WHERE Id = (- SELECT ServiceId- FROM Credentials- WHERE Id = ?- )`;-- const passkeyQuery = `- UPDATE Passkeys- SET IsDeleted = 1,- UpdatedAt = ?- WHERE CredentialId = ?`;-- const results = await this.executeUpdate(query, [currentDateTime, credentialId]);- await this.executeUpdate(aliasQuery, [currentDateTime, credentialId]);- await this.executeUpdate(serviceQuery, [currentDateTime, credentialId]);- await this.executeUpdate(passkeyQuery, [currentDateTime, credentialId]);-- await NativeVaultManager.commitTransaction();- return results;- } catch (error) {- await NativeVaultManager.rollbackTransaction();- console.error('Error deleting credential:', error);- throw error;- }- }-- /**- * Fetch all unique email addresses from all credentials.- * @returns Array of email addresses.- */- public async getAllEmailAddresses(): Promise<string[]> {- const query = `- SELECT DISTINCT- a.Email- FROM Credentials c- LEFT JOIN Aliases a ON c.AliasId = a.Id- WHERE a.Email IS NOT NULL AND a.Email != '' AND c.IsDeleted = 0- `;-- const results = await this.executeQuery(query);-- // eslint-disable-next-line @typescript-eslint/no-explicit-any- return results.map((row: any) => row.Email);- }-/*** Fetch all encryption keys.*/@@ -857,146 +610,6 @@ class SqliteClient implements IDatabaseClient {return defaultSettings;}- /**- * Create a new credential with associated entities- * @param credential The credential object to insert- * @param attachments The attachments to insert- * @returns The ID of the newly created credential- */- public async createCredential(credential: Credential, attachments: Attachment[], totpCodes: TotpCode[] = []): Promise<string> {- try {- await NativeVaultManager.beginTransaction();-- // 1. Insert Service- let logoData = null;- try {- if (credential.Logo) {- // Handle object-like array conversion- if (typeof credential.Logo === 'object' && !ArrayBuffer.isView(credential.Logo)) {- const values = Object.values(credential.Logo);- logoData = new Uint8Array(values);- // Handle existing array types- } else if (Array.isArray(credential.Logo) || credential.Logo instanceof ArrayBuffer || credential.Logo instanceof Uint8Array) {- logoData = new Uint8Array(credential.Logo);- }- }- } catch (error) {- console.warn('Failed to convert logo to Uint8Array:', error);- logoData = null;- }-- const serviceQuery = `- INSERT INTO Services (Id, Name, Url, Logo, CreatedAt, UpdatedAt, IsDeleted)- VALUES (?, ?, ?, ?, ?, ?, ?)`;- const serviceId = crypto.randomUUID().toUpperCase();- const currentDateTime = dateFormatter.now();- await this.executeUpdate(serviceQuery, [- serviceId,- credential.ServiceName,- credential.ServiceUrl ?? null,- logoData,- currentDateTime,- currentDateTime,- 0- ]);-- // 2. Insert Alias- const aliasQuery = `- INSERT INTO Aliases (Id, FirstName, LastName, NickName, BirthDate, Gender, Email, CreatedAt, UpdatedAt, IsDeleted)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;- const aliasId = crypto.randomUUID().toUpperCase();- await this.executeUpdate(aliasQuery, [- aliasId,- credential.Alias.FirstName ?? null,- credential.Alias.LastName ?? null,- credential.Alias.NickName ?? null,- credential.Alias.BirthDate ?? null,- credential.Alias.Gender ?? null,- credential.Alias.Email ?? null,- currentDateTime,- currentDateTime,- 0- ]);-- // 3. Insert Credential- const credentialQuery = `- INSERT INTO Credentials (Id, Username, Notes, ServiceId, AliasId, CreatedAt, UpdatedAt, IsDeleted)- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`;- const credentialId = crypto.randomUUID().toUpperCase();- await this.executeUpdate(credentialQuery, [- credentialId,- credential.Username ?? null,- credential.Notes ?? null,- serviceId,- aliasId,- currentDateTime,- currentDateTime,- 0- ]);-- // 4. Insert Password- if (credential.Password) {- const passwordQuery = `- INSERT INTO Passwords (Id, Value, CredentialId, CreatedAt, UpdatedAt, IsDeleted)- VALUES (?, ?, ?, ?, ?, ?)`;- const passwordId = crypto.randomUUID().toUpperCase();- await this.executeUpdate(passwordQuery, [- passwordId,- credential.Password,- credentialId,- currentDateTime,- currentDateTime,- 0- ]);- }-- // 5. Insert Attachments- for (const attachment of attachments) {- const attachmentQuery = `- INSERT INTO Attachments (Id, Filename, Blob, CredentialId, CreatedAt, UpdatedAt, IsDeleted)- VALUES (?, ?, ?, ?, ?, ?, ?)`;- await this.executeUpdate(attachmentQuery, [- attachment.Id,- attachment.Filename,- attachment.Blob as Uint8Array,- credentialId,- currentDateTime,- currentDateTime,- 0- ]);- }-- // 6. Insert TOTP codes- for (const totpCode of totpCodes) {- // Skip deleted codes- if (totpCode.IsDeleted) {- continue;- }-- const totpCodeQuery = `- INSERT INTO TotpCodes (Id, Name, SecretKey, CredentialId, CreatedAt, UpdatedAt, IsDeleted)- VALUES (?, ?, ?, ?, ?, ?, ?)`;- await this.executeUpdate(totpCodeQuery, [- totpCode.Id || crypto.randomUUID().toUpperCase(),- totpCode.Name,- totpCode.SecretKey,- credentialId,- currentDateTime,- currentDateTime,- 0- ]);- }-- await NativeVaultManager.commitTransaction();- return credentialId;-- } catch (error) {- await NativeVaultManager.rollbackTransaction();- console.error('Error creating credential:', error);- throw error;- }- }-/*** Get the current database version from the migrations history.* Returns the internal version information that matches the current database version.@@ -1062,674 +675,48 @@ class SqliteClient implements IDatabaseClient {}/**- * Get TOTP codes for a credential- * @param credentialId - The ID of the credential to get TOTP codes for- * @returns Array of TotpCode objects- */- public async getTotpCodesForCredential(credentialId: string): Promise<TotpCode[]> {- try {- const query = `- SELECT- Id,- Name,- SecretKey,- CredentialId- FROM TotpCodes- WHERE CredentialId = ? AND IsDeleted = 0`;-- return this.executeQuery<TotpCode>(query, [credentialId]);- } catch (error) {- console.error('Error getting TOTP codes:', error);- // Return empty array instead of throwing to be robust- return [];- }- }-- /**- * Get attachments for a specific credential- * @param credentialId - The ID of the credential- * @returns Array of attachments for the credential- */- public async getAttachmentsForCredential(credentialId: string): Promise<Attachment[]> {- try {- if (!await this.tableExists('Attachments')) {- return [];- }-- const query = `- SELECT- Id,- Filename,- Blob,- CredentialId,- CreatedAt,- UpdatedAt,- IsDeleted- FROM Attachments- WHERE CredentialId = ? AND IsDeleted = 0`;- return this.executeQuery<Attachment>(query, [credentialId]);- } catch (error) {- console.error('Error getting attachments:', error);- return [];- }- }-- /**- * Check if a table exists in the database- * @param tableName - The name of the table to check- * @returns True if the table exists, false otherwise- */- private async tableExists(tableName: string): Promise<boolean> {- try {- const query = `- SELECT name FROM sqlite_master- WHERE type='table' AND name=?`;-- const results = await this.executeQuery(query, [tableName]);- return results.length > 0;- } catch (error) {- console.error(`Error checking if table ${tableName} exists:`, error);- return false;- }- }-- /**- * Get credential by email address- * @param email - The email address to look up- * @returns Credential object with service details or null if not found- */- public async getCredentialByEmail(email: string): Promise<Credential | null> {- const query = `- SELECT DISTINCT- c.Id,- c.Username,- c.Notes,- c.ServiceId,- s.Name as ServiceName,- s.Url as ServiceUrl,- s.Logo as Logo,- a.FirstName,- a.LastName,- a.NickName,- a.BirthDate,- a.Gender,- a.Email,- p.Value as Password- FROM Credentials c- LEFT JOIN Services s ON c.ServiceId = s.Id- LEFT JOIN Aliases a ON c.AliasId = a.Id- LEFT JOIN Passwords p ON p.CredentialId = c.Id- WHERE c.IsDeleted = 0- AND LOWER(a.Email) = LOWER(?)- LIMIT 1`;-- const results = await this.executeQuery(query, [email]);-- if (results.length === 0) {- return null;- }-- // Convert the first row to a Credential object- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const row = results[0] as any;- return {- Id: row.Id,- Username: row.Username,- Password: row.Password,- ServiceName: row.ServiceName,- ServiceUrl: row.ServiceUrl,- Logo: row.Logo,- Notes: row.Notes,- Alias: {- FirstName: row.FirstName,- LastName: row.LastName,- NickName: row.NickName,- BirthDate: row.BirthDate,- Gender: row.Gender,- Email: row.Email- }- };- }-- /**- * Update an existing credential with associated entities- * @param credential The credential object to update- * @param originalAttachmentIds The IDs of the original attachments- * @param attachments The attachments to update- * @param originalTotpCodeIds The IDs of the original TOTP codes- * @param totpCodes The TOTP codes to update- * @returns The number of rows modified- */- public async updateCredentialById(credential: Credential, originalAttachmentIds: string[], attachments: Attachment[], originalTotpCodeIds: string[], totpCodes: TotpCode[]): Promise<number> {- try {- await NativeVaultManager.beginTransaction();- const currentDateTime = dateFormatter.now();-- // Get existing credential to compare changes- const existingCredential = await this.getCredentialById(credential.Id);- if (!existingCredential) {- throw new Error('Credential not found');- }-- // 1. Update Service- const serviceQuery = `- UPDATE Services- SET Name = ?,- Url = ?,- Logo = COALESCE(?, Logo),- UpdatedAt = ?- WHERE Id = (- SELECT ServiceId- FROM Credentials- WHERE Id = ?- )`;-- let logoData = null;- try {- if (credential.Logo) {- // Handle object-like array conversion- if (typeof credential.Logo === 'object' && !ArrayBuffer.isView(credential.Logo)) {- const values = Object.values(credential.Logo);- logoData = new Uint8Array(values);- // Handle existing array types- } else if (Array.isArray(credential.Logo) || credential.Logo instanceof ArrayBuffer || credential.Logo instanceof Uint8Array) {- logoData = new Uint8Array(credential.Logo);- }- }- } catch (error) {- console.warn('Failed to convert logo to Uint8Array:', error);- logoData = null;- }-- await this.executeUpdate(serviceQuery, [- credential.ServiceName,- credential.ServiceUrl ?? null,- logoData,- currentDateTime,- credential.Id- ]);-- // 2. Update Alias- const aliasQuery = `- UPDATE Aliases- SET FirstName = ?,- LastName = ?,- NickName = ?,- BirthDate = ?,- Gender = ?,- Email = ?,- UpdatedAt = ?- WHERE Id = (- SELECT AliasId- FROM Credentials- WHERE Id = ?- )`;-- // Only update BirthDate if it's actually different (accounting for format differences)- let birthDate = credential.Alias.BirthDate;- if (birthDate && existingCredential.Alias.BirthDate) {- const newDate = new Date(birthDate);- const existingDate = new Date(existingCredential.Alias.BirthDate);- if (newDate.getTime() === existingDate.getTime()) {- birthDate = existingCredential.Alias.BirthDate;- }- }-- await this.executeUpdate(aliasQuery, [- credential.Alias.FirstName ?? null,- credential.Alias.LastName ?? null,- credential.Alias.NickName ?? null,- birthDate ?? null,- credential.Alias.Gender ?? null,- credential.Alias.Email ?? null,- currentDateTime,- credential.Id- ]);-- // 3. Update Credential- const credentialQuery = `- UPDATE Credentials- SET Username = ?,- Notes = ?,- UpdatedAt = ?- WHERE Id = ?`;-- await this.executeUpdate(credentialQuery, [- credential.Username ?? null,- credential.Notes ?? null,- currentDateTime,- credential.Id- ]);-- // 4. Update Password if changed- if (credential.Password !== existingCredential.Password) {- // Check if a password record already exists for this credential, if not, then create one.- const passwordRecordExistsQuery = `- SELECT Id- FROM Passwords- WHERE CredentialId = ?`;- const passwordResults = await this.executeQuery(passwordRecordExistsQuery, [credential.Id]);-- if (passwordResults.length === 0) {- // Create a new password record- const passwordQuery = `- INSERT INTO Passwords (Id, Value, CredentialId, CreatedAt, UpdatedAt, IsDeleted)- VALUES (?, ?, ?, ?, ?, ?)`;-- await this.executeUpdate(passwordQuery, [- crypto.randomUUID().toUpperCase(),- credential.Password,- credential.Id,- currentDateTime,- currentDateTime,- 0- ]);- } else {- // Update the existing password record- const passwordQuery = `- UPDATE Passwords- SET Value = ?, UpdatedAt = ?- WHERE CredentialId = ?`;-- await this.executeUpdate(passwordQuery, [- credential.Password,- currentDateTime,- credential.Id- ]);- }- }-- // 5. Handle Attachments- if (attachments) {- // Get current attachment IDs to track what needs to be deleted- const currentAttachmentIds = attachments.map(a => a.Id);-- // Delete attachments that were removed (in originalAttachmentIds but not in current attachments)- const attachmentsToDelete = originalAttachmentIds.filter(id => !currentAttachmentIds.includes(id));- for (const attachmentId of attachmentsToDelete) {- const deleteQuery = `- UPDATE Attachments- SET IsDeleted = 1,- UpdatedAt = ?- WHERE Id = ?`;- await this.executeUpdate(deleteQuery, [currentDateTime, attachmentId]);- }-- // Process each attachment- for (const attachment of attachments) {- const isExistingAttachment = originalAttachmentIds.includes(attachment.Id);-- if (!isExistingAttachment) {- // Insert new attachment- const insertQuery = `- INSERT INTO Attachments (Id, Filename, Blob, CredentialId, CreatedAt, UpdatedAt, IsDeleted)- VALUES (?, ?, ?, ?, ?, ?, ?)`;- await this.executeUpdate(insertQuery, [- attachment.Id,- attachment.Filename,- attachment.Blob as Uint8Array,- credential.Id,- currentDateTime,- currentDateTime,- 0- ]);- }- }- }-- // 6. Handle TOTP Codes- if (totpCodes) {- // Get current TOTP code IDs to track what needs to be deleted- const currentTotpCodeIds = totpCodes.filter(tc => !tc.IsDeleted).map(tc => tc.Id);-- // Delete TOTP codes that were removed (in originalTotpCodeIds but not in current codes)- const totpCodesToDelete = originalTotpCodeIds.filter(id => !currentTotpCodeIds.includes(id));- for (const totpCodeId of totpCodesToDelete) {- const deleteQuery = `- UPDATE TotpCodes- SET IsDeleted = 1,- UpdatedAt = ?- WHERE Id = ?`;- await this.executeUpdate(deleteQuery, [currentDateTime, totpCodeId]);- }-- // Process each TOTP code- for (const totpCode of totpCodes) {- // Skip codes marked as deleted- if (totpCode.IsDeleted) {- // If it was an original code, mark it as deleted in DB- if (originalTotpCodeIds.includes(totpCode.Id)) {- const deleteQuery = `- UPDATE TotpCodes- SET IsDeleted = 1,- UpdatedAt = ?- WHERE Id = ?`;- await this.executeUpdate(deleteQuery, [currentDateTime, totpCode.Id]);- }- continue;- }-- const isExistingTotpCode = originalTotpCodeIds.includes(totpCode.Id);-- if (!isExistingTotpCode) {- // Insert new TOTP code- const insertQuery = `- INSERT INTO TotpCodes (Id, Name, SecretKey, CredentialId, CreatedAt, UpdatedAt, IsDeleted)- VALUES (?, ?, ?, ?, ?, ?, ?)`;- await this.executeUpdate(insertQuery, [- totpCode.Id,- totpCode.Name,- totpCode.SecretKey,- credential.Id,- currentDateTime,- currentDateTime,- 0- ]);- } else {- // Update existing TOTP code- const updateQuery = `- UPDATE TotpCodes- SET Name = ?,- SecretKey = ?,- UpdatedAt = ?- WHERE Id = ?`;- await this.executeUpdate(updateQuery, [- totpCode.Name,- totpCode.SecretKey,- currentDateTime,- totpCode.Id- ]);- }- }- }-- await NativeVaultManager.commitTransaction();- return 1;-- } catch (error) {- console.error('Error updating credential:', error);- await NativeVaultManager.rollbackTransaction();- throw error;- }- }-- /**- * Get all passkeys for a specific relying party (rpId)+ * Get all passkeys for a specific relying party (rpId).* @param rpId - The relying party identifier (domain)- * @returns Array of passkey objects with credential info+ * @returns Array of passkey objects with item info*/- public async getPasskeysByRpId(rpId: string): Promise<Array<Passkey & { Username?: string | null; ServiceName?: string | null }>> {- const query = `- SELECT- p.Id,- p.CredentialId,- p.RpId,- p.UserId,- p.PublicKey,- p.PrivateKey,- p.DisplayName,- p.PrfKey,- p.AdditionalData,- p.CreatedAt,- p.UpdatedAt,- p.IsDeleted,- c.Username,- s.Name as ServiceName- FROM Passkeys p- LEFT JOIN Credentials c ON p.CredentialId = c.Id- LEFT JOIN Services s ON c.ServiceId = s.Id- WHERE p.RpId = ? AND p.IsDeleted = 0- ORDER BY p.CreatedAt DESC- `;-- const results = await this.executeQuery(query, [rpId]);-- // eslint-disable-next-line @typescript-eslint/no-explicit-any- return results.map((row: any) => ({- Id: row.Id,- ItemId: row.ItemId ?? row.CredentialId, // Support both old and new schema- RpId: row.RpId,- PublicKey: row.PublicKey,- PrivateKey: row.PrivateKey,- DisplayName: row.DisplayName,- PrfKey: row.PrfKey,- AdditionalData: row.AdditionalData,- CreatedAt: row.CreatedAt,- UpdatedAt: row.UpdatedAt,- IsDeleted: row.IsDeleted,- Username: row.Username,- ServiceName: row.ServiceName- }));+ public async getPasskeysByRpId(rpId: string): Promise<PasskeyWithItemInfo[]> {+ return this.passkeys.getByRpId(rpId);}/**- * Get a passkey by its ID+ * Get a passkey by its ID.* @param passkeyId - The passkey ID* @returns The passkey object or null if not found*/- public async getPasskeyById(passkeyId: string): Promise<(Passkey & { Username?: string | null; ServiceName?: string | null }) | null> {- const query = `- SELECT- p.Id,- p.CredentialId,- p.RpId,- p.UserId,- p.PublicKey,- p.PrivateKey,- p.DisplayName,- p.PrfKey,- p.AdditionalData,- p.CreatedAt,- p.UpdatedAt,- p.IsDeleted,- c.Username,- s.Name as ServiceName- FROM Passkeys p- LEFT JOIN Credentials c ON p.CredentialId = c.Id- LEFT JOIN Services s ON c.ServiceId = s.Id- WHERE p.Id = ? AND p.IsDeleted = 0- `;-- const results = await this.executeQuery(query, [passkeyId]);-- if (results.length === 0) {- return null;- }-- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const row: any = results[0];- return {- Id: row.Id,- ItemId: row.ItemId ?? row.CredentialId, // Support both old and new schema- RpId: row.RpId,- PublicKey: row.PublicKey,- PrivateKey: row.PrivateKey,- DisplayName: row.DisplayName,- PrfKey: row.PrfKey,- AdditionalData: row.AdditionalData,- CreatedAt: row.CreatedAt,- UpdatedAt: row.UpdatedAt,- IsDeleted: row.IsDeleted,- Username: row.Username,- ServiceName: row.ServiceName- };- }-- /**- * Get all passkeys for a specific credential- * @param credentialId - The credential ID- * @returns Array of passkey objects- */- public async getPasskeysByCredentialId(credentialId: string): Promise<Passkey[]> {- const query = `- SELECT- p.Id,- p.CredentialId,- p.RpId,- p.UserId,- p.PublicKey,- p.PrivateKey,- p.DisplayName,- p.PrfKey,- p.AdditionalData,- p.CreatedAt,- p.UpdatedAt,- p.IsDeleted- FROM Passkeys p- WHERE p.CredentialId = ? AND p.IsDeleted = 0- ORDER BY p.CreatedAt DESC- `;-- const results = await this.executeQuery(query, [credentialId]);-- // eslint-disable-next-line @typescript-eslint/no-explicit-any- return results.map((row: any) => ({- Id: row.Id,- ItemId: row.ItemId ?? row.CredentialId, // Support both old and new schema- RpId: row.RpId,- PublicKey: row.PublicKey,- PrivateKey: row.PrivateKey,- DisplayName: row.DisplayName,- PrfKey: row.PrfKey,- AdditionalData: row.AdditionalData,- CreatedAt: row.CreatedAt,- UpdatedAt: row.UpdatedAt,- IsDeleted: row.IsDeleted- }));+ public async getPasskeyById(passkeyId: string): Promise<PasskeyWithItemInfo | null> {+ return this.passkeys.getById(passkeyId);}/**- * Create a new passkey linked to an item+ * Create a new passkey linked to an item.* @param passkey - The passkey object to create*/public async createPasskey(passkey: Omit<Passkey, 'CreatedAt' | 'UpdatedAt' | 'IsDeleted'>): Promise<void> {- try {- await NativeVaultManager.beginTransaction();-- const currentDateTime = dateFormatter.now();-- const query = `- INSERT INTO Passkeys (- Id, ItemId, RpId, PublicKey, PrivateKey,- PrfKey, DisplayName, AdditionalData, CreatedAt, UpdatedAt, IsDeleted- )- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)- `;-- // Convert PrfKey to Uint8Array if it's a number array- let prfKeyData: Uint8Array | null = null;- if (passkey.PrfKey) {- prfKeyData = passkey.PrfKey instanceof Uint8Array ? passkey.PrfKey : new Uint8Array(passkey.PrfKey);- }-- await this.executeUpdate(query, [- passkey.Id,- passkey.ItemId,- passkey.RpId,- passkey.PublicKey,- passkey.PrivateKey,- prfKeyData,- passkey.DisplayName,- passkey.AdditionalData ?? null,- currentDateTime,- currentDateTime,- 0- ]);-- await NativeVaultManager.commitTransaction();- } catch (error) {- await NativeVaultManager.rollbackTransaction();- console.error('Error creating passkey:', error);- throw error;- }+ return this.passkeys.create(passkey);}/**- * Delete a passkey by its ID (soft delete)+ * Delete a passkey by its ID (soft delete).* @param passkeyId - The ID of the passkey to delete* @returns The number of rows updated*/public async deletePasskeyById(passkeyId: string): Promise<number> {- try {- await NativeVaultManager.beginTransaction();-- const currentDateTime = dateFormatter.now();-- const query = `- UPDATE Passkeys- SET IsDeleted = 1,- UpdatedAt = ?- WHERE Id = ?- `;-- const result = await this.executeUpdate(query, [currentDateTime, passkeyId]);-- await NativeVaultManager.commitTransaction();- return result;- } catch (error) {- await NativeVaultManager.rollbackTransaction();- console.error('Error deleting passkey:', error);- throw error;- }- }-- /**- * Delete all passkeys for a specific credential (soft delete)- * @param credentialId - The ID of the credential- * @returns The number of rows updated- */- public async deletePasskeysByCredentialId(credentialId: string): Promise<number> {- try {- await NativeVaultManager.beginTransaction();-- const currentDateTime = dateFormatter.now();-- const query = `- UPDATE Passkeys- SET IsDeleted = 1,- UpdatedAt = ?- WHERE CredentialId = ?- `;-- const result = await this.executeUpdate(query, [currentDateTime, credentialId]);-- await NativeVaultManager.commitTransaction();- return result;- } catch (error) {- await NativeVaultManager.rollbackTransaction();- console.error('Error deleting passkeys for credential:', error);- throw error;- }+ return this.passkeys.delete(passkeyId);}/**- * Update a passkey's display name+ * Update a passkey's display name.* @param passkeyId - The ID of the passkey to update* @param displayName - The new display name* @returns The number of rows updated*/public async updatePasskeyDisplayName(passkeyId: string, displayName: string): Promise<number> {- try {- await NativeVaultManager.beginTransaction();-- const currentDateTime = dateFormatter.now();-- const query = `- UPDATE Passkeys- SET DisplayName = ?,- UpdatedAt = ?- WHERE Id = ?- `;-- const result = await this.executeUpdate(query, [displayName, currentDateTime, passkeyId]);-- await NativeVaultManager.commitTransaction();- return result;- } catch (error) {- await NativeVaultManager.rollbackTransaction();- console.error('Error updating passkey display name:', error);- throw error;- }+ return this.passkeys.updateDisplayName(passkeyId, displayName);}}diff --git a/apps/mobile-app/utils/VaultMergeService.ts b/apps/mobile-app/utils/VaultMergeService.tsnew file mode 100644index 000000000..8931d89cf--- /dev/null+++ b/apps/mobile-app/utils/VaultMergeService.ts@@ -0,0 +1,93 @@+import NativeVaultManager from '@/specs/NativeVaultManager';++/**+ * Statistics about what was merged.+ */+export type MergeStats = {+ tablesProcessed: number;+ recordsFromLocal: number;+ recordsFromServer: number;+ recordsCreatedLocally: number;+ conflicts: number;+}++/**+ * Result of a merge operation.+ */+export type MergeResult = {+ success: boolean;+ mergedVaultBase64: string;+ stats: MergeStats;+}++/**+ * Service for merging two vault SQLite databases using Last-Write-Wins (LWW) strategy.+ *+ * For mobile apps, the merge logic is delegated to the native layer since it already+ * has access to the SQLite database and encryption operations. The native layer+ * uses the Rust core library (compiled to Swift bindings for iOS and Kotlin bindings+ * for Android) for the actual merge logic.+ *+ * The merge uses UpdatedAt timestamps on all SyncableEntity records to determine+ * which version of a record wins in case of conflict.+ *+ * Note: In the mobile app, the vault merge happens differently from the browser extension.+ * The browser extension uses sql.js (JavaScript SQLite) in the popup, while the mobile app+ * delegates to native code which directly manipulates the encrypted SQLite database.+ *+ * For now, we implement a simplified approach where the native layer handles the merge+ * by re-initializing the database with the merged content.+ */+export class VaultMergeService {+ /**+ * Merge local vault changes with server vault using LWW strategy.+ *+ * For mobile, this currently takes a simplified approach:+ * 1. The local and server vaults are both encrypted SQLite blobs+ * 2. We need to decrypt both, merge in-memory, and re-encrypt+ *+ * Since the native layer already has the decryption key and SQLite database,+ * the actual merge happens there. This wrapper provides a consistent API.+ *+ * @param localVaultBase64 - The local vault (with offline changes) as base64 encrypted SQLite+ * @param serverVaultBase64 - The server vault (latest version) as base64 encrypted SQLite+ * @param encryptionKey - The encryption key to decrypt/encrypt the vaults+ * @returns The merged vault as base64 encrypted SQLite+ */+ static async mergeVaults(+ localVaultBase64: string,+ serverVaultBase64: string,+ encryptionKey: string | null+ ): Promise<string> {+ /**+ * For the mobile app, we use a simpler merge strategy:+ * Since the local vault is already loaded in memory by the native layer,+ * we can:+ * 1. Store the server vault temporarily+ * 2. Have the native layer perform the merge+ * 3. Return the merged (re-encrypted) vault+ *+ * However, the current native implementation doesn't have a dedicated merge API.+ * For now, we return the local vault (preserving local changes) and log a warning.+ *+ * TODO: Implement proper LWW merge in native layer using Rust bindings.+ * The Rust core library already has the merge logic, we just need to expose it+ * through Swift/Kotlin bindings.+ */+ console.warn(+ '[VaultMergeService] Full LWW merge not yet implemented for mobile. ' ++ 'Preserving local changes. Server changes may be lost until next sync.'+ );++ /**+ * Fallback: Return the local vault to preserve local changes.+ * The sync mechanism will retry on next app open.+ *+ * A proper implementation would:+ * 1. Decrypt both vaults using the encryption key+ * 2. Use Rust core's mergeVaults() function+ * 3. Re-encrypt the merged result+ */+ return localVaultBase64;+ }+}diff --git a/apps/mobile-app/utils/db/BaseRepository.ts b/apps/mobile-app/utils/db/BaseRepository.tsindex e8f9f3f54..d5630afcd 100644--- a/apps/mobile-app/utils/db/BaseRepository.ts+++ b/apps/mobile-app/utils/db/BaseRepository.ts@@ -24,7 +24,7 @@ export abstract class BaseRepository {* Constructor for the BaseRepository class.* @param client - The database client to use for the repository*/- protected constructor(protected client: IDatabaseClient) {}+ public constructor(protected client: IDatabaseClient) {}/*** Execute a function within a transaction.diff --git a/apps/mobile-app/utils/db/queries/ItemQueries.ts b/apps/mobile-app/utils/db/queries/ItemQueries.tsindex 71f2c950a..abd7b8d0b 100644--- a/apps/mobile-app/utils/db/queries/ItemQueries.ts+++ b/apps/mobile-app/utils/db/queries/ItemQueries.ts@@ -111,6 +111,34 @@ export class ItemQueries {AND i.IsDeleted = 0AND i.DeletedAt IS NULL`;+ /**+ * Get an item by email address (case-insensitive).+ * Used to find items associated with a specific email address.+ */+ public static readonly GET_BY_EMAIL = `+ SELECT DISTINCT+ i.Id,+ i.Name,+ i.ItemType,+ i.FolderId,+ f.Name as FolderPath,+ l.FileData as Logo,+ CASE WHEN EXISTS (SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.IsDeleted = 0) THEN 1 ELSE 0 END as HasPasskey,+ CASE WHEN EXISTS (SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.IsDeleted = 0) THEN 1 ELSE 0 END as HasAttachment,+ CASE WHEN EXISTS (SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.IsDeleted = 0) THEN 1 ELSE 0 END as HasTotp,+ i.CreatedAt,+ i.UpdatedAt+ FROM Items i+ LEFT JOIN Logos l ON i.LogoId = l.Id+ LEFT JOIN Folders f ON i.FolderId = f.Id+ INNER JOIN FieldValues fv ON fv.ItemId = i.Id+ WHERE LOWER(fv.Value) = LOWER(?)+ AND fv.FieldKey = ?+ AND fv.IsDeleted = 0+ AND i.IsDeleted = 0+ AND i.DeletedAt IS NULL+ LIMIT 1`;+/*** Get all recently deleted items (in trash).*/diff --git a/apps/mobile-app/utils/db/repositories/ItemRepository.ts b/apps/mobile-app/utils/db/repositories/ItemRepository.tsindex 3c65a0169..c8abf8e63 100644--- a/apps/mobile-app/utils/db/repositories/ItemRepository.ts+++ b/apps/mobile-app/utils/db/repositories/ItemRepository.ts@@ -123,6 +123,35 @@ export class ItemRepository extends BaseRepository {return results.map(row => row.Email);}+ /**+ * Fetch an item by its email address (case-insensitive).+ * @param email - The email address to search for+ * @returns Item object or null if not found+ */+ public async getByEmail(email: string): Promise<Item | null> {+ // 1. Fetch item row by email+ const itemRows = await this.client.executeQuery<ItemRow>(+ ItemQueries.GET_BY_EMAIL,+ [email, FieldKey.LoginEmail]+ );++ if (itemRows.length === 0) {+ return null;+ }++ const itemRow = itemRows[0];++ // 2. Fetch field values+ const fieldRows = await this.client.executeQuery<Omit<FieldRow, 'ItemId'>>(+ ItemQueries.GET_FIELD_VALUES_FOR_ITEM,+ [itemRow.Id]+ );+ const fields = FieldMapper.processFieldRowsForSingleItem(fieldRows);++ // 3. Map to Item object+ return ItemMapper.mapRow(itemRow, fields, []);+ }+/*** Get recently deleted items (in trash).* @returns Array of items with DeletedAt fielddiff --git a/apps/mobile-app/utils/db/repositories/PasskeyRepository.ts b/apps/mobile-app/utils/db/repositories/PasskeyRepository.tsnew file mode 100644index 000000000..ada9e669f--- /dev/null+++ b/apps/mobile-app/utils/db/repositories/PasskeyRepository.ts@@ -0,0 +1,214 @@+import type { Passkey } from '@/utils/dist/core/models/vault';++import { BaseRepository } from '../BaseRepository';++/**+ * Extended passkey type with item metadata.+ */+export type PasskeyWithItemInfo = Passkey & {+ Username?: string | null;+ ItemName?: string | null;+};++/**+ * SQL query constants for Passkey operations.+ */+const PasskeyQueries = {+ /**+ * Get all passkeys for a specific relying party (rpId).+ * Joins with Items and FieldValues to get item name and username.+ */+ GET_BY_RP_ID: `+ SELECT+ p.Id,+ p.ItemId,+ p.RpId,+ p.UserId,+ p.PublicKey,+ p.PrivateKey,+ p.DisplayName,+ p.PrfKey,+ p.AdditionalData,+ p.CreatedAt,+ p.UpdatedAt,+ p.IsDeleted,+ i.Name as ItemName,+ fv.Value as Username+ FROM Passkeys p+ LEFT JOIN Items i ON p.ItemId = i.Id+ LEFT JOIN FieldValues fv ON fv.ItemId = i.Id AND fv.FieldKey = 'login.username' AND fv.IsDeleted = 0+ WHERE p.RpId = ? AND p.IsDeleted = 0+ ORDER BY p.CreatedAt DESC`,++ /**+ * Get a passkey by its ID.+ * Joins with Items and FieldValues to get item name and username.+ */+ GET_BY_ID: `+ SELECT+ p.Id,+ p.ItemId,+ p.RpId,+ p.UserId,+ p.PublicKey,+ p.PrivateKey,+ p.DisplayName,+ p.PrfKey,+ p.AdditionalData,+ p.CreatedAt,+ p.UpdatedAt,+ p.IsDeleted,+ i.Name as ItemName,+ fv.Value as Username+ FROM Passkeys p+ LEFT JOIN Items i ON p.ItemId = i.Id+ LEFT JOIN FieldValues fv ON fv.ItemId = i.Id AND fv.FieldKey = 'login.username' AND fv.IsDeleted = 0+ WHERE p.Id = ? AND p.IsDeleted = 0`,++ /**+ * Insert a new passkey.+ */+ INSERT: `+ INSERT INTO Passkeys (+ Id, ItemId, RpId, PublicKey, PrivateKey,+ PrfKey, DisplayName, AdditionalData, CreatedAt, UpdatedAt, IsDeleted+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,++ /**+ * Soft delete a passkey by ID.+ */+ SOFT_DELETE: `+ UPDATE Passkeys+ SET IsDeleted = 1,+ UpdatedAt = ?+ WHERE Id = ?`,++ /**+ * Update passkey display name.+ */+ UPDATE_DISPLAY_NAME: `+ UPDATE Passkeys+ SET DisplayName = ?,+ UpdatedAt = ?+ WHERE Id = ?`+};++/**+ * Repository for Passkey CRUD operations.+ */+export class PasskeyRepository extends BaseRepository {+ /**+ * Get all passkeys for a specific relying party (rpId).+ * @param rpId - The relying party identifier (domain)+ * @returns Array of passkey objects with item info+ */+ public async getByRpId(rpId: string): Promise<PasskeyWithItemInfo[]> {+ const results = await this.client.executeQuery(PasskeyQueries.GET_BY_RP_ID, [rpId]);++ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ return results.map((row: any) => this.mapRow(row));+ }++ /**+ * Get a passkey by its ID.+ * @param passkeyId - The passkey ID+ * @returns The passkey object or null if not found+ */+ public async getById(passkeyId: string): Promise<PasskeyWithItemInfo | null> {+ const results = await this.client.executeQuery(PasskeyQueries.GET_BY_ID, [passkeyId]);++ if (results.length === 0) {+ return null;+ }++ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ return this.mapRow(results[0] as any);+ }++ /**+ * Create a new passkey linked to an item.+ * @param passkey - The passkey object to create (without timestamps and IsDeleted)+ */+ public async create(passkey: Omit<Passkey, 'CreatedAt' | 'UpdatedAt' | 'IsDeleted'>): Promise<void> {+ return this.withTransaction(async () => {+ const currentDateTime = this.now();++ // Convert PrfKey to Uint8Array if it's a number array+ let prfKeyData: Uint8Array | null = null;+ if (passkey.PrfKey) {+ prfKeyData = passkey.PrfKey instanceof Uint8Array ? passkey.PrfKey : new Uint8Array(passkey.PrfKey);+ }++ await this.client.executeUpdate(PasskeyQueries.INSERT, [+ passkey.Id,+ passkey.ItemId,+ passkey.RpId,+ passkey.PublicKey,+ passkey.PrivateKey,+ prfKeyData,+ passkey.DisplayName,+ passkey.AdditionalData ?? null,+ currentDateTime,+ currentDateTime,+ 0+ ]);+ });+ }++ /**+ * Delete a passkey by its ID (soft delete).+ * @param passkeyId - The ID of the passkey to delete+ * @returns The number of rows updated+ */+ public async delete(passkeyId: string): Promise<number> {+ return this.withTransaction(async () => {+ const currentDateTime = this.now();+ return this.client.executeUpdate(PasskeyQueries.SOFT_DELETE, [+ currentDateTime,+ passkeyId+ ]);+ });+ }++ /**+ * Update a passkey's display name.+ * @param passkeyId - The ID of the passkey to update+ * @param displayName - The new display name+ * @returns The number of rows updated+ */+ public async updateDisplayName(passkeyId: string, displayName: string): Promise<number> {+ return this.withTransaction(async () => {+ const currentDateTime = this.now();+ return this.client.executeUpdate(PasskeyQueries.UPDATE_DISPLAY_NAME, [+ displayName,+ currentDateTime,+ passkeyId+ ]);+ });+ }++ /**+ * Map a database row to a PasskeyWithItemInfo object.+ * @param row - Raw database row+ * @returns PasskeyWithItemInfo object+ */+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ private mapRow(row: any): PasskeyWithItemInfo {+ return {+ Id: row.Id,+ ItemId: row.ItemId,+ RpId: row.RpId,+ PublicKey: row.PublicKey,+ PrivateKey: row.PrivateKey,+ DisplayName: row.DisplayName,+ PrfKey: row.PrfKey,+ AdditionalData: row.AdditionalData,+ CreatedAt: row.CreatedAt,+ UpdatedAt: row.UpdatedAt,+ IsDeleted: row.IsDeleted,+ Username: row.Username,+ ItemName: row.ItemName+ };+ }+}