passwords: two-way sync with an external KDBX file
- Commit
31f2e8e03584224672a4a4df535b9d1d9599ef8b- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-05 19:09 UTC (4 months ago)
- Parents
3a738d0
Diff
library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt b/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.ktindex 3cc9da1658..5a35f7e9be 100644--- a/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt+++ b/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt@@ -66,6 +66,11 @@ class DataStoreUtils private constructor(context: Context) { return dataStore.data.mapNotNull { it[booleanPreferencesKey(name)] } } + /** Suspend variant that awaits DataStore hydration. */+ suspend fun getBooleanAwait(name: String, default: Boolean = false): Boolean {+ return dataStore.data.first()[booleanPreferencesKey(name)] ?: default+ }+ suspend fun setBoolean(name: String, value: Boolean) { dataStore.edit { it[booleanPreferencesKey(name)] = value
passwords/build.gradle.kts
diff --git a/passwords/build.gradle.kts b/passwords/build.gradle.ktsindex 53f04c6713..f8bb8370a1 100644--- a/passwords/build.gradle.kts+++ b/passwords/build.gradle.kts@@ -41,6 +41,7 @@ dependencies { implementation(libs.androidx.biometric) implementation(libs.androidx.credentials.lib) implementation(libs.androidx.autofill)+ implementation(libs.androidx.work.runtime.ktx) // Own WebSocketClient via :library:network – no Ktor implementation(project(":library:network")) }
passwords/src/main/java/com/vayunmathur/passwords/MainActivity.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/MainActivity.kt b/passwords/src/main/java/com/vayunmathur/passwords/MainActivity.ktindex d5717c3ce3..822960f97d 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/MainActivity.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/MainActivity.kt@@ -6,6 +6,8 @@ import androidx.activity.enableEdgeToEdge import androidx.activity.viewModels import androidx.compose.runtime.Composable import androidx.fragment.app.FragmentActivity+import androidx.lifecycle.lifecycleScope+import kotlinx.coroutines.launch import com.vayunmathur.library.util.openSettingsIfRequested import com.vayunmathur.library.util.AppMessages import com.vayunmathur.library.util.NavKey@@ -25,6 +27,8 @@ import com.vayunmathur.passwords.ui.PasskeyPage import com.vayunmathur.passwords.ui.PasswordEditPage import com.vayunmathur.passwords.ui.PasswordPage import com.vayunmathur.passwords.ui.SettingsPage+import com.vayunmathur.passwords.sync.KdbxSyncScheduler+import com.vayunmathur.passwords.sync.KdbxSyncSettings import com.vayunmathur.passwords.util.PasswordsViewModel import com.vayunmathur.passwords.util.PasswordsViewModelFactory import kotlinx.serialization.Serializable@@ -53,6 +57,13 @@ class MainActivity : FragmentActivity() { val db = buildDatabase<PasswordDatabase>(encryptionPassword = passphrase) passwordDao = db.passwordDao() passkeyDao = db.passkeyDao()+ lifecycleScope.launch {+ if (KdbxSyncSettings.enabled(this@MainActivity)) {+ // Re-registering keeps the periodic work alive across app updates.+ KdbxSyncScheduler.schedulePeriodic(this@MainActivity)+ KdbxSyncScheduler.syncNow(this@MainActivity)+ }+ } setContent { DynamicTheme { Navigation(passwordsViewModel, passphrase)
passwords/src/main/java/com/vayunmathur/passwords/data/Passkey.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/data/Passkey.kt b/passwords/src/main/java/com/vayunmathur/passwords/data/Passkey.ktindex 8065896d17..15caa80ede 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/data/Passkey.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/data/Passkey.kt@@ -17,6 +17,8 @@ data class Passkey( val creationTime: Long = System.currentTimeMillis(), val lastUsedTime: Long = System.currentTimeMillis(), val signCount: Int = 0,+ val syncId: String = newSyncId(),+ val updatedAt: Long = System.currentTimeMillis(), ) : DatabaseItem { override fun equals(other: Any?): Boolean { if (this === other) return true
passwords/src/main/java/com/vayunmathur/passwords/data/Password.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/data/Password.kt b/passwords/src/main/java/com/vayunmathur/passwords/data/Password.ktindex a343d3e96a..d3830c1bbf 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/data/Password.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/data/Password.kt@@ -12,5 +12,7 @@ data class Password( val userId: String = "", val password: String = "", val totpSecret: String? = null,- val websites: List<String> = emptyList()+ val websites: List<String> = emptyList(),+ val syncId: String = newSyncId(),+ val updatedAt: Long = System.currentTimeMillis(), ): DatabaseItem
passwords/src/main/java/com/vayunmathur/passwords/data/PasswordDatabase.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/data/PasswordDatabase.kt b/passwords/src/main/java/com/vayunmathur/passwords/data/PasswordDatabase.ktindex bdb9e41fe2..823f9315dd 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/data/PasswordDatabase.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/data/PasswordDatabase.kt@@ -12,56 +12,65 @@ import com.vayunmathur.library.util.DatabaseMigrations import kotlinx.coroutines.flow.Flow @Dao-interface PasswordDao {+abstract class PasswordDao { @Query("SELECT * FROM Password")- fun getAllFlow(): Flow<List<Password>>+ abstract fun getAllFlow(): Flow<List<Password>> @Query("SELECT * FROM Password")- suspend fun getAll(): List<Password>+ abstract suspend fun getAll(): List<Password> @Query("SELECT * FROM Password WHERE id = :id")- fun getByIdFlow(id: Long): Flow<Password?>+ abstract fun getByIdFlow(id: Long): Flow<Password?> @Query("SELECT * FROM Password WHERE id = :id")- suspend fun getById(id: Long): Password?+ abstract suspend fun getById(id: Long): Password? + /** Writes [value] verbatim. Only the kdbx sync uses this, to preserve a pulled timestamp. */ @Upsert- suspend fun upsert(value: Password): Long+ abstract suspend fun upsertRaw(value: Password): Long @Delete- suspend fun delete(value: Password): Int+ abstract suspend fun delete(value: Password): Int++ suspend fun upsert(value: Password): Long =+ upsertRaw(value.copy(updatedAt = System.currentTimeMillis())) } @Dao-interface PasskeyDao {+abstract class PasskeyDao { @Query("SELECT * FROM Passkey")- fun getAllFlow(): Flow<List<Passkey>>+ abstract fun getAllFlow(): Flow<List<Passkey>> @Query("SELECT * FROM Passkey")- suspend fun getAll(): List<Passkey>+ abstract suspend fun getAll(): List<Passkey> @Query("SELECT * FROM Passkey WHERE rpId = :rpId")- suspend fun getByRpId(rpId: String): List<Passkey>+ abstract suspend fun getByRpId(rpId: String): List<Passkey> @Query("SELECT * FROM Passkey WHERE credentialId = :credentialId")- suspend fun getByCredentialId(credentialId: String): Passkey?+ abstract suspend fun getByCredentialId(credentialId: String): Passkey? + /** Writes [passkey] verbatim. Only the kdbx sync uses this, to preserve a pulled timestamp. */ @Upsert- suspend fun upsert(passkey: Passkey): Long+ abstract suspend fun upsertRaw(passkey: Passkey): Long @Delete- suspend fun delete(passkey: Passkey): Int+ abstract suspend fun delete(passkey: Passkey): Int++ suspend fun upsert(passkey: Passkey): Long =+ upsertRaw(passkey.copy(updatedAt = System.currentTimeMillis())) } @Database(- entities = [Password::class, Passkey::class],- version = 2,+ entities = [Password::class, Passkey::class, SyncSnapshot::class],+ version = 3, exportSchema = false, ) @TypeConverters(Converters::class) abstract class PasswordDatabase : RoomDatabase() { abstract fun passwordDao(): PasswordDao abstract fun passkeyDao(): PasskeyDao+ abstract fun syncSnapshotDao(): SyncSnapshotDao companion object : DatabaseMigrations { override val migrations = listOf(@@ -81,7 +90,27 @@ abstract class PasswordDatabase : RoomDatabase() { `signCount` INTEGER NOT NULL )""" )- }+ },+ Migration(2, 3) {+ for (table in listOf("Password", "Passkey")) {+ it.execSQL("ALTER TABLE `$table` ADD COLUMN `syncId` TEXT NOT NULL DEFAULT ''")+ it.execSQL("ALTER TABLE `$table` ADD COLUMN `updatedAt` INTEGER NOT NULL DEFAULT 0")+ it.execSQL("UPDATE `$table` SET `syncId` = lower(hex(randomblob(16))) WHERE `syncId` = ''")+ }+ it.execSQL("UPDATE `Password` SET `updatedAt` = ${System.currentTimeMillis()} WHERE `updatedAt` = 0")+ it.execSQL("UPDATE `Passkey` SET `updatedAt` = `creationTime` WHERE `updatedAt` = 0")+ it.execSQL(+ """CREATE TABLE IF NOT EXISTS `SyncSnapshot` (+ `syncId` TEXT NOT NULL,+ `kind` TEXT NOT NULL,+ `contentHash` TEXT NOT NULL,+ `localUpdatedAt` INTEGER NOT NULL,+ `remoteModified` INTEGER NOT NULL,+ `lastSyncedAt` INTEGER NOT NULL,+ PRIMARY KEY(`syncId`)+ )"""+ )+ }, ) } }
passwords/src/main/java/com/vayunmathur/passwords/data/SyncSnapshot.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/data/SyncSnapshot.kt b/passwords/src/main/java/com/vayunmathur/passwords/data/SyncSnapshot.ktnew file mode 100644index 0000000000..4d2c57e0db--- /dev/null+++ b/passwords/src/main/java/com/vayunmathur/passwords/data/SyncSnapshot.kt@@ -0,0 +1,29 @@+package com.vayunmathur.passwords.data++import androidx.room.Entity+import androidx.room.PrimaryKey+import java.util.UUID++/** Opaque 32-char identity shared between a local row and its kdbx entry. */+fun newSyncId(): String = UUID.randomUUID().toString().replace("-", "")++/**+ * Last agreed state of one synced entry, written after a successful kdbx sync.+ *+ * Without this baseline "present locally, absent remotely" cannot be told apart from+ * "created locally, not pushed yet", so deletions could never propagate.+ */+@Entity+data class SyncSnapshot(+ @PrimaryKey val syncId: String,+ val kind: String,+ val contentHash: String,+ val localUpdatedAt: Long,+ val remoteModified: Long,+ val lastSyncedAt: Long,+) {+ companion object {+ const val KIND_PASSWORD = "password"+ const val KIND_PASSKEY = "passkey"+ }+}
passwords/src/main/java/com/vayunmathur/passwords/data/SyncSnapshotDao.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/data/SyncSnapshotDao.kt b/passwords/src/main/java/com/vayunmathur/passwords/data/SyncSnapshotDao.ktnew file mode 100644index 0000000000..1d394d0d0c--- /dev/null+++ b/passwords/src/main/java/com/vayunmathur/passwords/data/SyncSnapshotDao.kt@@ -0,0 +1,20 @@+package com.vayunmathur.passwords.data++import androidx.room.Dao+import androidx.room.Query+import androidx.room.Upsert++@Dao+interface SyncSnapshotDao {+ @Query("SELECT * FROM SyncSnapshot")+ suspend fun getAll(): List<SyncSnapshot>++ @Upsert+ suspend fun upsert(snapshot: SyncSnapshot)++ @Query("DELETE FROM SyncSnapshot WHERE syncId = :syncId")+ suspend fun deleteBySyncId(syncId: String)++ @Query("DELETE FROM SyncSnapshot")+ suspend fun deleteAll()+}
passwords/src/main/java/com/vayunmathur/passwords/sync/EntryMapper.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/sync/EntryMapper.kt b/passwords/src/main/java/com/vayunmathur/passwords/sync/EntryMapper.ktnew file mode 100644index 0000000000..b1a9d38a82--- /dev/null+++ b/passwords/src/main/java/com/vayunmathur/passwords/sync/EntryMapper.kt@@ -0,0 +1,134 @@+package com.vayunmathur.passwords.sync++import com.vayunmathur.passwords.data.Passkey+import com.vayunmathur.passwords.data.Password+import com.vayunmathur.passwords.data.newSyncId+import java.security.MessageDigest+import java.util.Base64++/**+ * The single Password/Passkey <-> kdbx field-map conversion, shared by the one-shot+ * backup format and the bidirectional sync.+ *+ * The mapping must round-trip: `toFields(fromFields(f))` has to be stable, because the+ * merge compares content hashes computed from it on both sides.+ */+object EntryMapper {+ const val FIELD_TYPE = "_Type"+ const val FIELD_SYNC_ID = "_SyncId"+ const val FIELD_MODIFIED = "_Modified"++ private const val FIELD_SIGN_COUNT = "_SignCount"+ private const val FIELD_CREATED = "_Created"+ private const val FIELD_LAST_USED = "_LastUsed"++ /**+ * Every key this mapper can emit. Keys outside this set belong to whatever client+ * wrote the vault (Notes, Tags, ...) and are carried through untouched on push.+ */+ val OWNED_KEYS = setOf(+ "Title", "UserName", "Password", "URL", "Websites", "otp", "TOTP Seed",+ FIELD_TYPE, FIELD_SYNC_ID, FIELD_MODIFIED,+ FIELD_SIGN_COUNT, FIELD_CREATED, FIELD_LAST_USED,+ "KPEX_PASSKEY_USERNAME", "KPEX_PASSKEY_PRIVATE_KEY_PEM", "KPEX_PASSKEY_CREDENTIAL_ID",+ "KPEX_PASSKEY_USER_HANDLE", "KPEX_PASSKEY_RELYING_PARTY",+ )++ fun isPasskeyEntry(entry: Map<String, String>): Boolean =+ entry.keys.any { it.startsWith("KPEX_PASSKEY_") }++ fun toFields(pw: Password): Map<String, String> = buildMap {+ put("Title", pw.name)+ put("UserName", pw.userId)+ put("Password", pw.password)+ if (pw.websites.isNotEmpty()) {+ put("URL", pw.websites.first())+ if (pw.websites.size > 1) put("Websites", pw.websites.joinToString("\n"))+ }+ pw.totpSecret?.takeIf { it.isNotBlank() }?.let { put("otp", "otpauth://totp/?secret=$it") }+ put(FIELD_TYPE, "password")+ put(FIELD_SYNC_ID, pw.syncId)+ put(FIELD_MODIFIED, pw.updatedAt.toString())+ }++ fun toPassword(entry: Map<String, String>): Password {+ val websites = mutableListOf<String>()+ entry["URL"]?.takeIf { it.isNotEmpty() }?.let { websites.add(it) }+ entry["Websites"]?.split("\n")?.filter { it.isNotBlank() }?.forEach {+ if (it !in websites) websites.add(it)+ }+ val otp = entry["otp"]+ val totpSecret = if (!otp.isNullOrEmpty()) {+ Regex("[?&]secret=([^&]+)").find(otp)?.groupValues?.get(1) ?: otp+ } else {+ entry["TOTP Seed"]?.takeIf { it.isNotBlank() }+ }++ return Password(+ name = entry["Title"].orEmpty(),+ userId = entry["UserName"].orEmpty(),+ password = entry["Password"].orEmpty(),+ websites = websites,+ totpSecret = totpSecret,+ syncId = entry[FIELD_SYNC_ID]?.takeIf { it.isNotBlank() } ?: newSyncId(),+ updatedAt = entry[FIELD_MODIFIED]?.toLongOrNull() ?: System.currentTimeMillis(),+ )+ }++ fun toFields(pk: Passkey): Map<String, String> = buildMap {+ put("Title", pk.rpName)+ put("UserName", pk.userDisplayName)+ put("URL", pk.rpId)+ put(FIELD_TYPE, "passkey")+ put("KPEX_PASSKEY_USERNAME", pk.userName)+ put("KPEX_PASSKEY_PRIVATE_KEY_PEM", Base64.getEncoder().encodeToString(pk.privateKeyBytes))+ put("KPEX_PASSKEY_CREDENTIAL_ID", pk.credentialId)+ put("KPEX_PASSKEY_USER_HANDLE", pk.userId)+ put("KPEX_PASSKEY_RELYING_PARTY", pk.rpId)+ put(FIELD_SIGN_COUNT, pk.signCount.toString())+ put(FIELD_CREATED, pk.creationTime.toString())+ put(FIELD_LAST_USED, pk.lastUsedTime.toString())+ put(FIELD_SYNC_ID, pk.syncId)+ put(FIELD_MODIFIED, pk.updatedAt.toString())+ }++ fun toPasskey(entry: Map<String, String>): Passkey {+ val privateKeyB64 = entry["KPEX_PASSKEY_PRIVATE_KEY_PEM"].orEmpty()+ val privateKeyBytes = if (privateKeyB64.isNotEmpty()) {+ runCatching { Base64.getDecoder().decode(privateKeyB64) }.getOrDefault(ByteArray(0))+ } else {+ ByteArray(0)+ }+ val now = System.currentTimeMillis()++ return Passkey(+ rpId = entry["KPEX_PASSKEY_RELYING_PARTY"].orEmpty().ifEmpty { entry["URL"].orEmpty() },+ rpName = entry["Title"].orEmpty(),+ credentialId = entry["KPEX_PASSKEY_CREDENTIAL_ID"].orEmpty(),+ userId = entry["KPEX_PASSKEY_USER_HANDLE"].orEmpty(),+ userName = entry["KPEX_PASSKEY_USERNAME"].orEmpty().ifEmpty { entry["UserName"].orEmpty() },+ userDisplayName = entry["UserName"].orEmpty(),+ privateKeyBytes = privateKeyBytes,+ creationTime = entry[FIELD_CREATED]?.toLongOrNull() ?: now,+ lastUsedTime = entry[FIELD_LAST_USED]?.toLongOrNull() ?: now,+ signCount = entry[FIELD_SIGN_COUNT]?.toIntOrNull() ?: 0,+ syncId = entry[FIELD_SYNC_ID]?.takeIf { it.isNotBlank() } ?: newSyncId(),+ updatedAt = entry[FIELD_MODIFIED]?.toLongOrNull() ?: now,+ )+ }++ /** Content fingerprint ignoring identity and timestamps, so it is comparable across sides. */+ fun contentHash(fields: Map<String, String>): String {+ val digest = MessageDigest.getInstance("SHA-256")+ fields.entries+ .filter { it.key != FIELD_SYNC_ID && it.key != FIELD_MODIFIED }+ .sortedBy { it.key }+ .forEach { digest.update("${it.key}=${it.value}\n".toByteArray(Charsets.UTF_8)) }+ return digest.digest().joinToString("") { "%02x".format(it) }+ }++ /** Match key used to adopt pre-existing vault entries on the very first sync. */+ fun contentKey(pw: Password): String = "pw\u0000${pw.name}\u0000${pw.userId}"++ fun contentKey(pk: Passkey): String = "pk\u0000${pk.rpId}\u0000${pk.credentialId}"+}
passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxPasswordHelper.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxPasswordHelper.kt b/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxPasswordHelper.ktnew file mode 100644index 0000000000..ec70da4fae--- /dev/null+++ b/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxPasswordHelper.kt@@ -0,0 +1,18 @@+package com.vayunmathur.passwords.sync++import android.content.Context+import com.vayunmathur.library.util.DatabaseHelper++/**+ * Keystore-backed storage for the kdbx vault password, under its own alias so it is+ * independent of the Room passphrase.+ *+ * The key is deliberately not user-authentication bound: the periodic worker has no way+ * to show a biometric prompt.+ */+class KdbxPasswordHelper(context: Context) : DatabaseHelper(context) {+ override val keyStoreAlias = "kdbx_vault_key"+ override val sharedPrefsName = "kdbx_sync_prefs"+ override val passphraseKey = "encrypted_kdbx_password"+ override val ivKey = "kdbx_password_iv"+}
passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncEngine.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncEngine.kt b/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncEngine.ktnew file mode 100644index 0000000000..feab9491bd--- /dev/null+++ b/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncEngine.kt@@ -0,0 +1,403 @@+package com.vayunmathur.passwords.sync++import android.content.Context+import android.net.Uri+import androidx.core.net.toUri+import androidx.room.withTransaction+import com.vayunmathur.passwords.data.Passkey+import com.vayunmathur.passwords.data.PasskeyDao+import com.vayunmathur.passwords.data.Password+import com.vayunmathur.passwords.data.PasswordDao+import com.vayunmathur.passwords.data.PasswordDatabase+import com.vayunmathur.passwords.data.SyncSnapshot+import com.vayunmathur.passwords.data.SyncSnapshotDao+import com.vayunmathur.passwords.data.newSyncId+import com.vayunmathur.passwords.util.KdbxNative+import org.json.JSONArray+import org.json.JSONObject+import java.io.File+import java.io.FileNotFoundException++sealed interface KdbxSyncResult {+ data class Success(+ val pushed: Int,+ val pulled: Int,+ val deletedLocal: Int,+ val deletedRemote: Int,+ ) : KdbxSyncResult++ data object NotConfigured : KdbxSyncResult+ data object FileMissing : KdbxSyncResult+ data object WrongPassword : KdbxSyncResult+ data object VerifyFailed : KdbxSyncResult+ data class Error(val message: String) : KdbxSyncResult+}++/** Short machine-readable reason, stored in settings and rendered by the settings screen. */+fun KdbxSyncResult.errorCode(): String = when (this) {+ KdbxSyncResult.FileMissing -> "file_missing"+ KdbxSyncResult.WrongPassword -> "wrong_password"+ KdbxSyncResult.VerifyFailed -> "verify_failed"+ is KdbxSyncResult.Error -> message+ else -> ""+}++/** The kdbx file. Abstracted so the engine can be exercised without SAF. */+interface KdbxDocument {+ fun read(): ByteArray+ fun write(bytes: ByteArray)+}++/** kdbx (de)serialisation. Abstracted so the engine can be exercised without JNI. */+interface KdbxCodec {+ /** Returns null when the password is wrong or the payload is not a vault. */+ fun read(password: String, bytes: ByteArray): List<Map<String, String>>?+ fun write(password: String, entries: List<Map<String, String>>): ByteArray?+}++/**+ * Bidirectional sync between the encrypted Room database and one kdbx file.+ *+ * The whole merge is computed in memory. Nothing is mutated until the remote has been+ * read, decrypted, merged, re-encoded and verified — so a missing, unreadable or+ * wrongly-keyed file can never wipe the local vault.+ */+class KdbxSyncEngine(+ private val passwordDao: PasswordDao,+ private val passkeyDao: PasskeyDao,+ private val snapshotDao: SyncSnapshotDao,+ private val codec: KdbxCodec,+ private val inTransaction: suspend (suspend () -> Unit) -> Unit = { it() },+) {+ constructor(db: PasswordDatabase, codec: KdbxCodec) : this(+ db.passwordDao(),+ db.passkeyDao(),+ db.syncSnapshotDao(),+ codec,+ { db.withTransaction(it) },+ )++ private val passwordKind = object : EntityKind<Password>() {+ override val kind = SyncSnapshot.KIND_PASSWORD+ override fun syncId(e: Password) = e.syncId+ override fun updatedAt(e: Password) = e.updatedAt+ override fun rowId(e: Password) = e.id+ override fun fields(e: Password) = EntryMapper.toFields(e)+ override fun entity(fields: Map<String, String>) = EntryMapper.toPassword(fields)+ override fun contentKey(e: Password) = EntryMapper.contentKey(e)+ override fun rebind(e: Password, rowId: Long, syncId: String) = e.copy(id = rowId, syncId = syncId)+ override suspend fun persist(e: Password) { passwordDao.upsertRaw(e) }+ override suspend fun delete(e: Password) { passwordDao.delete(e) }+ }++ private val passkeyKind = object : EntityKind<Passkey>() {+ override val kind = SyncSnapshot.KIND_PASSKEY+ override fun syncId(e: Passkey) = e.syncId+ override fun updatedAt(e: Passkey) = e.updatedAt+ override fun rowId(e: Passkey) = e.id+ override fun fields(e: Passkey) = EntryMapper.toFields(e)+ override fun entity(fields: Map<String, String>) = EntryMapper.toPasskey(fields)+ override fun contentKey(e: Passkey) = EntryMapper.contentKey(e)+ override fun rebind(e: Passkey, rowId: Long, syncId: String) = e.copy(id = rowId, syncId = syncId)+ override suspend fun persist(e: Passkey) { passkeyDao.upsertRaw(e) }+ override suspend fun delete(e: Passkey) { passkeyDao.delete(e) }+ }++ suspend fun sync(+ document: KdbxDocument,+ vaultPassword: String,+ onBackup: (ByteArray) -> Unit = {},+ ): KdbxSyncResult {+ val remoteBytes = try {+ document.read()+ } catch (_: Exception) {+ return KdbxSyncResult.FileMissing+ }+ // A brand new SAF document is zero bytes; that is an empty vault, not a failure.+ val remoteEntries = if (remoteBytes.isEmpty()) {+ emptyList()+ } else {+ codec.read(vaultPassword, remoteBytes) ?: return KdbxSyncResult.WrongPassword+ }++ val now = System.currentTimeMillis()+ val baseline = snapshotDao.getAll().associateBy { it.syncId }+ val (remotePasskeys, remotePasswords) = remoteEntries.partition { EntryMapper.isPasskeyEntry(it) }++ val passwordPlan = merge(+ passwordKind,+ passwordDao.getAll(),+ remotePasswords,+ baseline.filterValues { it.kind == SyncSnapshot.KIND_PASSWORD },+ now,+ )+ val passkeyPlan = merge(+ passkeyKind,+ passkeyDao.getAll(),+ remotePasskeys,+ baseline.filterValues { it.kind == SyncSnapshot.KIND_PASSKEY },+ now,+ )++ if (passwordPlan.remoteChanged || passkeyPlan.remoteChanged) {+ val merged = passwordPlan.remoteFields + passkeyPlan.remoteFields+ val bytes = codec.write(vaultPassword, merged)+ ?: return KdbxSyncResult.Error("Failed to encode KDBX")+ // A SAF single-document write truncates, so prove the payload parses first.+ val verified = codec.read(vaultPassword, bytes)+ if (verified == null || verified.size != merged.size) return KdbxSyncResult.VerifyFailed+ if (remoteBytes.isNotEmpty()) onBackup(remoteBytes)+ try {+ document.write(bytes)+ } catch (e: Exception) {+ return KdbxSyncResult.Error(e.message ?: "Failed to write KDBX file")+ }+ }++ inTransaction {+ applyPlan(passwordKind, passwordPlan)+ applyPlan(passkeyKind, passkeyPlan)+ }++ return KdbxSyncResult.Success(+ pushed = passwordPlan.pushed + passkeyPlan.pushed,+ pulled = passwordPlan.pulled + passkeyPlan.pulled,+ deletedLocal = passwordPlan.deletedLocal + passkeyPlan.deletedLocal,+ deletedRemote = passwordPlan.deletedRemote + passkeyPlan.deletedRemote,+ )+ }++ private suspend fun <T> applyPlan(kind: EntityKind<T>, plan: Plan<T>) {+ for (entity in plan.localDeletes) kind.delete(entity)+ for (entity in plan.localUpserts) kind.persist(entity)+ for (syncId in plan.removedSyncIds) snapshotDao.deleteBySyncId(syncId)+ for (snapshot in plan.snapshots) snapshotDao.upsert(snapshot)+ }++ private fun <T> merge(+ kind: EntityKind<T>,+ localEntities: List<T>,+ remoteEntries: List<Map<String, String>>,+ baseline: Map<String, SyncSnapshot>,+ now: Long,+ ): Plan<T> {+ val localUpserts = mutableListOf<T>()+ val localDeletes = mutableListOf<T>()+ val remoteOut = mutableListOf<Map<String, String>>()+ val snapshots = mutableListOf<SyncSnapshot>()+ val removed = mutableListOf<String>()+ var remoteChanged = false+ var pushed = 0+ var pulled = 0+ var deletedLocal = 0+ var deletedRemote = 0++ // Rows written before the sync columns existed have no identity yet.+ val local = LinkedHashMap<String, T>()+ val freshlyIdentified = mutableSetOf<String>()+ for (raw in localEntities) {+ val entity = if (kind.syncId(raw).isBlank()) {+ kind.rebind(raw, kind.rowId(raw), newSyncId()).also { freshlyIdentified += kind.syncId(it) }+ } else {+ raw+ }+ local[kind.syncId(entity)] = entity+ }++ val remote = LinkedHashMap<String, Map<String, String>>()+ val unidentified = mutableListOf<Map<String, String>>()+ for (entry in remoteEntries) {+ val id = entry[EntryMapper.FIELD_SYNC_ID]?.takeIf { it.isNotBlank() }+ if (id != null && id !in remote) remote[id] = entry else unidentified += entry+ }++ // Entries written by another client carry no _SyncId. Adopt the identity of the+ // local row they describe, otherwise pointing the app at an existing KeePassXC+ // vault would duplicate every entry in it.+ val adoptableByContentKey = local.values.filter { kind.syncId(it) !in remote }+ .associateBy({ kind.contentKey(it) }, { kind.syncId(it) })+ val claimed = mutableSetOf<String>()+ for (entry in unidentified) {+ val match = adoptableByContentKey[kind.contentKey(kind.entity(entry))]+ val id = match?.takeIf { it !in claimed && it !in remote } ?: newSyncId()+ claimed += id+ remote[id] = entry + (EntryMapper.FIELD_SYNC_ID to id)+ remoteChanged = true+ }++ for (id in local.keys + remote.keys) {+ val localEntity = local[id]+ val remoteEntry = remote[id]+ val base = baseline[id]++ if (localEntity != null && remoteEntry != null) {+ val localFields = kind.fields(localEntity)+ val remoteEntity = kind.entity(remoteEntry)+ val remoteFields = kind.fields(remoteEntity)+ val localHash = EntryMapper.contentHash(localFields)+ val remoteHash = EntryMapper.contentHash(remoteFields)++ if (localHash == remoteHash) {+ remoteOut += remoteEntry+ if (id in freshlyIdentified) localUpserts += localEntity+ snapshots += kind.snapshot(id, localHash, kind.updatedAt(localEntity), kind.updatedAt(remoteEntity), now)+ continue+ }++ val localDirty = base == null || localHash != base.contentHash+ val remoteDirty = base == null || remoteHash != base.contentHash+ val localWins = when {+ localDirty && remoteDirty -> kind.updatedAt(localEntity) >= kind.updatedAt(remoteEntity)+ else -> localDirty+ }++ if (localWins) {+ // Keep fields no client of ours understands (Notes, Tags, ...).+ remoteOut += remoteEntry.filterKeys { it !in EntryMapper.OWNED_KEYS } + localFields+ remoteChanged = true+ pushed+++ if (id in freshlyIdentified) localUpserts += localEntity+ val stamp = kind.updatedAt(localEntity)+ snapshots += kind.snapshot(id, localHash, stamp, stamp, now)+ } else {+ // Pulled rows keep the remote timestamp, so the next cycle sees them+ // as clean rather than bouncing the change back.+ localUpserts += kind.rebind(remoteEntity, kind.rowId(localEntity), id)+ remoteOut += remoteEntry+ pulled+++ val stamp = kind.updatedAt(remoteEntity)+ snapshots += kind.snapshot(id, remoteHash, stamp, stamp, now)+ }+ continue+ }++ if (localEntity != null) {+ if (base != null) {+ localDeletes += localEntity+ removed += id+ deletedLocal+++ } else {+ val localFields = kind.fields(localEntity)+ remoteOut += localFields+ remoteChanged = true+ pushed+++ if (id in freshlyIdentified) localUpserts += localEntity+ val stamp = kind.updatedAt(localEntity)+ snapshots += kind.snapshot(id, EntryMapper.contentHash(localFields), stamp, stamp, now)+ }+ continue+ }++ val newRemote = remoteEntry!!+ if (base != null) {+ removed += id+ deletedRemote+++ remoteChanged = true+ } else {+ val remoteEntity = kind.entity(newRemote)+ localUpserts += kind.rebind(remoteEntity, 0, id)+ remoteOut += newRemote+ pulled+++ val stamp = kind.updatedAt(remoteEntity)+ snapshots += kind.snapshot(id, EntryMapper.contentHash(kind.fields(remoteEntity)), stamp, stamp, now)+ }+ }++ return Plan(+ localUpserts = localUpserts,+ localDeletes = localDeletes,+ remoteFields = remoteOut,+ snapshots = snapshots,+ removedSyncIds = removed,+ remoteChanged = remoteChanged,+ pushed = pushed,+ pulled = pulled,+ deletedLocal = deletedLocal,+ deletedRemote = deletedRemote,+ )+ }+}++private abstract class EntityKind<T> {+ abstract val kind: String+ abstract fun syncId(e: T): String+ abstract fun updatedAt(e: T): Long+ abstract fun rowId(e: T): Long+ abstract fun fields(e: T): Map<String, String>+ abstract fun entity(fields: Map<String, String>): T+ abstract fun contentKey(e: T): String+ abstract fun rebind(e: T, rowId: Long, syncId: String): T+ abstract suspend fun persist(e: T)+ abstract suspend fun delete(e: T)++ fun snapshot(syncId: String, hash: String, localUpdatedAt: Long, remoteModified: Long, now: Long) =+ SyncSnapshot(syncId, kind, hash, localUpdatedAt, remoteModified, now)+}++private class Plan<T>(+ val localUpserts: List<T>,+ val localDeletes: List<T>,+ val remoteFields: List<Map<String, String>>,+ val snapshots: List<SyncSnapshot>,+ val removedSyncIds: List<String>,+ val remoteChanged: Boolean,+ val pushed: Int,+ val pulled: Int,+ val deletedLocal: Int,+ val deletedRemote: Int,+)++object NativeKdbxCodec : KdbxCodec {+ override fun read(password: String, bytes: ByteArray): List<Map<String, String>>? {+ val json = KdbxNative.nativeImport(password, bytes) ?: return null+ val array = JSONArray(json)+ return (0 until array.length()).map { i ->+ val entry = array.getJSONObject(i)+ buildMap { for (key in entry.keys()) put(key, entry.getString(key)) }+ }+ }++ override fun write(password: String, entries: List<Map<String, String>>): ByteArray? {+ val array = JSONArray()+ for (entry in entries) array.put(JSONObject(entry as Map<*, *>))+ return KdbxNative.nativeExport(password, array.toString())+ }+}++class SafKdbxDocument(private val context: Context, private val uri: Uri) : KdbxDocument {+ override fun read(): ByteArray =+ context.contentResolver.openInputStream(uri)?.use { it.readBytes() }+ ?: throw FileNotFoundException("Cannot open $uri")++ override fun write(bytes: ByteArray) {+ context.contentResolver.openOutputStream(uri, "wt")?.use { it.write(bytes) }+ ?: throw FileNotFoundException("Cannot write $uri")+ }+}++/** Runs a sync from the persisted settings, recording the outcome for the settings screen. */+suspend fun runKdbxSync(context: Context, db: PasswordDatabase): KdbxSyncResult {+ if (!KdbxSyncSettings.enabled(context)) return KdbxSyncResult.NotConfigured+ val uri = KdbxSyncSettings.documentUri(context) ?: return KdbxSyncResult.NotConfigured+ val passwordHelper = KdbxPasswordHelper(context)+ if (!passwordHelper.isKeyGenerated()) return KdbxSyncResult.NotConfigured++ val result = try {+ KdbxSyncEngine(db, NativeKdbxCodec).sync(+ document = SafKdbxDocument(context, uri.toUri()),+ vaultPassword = passwordHelper.getPassphrase(),+ onBackup = { previous -> File(context.filesDir, BACKUP_FILE_NAME).writeBytes(previous) },+ )+ } catch (e: Exception) {+ KdbxSyncResult.Error(e.message ?: e.javaClass.simpleName)+ }++ when (result) {+ is KdbxSyncResult.Success -> KdbxSyncSettings.recordSuccess(context)+ KdbxSyncResult.NotConfigured -> Unit+ else -> KdbxSyncSettings.recordFailure(context, result.errorCode())+ }+ return result+}++private const val BACKUP_FILE_NAME = "kdbx-sync-backup.kdbx"
passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncScheduler.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncScheduler.kt b/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncScheduler.ktnew file mode 100644index 0000000000..bfa3cd1d1f--- /dev/null+++ b/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncScheduler.kt@@ -0,0 +1,56 @@+package com.vayunmathur.passwords.sync++import android.content.Context+import androidx.work.ExistingPeriodicWorkPolicy+import androidx.work.ExistingWorkPolicy+import androidx.work.OneTimeWorkRequestBuilder+import androidx.work.PeriodicWorkRequestBuilder+import androidx.work.WorkManager+import java.util.concurrent.TimeUnit++/**+ * WorkManager scheduling for the kdbx sync.+ *+ * Deliberately constraint-free: the document is usually a local file, so requiring a+ * network would stop it syncing offline. A cloud-backed document that cannot be opened+ * is handled as the normal "cannot read" abort instead.+ */+object KdbxSyncScheduler {+ private const val PERIODIC_WORK = "KdbxSyncPeriodic"+ private const val IMMEDIATE_WORK = "KdbxSyncNow"+ private const val DEBOUNCED_WORK = "KdbxSyncAfterEdit"+ private const val DEBOUNCE_SECONDS = 10L++ fun schedulePeriodic(context: Context) {+ val request = PeriodicWorkRequestBuilder<KdbxSyncWorker>(+ 15, TimeUnit.MINUTES,+ 5, TimeUnit.MINUTES,+ ).build()+ WorkManager.getInstance(context).enqueueUniquePeriodicWork(+ PERIODIC_WORK, ExistingPeriodicWorkPolicy.UPDATE, request,+ )+ }++ fun syncNow(context: Context) {+ WorkManager.getInstance(context).enqueueUniqueWork(+ IMMEDIATE_WORK, ExistingWorkPolicy.REPLACE, OneTimeWorkRequestBuilder<KdbxSyncWorker>().build(),+ )+ }++ /** Coalesces a burst of local edits: REPLACE on a delayed unique request is the debounce. */+ fun scheduleDebounced(context: Context) {+ val request = OneTimeWorkRequestBuilder<KdbxSyncWorker>()+ .setInitialDelay(DEBOUNCE_SECONDS, TimeUnit.SECONDS)+ .build()+ WorkManager.getInstance(context).enqueueUniqueWork(+ DEBOUNCED_WORK, ExistingWorkPolicy.REPLACE, request,+ )+ }++ fun cancel(context: Context) {+ val workManager = WorkManager.getInstance(context)+ workManager.cancelUniqueWork(PERIODIC_WORK)+ workManager.cancelUniqueWork(IMMEDIATE_WORK)+ workManager.cancelUniqueWork(DEBOUNCED_WORK)+ }+}
passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncSettings.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncSettings.kt b/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncSettings.ktnew file mode 100644index 0000000000..7380c01938--- /dev/null+++ b/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncSettings.kt@@ -0,0 +1,54 @@+package com.vayunmathur.passwords.sync++import android.content.Context+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.flow.Flow++/**+ * User-facing state of the kdbx sync. The getters are suspend because the background+ * worker may run before DataStore has hydrated; the flows back the settings screen.+ */+object KdbxSyncSettings {+ const val STATUS_OK = "ok"+ const val STATUS_ERROR = "error"++ private const val KEY_ENABLED = "kdbx_sync_enabled"+ private const val KEY_URI = "kdbx_sync_document_uri"+ private const val KEY_LAST_SYNC = "kdbx_sync_last_time"+ private const val KEY_STATUS = "kdbx_sync_last_status"+ private const val KEY_ERROR = "kdbx_sync_last_error"++ private fun store(context: Context) = DataStoreUtils.getInstance(context)++ suspend fun enabled(context: Context): Boolean = store(context).getBooleanAwait(KEY_ENABLED)++ suspend fun setEnabled(context: Context, value: Boolean) =+ store(context).setBoolean(KEY_ENABLED, value)++ fun enabledFlow(context: Context): Flow<Boolean> = store(context).booleanFlow(KEY_ENABLED)++ suspend fun documentUri(context: Context): String? =+ store(context).getStringAwait(KEY_URI)?.takeIf { it.isNotBlank() }++ suspend fun setDocumentUri(context: Context, uri: String) =+ store(context).setString(KEY_URI, uri)++ fun documentUriFlow(context: Context): Flow<String> = store(context).stringFlow(KEY_URI)++ fun lastSyncFlow(context: Context): Flow<Long> = store(context).longFlow(KEY_LAST_SYNC, 0L)++ fun statusFlow(context: Context): Flow<String> = store(context).stringFlow(KEY_STATUS)++ fun errorFlow(context: Context): Flow<String> = store(context).stringFlow(KEY_ERROR)++ suspend fun recordSuccess(context: Context) {+ store(context).setLong(KEY_LAST_SYNC, System.currentTimeMillis())+ store(context).setString(KEY_STATUS, STATUS_OK)+ store(context).setString(KEY_ERROR, "")+ }++ suspend fun recordFailure(context: Context, error: String) {+ store(context).setString(KEY_STATUS, STATUS_ERROR)+ store(context).setString(KEY_ERROR, error)+ }+}
passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncWorker.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncWorker.kt b/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncWorker.ktnew file mode 100644index 0000000000..bcb8c3e5f0--- /dev/null+++ b/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncWorker.kt@@ -0,0 +1,32 @@+package com.vayunmathur.passwords.sync++import android.content.Context+import androidx.work.CoroutineWorker+import androidx.work.WorkerParameters+import com.vayunmathur.library.room.buildDatabase+import com.vayunmathur.library.util.DatabaseHelper+import com.vayunmathur.passwords.data.PasswordDatabase++/** Drives the kdbx sync from WorkManager: periodically, on app open, and after local edits. */+class KdbxSyncWorker(+ appContext: Context,+ params: WorkerParameters,+) : CoroutineWorker(appContext, params) {++ override suspend fun doWork(): Result {+ // The Room passphrase is only mirrored to the non-auth key once the user has+ // unlocked the app; before that there is no database to sync.+ if (!DatabaseHelper(applicationContext).isKeyGenerated()) return Result.success()++ return try {+ val db = applicationContext.buildDatabase<PasswordDatabase>()+ when (runKdbxSync(applicationContext, db)) {+ is KdbxSyncResult.Success, KdbxSyncResult.NotConfigured -> Result.success()+ KdbxSyncResult.WrongPassword, KdbxSyncResult.VerifyFailed -> Result.failure()+ KdbxSyncResult.FileMissing, is KdbxSyncResult.Error -> Result.retry()+ }+ } catch (_: Exception) {+ Result.retry()+ }+ }+}
passwords/src/main/java/com/vayunmathur/passwords/ui/SettingsPage.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/ui/SettingsPage.kt b/passwords/src/main/java/com/vayunmathur/passwords/ui/SettingsPage.ktindex 02c01e9b4c..7b97756022 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/ui/SettingsPage.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/ui/SettingsPage.kt@@ -1,6 +1,8 @@ package com.vayunmathur.passwords.ui +import android.content.Intent import android.net.Uri+import android.text.format.DateFormat import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.Arrangement@@ -12,29 +14,46 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import com.vayunmathur.library.ui.AlertDialog import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.CircularProgressIndicator import com.vayunmathur.library.ui.DropdownMenu import com.vayunmathur.library.ui.DropdownMenuItem import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.SettingsDivider+import com.vayunmathur.library.ui.SettingsRow+import com.vayunmathur.library.ui.SettingsSection+import com.vayunmathur.library.ui.SettingsSwitchRow import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.ui.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.input.PasswordVisualTransformation import com.vayunmathur.passwords.R import androidx.compose.ui.unit.dp import com.vayunmathur.library.ui.BackupButtons import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.passwords.sync.KdbxPasswordHelper+import com.vayunmathur.passwords.sync.KdbxSyncScheduler+import com.vayunmathur.passwords.sync.KdbxSyncSettings import com.vayunmathur.passwords.util.ImportSource import com.vayunmathur.passwords.util.KdbxBackupFormat import com.vayunmathur.passwords.util.PasswordsViewModel+import kotlinx.coroutines.launch+import java.util.Date @OptIn(ExperimentalMaterial3Api::class) @Composable@@ -71,6 +90,7 @@ fun SettingsPage( Column(Modifier .padding(paddingValues) .fillMaxSize()+ .verticalScroll(rememberScrollState()) .padding(16.dp), Arrangement.Top ) { @@ -114,6 +134,169 @@ fun SettingsPage( Spacer(Modifier.height(8.dp)) Text(it) }++ KdbxSyncSection()+ }+ }+}++@Composable+private fun KdbxSyncSection() {+ val context = LocalContext.current+ val scope = rememberCoroutineScope()++ val enabled by KdbxSyncSettings.enabledFlow(context).collectAsState(false)+ val documentUri by KdbxSyncSettings.documentUriFlow(context).collectAsState("")+ val lastSync by KdbxSyncSettings.lastSyncFlow(context).collectAsState(0L)+ val status by KdbxSyncSettings.statusFlow(context).collectAsState("")+ val error by KdbxSyncSettings.errorFlow(context).collectAsState("")++ // Re-read on every recomposition rather than remembering: the dialog below writes it.+ var passwordSaved by remember { mutableStateOf(KdbxPasswordHelper(context).isKeyGenerated()) }+ var showPasswordDialog by remember { mutableStateOf(false) }+ var fileMenuExpanded by remember { mutableStateOf(false) }++ fun persistPermission(uri: Uri) {+ runCatching {+ context.contentResolver.takePersistableUriPermission(+ uri,+ Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION,+ )+ }+ scope.launch { KdbxSyncSettings.setDocumentUri(context, uri.toString()) }+ }++ val openLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->+ uri?.let(::persistPermission)+ }+ val createLauncher = rememberLauncherForActivityResult(+ ActivityResultContracts.CreateDocument("application/octet-stream"),+ ) { uri -> uri?.let(::persistPermission) }++ Spacer(Modifier.height(24.dp))++ SettingsSection(stringResource(R.string.sync_section)) {+ SettingsSwitchRow(+ title = stringResource(R.string.sync_enable),+ supportingText = stringResource(R.string.sync_enable_description),+ checked = enabled,+ onCheckedChange = { checked ->+ scope.launch {+ KdbxSyncSettings.setEnabled(context, checked)+ if (checked) {+ KdbxSyncScheduler.schedulePeriodic(context)+ KdbxSyncScheduler.syncNow(context)+ } else {+ KdbxSyncScheduler.cancel(context)+ }+ }+ },+ )+ SettingsDivider()++ Box {+ SettingsRow(+ title = stringResource(R.string.sync_file),+ supportingText = documentUri.ifBlank { stringResource(R.string.sync_file_none) },+ onClick = { fileMenuExpanded = true },+ )+ DropdownMenu(+ expanded = fileMenuExpanded,+ onDismissRequest = { fileMenuExpanded = false },+ ) {+ DropdownMenuItem(+ text = { Text(stringResource(R.string.sync_choose_file)) },+ onClick = {+ fileMenuExpanded = false+ openLauncher.launch(arrayOf("application/octet-stream", "application/x-keepass", "*/*"))+ },+ )+ DropdownMenuItem(+ text = { Text(stringResource(R.string.sync_create_file)) },+ onClick = {+ fileMenuExpanded = false+ createLauncher.launch("passwords.kdbx")+ },+ )+ } }+ SettingsDivider()++ SettingsRow(+ title = stringResource(R.string.sync_vault_password),+ supportingText = stringResource(+ if (passwordSaved) R.string.sync_vault_password_set else R.string.sync_vault_password_unset,+ ),+ onClick = { showPasswordDialog = true },+ )+ SettingsDivider()++ SettingsRow(+ title = stringResource(R.string.sync_last),+ supportingText = syncStatusText(lastSync, status, error),+ )+ SettingsDivider()++ SettingsRow(+ title = stringResource(R.string.sync_now),+ enabled = enabled,+ onClick = { KdbxSyncScheduler.syncNow(context) },+ ) }++ if (showPasswordDialog) {+ VaultPasswordDialog(+ onDismiss = { showPasswordDialog = false },+ onSave = { value ->+ KdbxPasswordHelper(context).storePassphrase(value)+ passwordSaved = true+ showPasswordDialog = false+ },+ )+ }+}++@Composable+private fun syncStatusText(lastSync: Long, status: String, error: String): String {+ val context = LocalContext.current+ val when_ = if (lastSync == 0L) {+ stringResource(R.string.sync_never)+ } else {+ DateFormat.getMediumDateFormat(context).format(Date(lastSync)) + " " ++ DateFormat.getTimeFormat(context).format(Date(lastSync))+ }+ if (status != KdbxSyncSettings.STATUS_ERROR) return when_+ val reason = when (error) {+ "file_missing" -> stringResource(R.string.sync_error_file_missing)+ "wrong_password" -> stringResource(R.string.sync_error_wrong_password)+ "verify_failed" -> stringResource(R.string.sync_error_verify_failed)+ else -> stringResource(R.string.sync_error_generic, error)+ }+ return "$when_\n$reason"+}++@Composable+private fun VaultPasswordDialog(onDismiss: () -> Unit, onSave: (String) -> Unit) {+ var value by remember { mutableStateOf("") }+ AlertDialog(+ onDismissRequest = onDismiss,+ title = { Text(stringResource(R.string.sync_vault_password)) },+ text = {+ OutlinedTextField(+ value = value,+ onValueChange = { value = it },+ singleLine = true,+ visualTransformation = PasswordVisualTransformation(),+ label = { Text(stringResource(R.string.sync_vault_password)) },+ )+ },+ confirmButton = {+ TextButton(onClick = { onSave(value) }, enabled = value.isNotEmpty()) {+ Text(stringResource(R.string.sync_save))+ }+ },+ dismissButton = {+ TextButton(onClick = onDismiss) { Text(stringResource(R.string.sync_cancel)) }+ },+ ) }
passwords/src/main/java/com/vayunmathur/passwords/util/KdbxBackupFormat.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/util/KdbxBackupFormat.kt b/passwords/src/main/java/com/vayunmathur/passwords/util/KdbxBackupFormat.ktindex 92d01f0421..38d9b4b6e2 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/util/KdbxBackupFormat.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/util/KdbxBackupFormat.kt@@ -1,17 +1,21 @@ package com.vayunmathur.passwords.util import android.content.Context-import android.util.Base64 import com.vayunmathur.library.util.BackupFormat-import com.vayunmathur.passwords.data.Passkey import com.vayunmathur.passwords.data.PasskeyDao-import com.vayunmathur.passwords.data.Password import com.vayunmathur.passwords.data.PasswordDao+import com.vayunmathur.passwords.data.newSyncId+import com.vayunmathur.passwords.sync.EntryMapper import org.json.JSONArray import org.json.JSONObject import java.io.InputStream import java.io.OutputStream +/**+ * One-shot kdbx backup/restore. Shares [EntryMapper] with the bidirectional sync, but+ * deliberately keeps the standalone semantics: exports carry no sync identity, and an+ * import always inserts fresh rows.+ */ class KdbxBackupFormat( private val passwordDao: PasswordDao, private val passkeyDao: PasskeyDao,@@ -24,38 +28,8 @@ class KdbxBackupFormat( requireNotNull(password) { "Password required for KDBX export" } val entries = JSONArray()-- for (pw in passwordDao.getAll()) {- val entry = JSONObject()- entry.put("Title", pw.name)- entry.put("UserName", pw.userId)- entry.put("Password", pw.password)- if (pw.websites.isNotEmpty()) {- entry.put("URL", pw.websites.first())- if (pw.websites.size > 1) {- entry.put("Websites", pw.websites.joinToString("\n"))- }- }- pw.totpSecret?.let { secret ->- entry.put("otp", "otpauth://totp/?secret=$secret")- }- entry.put("_Type", "password")- entries.put(entry)- }-- for (pk in passkeyDao.getAll()) {- val entry = JSONObject()- entry.put("Title", pk.rpName)- entry.put("UserName", pk.userName)- entry.put("URL", pk.rpId)- entry.put("_Type", "passkey")- entry.put("KPEX_PASSKEY_USERNAME", pk.userName)- entry.put("KPEX_PASSKEY_PRIVATE_KEY_PEM", Base64.encodeToString(pk.privateKeyBytes, Base64.NO_WRAP))- entry.put("KPEX_PASSKEY_CREDENTIAL_ID", pk.credentialId)- entry.put("KPEX_PASSKEY_USER_HANDLE", pk.userId)- entry.put("KPEX_PASSKEY_RELYING_PARTY", pk.rpId)- entries.put(entry)- }+ for (pw in passwordDao.getAll()) entries.put(EntryMapper.toFields(pw).withoutSyncFields())+ for (pk in passkeyDao.getAll()) entries.put(EntryMapper.toFields(pk).withoutSyncFields()) val bytes = KdbxNative.nativeExport(password, entries.toString()) ?: error("Failed to write KDBX file")@@ -71,59 +45,21 @@ class KdbxBackupFormat( val entries = JSONArray(json) for (i in 0 until entries.length()) { val entry = entries.getJSONObject(i).toStringMap()- val isPasskey = entry.keys.any { it.startsWith("KPEX_PASSKEY_") }- if (isPasskey) {- importPasskey(entry)+ if (EntryMapper.isPasskeyEntry(entry)) {+ passkeyDao.upsert(EntryMapper.toPasskey(entry).copy(syncId = newSyncId())) } else {- importPassword(entry)+ passwordDao.upsert(EntryMapper.toPassword(entry).copy(syncId = newSyncId())) } } } - private suspend fun importPassword(entry: Map<String, String>) {- val websites = mutableListOf<String>()- val url = entry["URL"].orEmpty()- if (url.isNotEmpty()) websites.add(url)- val extraWebsites = entry["Websites"]- if (!extraWebsites.isNullOrEmpty()) {- extraWebsites.split("\n").filter { it.isNotBlank() }.forEach { w ->- if (w !in websites) websites.add(w)- }+ private fun Map<String, String>.withoutSyncFields(): JSONObject {+ val json = JSONObject()+ for ((key, value) in this) {+ if (key == EntryMapper.FIELD_SYNC_ID || key == EntryMapper.FIELD_MODIFIED) continue+ json.put(key, value) }- var totpSecret: String? = null- val otp = entry["otp"]- if (!otp.isNullOrEmpty()) {- val match = Regex("[?&]secret=([^&]+)").find(otp)- totpSecret = match?.groupValues?.get(1) ?: otp- }- if (totpSecret == null) {- totpSecret = entry["TOTP Seed"]- }-- val pw = Password(- name = entry["Title"].orEmpty(),- userId = entry["UserName"].orEmpty(),- password = entry["Password"].orEmpty(),- websites = websites,- totpSecret = totpSecret,- )- passwordDao.upsert(pw)- }-- private suspend fun importPasskey(entry: Map<String, String>) {- val privateKeyB64 = entry["KPEX_PASSKEY_PRIVATE_KEY_PEM"].orEmpty()- val privateKeyBytes = if (privateKeyB64.isNotEmpty()) Base64.decode(privateKeyB64, Base64.NO_WRAP) else ByteArray(0)-- val pk = Passkey(- rpId = entry["KPEX_PASSKEY_RELYING_PARTY"].orEmpty().ifEmpty { entry["URL"].orEmpty() },- rpName = entry["Title"].orEmpty(),- credentialId = entry["KPEX_PASSKEY_CREDENTIAL_ID"].orEmpty(),- userId = entry["KPEX_PASSKEY_USER_HANDLE"].orEmpty(),- userName = entry["KPEX_PASSKEY_USERNAME"].orEmpty().ifEmpty { entry["UserName"].orEmpty() },- userDisplayName = entry["UserName"].orEmpty(),- privateKeyBytes = privateKeyBytes,- )- passkeyDao.upsert(pk)+ return json } private fun JSONObject.toStringMap(): Map<String, String> = buildMap {
passwords/src/main/java/com/vayunmathur/passwords/util/PasswordsViewModel.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/util/PasswordsViewModel.kt b/passwords/src/main/java/com/vayunmathur/passwords/util/PasswordsViewModel.ktindex db7c4ad7b3..8cc547275a 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/util/PasswordsViewModel.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/util/PasswordsViewModel.kt@@ -21,6 +21,8 @@ import com.vayunmathur.passwords.data.Passkey import com.vayunmathur.passwords.data.PasskeyDao import com.vayunmathur.passwords.data.Password import com.vayunmathur.passwords.data.PasswordDao+import com.vayunmathur.passwords.sync.KdbxSyncScheduler+import com.vayunmathur.passwords.sync.KdbxSyncSettings import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow@@ -72,6 +74,7 @@ class PasswordsViewModel( fun deletePasskey(passkey: Passkey) { viewModelScope.launch(Dispatchers.IO) { passkeyDao.delete(passkey)+ requestSync() } } @@ -79,15 +82,22 @@ class PasswordsViewModel( viewModelScope.launch(Dispatchers.IO) { val newId = passwordDao.upsert(password) onSaved?.invoke(newId)+ requestSync() } } override fun delete(password: Password) { viewModelScope.launch(Dispatchers.IO) { passwordDao.delete(password)+ requestSync() } } + private suspend fun requestSync() {+ val ctx = getApplication<Application>()+ if (KdbxSyncSettings.enabled(ctx)) KdbxSyncScheduler.scheduleDebounced(ctx)+ }+ /** * Returns a [State] tracking the password with [initialId]. If not yet * loaded (or absent), returns [default]. Recomposes when the underlying
passwords/src/main/res/values/strings.xml
diff --git a/passwords/src/main/res/values/strings.xml b/passwords/src/main/res/values/strings.xmlindex 9704e5cfa0..128c29e40d 100644--- a/passwords/src/main/res/values/strings.xml+++ b/passwords/src/main/res/values/strings.xml@@ -83,4 +83,43 @@ <string name="cable_prompt_title">Sign in on your other device?</string> <string name="cable_prompt_subtitle">Verify to approve this passkey sign-in</string> <string name="name_and_user_id_required">Name and User ID cannot be empty</string>++ <!-- Section header for the two-way KeePass file sync settings. KDBX = KeePass database file extension, keep as-is -->+ <string name="sync_section">KDBX Sync</string>+ <!-- Toggle row title. Verb phrase enabling two-way sync with a KeePass file -->+ <string name="sync_enable">Sync with a KDBX file</string>+ <!-- Supporting text under the sync toggle explaining the behaviour -->+ <string name="sync_enable_description">Keeps this vault and a KeePass file in agreement every 15 minutes and after each change.</string>+ <!-- Row title for choosing which file to sync with. Noun phrase -->+ <string name="sync_file">KDBX file</string>+ <!-- Supporting text when no file has been picked yet. Parentheses intentional -->+ <string name="sync_file_none">(none selected)</string>+ <!-- Menu item: pick an existing .kdbx file via the system file picker. Verb phrase -->+ <string name="sync_choose_file">Choose existing file</string>+ <!-- Menu item: create a brand new empty .kdbx file. Verb phrase -->+ <string name="sync_create_file">Create new file</string>+ <!-- Row title for the password that unlocks the KDBX file. Distinct from the app unlock -->+ <string name="sync_vault_password">Vault password</string>+ <!-- Supporting text when the vault password has been stored -->+ <string name="sync_vault_password_set">Saved</string>+ <!-- Supporting text when no vault password has been stored yet. Parentheses intentional -->+ <string name="sync_vault_password_unset">(not set)</string>+ <!-- Dialog button. Verb, Title Case -->+ <string name="sync_save">Save</string>+ <!-- Dialog button. Verb, Title Case -->+ <string name="sync_cancel">Cancel</string>+ <!-- Row title showing when the last sync ran. Noun phrase -->+ <string name="sync_last">Last sync</string>+ <!-- Supporting text when no sync has ever completed. Adverb -->+ <string name="sync_never">Never</string>+ <!-- Row title triggering an immediate sync. Verb phrase, Title Case -->+ <string name="sync_now">Sync now</string>+ <!-- Error: the chosen file could not be opened, e.g. moved, deleted, or permission revoked -->+ <string name="sync_error_file_missing">The KDBX file could not be opened. Nothing was changed locally.</string>+ <!-- Error: the stored vault password does not unlock the file -->+ <string name="sync_error_wrong_password">Wrong vault password. Nothing was changed locally.</string>+ <!-- Error: the merged vault failed its re-parse check, so the file was left untouched -->+ <string name="sync_error_verify_failed">The merged vault failed verification, so the file was not written.</string>+ <!-- Error with details. %1$s = raw failure message from the sync -->+ <string name="sync_error_generic">Sync failed: <xliff:g id="reason" example="No space left on device">%1$s</xliff:g></string> </resources>
passwords/src/main/rust/src/tests.rs
diff --git a/passwords/src/main/rust/src/tests.rs b/passwords/src/main/rust/src/tests.rsindex bc94020aab..bb08374e46 100644--- a/passwords/src/main/rust/src/tests.rs+++ b/passwords/src/main/rust/src/tests.rs@@ -66,6 +66,27 @@ fn export_then_import_roundtrips_all_fields() { assert_eq!(pk.get("KPEX_PASSKEY_RELYING_PARTY").map(|s| s.as_str()), Some("acme.example")); } +#[test]+fn sync_metadata_fields_survive_roundtrip() {+ let mut m = EntryMap::new();+ m.insert("Title".into(), "Synced".into());+ m.insert("Password".into(), "p".into());+ m.insert("_Type".into(), "password".into());+ m.insert("_SyncId".into(), "0123456789abcdef0123456789abcdef".into());+ m.insert("_Modified".into(), "1785954985000".into());+ let json_str = json_array_of(&[m]);++ let bytes = export_kdbx(PW, &json_str).expect("export");+ let parsed = entries_of(&import_kdbx(PW, &bytes).expect("import"));++ let e = find_entry(&parsed, "Synced");+ assert_eq!(+ e.get("_SyncId").map(|s| s.as_str()),+ Some("0123456789abcdef0123456789abcdef"),+ );+ assert_eq!(e.get("_Modified").map(|s| s.as_str()), Some("1785954985000"));+}+ #[test] fn password_field_is_stored_protected() { let mut m = EntryMap::new();
passwords/src/test/java/com/vayunmathur/passwords/cable/CtapProcessorTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/cable/CtapProcessorTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/cable/CtapProcessorTest.ktindex c2879c088e..73b1a58014 100644--- a/passwords/src/test/java/com/vayunmathur/passwords/cable/CtapProcessorTest.kt+++ b/passwords/src/test/java/com/vayunmathur/passwords/cable/CtapProcessorTest.kt@@ -27,14 +27,14 @@ class CtapProcessorTest { private val urlEncoder = Base64.UrlSafe.withPadding(Base64.PaddingOption.ABSENT) - private class FakePasskeyDao(initial: List<Passkey>) : PasskeyDao {+ private class FakePasskeyDao(initial: List<Passkey>) : PasskeyDao() { val store = initial.toMutableList() override fun getAllFlow(): Flow<List<Passkey>> = flowOf(store.toList()) override suspend fun getAll(): List<Passkey> = store.toList() override suspend fun getByRpId(rpId: String): List<Passkey> = store.filter { it.rpId == rpId } override suspend fun getByCredentialId(credentialId: String): Passkey? = store.firstOrNull { it.credentialId == credentialId }- override suspend fun upsert(passkey: Passkey): Long {+ override suspend fun upsertRaw(passkey: Passkey): Long { store.removeAll { it.id == passkey.id } store.add(passkey) return passkey.id
passwords/src/test/java/com/vayunmathur/passwords/sync/EntryMapperTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/sync/EntryMapperTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/sync/EntryMapperTest.ktnew file mode 100644index 0000000000..0bcd577a83--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/sync/EntryMapperTest.kt@@ -0,0 +1,99 @@+package com.vayunmathur.passwords.sync++import com.vayunmathur.passwords.data.Passkey+import com.vayunmathur.passwords.data.Password+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** The merge compares hashes derived from this mapping, so it has to round-trip exactly. */+class EntryMapperTest {++ @Test fun passwordRoundTripsApartFromRowId() {+ val pw = Password(+ id = 7,+ name = "GitHub",+ userId = "octocat",+ password = "s3cr3t!",+ totpSecret = "JBSWY3DPEHPK3PXP",+ websites = listOf("https://github.com", "https://gist.github.com"),+ syncId = "abc123",+ updatedAt = 1_700_000_000_000,+ )++ val back = EntryMapper.toPassword(EntryMapper.toFields(pw))++ assertEquals(0L, back.id)+ assertEquals(pw.copy(id = 0), back)+ }++ @Test fun passwordWithoutWebsitesOrTotpRoundTrips() {+ val pw = Password(name = "Bare", userId = "u", password = "p", syncId = "s", updatedAt = 5)+ assertEquals(pw, EntryMapper.toPassword(EntryMapper.toFields(pw)))+ }++ @Test fun passkeyRoundTripsApartFromRowId() {+ val pk = Passkey(+ id = 3,+ rpId = "acme.example",+ rpName = "Acme",+ credentialId = "cred-123",+ userId = "user-abc",+ userName = "alice",+ userDisplayName = "Alice Anderson",+ privateKeyBytes = byteArrayOf(1, 2, 3, 4, -5),+ creationTime = 111,+ lastUsedTime = 222,+ signCount = 9,+ syncId = "pk-sync",+ updatedAt = 333,+ )++ val back = EntryMapper.toPasskey(EntryMapper.toFields(pk))++ assertEquals(0L, back.id)+ assertEquals(pk.rpName, back.rpName)+ assertEquals(pk.userName, back.userName)+ assertEquals(pk.userDisplayName, back.userDisplayName)+ assertEquals(pk.creationTime, back.creationTime)+ assertEquals(pk.lastUsedTime, back.lastUsedTime)+ assertEquals(pk.signCount, back.signCount)+ assertEquals(pk.syncId, back.syncId)+ assertEquals(pk.updatedAt, back.updatedAt)+ assertContentEquals(pk.privateKeyBytes, back.privateKeyBytes)+ }++ @Test fun passkeyEntriesAreDetected() {+ assertTrue(EntryMapper.isPasskeyEntry(EntryMapper.toFields(Passkey())))+ assertTrue(!EntryMapper.isPasskeyEntry(EntryMapper.toFields(Password())))+ }++ @Test fun contentHashIgnoresIdentityAndTimestamp() {+ val pw = Password(name = "A", userId = "u", password = "p", syncId = "one", updatedAt = 1)+ val moved = pw.copy(syncId = "two", updatedAt = 999, id = 42)++ assertEquals(+ EntryMapper.contentHash(EntryMapper.toFields(pw)),+ EntryMapper.contentHash(EntryMapper.toFields(moved)),+ )+ assertNotEquals(+ EntryMapper.contentHash(EntryMapper.toFields(pw)),+ EntryMapper.contentHash(EntryMapper.toFields(pw.copy(password = "other"))),+ )+ }++ @Test fun otpauthUriAndTotpSeedBothYieldTheSecret() {+ assertEquals(+ "JBSWY3DPEHPK3PXP",+ EntryMapper.toPassword(mapOf("otp" to "otpauth://totp/Foo?secret=JBSWY3DPEHPK3PXP&issuer=Foo")).totpSecret,+ )+ assertEquals(+ "SEEDVALUE",+ EntryMapper.toPassword(mapOf("TOTP Seed" to "SEEDVALUE")).totpSecret,+ )+ assertNull(EntryMapper.toPassword(mapOf("Title" to "x")).totpSecret)+ }+}
passwords/src/test/java/com/vayunmathur/passwords/sync/KdbxSyncEngineTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/sync/KdbxSyncEngineTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/sync/KdbxSyncEngineTest.ktnew file mode 100644index 0000000000..322b4c706b--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/sync/KdbxSyncEngineTest.kt@@ -0,0 +1,312 @@+package com.vayunmathur.passwords.sync++import com.vayunmathur.passwords.data.Passkey+import com.vayunmathur.passwords.data.PasskeyDao+import com.vayunmathur.passwords.data.Password+import com.vayunmathur.passwords.data.PasswordDao+import com.vayunmathur.passwords.data.SyncSnapshot+import com.vayunmathur.passwords.data.SyncSnapshotDao+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.runBlocking+import java.io.FileNotFoundException+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++private const val VAULT_PW = "correct horse battery staple"++class KdbxSyncEngineTest {++ @Test fun newLocalEntryIsPushed() = runBlocking {+ val harness = Harness(passwords = listOf(password(1, "GitHub", "octocat", "p", updatedAt = 1000)))++ val result = harness.sync()++ assertEquals(KdbxSyncResult.Success(pushed = 1, pulled = 0, deletedLocal = 0, deletedRemote = 0), result)+ val remote = harness.remoteEntries()+ assertEquals(1, remote.size)+ assertEquals("GitHub", remote.single()["Title"])+ assertEquals("sync-1", remote.single()[EntryMapper.FIELD_SYNC_ID])+ }++ @Test fun newRemoteEntryIsPulled() = runBlocking {+ val harness = Harness(remote = listOf(fields(password(0, "Remote", "bob", "rp", syncId = "r1", updatedAt = 500))))++ val result = harness.sync()++ assertEquals(KdbxSyncResult.Success(pushed = 0, pulled = 1, deletedLocal = 0, deletedRemote = 0), result)+ val stored = harness.pwDao.store.single()+ assertEquals("Remote", stored.name)+ assertEquals("r1", stored.syncId)+ // Pulled rows keep the remote timestamp so the next cycle does not see them as dirty.+ assertEquals(500, stored.updatedAt)+ assertEquals(0, harness.document.writes)+ }++ @Test fun bothModifiedResolvesToNewestTimestamp() = runBlocking {+ val harness = Harness(passwords = listOf(password(1, "A", "u", "original", updatedAt = 1000)))+ harness.sync()++ harness.pwDao.store[0] = harness.pwDao.store[0].copy(password = "local", updatedAt = 3000)+ harness.editRemote { it + mapOf("Password" to "remote", EntryMapper.FIELD_MODIFIED to "2000") }++ val result = harness.sync()++ assertEquals(1, (result as KdbxSyncResult.Success).pushed)+ assertEquals("local", harness.remoteEntries().single()["Password"])+ assertEquals("local", harness.pwDao.store.single().password)+ }++ @Test fun remoteWinsWhenItIsNewer() = runBlocking {+ val harness = Harness(passwords = listOf(password(1, "A", "u", "original", updatedAt = 1000)))+ harness.sync()++ harness.pwDao.store[0] = harness.pwDao.store[0].copy(password = "local", updatedAt = 2000)+ harness.editRemote { it + mapOf("Password" to "remote", EntryMapper.FIELD_MODIFIED to "3000") }++ val result = harness.sync()++ assertEquals(1, (result as KdbxSyncResult.Success).pulled)+ assertEquals("remote", harness.pwDao.store.single().password)+ assertEquals(3000, harness.pwDao.store.single().updatedAt)+ }++ @Test fun entryDeletedRemotelyIsDeletedLocally() = runBlocking {+ val harness = Harness(passwords = listOf(password(1, "A", "u", "p", updatedAt = 1000)))+ harness.sync()++ harness.setRemote(emptyList())+ val result = harness.sync()++ assertEquals(1, (result as KdbxSyncResult.Success).deletedLocal)+ assertTrue(harness.pwDao.store.isEmpty())+ assertTrue(harness.snapshotDao.store.isEmpty())+ }++ @Test fun entryDeletedLocallyIsDeletedRemotely() = runBlocking {+ val harness = Harness(passwords = listOf(password(1, "A", "u", "p", updatedAt = 1000)))+ harness.sync()++ harness.pwDao.store.clear()+ val result = harness.sync()++ assertEquals(1, (result as KdbxSyncResult.Success).deletedRemote)+ assertTrue(harness.remoteEntries().isEmpty())+ assertTrue(harness.snapshotDao.store.isEmpty())+ }++ @Test fun firstSyncAdoptsMatchingVaultEntriesInsteadOfDuplicating() = runBlocking {+ val local = password(1, "GitHub", "octocat", "p", syncId = "local-1", updatedAt = 1000)+ // An entry written by KeePassXC: same credential, but no sync identity.+ val foreign = fields(local) - EntryMapper.FIELD_SYNC_ID - EntryMapper.FIELD_MODIFIED+ val harness = Harness(passwords = listOf(local), remote = listOf(foreign))++ harness.sync()++ assertEquals(1, harness.pwDao.store.size)+ assertEquals("local-1", harness.pwDao.store.single().syncId)+ val remote = harness.remoteEntries()+ assertEquals(1, remote.size)+ assertEquals("local-1", remote.single()[EntryMapper.FIELD_SYNC_ID])+ }++ @Test fun unmatchedForeignEntryIsPulledAsNew() = runBlocking {+ val harness = Harness(remote = listOf(mapOf("Title" to "Foreign", "UserName" to "x", "Password" to "y")))++ harness.sync()++ val stored = harness.pwDao.store.single()+ assertEquals("Foreign", stored.name)+ assertTrue(stored.syncId.isNotBlank())+ }++ @Test fun pulledEntryIsNotDirtyOnTheFollowingSync() = runBlocking {+ val harness = Harness(remote = listOf(fields(password(0, "Remote", "bob", "rp", syncId = "r1", updatedAt = 500))))+ harness.sync()++ val result = harness.sync()++ assertEquals(KdbxSyncResult.Success(pushed = 0, pulled = 0, deletedLocal = 0, deletedRemote = 0), result)+ assertEquals(0, harness.document.writes)+ assertEquals(1, harness.pwDao.store.size)+ }++ @Test fun pushedEntryIsNotDirtyOnTheFollowingSync() = runBlocking {+ val harness = Harness(passwords = listOf(password(1, "A", "u", "p", updatedAt = 1000)))+ harness.sync()+ val writesAfterFirst = harness.document.writes++ val result = harness.sync()++ assertEquals(KdbxSyncResult.Success(pushed = 0, pulled = 0, deletedLocal = 0, deletedRemote = 0), result)+ assertEquals(writesAfterFirst, harness.document.writes)+ }++ @Test fun missingFileAbortsWithoutMutating() = runBlocking {+ val harness = Harness(passwords = listOf(password(1, "A", "u", "p", updatedAt = 1000)))+ harness.document.bytes = null++ val result = harness.sync()++ assertEquals(KdbxSyncResult.FileMissing, result)+ assertEquals(1, harness.pwDao.store.size)+ assertTrue(harness.snapshotDao.store.isEmpty())+ assertEquals(0, harness.document.writes)+ }++ @Test fun wrongPasswordAbortsWithoutMutating() = runBlocking {+ val harness = Harness(passwords = listOf(password(1, "A", "u", "p", updatedAt = 1000)))++ val result = harness.engine.sync(harness.document, "not the password")++ assertEquals(KdbxSyncResult.WrongPassword, result)+ assertEquals(1, harness.pwDao.store.size)+ assertTrue(harness.snapshotDao.store.isEmpty())+ assertEquals(0, harness.document.writes)+ }++ @Test fun passkeysSyncAlongsidePasswords() = runBlocking {+ val passkey = Passkey(+ id = 1,+ rpId = "acme.example",+ rpName = "Acme",+ credentialId = "cred-1",+ userId = "user-1",+ userName = "alice",+ privateKeyBytes = byteArrayOf(1, 2, 3),+ creationTime = 10,+ lastUsedTime = 20,+ signCount = 1,+ syncId = "pk-1",+ updatedAt = 1000,+ )+ val harness = Harness(passkeys = listOf(passkey))++ assertEquals(1, (harness.sync() as KdbxSyncResult.Success).pushed)++ val remote = harness.remoteEntries().single()+ assertEquals("cred-1", remote["KPEX_PASSKEY_CREDENTIAL_ID"])++ // A sign-count bump is a content change and propagates.+ harness.pkDao.store[0] = harness.pkDao.store[0].copy(signCount = 2, updatedAt = 2000)+ assertEquals(1, (harness.sync() as KdbxSyncResult.Success).pushed)+ assertEquals("2", harness.remoteEntries().single()["_SignCount"])+ }+}++private fun password(+ id: Long,+ name: String,+ userId: String,+ password: String,+ syncId: String = "sync-$id",+ updatedAt: Long = 0,+) = Password(id = id, name = name, userId = userId, password = password, syncId = syncId, updatedAt = updatedAt)++private fun fields(pw: Password) = EntryMapper.toFields(pw)++private class Harness(+ passwords: List<Password> = emptyList(),+ passkeys: List<Passkey> = emptyList(),+ remote: List<Map<String, String>> = emptyList(),+) {+ val codec = FakeCodec()+ val pwDao = FakePasswordDao(passwords)+ val pkDao = FakePasskeyDao(passkeys)+ val snapshotDao = FakeSyncSnapshotDao()+ val document = FakeDocument(codec.write(VAULT_PW, remote))++ val engine get() = KdbxSyncEngine(pwDao, pkDao, snapshotDao, codec)++ suspend fun sync() = engine.sync(document, VAULT_PW)++ fun remoteEntries(): List<Map<String, String>> = codec.read(VAULT_PW, assertNotNull(document.bytes))!!++ fun setRemote(entries: List<Map<String, String>>) {+ document.bytes = codec.write(VAULT_PW, entries)+ }++ fun editRemote(transform: (Map<String, String>) -> Map<String, String>) {+ setRemote(remoteEntries().map(transform))+ }+}++/** Stands in for the JNI codec: "encryption" is a lookup table keyed by the returned blob. */+private class FakeCodec : KdbxCodec {+ private val vaults = mutableMapOf<String, List<Map<String, String>>>()+ private var counter = 0++ override fun read(password: String, bytes: ByteArray): List<Map<String, String>>? {+ if (password != VAULT_PW) return null+ return vaults[String(bytes)]+ }++ override fun write(password: String, entries: List<Map<String, String>>): ByteArray {+ val handle = "vault-${counter++}"+ vaults[handle] = entries.map { it.toMap() }+ return handle.toByteArray()+ }+}++private class FakeDocument(var bytes: ByteArray?) : KdbxDocument {+ var writes = 0++ override fun read(): ByteArray = bytes ?: throw FileNotFoundException("no document")++ override fun write(bytes: ByteArray) {+ this.bytes = bytes+ writes+++ }+}++private class FakePasswordDao(initial: List<Password>) : PasswordDao() {+ val store = initial.toMutableList()+ private var nextId = (initial.maxOfOrNull { it.id } ?: 0L) + 1++ override fun getAllFlow(): Flow<List<Password>> = flowOf(store.toList())+ override suspend fun getAll(): List<Password> = store.toList()+ override fun getByIdFlow(id: Long): Flow<Password?> = flowOf(store.firstOrNull { it.id == id })+ override suspend fun getById(id: Long): Password? = store.firstOrNull { it.id == id }++ override suspend fun upsertRaw(value: Password): Long {+ val row = if (value.id == 0L) value.copy(id = nextId++) else value+ val index = store.indexOfFirst { it.id == row.id }+ if (index >= 0) store[index] = row else store.add(row)+ return row.id+ }++ override suspend fun delete(value: Password): Int =+ if (store.removeAll { it.id == value.id }) 1 else 0+}++private class FakePasskeyDao(initial: List<Passkey>) : PasskeyDao() {+ val store = initial.toMutableList()+ private var nextId = (initial.maxOfOrNull { it.id } ?: 0L) + 1++ override fun getAllFlow(): Flow<List<Passkey>> = flowOf(store.toList())+ override suspend fun getAll(): List<Passkey> = store.toList()+ override suspend fun getByRpId(rpId: String): List<Passkey> = store.filter { it.rpId == rpId }+ override suspend fun getByCredentialId(credentialId: String): Passkey? =+ store.firstOrNull { it.credentialId == credentialId }++ override suspend fun upsertRaw(passkey: Passkey): Long {+ val row = if (passkey.id == 0L) passkey.copy(id = nextId++) else passkey+ val index = store.indexOfFirst { it.id == row.id }+ if (index >= 0) store[index] = row else store.add(row)+ return row.id+ }++ override suspend fun delete(passkey: Passkey): Int =+ if (store.removeAll { it.id == passkey.id }) 1 else 0+}++private class FakeSyncSnapshotDao : SyncSnapshotDao {+ val store = mutableMapOf<String, SyncSnapshot>()++ override suspend fun getAll(): List<SyncSnapshot> = store.values.toList()+ override suspend fun upsert(snapshot: SyncSnapshot) { store[snapshot.syncId] = snapshot }+ override suspend fun deleteBySyncId(syncId: String) { store.remove(syncId) }+ override suspend fun deleteAll() = store.clear()+}