VaultRepository.kt

42.8 KB · raw

1package com.peachpasswords.vault23import kotlinx.coroutines.flow.MutableStateFlow4import kotlinx.coroutines.flow.StateFlow5import kotlinx.coroutines.flow.asStateFlow6import kotlinx.coroutines.sync.Mutex7import kotlinx.coroutines.sync.withLock8import java.security.SecureRandom9import java.util.Base6410import java.util.UUID11import javax.inject.Inject12import javax.inject.Singleton1314private fun b64(bytes: ByteArray): String = Base64.getEncoder().withoutPadding().encodeToString(bytes)15private fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s)1617/** Cap on retained past passwords per entry. Mirrors the browser PASSWORD_HISTORY_MAX. */18private const val PASSWORD_HISTORY_MAX = 501920sealed interface UnlockResult {21    data object Success : UnlockResult22    data object WrongPassword : UnlockResult23    data class Error(val reason: String) : UnlockResult24}2526sealed interface CreateVaultResult {27    data object Success : CreateVaultResult28    data class Error(val reason: String) : CreateVaultResult29}3031/**32 * In-memory vault session backed by [VaultStore]. Faithful port of the browser33 * `vault.ts` semantics that matter for correctness:34 *35 *  - Two-slot at rest: slot A is the real (encrypted) vault, slot B a size-matched36 *    noise blob so a fresh install shows two similarly-shaped records.37 *  - Every modifiedAt/deletedAt uses [VaultCrypto.monotonicEntryTimestamp] so a38 *    deletion always wins last-write-wins against an in-flight edit.39 *  - Local writes bump the version counter; sync-applied writes do NOT (so a40 *    sync round never cascades into another outbound sync).41 *  - add/update/delete roll back in-memory state if the disk write fails.42 *  - destroyVault never touches the Pro license (separate store).43 */44@Singleton45class VaultRepository @Inject constructor(46    private val store: VaultStorage,47) {48    private val mutex = Mutex()49    private val rng = SecureRandom()5051    private var derivedKey: ByteArray? = null52    private var rootKey: ByteArray? = null53    private var entryList: MutableList<VaultEntry> = mutableListOf()54    private var duressConfigured: Boolean = false55    private var recoveryWordHash: String? = null56    private var recoveryWordsSet: Boolean = false57    /** True while a decoy (duress) session is active — persistence targets the decoy slot. */58    private var decoyMode: Boolean = false5960    private val _isUnlocked = MutableStateFlow(false)61    val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()6263    private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())64    /** Active (non-deleted) entryList. */65    val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()6667    private val _settings = MutableStateFlow(VaultSettings())68    val settings: StateFlow<VaultSettings> = _settings.asStateFlow()6970    fun hasVault(): Boolean = store.hasVault()7172    // ---- Codex (printed paper backup) -------------------------------------7374    /**75     * The at-rest slot-A envelope as base64 JSON `{"a": <StoredVault>}` — the76     * Codex payload's vaultBlob. Slot B is noise, so it is omitted. Restorable77     * on any device that has the master password. Null when no vault exists.78     */79    fun codexVaultBlobBase64(): String? {80        val slotA = store.loadSlotA() ?: return null81        val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)}}"""82        return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))83    }8485    /**86     * Replace the local vault from a Codex blob, then unlock with [password].87     * Writes slot A (and a size-matched noise slot B) before unlocking so the88     * restored vault is at rest exactly as a freshly-created one would be.89     */90    suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {91        return try {92            val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)93            val slotJson = Regex("\"a\"\\s*:\\s*(\\{.*\\})\\s*}\\s*$").find(wrapperJson)?.groupValues?.get(1)94                ?: return UnlockResult.Error("invalid_codex_blob")95            val slotA = VaultCodec.decodeSlot(slotJson) ?: return UnlockResult.Error("invalid_codex_blob")96            if (!store.writeSlotA(slotA)) return UnlockResult.Error("storage_write_failed")97            writeMatchingNoiseSlotB(slotA)98            store.stampLocalMutation()99            unlockLocked(password)100        } catch (e: Exception) {101            UnlockResult.Error(e.message ?: "restore_failed")102        }103    }104105    suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {106        return try {107            val salt = VaultCrypto.generateSalt()108            val key = VaultCrypto.deriveKey(password, salt)109            entryList = mutableListOf()110            duressConfigured = false111            recoveryWordHash = null112            recoveryWordsSet = false113            decoyMode = false114            rootKey = generateRecoverableRootKey()115            val slotA = sealSlotA(key, salt)116            if (!store.writeSlotA(slotA)) return CreateVaultResult.Error("storage_write_failed")117            writeMatchingNoiseSlotB(slotA)118            store.stampLocalMutation()119            store.writeSettings(_settings.value)120            derivedKey = key121            publish()122            _isUnlocked.value = true123            CreateVaultResult.Success124        } catch (e: Exception) {125            CreateVaultResult.Error(e.message ?: "create_failed")126        }127    }128129    suspend fun unlock(password: String): UnlockResult = mutex.withLock { unlockLocked(password) }130131    /** Unlock body without acquiring the mutex — callers must already hold it. */132    private fun unlockLocked(password: String): UnlockResult {133        val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")134        val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))135        val payload = try {136            VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))137        } catch (_: Exception) {138            VaultCrypto.zero(key)139            return UnlockResult.WrongPassword140        }141        return adoptSlotA(key, payload)142    }143144    /** Adopt a derived slot-A [key]/[payload] as the live (real-vault) session. */145    private fun adoptSlotA(key: ByteArray, payload: VaultPayload): UnlockResult {146        return try {147            derivedKey = key148            decoyMode = false149            entryList = payload.entries.toMutableList()150            duressConfigured = payload.duressConfigured151            recoveryWordHash = payload.recoveryWordHash152            recoveryWordsSet = payload.recoveryWordsSet153            _settings.value = store.loadSettings()154            ensureRootKey(payload)155            autoPurgeExpiredTrash()156            publish()157            _isUnlocked.value = true158            UnlockResult.Success159        } catch (e: Exception) {160            UnlockResult.Error(e.message ?: "unlock_failed")161        }162    }163164    // ---- Constant-time unlock (MF-5) --------------------------------------165166    /**167     * A slot-A unlock that has been derived but not yet adopted. Holds the live168     * Argon2id key and decoded payload so the caller can derive several candidates169     * concurrently and commit only the winner. The key is owned by this token until170     * [commitSlotAUnlock] adopts it or [discardSlotAUnlock] zeroes it.171     */172    class SlotAUnlock internal constructor(173        internal val key: ByteArray,174        internal val payload: VaultPayload,175    )176177    /**178     * Derive the slot-A key and decrypt its payload WITHOUT mutating session state.179     * Pure computation (no mutex), so it can run concurrently with other candidate180     * derivations before the caller decides which to commit (MF-5). Returns null on181     * no-vault or wrong password (the derived key is zeroed on a tag mismatch).182     */183    fun tryUnlockSlotA(password: String): SlotAUnlock? {184        val slotA = store.loadSlotA() ?: return null185        val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))186        return try {187            val payload = VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))188            SlotAUnlock(key, payload)189        } catch (_: Exception) {190            VaultCrypto.zero(key)191            null192        }193    }194195    /** Adopt a previously-derived [SlotAUnlock] as the live session. */196    suspend fun commitSlotAUnlock(unlock: SlotAUnlock): UnlockResult = mutex.withLock {197        adoptSlotA(unlock.key, unlock.payload)198    }199200    /** Zero a derived [SlotAUnlock] that will not be adopted. */201    fun discardSlotAUnlock(unlock: SlotAUnlock) = VaultCrypto.zero(unlock.key)202203    // ---- Duress slot B (MF-6) ---------------------------------------------204205    /**206     * A duress-slot (slot B) unlock derived but not yet adopted. Holds the live key207     * and decoded decoy payload so it can be derived concurrently with slot A and208     * only committed if the duress passphrase was the one entered (MF-5/MF-6).209     */210    class DuressUnlock internal constructor(211        internal val key: ByteArray,212        internal val payload: VaultPayload,213    )214215    /**216     * Try to decrypt the duress slot (slot B) with [password] WITHOUT mutating the217     * session. Success means the entered password is the duress passphrase that keys218     * slot B — indistinguishable from the real slot A at the lock screen. Pure219     * computation (no mutex), safe to run concurrently with [tryUnlockSlotA].220     * Returns null when no duress slot exists or the password is not the duress one.221     */222    fun tryUnlockDuress(password: String): DuressUnlock? {223        val slot = store.loadDecoySlot() ?: return null224        val key = VaultCrypto.deriveKey(password, unb64(slot.salt))225        return try {226            val payload = VaultCodec.decode(VaultCrypto.decrypt(unb64(slot.blob), key, VaultCrypto.AAD_SLOT_A))227            DuressUnlock(key, payload)228        } catch (_: Exception) {229            VaultCrypto.zero(key)230            null231        }232    }233234    /** Adopt a derived [DuressUnlock] as a live decoy session (edits persist to slot B only). */235    suspend fun commitDuressUnlock(unlock: DuressUnlock): UnlockResult = mutex.withLock {236        return try {237            derivedKey = unlock.key238            decoyMode = true239            entryList = unlock.payload.entries.toMutableList()240            duressConfigured = false241            recoveryWordHash = unlock.payload.recoveryWordHash242            recoveryWordsSet = unlock.payload.recoveryWordsSet243            rootKey = if (unlock.payload.rootKeyB64.isNotBlank()) unb64(unlock.payload.rootKeyB64)244                      else VaultCrypto.generateRootKey()245            _settings.value = store.loadSettings()246            publish()247            _isUnlocked.value = true248            UnlockResult.Success249        } catch (e: Exception) {250            UnlockResult.Error(e.message ?: "decoy_unlock_failed")251        }252    }253254    /** Zero a derived [DuressUnlock] that will not be adopted. */255    fun discardDuressUnlock(unlock: DuressUnlock) = VaultCrypto.zero(unlock.key)256257    /**258     * Configure the duress vault (MF-6): seal a fresh, empty decoy payload under an259     * Argon2id key derived from [duressPassphrase] (fresh salt) into slot B. The260     * passphrase is never stored — only its ability to decrypt slot B proves it.261     * Requires the real vault to be unlocked and not itself a decoy session.262     */263    suspend fun setDuressPassphrase(duressPassphrase: String): Boolean = mutex.withLock {264        if (derivedKey == null || decoyMode) return false265        // Reject a duress passphrase that also opens the real vault: it would make the266        // lock screen ambiguous (both slots would decrypt for the same input).267        tryUnlockSlotA(duressPassphrase)?.let { discardSlotAUnlock(it); return false }268        return try {269            val salt = VaultCrypto.generateSalt()270            val key = VaultCrypto.deriveKey(duressPassphrase, salt)271            // An empty decoy vault with its own fresh sync root key — nothing real leaks.272            val decoyPayload = VaultPayload(entries = emptyList(), rootKeyB64 = b64(VaultCrypto.generateRootKey()))273            val plaintext = VaultCodec.encode(decoyPayload)274            val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))275            VaultCrypto.zero(key)276            VaultCrypto.zero(plaintext)277            val ok = store.writeDecoySlot(StoredVault(version = 1, salt = b64(salt), blob = blob))278            if (ok) {279                duressConfigured = true280                runCatching { persistSlotA(bumpVersion = false) }281            }282            ok283        } catch (_: Exception) {284            false285        }286    }287288    /** Tear down the duress vault: drop slot B and the duress flag on the real payload. */289    suspend fun clearDuress(): Boolean = mutex.withLock {290        store.clearDecoySlot()291        if (derivedKey != null && !decoyMode) {292            duressConfigured = false293            runCatching { persistSlotA(bumpVersion = false) }294        }295        true296    }297298    /** Unlock with an already-derived AES-256 key (biometric path). */299    suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {300        val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")301        return try {302            val payload = VaultCodec.decode(303                VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A),304            )305            derivedKey = key.copyOf()306            decoyMode = false307            entryList = payload.entries.toMutableList()308            duressConfigured = payload.duressConfigured309            recoveryWordHash = payload.recoveryWordHash310            recoveryWordsSet = payload.recoveryWordsSet311            _settings.value = store.loadSettings()312            ensureRootKey(payload)313            autoPurgeExpiredTrash()314            publish()315            _isUnlocked.value = true316            UnlockResult.Success317        } catch (_: Exception) {318            UnlockResult.WrongPassword319        }320    }321322    fun lock() {323        derivedKey?.let(VaultCrypto::zero)324        rootKey?.let(VaultCrypto::zero)325        derivedKey = null326        rootKey = null327        entryList = mutableListOf()328        duressConfigured = false329        recoveryWordHash = null330        recoveryWordsSet = false331        decoyMode = false332        _entries.value = emptyList()333        _isUnlocked.value = false334    }335336    // ---- Sync identity ----------------------------------------------------337338    /**339     * The vault's stable sync master key (a copy). Caller must zero it. Backs340     * vault_id, the Noise static key, the Ed25519 manifest key, and per-entry341     * envelope keys. Null when locked. See [VaultPayload.rootKeyB64].342     */343    fun syncMasterKey(): ByteArray? = rootKey?.copyOf()344345    /** Stable per-vault id two paired devices must share to sync. Null when locked. */346    fun syncVaultId(): String? = rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }347348    /**349     * A copy of the live Argon2id-derived vault key, for biometric escrow only350     * (wrapped under a hardware KeyStore key on biometric enable). Null when351     * locked. Caller must [VaultCrypto.zero] it after use.352     */353    fun currentVaultKey(): ByteArray? = derivedKey?.copyOf()354355    suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {356        val slotA = store.loadSlotA() ?: return false357        return try {358            val oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))359            val payload = VaultCodec.decode(360                VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A),361            )362            val newSalt = VaultCrypto.generateSalt()363            val newKey = VaultCrypto.deriveKey(newPassword, newSalt)364            // Re-seal the existing payload under the new key/salt.365            val plaintext = VaultCodec.encode(payload)366            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))367            // The escrow seals the slot-A PLAINTEXT, which a password change does not368            // alter — only the wrapping changes — so carry it forward; rebuilding the369            // StoredVault from scratch would silently drop it.370            // Carry BOTH escrows forward unchanged: each seals plaintext/root-key371            // content that a password change does not alter — only the slot-A372            // wrapping rotates. The root-key escrow staying stable across password373            // changes matches the browser (`vault.ts:363-364`).374            val next = StoredVault(375                version = slotA.version,376                salt = b64(newSalt),377                blob = blob,378                recoveryEscrow = slotA.recoveryEscrow,379                rootKeyEscrow = slotA.rootKeyEscrow,380            )381            if (!store.writeSlotA(next)) return false382            writeMatchingNoiseSlotB(next)383            store.stampLocalMutation()384            VaultCrypto.zero(oldKey)385            derivedKey?.let(VaultCrypto::zero)386            derivedKey = newKey387            true388        } catch (_: Exception) {389            false390        }391    }392393    /**394     * Irreversible wipe. Locks the session and clears every vault key. The Pro395     * license is in a separate store and is preserved by construction.396     */397    suspend fun destroyVault() = mutex.withLock {398        lock()399        store.clearVault()400        store.clearDecoySlot()401    }402403    // ---- Entry CRUD -------------------------------------------------------404405    suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {406        requireUnlocked()407        val stamp = VaultCrypto.monotonicEntryTimestamp()408        val now = System.currentTimeMillis()409        val entry = withDerivedLast4(draft.copy(410            id = draft.id.ifBlank { UUID.randomUUID().toString() },411            createdAt = if (draft.createdAt > 0) draft.createdAt else now,412            modifiedAt = stamp,413            passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,414        ))415        val rollback = entryList.toMutableList()416        entryList.add(entry)417        persistOrRollback(rollback)418        entry419    }420421    suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {422        requireUnlocked()423        val idx = entryList.indexOfFirst { it.id == patch.id }424        if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")425        val current = entryList[idx]426        val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)427        // Only refresh passwordChangedAt when the password value actually changes.428        val passwordChanged = patch.password != null && patch.password != current.password429        // Capture the outgoing password (newest first) so the user can reveal/copy/430        // restore it later. History is computed authoritatively from `current`, not431        // the patch — updateEntry is a full-entry replace, so trusting patch's value432        // would let a stale form clobber the real history. Record the age the old433        // password carried, skip an empty prior, and skip an immediate exact dupe434        // (e.g. restore-then-restore). Capped at PASSWORD_HISTORY_MAX.435        val priorPassword = current.password436        val shouldCapture = passwordChanged &&437            !priorPassword.isNullOrEmpty() &&438            current.passwordHistory?.firstOrNull()?.password != priorPassword439        val nextHistory = if (shouldCapture) {440            (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +441                (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)442        } else {443            current.passwordHistory444        }445        val updated = withDerivedLast4(patch.copy(446            createdAt = current.createdAt,447            modifiedAt = stamp,448            passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,449            passwordHistory = nextHistory,450        ))451        val rollback = entryList.toMutableList()452        entryList[idx] = updated453        persistOrRollback(rollback)454        updated455    }456457    /** Soft-delete: writes a tombstone whose timestamp beats any in-flight edit. */458    suspend fun deleteEntry(id: String) = mutex.withLock {459        requireUnlocked()460        val idx = entryList.indexOfFirst { it.id == id }461        if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")462        val current = entryList[idx]463        val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)464        val rollback = entryList.toMutableList()465        entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)466        persistOrRollback(rollback)467    }468469    suspend fun restoreEntry(id: String) = mutex.withLock {470        requireUnlocked()471        val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }472        if (idx == -1) throw IllegalStateException("deleted entry not found")473        val current = entryList[idx]474        val rollback = entryList.toMutableList()475        entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))476        persistOrRollback(rollback)477    }478479    /** Permanent delete — no tombstone, no recovery. */480    suspend fun purgeEntry(id: String) = mutex.withLock {481        requireUnlocked()482        val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }483        if (idx == -1) throw IllegalStateException("deleted entry not found")484        val rollback = entryList.toMutableList()485        entryList.removeAt(idx)486        persistOrRollback(rollback)487    }488489    /** Permanently empty the trash — hard-deletes every soft-deleted entry. */490    suspend fun purgeDeletedEntries(): Int = mutex.withLock {491        requireUnlocked()492        val rollback = entryList.toMutableList()493        val before = entryList.size494        entryList.removeAll { it.deletedAt != null }495        val removed = before - entryList.size496        if (removed > 0) persistOrRollback(rollback)497        removed498    }499500    fun getEntries(): List<VaultEntry> = entryList.filter { it.deletedAt == null }501    fun getEntry(id: String): VaultEntry? = entryList.firstOrNull { it.id == id && it.deletedAt == null }502    fun getDeletedEntries(): List<VaultEntry> =503        entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }504505    /** Active entries, optionally narrowed to those carrying [tagFilter]. */506    fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {507        val active = entryList.filter { it.deletedAt == null }508        if (tagFilter == null) return active509        val needle = tagFilter.trim().lowercase()510        return active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }511    }512513    /** Sorted, de-duplicated tags across all active entries. */514    fun getDistinctTags(): List<String> =515        entryList.asSequence()516            .filter { it.deletedAt == null }517            .flatMap { it.tags?.asSequence() ?: emptySequence() }518            .map { it.trim().lowercase() }519            .filter { it.isNotEmpty() }520            .distinct()521            .sorted()522            .toList()523524    /**525     * Distinct non-blank values for an identity field across active entries,526     * most-frequently-used first. Supports "username" and "email"; unknown field527     * names return an empty list. Values keep original casing (deduped528     * case-insensitively) so a suggestion matches what the user typed.529     */530    fun getDistinctFieldValues(field: String): List<String> {531        val select: (VaultEntry) -> String? = when (field) {532            "username" -> { e -> e.username }533            "email" -> { e -> e.email }534            else -> return emptyList()535        }536        return entryList.asSequence()537            .filter { it.deletedAt == null }538            .mapNotNull { select(it)?.trim() }539            .filter { it.isNotEmpty() }540            .groupingBy { it.lowercase() }541            .aggregate { _, acc: Pair<String, Int>?, value, _ ->542                Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)543            }544            .values545            .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })546            .map { it.first }547    }548549    fun getTombstones(): List<Tombstone> =550        entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }551    fun getVaultVersion(): Long = store.version()552553    // ---- Sync apply (does NOT advance the version) ------------------------554555    /**556     * Apply remote entryList + tombstones with per-entry last-write-wins. Persists557     * WITHOUT bumping the version counter, so a sync round cannot cascade into558     * another outbound sync. Returns the number of locally-applied changes.559     */560    suspend fun applyMergedRemoteEntries(561        remoteEntries: List<VaultEntry>,562        remoteTombstones: List<Tombstone>,563    ): Int = mutex.withLock {564        requireUnlocked()565        val tombMap = remoteTombstones.associate { it.id to it.deletedAt }566        var applied = 0567        val byId = entryList.associateBy { it.id }.toMutableMap()568569        for (remote in remoteEntries) {570            val tomb = tombMap[remote.id]571            if (tomb != null && tomb >= remote.modifiedAt) continue572            val local = byId[remote.id]573            if (local == null) {574                entryList.add(remote); byId[remote.id] = remote; applied++575            } else if (remote.modifiedAt > local.modifiedAt) {576                val i = entryList.indexOfFirst { it.id == local.id }577                if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; applied++ }578            }579        }580581        for ((id, deletedAt) in tombMap) {582            val local = byId[id] ?: continue583            if (local.deletedAt != null && local.deletedAt >= deletedAt) continue584            if (deletedAt < local.modifiedAt) continue585            val i = entryList.indexOfFirst { it.id == id }586            if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); applied++ }587        }588589        if (applied > 0) {590            persistSlotA(bumpVersion = false)591            publish()592        }593        applied594    }595596    suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {597        _settings.value = settings598        store.writeSettings(settings)599    }600601    // ---- Recovery words (vault metadata) ----------------------------------602603    /** True once the user has confirmed their recovery words for this vault. */604    fun isRecoveryWordsSet(): Boolean = recoveryWordsSet605606    /**607     * Record the BLAKE3 hash of the confirmed recovery words and mark them set.608     * Persisted without bumping the version — recovery metadata is local-only and609     * is not an entry mutation paired devices should sync against.610     */611    suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {612        requireUnlocked()613        recoveryWordHash = recoveryWordsHash(words)614        recoveryWordsSet = true615        // Seal TWO escrows (MF-1): the browser-byte-compatible root-key escrow616        // (cross-platform recovery of the sync root key) and Android's whole-payload617        // escrow (offline forgot-password restore of entries). Both derive their key618        // from the same `wordsToRootKeyMaterial` IKM but use distinct AADs.619        runCatching {620            persistSlotAWithEscrows(buildRecoveryEscrow(words), buildRootKeyEscrow(words))621        }.getOrDefault(false)622    }623624    /** Verify entered words against the stored recovery hash. */625    fun verifyRecoveryWords(words: List<String>): Boolean {626        val stored = recoveryWordHash ?: return false627        return stored == recoveryWordsHash(words)628    }629630    // ---- Recovery escrow (forgot-password) --------------------------------631632    /** True at rest if this vault has any recovery escrow the recovery flow can use. */633    fun hasRecoveryEscrow(): Boolean =634        store.loadSlotA()?.let { it.recoveryEscrow != null || it.rootKeyEscrow != null } ?: false635636    /**637     * Attempt to unlock the vault using the 12 BIP39 recovery [words] instead of638     * the master password. On success the slot-A plaintext sealed in the escrow is639     * adopted as the live session (entries, rootKey, settings), but no Argon2id640     * password key exists yet — call [resetPasswordWithRecoveryWords] next to set a641     * new password and finish unlocking. Returns false when there is no escrow, the642     * words fail the BIP39 checksum, or the words are wrong (GCM tag mismatch).643     *644     * Unlike the brief's `unlockWithRecoveryWords(): ByteArray?`, there is no645     * detached vault key to return here — slot A is wrapped under the rotating646     * Argon2id key — so this opens the escrowed payload directly.647     */648    suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {649        val slotA = store.loadSlotA() ?: return false650        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false651652        // Prefer Android's whole-payload escrow: a full offline restore of entries,653        // root key, and settings. Present for Android-created vaults.654        slotA.recoveryEscrow?.let { escrow ->655            val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return@let656            val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))657            val keyBytes = recoveryKey.encoded658            try {659                val plaintext = VaultCrypto.decrypt(unb64(escrow.blob), keyBytes, VaultCrypto.AAD_RECOVERY)660                val payload = VaultCodec.decode(plaintext)661                decoyMode = false662                entryList = payload.entries.toMutableList()663                duressConfigured = payload.duressConfigured664                recoveryWordHash = payload.recoveryWordHash665                recoveryWordsSet = payload.recoveryWordsSet666                rootKey = if (payload.rootKeyB64.isNotBlank()) unb64(payload.rootKeyB64)667                          else generateRecoverableRootKey()668                _settings.value = store.loadSettings()669                VaultCrypto.zero(plaintext)670                return true671            } catch (_: Exception) {672                // Wrong words against this escrow — fall through to the root-key escrow.673            } finally {674                VaultCrypto.zero(material)675                VaultCrypto.zero(keyBytes)676            }677        }678679        // Browser-format vault (only the root-key escrow): recover the 32-byte root680        // key (sync identity) and reset the password; entries return via sync. This681        // is exactly the browser's recovery semantics (`messages.ts:312-347`).682        slotA.rootKeyEscrow?.let { escrow ->683            val rk = unsealRootKeyEscrow(words, escrow) ?: return false684            decoyMode = false685            entryList = mutableListOf()686            duressConfigured = false687            recoveryWordHash = recoveryWordsHash(words)688            recoveryWordsSet = true689            rootKey = rk690            _settings.value = store.loadSettings()691            return true692        }693        return false694    }695696    /**697     * After [unlockWithRecoveryWords] succeeds, set a brand-new master password:698     * re-seal slot A under a fresh Argon2id key, rotate the escrow under the same699     * words, mark the session fully unlocked, and publish. Returns false if called700     * without a prior successful recovery unlock (no in-memory root key).701     *702     * Folds the brief's `resetPasswordWithRecoveryKey(vaultKey, …)` + `unlock(…)`703     * into one step, since there is no detached vault key here.704     */705    suspend fun resetPasswordWithRecoveryWords(706        words: List<String>,707        newPassword: String,708    ): Boolean = mutex.withLock {709        if (rootKey == null) return false // must have recovered first710        return try {711            val newSalt = VaultCrypto.generateSalt()712            val newKey = VaultCrypto.deriveKey(newPassword, newSalt)713            val plaintext = VaultCodec.encode(currentPayload())714            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))715            val prior = store.loadSlotA()716            // Rebuild both escrows against the recovered session so their salts rotate717            // with the password reset; fall back to the prior escrows if rebuild fails718            // (e.g. a checksum-invalid phrase). The same 12 words keep working.719            val valid = words.size == 12 && findInvalidWords(words).isEmpty()720            val freshRecovery = if (valid) buildRecoveryEscrow(words) ?: prior?.recoveryEscrow else prior?.recoveryEscrow721            val freshRootKey = if (valid) buildRootKeyEscrow(words) ?: prior?.rootKeyEscrow else prior?.rootKeyEscrow722            val next = StoredVault(723                version = prior?.version ?: 1,724                salt = b64(newSalt),725                blob = blob,726                recoveryEscrow = freshRecovery,727                rootKeyEscrow = freshRootKey,728            )729            if (!store.writeSlotA(next)) return false730            writeMatchingNoiseSlotB(next)731            store.stampLocalMutation()732            derivedKey?.let(VaultCrypto::zero)733            derivedKey = newKey734            VaultCrypto.zero(plaintext)735            publish()736            _isUnlocked.value = true737            true738        } catch (_: Exception) {739            false740        }741    }742743    /**744     * Seal the current slot-A plaintext under a key derived from the 12 BIP39745     * recovery [words] (Android offline-restore escrow). IKM is the browser's746     * `wordsToRootKeyMaterial` (MF-1), AAD is the string [VaultCrypto.AAD_RECOVERY].747     * Returns null for a checksum-invalid phrase.748     */749    private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {750        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null751        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null752        val salt = VaultCrypto.generateSalt()753        val recoveryKey = deriveRecoveryKey(material, salt)754        val keyBytes = recoveryKey.encoded755        val plaintext = VaultCodec.encode(currentPayload())756        return try {757            val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)758            RecoveryEscrow(salt = b64(salt), blob = b64(sealed))759        } finally {760            VaultCrypto.zero(material)761            VaultCrypto.zero(keyBytes)762            VaultCrypto.zero(plaintext)763        }764    }765766    /**767     * Seal ONLY the 32-byte root key under a key the recovery [words] derive,768     * byte-for-byte the browser algorithm (MF-1): plaintext = lowercase ASCII hex769     * of the root key, IKM = `wordsToRootKeyMaterial`, HKDF salt random-16,770     * info `peach-recovery-v1`, AES-256-GCM AAD = 0x01. The same 12 words unwrap771     * the same root key on the browser. Returns null with no in-memory root key or772     * a checksum-invalid phrase.773     */774    private fun buildRootKeyEscrow(words: List<String>): RootKeyEscrow? {775        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null776        val rk = rootKey ?: return null777        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null778        val salt = VaultCrypto.generateSalt()779        val recoveryKey = deriveRecoveryKey(material, salt)780        val keyBytes = recoveryKey.encoded781        val plaintext = rootKeyToHex(rk).toByteArray(Charsets.US_ASCII)782        return try {783            // combined = nonce(12) || ciphertext || tag(16)784            val combined = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)785            val nonce = combined.copyOfRange(0, VaultCrypto.NONCE_SIZE)786            val ctTag = combined.copyOfRange(VaultCrypto.NONCE_SIZE, combined.size)787            val tag = ctTag.copyOfRange(ctTag.size - 16, ctTag.size)788            val ct = ctTag.copyOfRange(0, ctTag.size - 16)789            RootKeyEscrow(salt = b64(salt), wrappedRootKey = b64(ct), nonce = b64(nonce), tag = b64(tag))790        } finally {791            VaultCrypto.zero(material)792            VaultCrypto.zero(keyBytes)793            VaultCrypto.zero(plaintext)794        }795    }796797    /** Unwrap the 32-byte root key from a browser-compatible [escrow]; null on wrong words. */798    private fun unsealRootKeyEscrow(words: List<String>, escrow: RootKeyEscrow): ByteArray? {799        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null800        val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))801        val keyBytes = recoveryKey.encoded802        return try {803            val combined = unb64(escrow.nonce) + unb64(escrow.wrappedRootKey) + unb64(escrow.tag)804            val pt = VaultCrypto.decrypt(combined, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)805            hexToRootKey(String(pt, Charsets.US_ASCII))806        } catch (_: Exception) {807            null808        } finally {809            VaultCrypto.zero(material)810            VaultCrypto.zero(keyBytes)811        }812    }813814    /**815     * Re-seal slot A from the current in-memory state under the live key, carrying816     * both [recoveryEscrow] and [rootKeyEscrow] onto the written record. Never runs817     * in decoy mode (recovery is never offered for the decoy) and persists without818     * a version bump, like the recovery-words metadata write it replaces.819     */820    private fun persistSlotAWithEscrows(821        recoveryEscrow: RecoveryEscrow?,822        rootKeyEscrow: RootKeyEscrow?,823    ): Boolean {824        val key = derivedKey ?: throw IllegalStateException("vault_locked")825        if (decoyMode) return false826        val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")827        val plaintext = VaultCodec.encode(currentPayload())828        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))829        val next = prior.copy(830            blob = blob,831            recoveryEscrow = recoveryEscrow ?: prior.recoveryEscrow,832            rootKeyEscrow = rootKeyEscrow ?: prior.rootKeyEscrow,833        )834        if (!store.writeSlotA(next)) return false835        try {836            writeMatchingNoiseSlotB(next)837        } catch (e: Exception) {838            store.writeSlotA(prior)839            throw e840        }841        return true842    }843844    // ---- Internals --------------------------------------------------------845846    private fun requireUnlocked() {847        if (derivedKey == null) throw IllegalStateException("vault_locked")848    }849850    /**851     * Keep [VaultEntry.last4] in sync with the card number for card entries (MF-3),852     * so it is stored explicitly and survives the sync wire format rather than being853     * re-derived at render time. Non-card entries pass through unchanged.854     */855    private fun withDerivedLast4(entry: VaultEntry): VaultEntry {856        if (!entry.isCard()) return entry857        val digits = entry.cardNumber?.filter { it.isDigit() } ?: ""858        return entry.copy(last4 = if (digits.length >= 4) digits.takeLast(4) else null)859    }860861    /**862     * On unlock, hard-delete trashed entries older than the retention window.863     * A null or non-positive [VaultSettings.trashRetentionDays] means "never"864     * (the app's "Never" option), so nothing is purged. Persists without a865     * version bump and without touching the publish state (caller publishes).866     */867    private fun autoPurgeExpiredTrash() {868        val days = _settings.value.trashRetentionDays ?: return869        if (days <= 0) return870        val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L871        val before = entryList.size872        entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }873        if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }874    }875876    /** The slot-A plaintext envelope for the current in-memory session. */877    private fun currentPayload(): VaultPayload =878        VaultPayload(879            entries = entryList.toList(),880            duressConfigured = duressConfigured,881            rootKeyB64 = rootKey?.let(::b64) ?: "",882            recoveryWordHash = recoveryWordHash,883            recoveryWordsSet = recoveryWordsSet,884        )885886    /**887     * Adopt the payload's root key, lazily minting one for legacy payloads.888     * A freshly-minted key is persisted WITHOUT bumping the version — adopting889     * a root key is not a mutation paired devices should sync against.890     */891    private fun ensureRootKey(payload: VaultPayload) {892        if (payload.rootKeyB64.isNotBlank()) {893            rootKey = unb64(payload.rootKeyB64)894            return895        }896        rootKey = generateRecoverableRootKey()897        runCatching { persistSlotA(bumpVersion = false) }898    }899900    private fun publish() {901        _entries.value = entryList.filter { it.deletedAt == null }902    }903904    private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {905        val plaintext = VaultCodec.encode(currentPayload())906        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))907        return StoredVault(version = 1, salt = b64(salt), blob = blob)908    }909910    private fun writeMatchingNoiseSlotB(slotA: StoredVault) {911        // Size the noise so its base64 length matches slot A's blob (MN-1): with the912        // plaintext now bucket-padded, an at-rest observer sees two equal-length slots913        // and cannot pick the real one by size. b64(N bytes) ≈ N*4/3 chars.914        val approxBytes = (slotA.blob.length * 3 / 4).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)915        val noise = ByteArray(approxBytes).also(rng::nextBytes)916        store.writeSlotB(b64(noise))917    }918919    /** Re-seal slot A from the current in-memory state under the live key. */920    private fun persistSlotA(bumpVersion: Boolean): Boolean {921        val key = derivedKey ?: throw IllegalStateException("vault_locked")922        // Decoy sessions persist to the decoy slot only — never touch the real slot A.923        if (decoyMode) {924            val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")925            val plaintext = VaultCodec.encode(currentPayload())926            val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))927            return store.writeDecoySlot(prior.copy(blob = blob))928        }929        val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")930        val plaintext = VaultCodec.encode(currentPayload())931        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))932        val next = prior.copy(blob = blob)933        if (!store.writeSlotA(next)) return false934        // Slot A committed — keep slot B size-matched, then advance the version935        // for local writes only. Restore slot A if a later step fails.936        try {937            writeMatchingNoiseSlotB(next)938            if (bumpVersion) store.stampLocalMutation()939        } catch (e: Exception) {940            store.writeSlotA(prior)941            throw e942        }943        return true944    }945946    /** Persist a local mutation, rolling the in-memory list back on failure. */947    private fun persistOrRollback(rollback: MutableList<VaultEntry>) {948        try {949            if (!persistSlotA(bumpVersion = true)) {950                entryList = rollback951                throw IllegalStateException("storage_write_failed")952            }953        } catch (e: Exception) {954            entryList = rollback955            throw e956        }957        publish()958    }959}