vpn: extract VpnTabs to ui/VpnTabs.kt (one composable per file)
- Commit
6e967a2a25f1582e109046ec4cdc490fcb16a6b6- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-15 19:35 UTC (3 months ago)
- Parents
163c10b
Diff
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.ktindex a2ff3df4b5..3a3580f1f1 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncEngine.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncEngine.kt@@ -1,458 +1,458 @@-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.PasswordRepository-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 kotlinx.coroutines.flow.Flow-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) },- )-- constructor(repository: PasswordRepository, codec: KdbxCodec) : this(- passwordDao = object : PasswordDao() {- override fun getAllFlow(): Flow<List<Password>> = repository.passwords- override suspend fun getAll(): List<Password> = repository.getAllPasswords()- override fun getByIdFlow(id: Long): Flow<Password?> = repository.getPasswordByIdFlow(id)- override suspend fun getById(id: Long): Password? = repository.getPasswordById(id)- override suspend fun upsertRaw(value: Password): Long = repository.upsertPasswordRaw(value)- override suspend fun delete(value: Password): Int = repository.deletePassword(value)- },- passkeyDao = object : PasskeyDao() {- override fun getAllFlow(): Flow<List<Passkey>> = repository.passkeys- override suspend fun getAll(): List<Passkey> = repository.getAllPasskeys()- override suspend fun getByRpId(rpId: String): List<Passkey> = repository.getPasskeysByRpId(rpId)- override suspend fun getByCredentialId(credentialId: String): Passkey? =- repository.getPasskeyByCredentialId(credentialId)- override suspend fun upsertRaw(passkey: Passkey): Long = repository.upsertPasskeyRaw(passkey)- override suspend fun delete(passkey: Passkey): Int = repository.deletePasskey(passkey)- },- snapshotDao = object : SyncSnapshotDao {- override suspend fun getAll(): List<SyncSnapshot> = repository.getAllSnapshots()- override suspend fun upsert(snapshot: SyncSnapshot) = repository.upsertSnapshot(snapshot)- override suspend fun deleteBySyncId(syncId: String) = repository.deleteSnapshotBySyncId(syncId)- override suspend fun deleteAll() = repository.deleteAllSnapshots()- },- codec = codec,- inTransaction = { repository.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-}--/** Repository-based overload — preferred; avoids direct PasswordDatabase access. */-suspend fun runKdbxSync(context: Context, repository: PasswordRepository): 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(repository, 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"+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.PasswordRepository+import com.vayunmathur.passwords.data.SyncSnapshot+import com.vayunmathur.passwords.data.SyncSnapshotDao+import com.vayunmathur.passwords.data.newSyncId+import com.vayunmathur.passwords.domain.KdbxNative+import kotlinx.coroutines.flow.Flow+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) },+ )++ constructor(repository: PasswordRepository, codec: KdbxCodec) : this(+ passwordDao = object : PasswordDao() {+ override fun getAllFlow(): Flow<List<Password>> = repository.passwords+ override suspend fun getAll(): List<Password> = repository.getAllPasswords()+ override fun getByIdFlow(id: Long): Flow<Password?> = repository.getPasswordByIdFlow(id)+ override suspend fun getById(id: Long): Password? = repository.getPasswordById(id)+ override suspend fun upsertRaw(value: Password): Long = repository.upsertPasswordRaw(value)+ override suspend fun delete(value: Password): Int = repository.deletePassword(value)+ },+ passkeyDao = object : PasskeyDao() {+ override fun getAllFlow(): Flow<List<Passkey>> = repository.passkeys+ override suspend fun getAll(): List<Passkey> = repository.getAllPasskeys()+ override suspend fun getByRpId(rpId: String): List<Passkey> = repository.getPasskeysByRpId(rpId)+ override suspend fun getByCredentialId(credentialId: String): Passkey? =+ repository.getPasskeyByCredentialId(credentialId)+ override suspend fun upsertRaw(passkey: Passkey): Long = repository.upsertPasskeyRaw(passkey)+ override suspend fun delete(passkey: Passkey): Int = repository.deletePasskey(passkey)+ },+ snapshotDao = object : SyncSnapshotDao {+ override suspend fun getAll(): List<SyncSnapshot> = repository.getAllSnapshots()+ override suspend fun upsert(snapshot: SyncSnapshot) = repository.upsertSnapshot(snapshot)+ override suspend fun deleteBySyncId(syncId: String) = repository.deleteSnapshotBySyncId(syncId)+ override suspend fun deleteAll() = repository.deleteAllSnapshots()+ },+ codec = codec,+ inTransaction = { repository.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+}++/** Repository-based overload — preferred; avoids direct PasswordDatabase access. */+suspend fun runKdbxSync(context: Context, repository: PasswordRepository): 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(repository, 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/ui/PasskeyAuthActivity.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyAuthActivity.kt b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyAuthActivity.ktindex a18a037203..a85f676e7b 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyAuthActivity.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyAuthActivity.kt@@ -1,363 +1,363 @@-@file:OptIn(kotlin.uuid.ExperimentalUuidApi::class)--package com.vayunmathur.passwords.ui--import kotlin.uuid.Uuid-import android.content.Intent-import android.os.Bundle-import android.util.Base64-import android.util.Log-import androidx.credentials.CreatePublicKeyCredentialRequest-import androidx.credentials.GetPublicKeyCredentialOption-import androidx.credentials.PublicKeyCredential-import androidx.credentials.provider.PendingIntentHandler-import androidx.fragment.app.FragmentActivity-import com.vayunmathur.library.util.AppMessages-import com.vayunmathur.library.biometric.unlockDatabaseWithBiometrics-import com.vayunmathur.library.util.DatabaseHelper-import com.vayunmathur.passwords.cable.WebAuthnAuthenticator-import com.vayunmathur.passwords.data.Passkey-import com.vayunmathur.passwords.data.PasswordRepository-import com.vayunmathur.passwords.util.Cbor-import com.vayunmathur.passwords.util.PasskeyCredentialService-import com.vayunmathur.passwords.util.PasskeyUtils-import com.vayunmathur.passwords.util.buildGetCredentialResponse-import kotlinx.coroutines.runBlocking-import org.json.JSONArray-import org.json.JSONObject-import java.security.KeyPairGenerator-import java.security.MessageDigest-import java.security.interfaces.ECPublicKey-import java.security.spec.ECGenParameterSpec--class PasskeyAuthActivity : FragmentActivity() {-- private lateinit var repository: PasswordRepository-- override fun onCreate(savedInstanceState: Bundle?) {- super.onCreate(savedInstanceState)-- val helper = DatabaseHelper(applicationContext)- if (helper.isKeyGenerated()) {- repository = PasswordRepository.get(applicationContext)- proceedWithFlow()- } else {- unlockDatabaseWithBiometrics(- activity = this,- onSuccess = { passphrase ->- helper.storePassphrase(passphrase)- repository = PasswordRepository.get(applicationContext)- proceedWithFlow()- },- onFailure = { message ->- message?.let { AppMessages.show(it) }- setResult(RESULT_CANCELED)- finish()- }- )- }- }-- private fun proceedWithFlow() {- val flow = intent.getStringExtra(EXTRA_FLOW)- try {- when (flow) {- FLOW_CREATE -> handleCreate()- FLOW_GET -> handleGet()- FLOW_PASSWORD -> handlePassword()- FLOW_UNLOCK -> handleUnlock()- else -> {- Log.e(TAG, "Unknown flow: $flow")- setResult(RESULT_CANCELED)- }- }- } catch (e: Exception) {- Log.e(TAG, "Error in passkey $flow flow", e)- setResult(RESULT_CANCELED)- }- finish()- }-- private fun handleCreate() {- val request = PendingIntentHandler.retrieveProviderCreateCredentialRequest(intent) ?: run {- Log.e(TAG, "No create credential request in intent")- setResult(RESULT_CANCELED)- return- }- val publicKeyRequest = request.callingRequest as? CreatePublicKeyCredentialRequest ?: run {- Log.e(TAG, "Request is not a PublicKeyCredentialRequest")- setResult(RESULT_CANCELED)- return- }-- val json = JSONObject(publicKeyRequest.requestJson)- val rp = json.getJSONObject("rp")- val rpId = rp.getString("id")- val rpName = rp.optString("name", rpId)- val user = json.getJSONObject("user")- val userId = user.getString("id")- val userName = user.optString("name", "")- val userDisplayName = user.optString("displayName", userName)- val challenge = json.getString("challenge")-- // Privileged browsers provide clientDataHash directly- val callingAppInfo = request.callingAppInfo- val privilegedOrigin = PasskeyUtils.getPrivilegedOrigin(callingAppInfo, applicationContext)- val isPrivileged = privilegedOrigin != null- val origin = privilegedOrigin ?: PasskeyUtils.getAndroidOrigin(callingAppInfo)- Log.d(TAG, "Create passkey for rpId=$rpId, origin=$origin, privileged=$isPrivileged")-- // Generate EC P-256 key pair- val keyPairGenerator = KeyPairGenerator.getInstance("EC")- keyPairGenerator.initialize(ECGenParameterSpec("secp256r1"))- val keyPair = keyPairGenerator.generateKeyPair()- val ecPublicKey = keyPair.public as ECPublicKey-- val credentialId = PasskeyUtils.generateCredentialId()- val credentialIdB64 = b64Url(credentialId)-- // Build COSE public key- val xBytes = toFixedBytes(ecPublicKey.w.affineX, 32)- val yBytes = toFixedBytes(ecPublicKey.w.affineY, 32)- val coseKeyMap = linkedMapOf<Any, Any>(- 1L to 2L, // kty: EC2- 3L to -7L, // alg: ES256- -1L to 1L, // crv: P-256- -2L to xBytes as Any, // x- -3L to yBytes as Any, // y- )- val coseKeyBytes = Cbor.encode(coseKeyMap)-- // Build authenticator data with attested credential data- val authDataBase = PasskeyUtils.buildAuthenticatorData(- rpId = rpId,- attestedCredentialData = true,- )- val authData = authDataBase +- AAGUID +- byteArrayOf((credentialId.size shr 8).toByte(), credentialId.size.toByte()) +- credentialId +- coseKeyBytes-- // Build attestation object using CBOR- val attestationObject = Cbor.encode(linkedMapOf<String, Any>(- "fmt" to "none",- "attStmt" to emptyMap<Any, Any>(),- "authData" to authData,- ))-- // For privileged browsers: use placeholder clientDataJSON (browser replaces it)- // For Android apps: build our own clientDataJSON- val clientDataJsonB64 = if (isPrivileged) {- b64Url("<placeholder>".toByteArray())- } else {- val clientDataJson = JSONObject().apply {- put("type", "webauthn.create")- put("challenge", challenge)- put("origin", origin)- put("crossOrigin", false)- }.toString()- b64Url(clientDataJson.toByteArray())- }-- val responseJson = JSONObject().apply {- put("id", credentialIdB64)- put("rawId", credentialIdB64)- put("type", "public-key")- put("authenticatorAttachment", "platform")- put("response", JSONObject().apply {- put("clientDataJSON", clientDataJsonB64)- put("attestationObject", b64Url(attestationObject))- put("transports", JSONArray(listOf("internal", "hybrid")))- put("publicKeyAlgorithm", -7)- put("publicKey", b64Url(keyPair.public.encoded))- put("authenticatorData", b64Url(authData))- })- put("clientExtensionResults", JSONObject())- }.toString()-- runBlocking {- repository.upsertPasskey(- Passkey(- rpId = rpId,- rpName = rpName,- credentialId = credentialIdB64,- userId = userId,- userName = userName,- userDisplayName = userDisplayName,- privateKeyBytes = keyPair.private.encoded,- creationTime = System.currentTimeMillis(),- lastUsedTime = System.currentTimeMillis(),- signCount = 0,- )- )- }-- Log.d(TAG, "Passkey created successfully for rpId=$rpId, credId=$credentialIdB64")- val credentialResponse = androidx.credentials.CreatePublicKeyCredentialResponse(responseJson)- val result = Intent()- PendingIntentHandler.setCreateCredentialResponse(result, credentialResponse)- setResult(RESULT_OK, result)- }-- private fun handleGet() {- val providerRequest = PendingIntentHandler.retrieveProviderGetCredentialRequest(intent) ?: run {- Log.e(TAG, "No get credential request in intent")- setResult(RESULT_CANCELED)- return- }- val credentialId = intent.getStringExtra(EXTRA_CREDENTIAL_ID) ?: run {- Log.e(TAG, "No credential ID in intent")- setResult(RESULT_CANCELED)- return- }-- val passkey = runBlocking { repository.getPasskeyByCredentialId(credentialId) } ?: run {- Log.e(TAG, "Passkey not found for credentialId=$credentialId")- setResult(RESULT_CANCELED)- return- }-- val publicKeyOption = providerRequest.credentialOptions- .filterIsInstance<GetPublicKeyCredentialOption>()- .firstOrNull() ?: run {- Log.e(TAG, "No PublicKeyCredentialOption in request")- setResult(RESULT_CANCELED)- return- }-- val json = JSONObject(publicKeyOption.requestJson)- val challenge = json.getString("challenge")-- val callingAppInfo = providerRequest.callingAppInfo- val privilegedOrigin = PasskeyUtils.getPrivilegedOrigin(callingAppInfo, applicationContext)- val isPrivileged = privilegedOrigin != null- val origin = privilegedOrigin ?: PasskeyUtils.getAndroidOrigin(callingAppInfo)- Log.d(TAG, "Get passkey for rpId=${passkey.rpId}, origin=$origin, privileged=$isPrivileged")-- val clientDataJson = JSONObject().apply {- put("type", "webauthn.get")- put("challenge", challenge)- put("origin", origin)- put("crossOrigin", false)- }.toString()-- val clientDataHash: ByteArray- val clientDataJsonB64: String- if (isPrivileged) {- clientDataHash = (try { publicKeyOption.clientDataHash } catch (_: Exception) { null })- ?: MessageDigest.getInstance("SHA-256").digest(clientDataJson.toByteArray())- clientDataJsonB64 = b64Url("<placeholder>".toByteArray())- } else {- clientDataHash = MessageDigest.getInstance("SHA-256").digest(clientDataJson.toByteArray())- clientDataJsonB64 = b64Url(clientDataJson.toByteArray())- }-- val assertion = runBlocking {- WebAuthnAuthenticator.signAssertion(passkey, clientDataHash, repository)- }- val authenticatorData = assertion.authenticatorData- val sig = assertion.signature-- val credIdBytes = Base64.decode(- passkey.credentialId,- Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP- )-- val responseJson = JSONObject().apply {- put("id", passkey.credentialId)- put("rawId", b64Url(credIdBytes))- put("type", "public-key")- put("authenticatorAttachment", "platform")- put("response", JSONObject().apply {- put("clientDataJSON", clientDataJsonB64)- put("authenticatorData", b64Url(authenticatorData))- put("signature", b64Url(sig))- put("userHandle", passkey.userId)- })- put("clientExtensionResults", JSONObject())- }.toString()-- Log.d(TAG, "Passkey assertion successful for rpId=${passkey.rpId}")- val credentialResponse = PublicKeyCredential(responseJson)- val result = Intent()- PendingIntentHandler.setGetCredentialResponse(- result,- androidx.credentials.GetCredentialResponse(credentialResponse),- providerRequest,- )- setResult(RESULT_OK, result)- }-- private fun b64Url(data: ByteArray): String =- Base64.encodeToString(data, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP)-- private fun toFixedBytes(value: java.math.BigInteger, length: Int): ByteArray {- val bytes = value.toByteArray()- return when {- bytes.size == length -> bytes- bytes.size > length -> bytes.copyOfRange(bytes.size - length, bytes.size)- else -> ByteArray(length - bytes.size) + bytes- }- }-- private fun handlePassword() {- val providerRequest = PendingIntentHandler.retrieveProviderGetCredentialRequest(intent) ?: run {- Log.e(TAG, "No get credential request in intent")- setResult(RESULT_CANCELED)- return- }- val passwordId = intent.getLongExtra(PasskeyCredentialService.EXTRA_PASSWORD_ID, -1)- if (passwordId == -1L) {- Log.e(TAG, "No password ID in intent")- setResult(RESULT_CANCELED)- return- }- val password = runBlocking { repository.getPasswordById(passwordId) }- if (password == null) {- Log.e(TAG, "Password not found for id=$passwordId")- setResult(RESULT_CANCELED)- return- }- val credentialResponse = androidx.credentials.PasswordCredential(password.username, password.password)- val result = Intent()- PendingIntentHandler.setGetCredentialResponse(- result,- androidx.credentials.GetCredentialResponse(credentialResponse),- providerRequest,- )- setResult(RESULT_OK, result)- }-- private fun handleUnlock() {- val request = PendingIntentHandler.retrieveBeginGetCredentialRequest(intent)- if (request == null) {- Log.e(TAG, "No BeginGetCredentialRequest in unlock intent")- setResult(RESULT_CANCELED)- return- }-- val response = runBlocking {- buildGetCredentialResponse(- applicationContext,- request.beginGetCredentialOptions,- repository,- )- }-- val result = Intent()- PendingIntentHandler.setBeginGetCredentialResponse(result, response)- setResult(RESULT_OK, result)- }-- companion object {- const val EXTRA_FLOW = "flow"- const val EXTRA_CREDENTIAL_ID = "credential_id"- const val FLOW_CREATE = "create"- const val FLOW_GET = "get"- const val FLOW_PASSWORD = "password"- const val FLOW_UNLOCK = "unlock"- private const val TAG = "PasskeyAuthActivity"- private val AAGUID = Uuid.parse("a1b2c3d4-e5f6-7890-abcd-ef1234567890").toByteArray()- }-}+@file:OptIn(kotlin.uuid.ExperimentalUuidApi::class)++package com.vayunmathur.passwords.ui++import kotlin.uuid.Uuid+import android.content.Intent+import android.os.Bundle+import android.util.Base64+import android.util.Log+import androidx.credentials.CreatePublicKeyCredentialRequest+import androidx.credentials.GetPublicKeyCredentialOption+import androidx.credentials.PublicKeyCredential+import androidx.credentials.provider.PendingIntentHandler+import androidx.fragment.app.FragmentActivity+import com.vayunmathur.library.util.AppMessages+import com.vayunmathur.library.biometric.unlockDatabaseWithBiometrics+import com.vayunmathur.library.util.DatabaseHelper+import com.vayunmathur.passwords.platform.cable.WebAuthnAuthenticator+import com.vayunmathur.passwords.data.Passkey+import com.vayunmathur.passwords.data.PasswordRepository+import com.vayunmathur.passwords.domain.Cbor+import com.vayunmathur.passwords.platform.PasskeyCredentialService+import com.vayunmathur.passwords.platform.PasskeyUtils+import com.vayunmathur.passwords.platform.buildGetCredentialResponse+import kotlinx.coroutines.runBlocking+import org.json.JSONArray+import org.json.JSONObject+import java.security.KeyPairGenerator+import java.security.MessageDigest+import java.security.interfaces.ECPublicKey+import java.security.spec.ECGenParameterSpec++class PasskeyAuthActivity : FragmentActivity() {++ private lateinit var repository: PasswordRepository++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)++ val helper = DatabaseHelper(applicationContext)+ if (helper.isKeyGenerated()) {+ repository = PasswordRepository.get(applicationContext)+ proceedWithFlow()+ } else {+ unlockDatabaseWithBiometrics(+ activity = this,+ onSuccess = { passphrase ->+ helper.storePassphrase(passphrase)+ repository = PasswordRepository.get(applicationContext)+ proceedWithFlow()+ },+ onFailure = { message ->+ message?.let { AppMessages.show(it) }+ setResult(RESULT_CANCELED)+ finish()+ }+ )+ }+ }++ private fun proceedWithFlow() {+ val flow = intent.getStringExtra(EXTRA_FLOW)+ try {+ when (flow) {+ FLOW_CREATE -> handleCreate()+ FLOW_GET -> handleGet()+ FLOW_PASSWORD -> handlePassword()+ FLOW_UNLOCK -> handleUnlock()+ else -> {+ Log.e(TAG, "Unknown flow: $flow")+ setResult(RESULT_CANCELED)+ }+ }+ } catch (e: Exception) {+ Log.e(TAG, "Error in passkey $flow flow", e)+ setResult(RESULT_CANCELED)+ }+ finish()+ }++ private fun handleCreate() {+ val request = PendingIntentHandler.retrieveProviderCreateCredentialRequest(intent) ?: run {+ Log.e(TAG, "No create credential request in intent")+ setResult(RESULT_CANCELED)+ return+ }+ val publicKeyRequest = request.callingRequest as? CreatePublicKeyCredentialRequest ?: run {+ Log.e(TAG, "Request is not a PublicKeyCredentialRequest")+ setResult(RESULT_CANCELED)+ return+ }++ val json = JSONObject(publicKeyRequest.requestJson)+ val rp = json.getJSONObject("rp")+ val rpId = rp.getString("id")+ val rpName = rp.optString("name", rpId)+ val user = json.getJSONObject("user")+ val userId = user.getString("id")+ val userName = user.optString("name", "")+ val userDisplayName = user.optString("displayName", userName)+ val challenge = json.getString("challenge")++ // Privileged browsers provide clientDataHash directly+ val callingAppInfo = request.callingAppInfo+ val privilegedOrigin = PasskeyUtils.getPrivilegedOrigin(callingAppInfo, applicationContext)+ val isPrivileged = privilegedOrigin != null+ val origin = privilegedOrigin ?: PasskeyUtils.getAndroidOrigin(callingAppInfo)+ Log.d(TAG, "Create passkey for rpId=$rpId, origin=$origin, privileged=$isPrivileged")++ // Generate EC P-256 key pair+ val keyPairGenerator = KeyPairGenerator.getInstance("EC")+ keyPairGenerator.initialize(ECGenParameterSpec("secp256r1"))+ val keyPair = keyPairGenerator.generateKeyPair()+ val ecPublicKey = keyPair.public as ECPublicKey++ val credentialId = PasskeyUtils.generateCredentialId()+ val credentialIdB64 = b64Url(credentialId)++ // Build COSE public key+ val xBytes = toFixedBytes(ecPublicKey.w.affineX, 32)+ val yBytes = toFixedBytes(ecPublicKey.w.affineY, 32)+ val coseKeyMap = linkedMapOf<Any, Any>(+ 1L to 2L, // kty: EC2+ 3L to -7L, // alg: ES256+ -1L to 1L, // crv: P-256+ -2L to xBytes as Any, // x+ -3L to yBytes as Any, // y+ )+ val coseKeyBytes = Cbor.encode(coseKeyMap)++ // Build authenticator data with attested credential data+ val authDataBase = PasskeyUtils.buildAuthenticatorData(+ rpId = rpId,+ attestedCredentialData = true,+ )+ val authData = authDataBase ++ AAGUID ++ byteArrayOf((credentialId.size shr 8).toByte(), credentialId.size.toByte()) ++ credentialId ++ coseKeyBytes++ // Build attestation object using CBOR+ val attestationObject = Cbor.encode(linkedMapOf<String, Any>(+ "fmt" to "none",+ "attStmt" to emptyMap<Any, Any>(),+ "authData" to authData,+ ))++ // For privileged browsers: use placeholder clientDataJSON (browser replaces it)+ // For Android apps: build our own clientDataJSON+ val clientDataJsonB64 = if (isPrivileged) {+ b64Url("<placeholder>".toByteArray())+ } else {+ val clientDataJson = JSONObject().apply {+ put("type", "webauthn.create")+ put("challenge", challenge)+ put("origin", origin)+ put("crossOrigin", false)+ }.toString()+ b64Url(clientDataJson.toByteArray())+ }++ val responseJson = JSONObject().apply {+ put("id", credentialIdB64)+ put("rawId", credentialIdB64)+ put("type", "public-key")+ put("authenticatorAttachment", "platform")+ put("response", JSONObject().apply {+ put("clientDataJSON", clientDataJsonB64)+ put("attestationObject", b64Url(attestationObject))+ put("transports", JSONArray(listOf("internal", "hybrid")))+ put("publicKeyAlgorithm", -7)+ put("publicKey", b64Url(keyPair.public.encoded))+ put("authenticatorData", b64Url(authData))+ })+ put("clientExtensionResults", JSONObject())+ }.toString()++ runBlocking {+ repository.upsertPasskey(+ Passkey(+ rpId = rpId,+ rpName = rpName,+ credentialId = credentialIdB64,+ userId = userId,+ userName = userName,+ userDisplayName = userDisplayName,+ privateKeyBytes = keyPair.private.encoded,+ creationTime = System.currentTimeMillis(),+ lastUsedTime = System.currentTimeMillis(),+ signCount = 0,+ )+ )+ }++ Log.d(TAG, "Passkey created successfully for rpId=$rpId, credId=$credentialIdB64")+ val credentialResponse = androidx.credentials.CreatePublicKeyCredentialResponse(responseJson)+ val result = Intent()+ PendingIntentHandler.setCreateCredentialResponse(result, credentialResponse)+ setResult(RESULT_OK, result)+ }++ private fun handleGet() {+ val providerRequest = PendingIntentHandler.retrieveProviderGetCredentialRequest(intent) ?: run {+ Log.e(TAG, "No get credential request in intent")+ setResult(RESULT_CANCELED)+ return+ }+ val credentialId = intent.getStringExtra(EXTRA_CREDENTIAL_ID) ?: run {+ Log.e(TAG, "No credential ID in intent")+ setResult(RESULT_CANCELED)+ return+ }++ val passkey = runBlocking { repository.getPasskeyByCredentialId(credentialId) } ?: run {+ Log.e(TAG, "Passkey not found for credentialId=$credentialId")+ setResult(RESULT_CANCELED)+ return+ }++ val publicKeyOption = providerRequest.credentialOptions+ .filterIsInstance<GetPublicKeyCredentialOption>()+ .firstOrNull() ?: run {+ Log.e(TAG, "No PublicKeyCredentialOption in request")+ setResult(RESULT_CANCELED)+ return+ }++ val json = JSONObject(publicKeyOption.requestJson)+ val challenge = json.getString("challenge")++ val callingAppInfo = providerRequest.callingAppInfo+ val privilegedOrigin = PasskeyUtils.getPrivilegedOrigin(callingAppInfo, applicationContext)+ val isPrivileged = privilegedOrigin != null+ val origin = privilegedOrigin ?: PasskeyUtils.getAndroidOrigin(callingAppInfo)+ Log.d(TAG, "Get passkey for rpId=${passkey.rpId}, origin=$origin, privileged=$isPrivileged")++ val clientDataJson = JSONObject().apply {+ put("type", "webauthn.get")+ put("challenge", challenge)+ put("origin", origin)+ put("crossOrigin", false)+ }.toString()++ val clientDataHash: ByteArray+ val clientDataJsonB64: String+ if (isPrivileged) {+ clientDataHash = (try { publicKeyOption.clientDataHash } catch (_: Exception) { null })+ ?: MessageDigest.getInstance("SHA-256").digest(clientDataJson.toByteArray())+ clientDataJsonB64 = b64Url("<placeholder>".toByteArray())+ } else {+ clientDataHash = MessageDigest.getInstance("SHA-256").digest(clientDataJson.toByteArray())+ clientDataJsonB64 = b64Url(clientDataJson.toByteArray())+ }++ val assertion = runBlocking {+ WebAuthnAuthenticator.signAssertion(passkey, clientDataHash, repository)+ }+ val authenticatorData = assertion.authenticatorData+ val sig = assertion.signature++ val credIdBytes = Base64.decode(+ passkey.credentialId,+ Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP+ )++ val responseJson = JSONObject().apply {+ put("id", passkey.credentialId)+ put("rawId", b64Url(credIdBytes))+ put("type", "public-key")+ put("authenticatorAttachment", "platform")+ put("response", JSONObject().apply {+ put("clientDataJSON", clientDataJsonB64)+ put("authenticatorData", b64Url(authenticatorData))+ put("signature", b64Url(sig))+ put("userHandle", passkey.userId)+ })+ put("clientExtensionResults", JSONObject())+ }.toString()++ Log.d(TAG, "Passkey assertion successful for rpId=${passkey.rpId}")+ val credentialResponse = PublicKeyCredential(responseJson)+ val result = Intent()+ PendingIntentHandler.setGetCredentialResponse(+ result,+ androidx.credentials.GetCredentialResponse(credentialResponse),+ providerRequest,+ )+ setResult(RESULT_OK, result)+ }++ private fun b64Url(data: ByteArray): String =+ Base64.encodeToString(data, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP)++ private fun toFixedBytes(value: java.math.BigInteger, length: Int): ByteArray {+ val bytes = value.toByteArray()+ return when {+ bytes.size == length -> bytes+ bytes.size > length -> bytes.copyOfRange(bytes.size - length, bytes.size)+ else -> ByteArray(length - bytes.size) + bytes+ }+ }++ private fun handlePassword() {+ val providerRequest = PendingIntentHandler.retrieveProviderGetCredentialRequest(intent) ?: run {+ Log.e(TAG, "No get credential request in intent")+ setResult(RESULT_CANCELED)+ return+ }+ val passwordId = intent.getLongExtra(PasskeyCredentialService.EXTRA_PASSWORD_ID, -1)+ if (passwordId == -1L) {+ Log.e(TAG, "No password ID in intent")+ setResult(RESULT_CANCELED)+ return+ }+ val password = runBlocking { repository.getPasswordById(passwordId) }+ if (password == null) {+ Log.e(TAG, "Password not found for id=$passwordId")+ setResult(RESULT_CANCELED)+ return+ }+ val credentialResponse = androidx.credentials.PasswordCredential(password.username, password.password)+ val result = Intent()+ PendingIntentHandler.setGetCredentialResponse(+ result,+ androidx.credentials.GetCredentialResponse(credentialResponse),+ providerRequest,+ )+ setResult(RESULT_OK, result)+ }++ private fun handleUnlock() {+ val request = PendingIntentHandler.retrieveBeginGetCredentialRequest(intent)+ if (request == null) {+ Log.e(TAG, "No BeginGetCredentialRequest in unlock intent")+ setResult(RESULT_CANCELED)+ return+ }++ val response = runBlocking {+ buildGetCredentialResponse(+ applicationContext,+ request.beginGetCredentialOptions,+ repository,+ )+ }++ val result = Intent()+ PendingIntentHandler.setBeginGetCredentialResponse(result, response)+ setResult(RESULT_OK, result)+ }++ companion object {+ const val EXTRA_FLOW = "flow"+ const val EXTRA_CREDENTIAL_ID = "credential_id"+ const val FLOW_CREATE = "create"+ const val FLOW_GET = "get"+ const val FLOW_PASSWORD = "password"+ const val FLOW_UNLOCK = "unlock"+ private const val TAG = "PasskeyAuthActivity"+ private val AAGUID = Uuid.parse("a1b2c3d4-e5f6-7890-abcd-ef1234567890").toByteArray()+ }+}
passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyPage.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyPage.kt b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyPage.ktindex 03e2c5a920..9d5f7539f6 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyPage.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyPage.kt@@ -1,98 +1,98 @@-package com.vayunmathur.passwords.ui--import android.text.format.DateFormat-import androidx.compose.ui.platform.LocalContext-import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.Spacer-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.shape.RoundedCornerShape-import com.vayunmathur.library.ui.Card-import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.Scaffold-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TopAppBar-import androidx.compose.runtime.Composable-import androidx.compose.runtime.collectAsState-import androidx.compose.runtime.getValue-import androidx.compose.ui.Modifier-import androidx.compose.ui.res.stringResource-import androidx.compose.ui.unit.dp-import com.vayunmathur.library.util.NavBackStack-import com.vayunmathur.library.ui.IconDelete-import com.vayunmathur.library.ui.IconNavigation-import com.vayunmathur.passwords.R-import com.vayunmathur.passwords.Route-import com.vayunmathur.passwords.util.PasswordsViewModel-import java.util.Date--@OptIn(ExperimentalMaterial3Api::class)-@Composable-fun PasskeyPage(- backStack: NavBackStack<Route>,- id: Long,- viewModel: PasswordsViewModel,-) {- val passkeys by viewModel.passkeys.collectAsState()- val passkey = passkeys.firstOrNull { it.id == id }-- if (passkey == null) {- return- }-- val context = LocalContext.current- val mediumDate = DateFormat.getMediumDateFormat(context)- val shortTime = DateFormat.getTimeFormat(context)- val dateFormat = { ms: Long -> mediumDate.format(Date(ms)) + " " + shortTime.format(Date(ms)) }-- Scaffold(- topBar = {- TopAppBar(- title = { Text(passkey.rpName.ifBlank { stringResource(R.string.passkey_detail_title) }) },- actions = {- IconButton(onClick = { viewModel.deletePasskey(passkey); backStack.pop() }) {- IconDelete()- }- },- navigationIcon = {- IconNavigation(backStack)- }- )- },- ) { paddingValues ->- Column(- Modifier- .padding(paddingValues)- .padding(16.dp)- .fillMaxSize(),- verticalArrangement = Arrangement.spacedBy(12.dp)- ) {- DetailCard(stringResource(R.string.passkey_rp_name), passkey.rpName)- DetailCard(stringResource(R.string.passkey_rp_id), passkey.rpId)- DetailCard(stringResource(R.string.passkey_user_name), passkey.userName)- DetailCard(stringResource(R.string.passkey_user_display_name), passkey.userDisplayName)- DetailCard(- stringResource(R.string.passkey_credential_id),- passkey.credentialId.let { if (it.length > 20) it.take(20) + "…" else it }- )- DetailCard(stringResource(R.string.passkey_created), dateFormat(passkey.creationTime))- DetailCard(stringResource(R.string.passkey_last_used), dateFormat(passkey.lastUsedTime))- }- }-}--@Composable-private fun DetailCard(label: String, value: String) {- Card(shape = RoundedCornerShape(8.dp), modifier = Modifier.fillMaxWidth()) {- Column(Modifier.padding(12.dp)) {- Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)- Spacer(Modifier.height(4.dp))- Text(value.ifBlank { "—" }, style = MaterialTheme.typography.bodyLarge)- }- }-}+package com.vayunmathur.passwords.ui++import android.text.format.DateFormat+import androidx.compose.ui.platform.LocalContext+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Spacer+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.shape.RoundedCornerShape+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TopAppBar+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.passwords.R+import com.vayunmathur.passwords.Route+import com.vayunmathur.passwords.platform.PasswordsViewModel+import java.util.Date++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun PasskeyPage(+ backStack: NavBackStack<Route>,+ id: Long,+ viewModel: PasswordsViewModel,+) {+ val passkeys by viewModel.passkeys.collectAsState()+ val passkey = passkeys.firstOrNull { it.id == id }++ if (passkey == null) {+ return+ }++ val context = LocalContext.current+ val mediumDate = DateFormat.getMediumDateFormat(context)+ val shortTime = DateFormat.getTimeFormat(context)+ val dateFormat = { ms: Long -> mediumDate.format(Date(ms)) + " " + shortTime.format(Date(ms)) }++ Scaffold(+ topBar = {+ TopAppBar(+ title = { Text(passkey.rpName.ifBlank { stringResource(R.string.passkey_detail_title) }) },+ actions = {+ IconButton(onClick = { viewModel.deletePasskey(passkey); backStack.pop() }) {+ IconDelete()+ }+ },+ navigationIcon = {+ IconNavigation(backStack)+ }+ )+ },+ ) { paddingValues ->+ Column(+ Modifier+ .padding(paddingValues)+ .padding(16.dp)+ .fillMaxSize(),+ verticalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ DetailCard(stringResource(R.string.passkey_rp_name), passkey.rpName)+ DetailCard(stringResource(R.string.passkey_rp_id), passkey.rpId)+ DetailCard(stringResource(R.string.passkey_user_name), passkey.userName)+ DetailCard(stringResource(R.string.passkey_user_display_name), passkey.userDisplayName)+ DetailCard(+ stringResource(R.string.passkey_credential_id),+ passkey.credentialId.let { if (it.length > 20) it.take(20) + "…" else it }+ )+ DetailCard(stringResource(R.string.passkey_created), dateFormat(passkey.creationTime))+ DetailCard(stringResource(R.string.passkey_last_used), dateFormat(passkey.lastUsedTime))+ }+ }+}++@Composable+private fun DetailCard(label: String, value: String) {+ Card(shape = RoundedCornerShape(8.dp), modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.padding(12.dp)) {+ Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)+ Spacer(Modifier.height(4.dp))+ Text(value.ifBlank { "—" }, style = MaterialTheme.typography.bodyLarge)+ }+ }+}
passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordEditScreen.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordEditScreen.kt b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordEditScreen.ktnew file mode 100644index 0000000000..399a55c806--- /dev/null+++ b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordEditScreen.kt@@ -0,0 +1,208 @@+package com.vayunmathur.passwords.ui+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.FlowRow+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.KeyboardActions+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.runtime.Composable+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.LocalFocusManager+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.input.ImeAction+import androidx.compose.ui.text.input.KeyboardType+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.FloatingActionButton+import com.vayunmathur.library.ui.IconClose+import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.library.ui.IconSave+import com.vayunmathur.library.ui.InputChip+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.SnackbarHost+import com.vayunmathur.library.ui.SnackbarHostState+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.passwords.R+import com.vayunmathur.passwords.platform.PasswordEditUiState+import com.vayunmathur.passwords.platform.PasswordsActions+import kotlinx.coroutines.launch++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun PasswordEditScreen(+ state: PasswordEditUiState,+ actions: PasswordsActions,+ onBack: () -> Unit = {},+ /** Called with the assigned id after a brand-new entry is saved. */+ onCreated: (Long) -> Unit = {},+) {+ val draft = state.draft+ val current = draft ?: state.saved++ var websiteInput by remember { mutableStateOf("") }+ var showPassword by remember { mutableStateOf(false) }++ val snackbarHostState = remember { SnackbarHostState() }+ val scope = rememberCoroutineScope()+ val nameRequired = stringResource(R.string.name_required)+ val focusManager = LocalFocusManager.current++ fun addWebsiteFromInput() {+ val candidate = websiteInput.trim()+ if (candidate.isNotEmpty()) {+ actions.updateDraft { d ->+ if (d.websites.contains(candidate)) d+ else d.copy(websites = d.websites + candidate)+ }+ }+ websiteInput = ""+ }++ Scaffold(+ topBar = {+ TopAppBar(+ title = { Text(if (current.id == 0L) stringResource(R.string.add_password) else stringResource(R.string.edit_password)) },+ navigationIcon = {+ IconNavigation(onBack)+ }+ )+ },+ floatingActionButton = {+ FloatingActionButton(onClick = {+ val d = draft ?: return@FloatingActionButton+ if (d.name.isBlank()) {+ scope.launch { snackbarHostState.showSnackbar(nameRequired) }+ return@FloatingActionButton+ }+ // Normalize empty TOTP to null before saving.+ actions.updateDraft { it.copy(totpSecret = it.totpSecret?.ifBlank { null }) }+ if (d.id == 0L) {+ actions.saveDraft { newId -> onCreated(newId) }+ } else {+ actions.saveDraft()+ onBack()+ }+ }) {+ IconSave()+ }+ },+ snackbarHost = { SnackbarHost(hostState = snackbarHostState) }+ ) { paddingValues ->+ Column(Modifier.padding(paddingValues).padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {+ Card(shape = RoundedCornerShape(10.dp), modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ OutlinedTextField(+ value = current.name,+ onValueChange = { v -> actions.updateDraft { it.copy(name = v) } },+ label = { Text(stringResource(R.string.label_name)) },+ modifier = Modifier.fillMaxWidth(),+ )+ OutlinedTextField(+ value = current.username,+ onValueChange = { v -> actions.updateDraft { it.copy(username = v) } },+ label = { Text(stringResource(R.string.label_username)) },+ modifier = Modifier.fillMaxWidth(),+ )+ OutlinedTextField(+ value = current.email,+ onValueChange = { v -> actions.updateDraft { it.copy(email = v) } },+ label = { Text(stringResource(R.string.label_email)) },+ modifier = Modifier.fillMaxWidth(),+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),+ )+ }+ }++ Card(shape = RoundedCornerShape(10.dp), modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ OutlinedTextField(+ value = current.password,+ onValueChange = { v -> actions.updateDraft { it.copy(password = v) } },+ label = { Text(stringResource(R.string.label_password)) },+ modifier = Modifier.fillMaxWidth(),+ visualTransformation = if (showPassword) androidx.compose.ui.text.input.VisualTransformation.None else androidx.compose.ui.text.input.PasswordVisualTransformation(),+ trailingIcon = {+ TextButton(onClick = { showPassword = !showPassword }) { Text(if (showPassword) stringResource(R.string.hide) else stringResource(R.string.show)) }+ }+ )++ OutlinedTextField(+ value = current.totpSecret ?: "",+ onValueChange = { v -> actions.updateDraft { it.copy(totpSecret = v) } },+ label = { Text(stringResource(R.string.label_totp_secret)) },+ modifier = Modifier.fillMaxWidth(),+ keyboardOptions = KeyboardOptions.Default,+ )+ }+ }++ Card(shape = RoundedCornerShape(10.dp), modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ OutlinedTextField(+ value = current.note,+ onValueChange = { v -> actions.updateDraft { it.copy(note = v) } },+ label = { Text(stringResource(R.string.label_note)) },+ modifier = Modifier.fillMaxWidth(),+ singleLine = false,+ minLines = 3,+ )+ }+ }++ Card(shape = RoundedCornerShape(10.dp), modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ // Input for websites: pressing IME Done (Enter) adds to list+ OutlinedTextField(+ value = websiteInput,+ onValueChange = { websiteInput = it },+ label = { Text(stringResource(R.string.label_add_website)) },+ modifier = Modifier.fillMaxWidth(),+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),+ keyboardActions = KeyboardActions(onDone = {+ addWebsiteFromInput()+ focusManager.clearFocus()+ })+ )++ // websites preview as chips with remove X+ if (current.websites.isNotEmpty()) {+ FlowRow(+ modifier = Modifier.padding(8.dp),+ horizontalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ for ((index, w) in current.websites.withIndex()) {+ InputChip(true, {}, label = { Text(w)}, modifier = Modifier.padding(vertical = 4.dp),+ trailingIcon = {+ Box(Modifier.clickable {+ actions.updateDraft { d ->+ d.copy(websites = d.websites.filterIndexed { i, _ -> i != index })+ }+ }) {+ IconClose()+ }+ })+ }+ }+ }+ }+ }++ Spacer(Modifier.height(56.dp))+ }+ }+}
passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordScreen.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordScreen.kt b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordScreen.ktnew file mode 100644index 0000000000..d6ff6dafda--- /dev/null+++ b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordScreen.kt@@ -0,0 +1,296 @@+package com.vayunmathur.passwords.ui+import android.content.Intent+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+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.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.core.net.toUri+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.ExternalIntents+import com.vayunmathur.library.ui.FloatingActionButton+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconCopy+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.IconEdit+import com.vayunmathur.library.ui.IconLink+import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.library.ui.IconVisibilityOff+import com.vayunmathur.library.ui.IconVisible+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.SnackbarHost+import com.vayunmathur.library.ui.SnackbarHostState+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.passwords.R+import com.vayunmathur.passwords.data.Password+import com.vayunmathur.passwords.domain.TOTP+import com.vayunmathur.passwords.platform.PasswordUiState+import com.vayunmathur.passwords.platform.PasswordsActions++@Composable+fun PasswordScreen(+ state: PasswordUiState,+ actions: PasswordsActions,+ onBack: () -> Unit = {},+ onEdit: () -> Unit = {},+ /**+ * Seed for the screen's own UI-only state. The app always takes the default; a preview+ * can set it to capture the revealed form without driving the reveal button.+ */+ initialShowPassword: Boolean = false,+) {+ val password = state.password+ val now = state.now+ val context = LocalContext.current+ var showPassword by remember { mutableStateOf(initialShowPassword) }+ val snackbarHostState = remember { SnackbarHostState() }++ LaunchedEffect(Unit) {+ actions.copyEvents.collect { msg ->+ snackbarHostState.showSnackbar(msg)+ }+ }++ Scaffold(+ topBar = {+ TopAppBar(+ title = { Text(password.name.ifBlank { stringResource(R.string.section_password) }) },+ actions = {+ IconButton(onClick = { actions.delete(password); onBack() }) {+ IconDelete()+ }+ },+ navigationIcon = {+ IconNavigation(onBack)+ }+ )+ },+ floatingActionButton = {+ FloatingActionButton(onEdit) {+ IconEdit()+ }+ },+ snackbarHost = { SnackbarHost(snackbarHostState) }+ ) { paddingValues ->+ Column(+ Modifier+ .padding(paddingValues)+ .padding(16.dp)+ .fillMaxSize(),+ verticalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ // Header+ Card(+ shape = RoundedCornerShape(12.dp),+ modifier = Modifier.fillMaxWidth()+ ) {+ Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {+ // Avatar with initial+ val initial = password.name.firstOrNull()?.uppercaseChar()?.toString() ?: "?"+ Box(+ Modifier+ .size(56.dp)+ .clip(CircleShape)+ .background(MaterialTheme.colorScheme.primaryContainer),+ contentAlignment = Alignment.Center+ ) {+ Text(initial, style = MaterialTheme.typography.titleLarge, color = MaterialTheme.colorScheme.onPrimaryContainer)+ }++ Spacer(Modifier.width(12.dp))++ Column(Modifier.weight(1f)) {+ Text(password.name.ifBlank { stringResource(R.string.no_name) }, style = MaterialTheme.typography.titleMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)+ Spacer(Modifier.height(4.dp))+ val subtitle = password.username.ifBlank { password.email }+ Text(subtitle.ifBlank { stringResource(R.string.no_user) }, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)+ }+ }+ }++ // Login info: username / email+ if (password.username.isNotBlank() || password.email.isNotBlank()) {+ Card(shape = RoundedCornerShape(8.dp), modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.padding(12.dp)) {+ if (password.username.isNotBlank()) {+ CopyableRow(+ label = stringResource(R.string.label_username),+ value = password.username,+ onCopy = { actions.copyToClipboard("username", password.username) },+ )+ }+ if (password.username.isNotBlank() && password.email.isNotBlank()) {+ Spacer(Modifier.height(8.dp))+ }+ if (password.email.isNotBlank()) {+ CopyableRow(+ label = stringResource(R.string.label_email),+ value = password.email,+ onCopy = { actions.copyToClipboard("email", password.email) },+ )+ }+ }+ }+ }++ // Password card+ Card(shape = RoundedCornerShape(8.dp), modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.padding(12.dp)) {+ Text(stringResource(R.string.section_password), style = MaterialTheme.typography.titleMedium)+ Spacer(Modifier.height(8.dp))++ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {+ Text(+ text = if (showPassword) password.password else "•".repeat(password.password.length),+ style = MaterialTheme.typography.bodyLarge,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.weight(1f)+ )++ IconButton(onClick = { showPassword = !showPassword }) {+ if (showPassword) IconVisibilityOff()+ else IconVisible()+ }++ IconButton(onClick = {+ actions.copyToClipboard("password", password.password)+ }) {+ IconCopy()+ }+ }+ }+ }++ // TOTP card: show generated code and circular timer+ Card(shape = RoundedCornerShape(8.dp), modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.padding(12.dp)) {+ Text(stringResource(R.string.section_totp), style = MaterialTheme.typography.titleMedium)+ Spacer(Modifier.height(8.dp))++ val secret = password.totpSecret+ if (secret.isNullOrBlank()) {+ Text(stringResource(R.string.totp_not_configured))+ } else {+ val timeStep = now / 1000 / 30+ val currentCode = remember(secret, timeStep) {+ TOTP.generate(secret, timeStep * 30)+ }+ val millisIntoStep = now % 30000+ val millisRemaining = 30000 - millisIntoStep+ val secondsRemaining = (millisRemaining / 1000).toInt()+ val progress = millisRemaining / 30000f++ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) {+ Column {+ Text(currentCode, style = MaterialTheme.typography.displayMedium)+ Spacer(Modifier.height(4.dp))+ Text(stringResource(R.string.totp_refreshes_in, secondsRemaining), style = MaterialTheme.typography.bodySmall)+ }++ // Circular progress showing proportion of time remaining+ Box(contentAlignment = Alignment.Center) {+ CircularProgressIndicator({ progress }, Modifier.size(56.dp))+ IconButton({+ actions.copyToClipboard("totp", currentCode, "TOTP copied")+ }) {+ IconCopy()+ }+ }+ }+ }+ }+ }++ // Note+ if (password.note.isNotBlank()) {+ Card(shape = RoundedCornerShape(8.dp), modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.padding(12.dp)) {+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {+ Text(stringResource(R.string.section_note), style = MaterialTheme.typography.titleMedium, modifier = Modifier.weight(1f))+ IconButton(onClick = { actions.copyToClipboard("note", password.note) }) {+ IconCopy()+ }+ }+ Spacer(Modifier.height(8.dp))+ Text(password.note, style = MaterialTheme.typography.bodyMedium)+ }+ }+ }++ // Websites+ Card(shape = RoundedCornerShape(8.dp), modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.padding(12.dp)) {+ Text(stringResource(R.string.section_websites), style = MaterialTheme.typography.titleMedium)+ Spacer(Modifier.height(8.dp))+ if (password.websites.isEmpty()) {+ Text(stringResource(R.string.websites_none))+ } else {+ for (w in password.websites) {+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier+ .fillMaxWidth()+ .clickable {+ // open link+ val intent = Intent(Intent.ACTION_VIEW, sanitizeUrl(w).toUri())+ ExternalIntents.launch(context, intent)+ }+ .padding(vertical = 6.dp)) {+ Text(w, modifier = Modifier.weight(1f), style = MaterialTheme.typography.bodyMedium)+ IconLink()+ }+ }+ }+ }+ }+ }+ }+}++@Composable+private fun CopyableRow(label: String, value: String, onCopy: () -> Unit) {+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.weight(1f)) {+ Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)+ Text(value, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ IconButton(onClick = onCopy) {+ IconCopy()+ }+ }+}++fun sanitizeUrl(input: String): String {+ val trimmed = input.trim()+ return if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {+ trimmed+ } else {+ "https://$trimmed"+ }+}
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 e12cd68296..0b11abf9cc 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/ui/SettingsPage.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/ui/SettingsPage.kt@@ -1,302 +1,302 @@-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-import androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.Spacer-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-fun SettingsPage(- backStack: com.vayunmathur.library.util.NavBackStack<com.vayunmathur.passwords.Route>,- passwordsViewModel: PasswordsViewModel,- passphrase: String,-) {- val importing by passwordsViewModel.importing.collectAsState()- val message by passwordsViewModel.importMessage.collectAsState()-- var selectedSource by remember { mutableStateOf<ImportSource?>(null) }-- val pickLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri: Uri? ->- if (uri != null) {- selectedSource?.let { source ->- passwordsViewModel.importCsv(uri, source)- }- }- selectedSource = null- }-- Scaffold(Modifier, {- TopAppBar(- { Text(stringResource(R.string.title_settings)) },- navigationIcon = { IconNavigation(backStack) },- actions = {- BackupButtons(- format = passwordsViewModel.buildBackupFormat(),- )- },- )- }) { paddingValues ->- Column(Modifier- .padding(paddingValues)- .fillMaxSize()- .verticalScroll(rememberScrollState())- .padding(16.dp), Arrangement.Top- ) {-- Text(stringResource(R.string.import_csv_warning))- Spacer(Modifier.height(16.dp))-- var dropdownExpanded by remember { mutableStateOf(false) }- Box {- Button(- onClick = { dropdownExpanded = true },- enabled = !importing,- ) {- Text(stringResource(R.string.import_passwords))- }- DropdownMenu(- expanded = dropdownExpanded,- onDismissRequest = { dropdownExpanded = false },- ) {- ImportSource.entries.forEach { source ->- DropdownMenuItem(- text = { Text(stringResource(source.label)) },- onClick = {- dropdownExpanded = false- selectedSource = source- pickLauncher.launch(arrayOf("text/csv", "text/plain", "application/octet-stream", "text/comma-separated-values"))- },- )- }- }- }-- Spacer(Modifier.height(16.dp))-- if (importing) {- Row(Modifier.fillMaxWidth(), Arrangement.Center) {- CircularProgressIndicator()- }- }-- message?.let {- 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(title = 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)) }- },- )-}+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+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+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.domain.ImportSource+import com.vayunmathur.passwords.platform.KdbxBackupFormat+import com.vayunmathur.passwords.platform.PasswordsViewModel+import kotlinx.coroutines.launch+import java.util.Date++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun SettingsPage(+ backStack: com.vayunmathur.library.util.NavBackStack<com.vayunmathur.passwords.Route>,+ passwordsViewModel: PasswordsViewModel,+ passphrase: String,+) {+ val importing by passwordsViewModel.importing.collectAsState()+ val message by passwordsViewModel.importMessage.collectAsState()++ var selectedSource by remember { mutableStateOf<ImportSource?>(null) }++ val pickLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri: Uri? ->+ if (uri != null) {+ selectedSource?.let { source ->+ passwordsViewModel.importCsv(uri, source)+ }+ }+ selectedSource = null+ }++ Scaffold(Modifier, {+ TopAppBar(+ { Text(stringResource(R.string.title_settings)) },+ navigationIcon = { IconNavigation(backStack) },+ actions = {+ BackupButtons(+ format = passwordsViewModel.buildBackupFormat(),+ )+ },+ )+ }) { paddingValues ->+ Column(Modifier+ .padding(paddingValues)+ .fillMaxSize()+ .verticalScroll(rememberScrollState())+ .padding(16.dp), Arrangement.Top+ ) {++ Text(stringResource(R.string.import_csv_warning))+ Spacer(Modifier.height(16.dp))++ var dropdownExpanded by remember { mutableStateOf(false) }+ Box {+ Button(+ onClick = { dropdownExpanded = true },+ enabled = !importing,+ ) {+ Text(stringResource(R.string.import_passwords))+ }+ DropdownMenu(+ expanded = dropdownExpanded,+ onDismissRequest = { dropdownExpanded = false },+ ) {+ ImportSource.entries.forEach { source ->+ DropdownMenuItem(+ text = { Text(stringResource(source.label)) },+ onClick = {+ dropdownExpanded = false+ selectedSource = source+ pickLauncher.launch(arrayOf("text/csv", "text/plain", "application/octet-stream", "text/comma-separated-values"))+ },+ )+ }+ }+ }++ Spacer(Modifier.height(16.dp))++ if (importing) {+ Row(Modifier.fillMaxWidth(), Arrangement.Center) {+ CircularProgressIndicator()+ }+ }++ message?.let {+ 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(title = 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/test/java/com/vayunmathur/passwords/cable/CableEidTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/cable/CableEidTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/cable/CableEidTest.ktdeleted file mode 100644index 04bc73d14c..0000000000--- a/passwords/src/test/java/com/vayunmathur/passwords/cable/CableEidTest.kt+++ /dev/null@@ -1,58 +0,0 @@-package com.vayunmathur.passwords.cable--import kotlin.test.Test-import kotlin.test.assertContentEquals-import kotlin.test.assertEquals-import javax.crypto.Cipher-import javax.crypto.Mac-import javax.crypto.spe
Diff truncated.