package com.peachpasswords.vault import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import java.security.SecureRandom import java.util.Base64 import java.util.UUID import javax.inject.Inject import javax.inject.Singleton private fun b64(bytes: ByteArray): String = Base64.getEncoder().withoutPadding().encodeToString(bytes) private fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s) sealed interface UnlockResult { data object Success : UnlockResult data object WrongPassword : UnlockResult data class Error(val reason: String) : UnlockResult } sealed interface CreateVaultResult { data object Success : CreateVaultResult data class Error(val reason: String) : CreateVaultResult } /** * In-memory vault session backed by [VaultStore]. Faithful port of the browser * `vault.ts` semantics that matter for correctness: * * - Two-slot at rest: slot A is the real (encrypted) vault, slot B a size-matched * noise blob so a fresh install shows two similarly-shaped records. * - Every modifiedAt/deletedAt uses [VaultCrypto.monotonicEntryTimestamp] so a * deletion always wins last-write-wins against an in-flight edit. * - Local writes bump the version counter; sync-applied writes do NOT (so a * sync round never cascades into another outbound sync). * - add/update/delete roll back in-memory state if the disk write fails. * - destroyVault never touches the Pro license (separate store). */ @Singleton class VaultRepository @Inject constructor( private val store: VaultStorage, ) { private val mutex = Mutex() private val rng = SecureRandom() private var derivedKey: ByteArray? = null private var entryList: MutableList = mutableListOf() private var duressConfigured: Boolean = false private val _isUnlocked = MutableStateFlow(false) val isUnlocked: StateFlow = _isUnlocked.asStateFlow() private val _entries = MutableStateFlow>(emptyList()) /** Active (non-deleted) entryList. */ val entries: StateFlow> = _entries.asStateFlow() private val _settings = MutableStateFlow(VaultSettings()) val settings: StateFlow = _settings.asStateFlow() fun hasVault(): Boolean = store.hasVault() suspend fun createVault(password: String): CreateVaultResult = mutex.withLock { return try { val salt = VaultCrypto.generateSalt() val key = VaultCrypto.deriveKey(password, salt) entryList = mutableListOf() duressConfigured = false val slotA = sealSlotA(key, salt) if (!store.writeSlotA(slotA)) return CreateVaultResult.Error("storage_write_failed") writeMatchingNoiseSlotB(slotA) store.stampLocalMutation() store.writeSettings(_settings.value) derivedKey = key publish() _isUnlocked.value = true CreateVaultResult.Success } catch (e: Exception) { CreateVaultResult.Error(e.message ?: "create_failed") } } suspend fun unlock(password: String): UnlockResult = mutex.withLock { val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault") return try { val key = VaultCrypto.deriveKey(password, unb64(slotA.salt)) val payload = try { VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A)) } catch (_: Exception) { VaultCrypto.zero(key) return UnlockResult.WrongPassword } derivedKey = key entryList = payload.entries.toMutableList() duressConfigured = payload.duressConfigured _settings.value = store.loadSettings() publish() _isUnlocked.value = true UnlockResult.Success } catch (e: Exception) { UnlockResult.Error(e.message ?: "unlock_failed") } } /** Unlock with an already-derived AES-256 key (biometric path). */ suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock { val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault") return try { val payload = VaultCodec.decode( VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A), ) derivedKey = key.copyOf() entryList = payload.entries.toMutableList() duressConfigured = payload.duressConfigured _settings.value = store.loadSettings() publish() _isUnlocked.value = true UnlockResult.Success } catch (_: Exception) { UnlockResult.WrongPassword } } fun lock() { derivedKey?.let(VaultCrypto::zero) derivedKey = null entryList = mutableListOf() duressConfigured = false _entries.value = emptyList() _isUnlocked.value = false } suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock { val slotA = store.loadSlotA() ?: return false return try { val oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt)) val payload = VaultCodec.decode( VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A), ) val newSalt = VaultCrypto.generateSalt() val newKey = VaultCrypto.deriveKey(newPassword, newSalt) // Re-seal the existing payload under the new key/salt. val plaintext = VaultCodec.encode(payload) val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A)) val next = StoredVault(version = slotA.version, salt = b64(newSalt), blob = blob) if (!store.writeSlotA(next)) return false writeMatchingNoiseSlotB(next) store.stampLocalMutation() VaultCrypto.zero(oldKey) derivedKey?.let(VaultCrypto::zero) derivedKey = newKey true } catch (_: Exception) { false } } /** * Irreversible wipe. Locks the session and clears every vault key. The Pro * license is in a separate store and is preserved by construction. */ suspend fun destroyVault() = mutex.withLock { lock() store.clearVault() } // ---- Entry CRUD ------------------------------------------------------- suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock { requireUnlocked() val stamp = VaultCrypto.monotonicEntryTimestamp() val now = System.currentTimeMillis() val entry = draft.copy( id = draft.id.ifBlank { UUID.randomUUID().toString() }, createdAt = if (draft.createdAt > 0) draft.createdAt else now, modifiedAt = stamp, passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt, ) val rollback = entryList.toMutableList() entryList.add(entry) persistOrRollback(rollback) entry } suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock { requireUnlocked() val idx = entryList.indexOfFirst { it.id == patch.id } if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found") val current = entryList[idx] val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt) // Only refresh passwordChangedAt when the password value actually changes. val passwordChanged = patch.password != null && patch.password != current.password val updated = patch.copy( createdAt = current.createdAt, modifiedAt = stamp, passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt, ) val rollback = entryList.toMutableList() entryList[idx] = updated persistOrRollback(rollback) updated } /** Soft-delete: writes a tombstone whose timestamp beats any in-flight edit. */ suspend fun deleteEntry(id: String) = mutex.withLock { requireUnlocked() val idx = entryList.indexOfFirst { it.id == id } if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found") val current = entryList[idx] val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt) val rollback = entryList.toMutableList() entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp) persistOrRollback(rollback) } suspend fun restoreEntry(id: String) = mutex.withLock { requireUnlocked() val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null } if (idx == -1) throw IllegalStateException("deleted entry not found") val current = entryList[idx] val rollback = entryList.toMutableList() entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)) persistOrRollback(rollback) } /** Permanent delete — no tombstone, no recovery. */ suspend fun purgeEntry(id: String) = mutex.withLock { requireUnlocked() val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null } if (idx == -1) throw IllegalStateException("deleted entry not found") val rollback = entryList.toMutableList() entryList.removeAt(idx) persistOrRollback(rollback) } fun getEntries(): List = entryList.filter { it.deletedAt == null } fun getEntry(id: String): VaultEntry? = entryList.firstOrNull { it.id == id && it.deletedAt == null } fun getDeletedEntries(): List = entryList.filter { it.deletedAt != null } fun getTombstones(): List = entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) } fun getVaultVersion(): Long = store.version() // ---- Sync apply (does NOT advance the version) ------------------------ /** * Apply remote entryList + tombstones with per-entry last-write-wins. Persists * WITHOUT bumping the version counter, so a sync round cannot cascade into * another outbound sync. Returns the number of locally-applied changes. */ suspend fun applyMergedRemoteEntries( remoteEntries: List, remoteTombstones: List, ): Int = mutex.withLock { requireUnlocked() val tombMap = remoteTombstones.associate { it.id to it.deletedAt } var applied = 0 val byId = entryList.associateBy { it.id }.toMutableMap() for (remote in remoteEntries) { val tomb = tombMap[remote.id] if (tomb != null && tomb >= remote.modifiedAt) continue val local = byId[remote.id] if (local == null) { entryList.add(remote); byId[remote.id] = remote; applied++ } else if (remote.modifiedAt > local.modifiedAt) { val i = entryList.indexOfFirst { it.id == local.id } if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; applied++ } } } for ((id, deletedAt) in tombMap) { val local = byId[id] ?: continue if (local.deletedAt != null && local.deletedAt >= deletedAt) continue if (deletedAt < local.modifiedAt) continue val i = entryList.indexOfFirst { it.id == id } if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); applied++ } } if (applied > 0) { persistSlotA(bumpVersion = false) publish() } applied } suspend fun updateSettings(settings: VaultSettings) = mutex.withLock { _settings.value = settings store.writeSettings(settings) } // ---- Internals -------------------------------------------------------- private fun requireUnlocked() { if (derivedKey == null) throw IllegalStateException("vault_locked") } private fun publish() { _entries.value = entryList.filter { it.deletedAt == null } } private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault { val plaintext = VaultCodec.encode(VaultPayload(entryList.toList(), duressConfigured)) val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A)) return StoredVault(version = 1, salt = b64(salt), blob = blob) } private fun writeMatchingNoiseSlotB(slotA: StoredVault) { val approxBytes = (slotA.blob.length / 2).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16) val noise = ByteArray(approxBytes).also(rng::nextBytes) store.writeSlotB(b64(noise)) } /** Re-seal slot A from the current in-memory state under the live key. */ private fun persistSlotA(bumpVersion: Boolean): Boolean { val key = derivedKey ?: throw IllegalStateException("vault_locked") val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A") val plaintext = VaultCodec.encode(VaultPayload(entryList.toList(), duressConfigured)) val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A)) val next = prior.copy(blob = blob) if (!store.writeSlotA(next)) return false // Slot A committed — keep slot B size-matched, then advance the version // for local writes only. Restore slot A if a later step fails. try { writeMatchingNoiseSlotB(next) if (bumpVersion) store.stampLocalMutation() } catch (e: Exception) { store.writeSlotA(prior) throw e } return true } /** Persist a local mutation, rolling the in-memory list back on failure. */ private fun persistOrRollback(rollback: MutableList) { try { if (!persistSlotA(bumpVersion = true)) { entryList = rollback throw IllegalStateException("storage_write_failed") } } catch (e: Exception) { entryList = rollback throw e } publish() } }