VaultRepository.kt

54.7 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.text.Normalizer10import java.util.Base6411import java.util.UUID12import javax.inject.Inject13import javax.inject.Singleton1415private fun b64(bytes: ByteArray): String = Base64.getEncoder().withoutPadding().encodeToString(bytes)16private fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s)1718/** Cap on retained past passwords per entry. Mirrors the browser PASSWORD_HISTORY_MAX. */19private const val PASSWORD_HISTORY_MAX = 5020private const val VAULT_HISTORY_MAX = 52122sealed interface UnlockResult {23    data object Success : UnlockResult24    data object WrongPassword : UnlockResult25    data class Error(val reason: String) : UnlockResult26}2728sealed interface CreateVaultResult {29    data object Success : CreateVaultResult30    data class Error(val reason: String) : CreateVaultResult31}3233sealed interface AdoptVaultResult {34    data class Success(val vaultId: String) : AdoptVaultResult35    data class Error(val reason: String) : AdoptVaultResult36}3738/**39 * In-memory vault session backed by [VaultStore]. Faithful port of the browser40 * `vault.ts` semantics that matter for correctness:41 *42 *  - Two-slot at rest: slot A is the real (encrypted) vault, slot B a size-matched43 *    noise blob so a fresh install shows two similarly-shaped records.44 *  - Every modifiedAt/deletedAt uses [VaultCrypto.monotonicEntryTimestamp] so a45 *    deletion always wins last-write-wins against an in-flight edit.46 *  - Local writes bump the version counter; sync-applied writes do NOT (so a47 *    sync round never cascades into another outbound sync).48 *  - add/update/delete roll back in-memory state if the disk write fails.49 *  - destroyVault never touches the Pro license (separate store).50 */51@Singleton52class VaultRepository @Inject constructor(53    private val store: VaultStorage,54) {55    private val mutex = Mutex()56    private val rng = SecureRandom()5758    private var derivedKey: ByteArray? = null59    private var rootKey: ByteArray? = null60    private var entryList: MutableList<VaultEntry> = mutableListOf()61    private var duressConfigured: Boolean = false62    private var recoveryWordHash: String? = null63    private var recoveryWordsSet: Boolean = false64    /** True while a decoy (duress) session is active — persistence targets the decoy slot. */65    private var decoyMode: Boolean = false6667    private val _isUnlocked = MutableStateFlow(false)68    val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()6970    private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())71    /** Active (non-deleted) entryList. */72    val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()7374    private val _settings = MutableStateFlow(VaultSettings())75    val settings: StateFlow<VaultSettings> = _settings.asStateFlow()7677    fun hasVault(): Boolean = store.hasVault()7879    // ---- Codex (printed paper backup) -------------------------------------8081    /**82     * The at-rest slot-A envelope as base64 JSON `{"a": <StoredVault>}` — the83     * Codex payload's vaultBlob. Slot B is noise, so it is omitted. Restorable84     * on any device that has the master password. Null when no vault exists.85     */86    fun codexVaultBlobBase64(): String? {87        val slotA = store.loadSlotA() ?: return null88        val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)}}"""89        return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))90    }9192    /**93     * Replace the local vault from a Codex blob, then unlock with [password].94     * Writes slot A (and a size-matched noise slot B) before unlocking so the95     * restored vault is at rest exactly as a freshly-created one would be.96     */97    suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {98        return try {99            val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)100            val slotJson = Regex("\"a\"\\s*:\\s*(\\{.*\\})\\s*}\\s*$").find(wrapperJson)?.groupValues?.get(1)101                ?: return UnlockResult.Error("invalid_codex_blob")102            val slotA = VaultCodec.decodeSlot(slotJson) ?: return UnlockResult.Error("invalid_codex_blob")103            if (!store.writeSlotA(slotA)) return UnlockResult.Error("storage_write_failed")104            writeMatchingNoiseSlotB(slotA)105            store.stampLocalMutation()106            unlockLocked(password)107        } catch (e: Exception) {108            UnlockResult.Error(e.message ?: "restore_failed")109        }110    }111112    suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {113        return try {114            val salt = VaultCrypto.generateSalt()115            val key = VaultCrypto.deriveKey(password, salt)116            entryList = mutableListOf()117            duressConfigured = false118            recoveryWordHash = null119            recoveryWordsSet = false120            decoyMode = false121            rootKey = generateRecoverableRootKey()122            val slotA = sealSlotA(key, salt)123            if (!store.writeSlotA(slotA)) return CreateVaultResult.Error("storage_write_failed")124            writeMatchingNoiseSlotB(slotA)125            store.stampLocalMutation()126            store.writeSettings(_settings.value)127            derivedKey = key128            publish()129            _isUnlocked.value = true130            CreateVaultResult.Success131        } catch (e: Exception) {132            CreateVaultResult.Error(e.message ?: "create_failed")133        }134    }135136    suspend fun createVaultFromRootKey(password: String, rootKeyHex: String): AdoptVaultResult = mutex.withLock {137        if (password.isEmpty()) return AdoptVaultResult.Error("ADOPT_INVALID_PASSWORD")138        if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {139            return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars")140        }141        var adoptedRootKey: ByteArray? = null142        var nextDerivedKey: ByteArray? = null143        var sessionRootKey: ByteArray? = null144        return try {145            adoptedRootKey = hexToRootKey(rootKeyHex)146            if (adoptedRootKey.size != VaultCrypto.KEY_SIZE) {147                return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes")148            }149            val vaultId = com.peachpasswords.sync.computeVaultId(adoptedRootKey)150            val salt = VaultCrypto.generateSalt()151            nextDerivedKey = VaultCrypto.deriveKey(password, salt)152            sessionRootKey = adoptedRootKey.copyOf()153            val payload = VaultPayload(154                entries = emptyList(),155                duressConfigured = false,156                rootKeyB64 = b64(sessionRootKey),157                recoveryWordHash = null,158                recoveryWordsSet = false,159            )160            val blob = b64(VaultCrypto.encrypt(VaultCodec.encode(payload), nextDerivedKey, VaultCrypto.AAD_SLOT_A))161            val slotA = StoredVault(version = 1, salt = b64(salt), blob = blob)162            if (!store.writeSlotA(slotA)) return AdoptVaultResult.Error("storage_write_failed")163            writeMatchingNoiseSlotB(slotA)164            store.stampLocalMutation()165            store.writeSettings(_settings.value)166167            val previousDerivedKey = derivedKey168            val previousRootKey = rootKey169            derivedKey = nextDerivedKey170            rootKey = sessionRootKey171            nextDerivedKey = null172            sessionRootKey = null173            entryList = mutableListOf()174            duressConfigured = false175            recoveryWordHash = null176            recoveryWordsSet = false177            decoyMode = false178            publish()179            _isUnlocked.value = true180            previousDerivedKey?.let(VaultCrypto::zero)181            previousRootKey?.let(VaultCrypto::zero)182            AdoptVaultResult.Success(vaultId)183        } catch (e: Exception) {184            AdoptVaultResult.Error(e.message ?: "adoption_create_failed")185        } finally {186            adoptedRootKey?.let(VaultCrypto::zero)187            nextDerivedKey?.let(VaultCrypto::zero)188            sessionRootKey?.let(VaultCrypto::zero)189        }190    }191192    suspend fun unlock(password: String): UnlockResult = mutex.withLock { unlockLocked(password) }193194    /** Unlock body without acquiring the mutex — callers must already hold it. */195    private fun unlockLocked(password: String): UnlockResult {196        val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")197        val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))198        val payload = try {199            VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))200        } catch (_: Exception) {201            VaultCrypto.zero(key)202            // LV-1: a vault sealed before NFC normalization with a non-NFC203            // password derives a different key now. If the supplied password is204            // not already in NFC form, retry with the raw (un-normalized) bytes.205            if (password != Normalizer.normalize(password, Normalizer.Form.NFC)) {206                val legacy = tryLegacyRawUnlock(password, slotA)207                if (legacy != null) return legacy208            }209            return UnlockResult.WrongPassword210        }211        return adoptSlotA(key, payload)212    }213214    /**215     * LV-1 legacy fallback: unlock a slot-A vault that was sealed under the raw216     * (un-normalized) password bytes. On success the slot is HEALED — re-sealed217     * under the NFC-normalized key — so every future unlock takes the normal218     * path. Returns null when the raw key also fails (genuinely wrong password).219     */220    private fun tryLegacyRawUnlock(password: String, slotA: StoredVault): UnlockResult? {221        val rawKey = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))222        val payload = try {223            VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), rawKey, VaultCrypto.AAD_SLOT_A))224        } catch (_: Exception) {225            VaultCrypto.zero(rawKey)226            return null227        }228        // Heal: re-seal slot A under the NFC key (mirrors changePassword's229        // re-seal). Escrows carry forward unchanged — only the wrapping rotates.230        val newSalt = VaultCrypto.generateSalt()231        val newKey = VaultCrypto.deriveKey(password, newSalt)232        val healed = try {233            val blob = b64(VaultCrypto.encrypt(VaultCodec.encode(payload), newKey, VaultCrypto.AAD_SLOT_A))234            val next = StoredVault(235                version = slotA.version,236                salt = b64(newSalt),237                blob = blob,238                recoveryEscrow = slotA.recoveryEscrow,239                rootKeyEscrow = slotA.rootKeyEscrow,240            )241            if (store.writeSlotA(next)) {242                writeMatchingNoiseSlotB(next)243                store.stampLocalMutation()244                true245            } else {246                false247            }248        } catch (_: Exception) {249            false250        }251        return if (healed) {252            VaultCrypto.zero(rawKey)253            adoptSlotA(newKey, payload) // session key now matches the re-sealed slot254        } else {255            VaultCrypto.zero(newKey)256            adoptSlotA(rawKey, payload) // heal failed — keep using the raw key257        }258    }259260    /** Adopt a derived slot-A [key]/[payload] as the live (real-vault) session. */261    private fun adoptSlotA(key: ByteArray, payload: VaultPayload): UnlockResult {262        return try {263            derivedKey = key264            decoyMode = false265            entryList = payload.entries.toMutableList()266            duressConfigured = payload.duressConfigured267            recoveryWordHash = payload.recoveryWordHash268            recoveryWordsSet = payload.recoveryWordsSet269            _settings.value = store.loadSettings()270            ensureRootKey(payload)271            autoPurgeExpiredTrash()272            publish()273            _isUnlocked.value = true274            UnlockResult.Success275        } catch (e: Exception) {276            UnlockResult.Error(e.message ?: "unlock_failed")277        }278    }279280    // ---- Constant-time unlock (MF-5) --------------------------------------281282    /**283     * A slot-A unlock that has been derived but not yet adopted. Holds the live284     * Argon2id key and decoded payload so the caller can derive several candidates285     * concurrently and commit only the winner. The key is owned by this token until286     * [commitSlotAUnlock] adopts it or [discardSlotAUnlock] zeroes it.287     */288    class SlotAUnlock internal constructor(289        internal val key: ByteArray,290        internal val payload: VaultPayload,291    )292293    /**294     * Derive the slot-A key and decrypt its payload WITHOUT mutating session state.295     * Pure computation (no mutex), so it can run concurrently with other candidate296     * derivations before the caller decides which to commit (MF-5). Returns null on297     * no-vault or wrong password (the derived key is zeroed on a tag mismatch).298     */299    fun tryUnlockSlotA(password: String): SlotAUnlock? {300        val slotA = store.loadSlotA() ?: return null301        val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))302        return try {303            val payload = VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))304            SlotAUnlock(key, payload)305        } catch (_: Exception) {306            VaultCrypto.zero(key)307            null308        }309    }310311    /** Adopt a previously-derived [SlotAUnlock] as the live session. */312    suspend fun commitSlotAUnlock(unlock: SlotAUnlock): UnlockResult = mutex.withLock {313        adoptSlotA(unlock.key, unlock.payload)314    }315316    /** Zero a derived [SlotAUnlock] that will not be adopted. */317    fun discardSlotAUnlock(unlock: SlotAUnlock) = VaultCrypto.zero(unlock.key)318319    // ---- Duress slot B (MF-6) ---------------------------------------------320321    /**322     * A duress-slot (slot B) unlock derived but not yet adopted. Holds the live key323     * and decoded decoy payload so it can be derived concurrently with slot A and324     * only committed if the duress passphrase was the one entered (MF-5/MF-6).325     */326    class DuressUnlock internal constructor(327        internal val key: ByteArray,328        internal val payload: VaultPayload,329    )330331    /**332     * Try to decrypt the duress slot (slot B) with [password] WITHOUT mutating the333     * session. Success means the entered password is the duress passphrase that keys334     * slot B — indistinguishable from the real slot A at the lock screen. Pure335     * computation (no mutex), safe to run concurrently with [tryUnlockSlotA].336     * Returns null when no duress slot exists or the password is not the duress one.337     */338    fun tryUnlockDuress(password: String): DuressUnlock? {339        val slot = store.loadDecoySlot() ?: return null340        val key = VaultCrypto.deriveKey(password, unb64(slot.salt))341        return try {342            val payload = VaultCodec.decode(VaultCrypto.decrypt(unb64(slot.blob), key, VaultCrypto.AAD_SLOT_A))343            DuressUnlock(key, payload)344        } catch (_: Exception) {345            VaultCrypto.zero(key)346            null347        }348    }349350    /** Adopt a derived [DuressUnlock] as a live decoy session (edits persist to slot B only). */351    suspend fun commitDuressUnlock(unlock: DuressUnlock): UnlockResult = mutex.withLock {352        return try {353            derivedKey = unlock.key354            decoyMode = true355            entryList = unlock.payload.entries.toMutableList()356            duressConfigured = false357            recoveryWordHash = unlock.payload.recoveryWordHash358            recoveryWordsSet = unlock.payload.recoveryWordsSet359            rootKey = if (unlock.payload.rootKeyB64.isNotBlank()) unb64(unlock.payload.rootKeyB64)360                      else VaultCrypto.generateRootKey()361            _settings.value = store.loadSettings()362            publish()363            _isUnlocked.value = true364            UnlockResult.Success365        } catch (e: Exception) {366            UnlockResult.Error(e.message ?: "decoy_unlock_failed")367        }368    }369370    /** Zero a derived [DuressUnlock] that will not be adopted. */371    fun discardDuressUnlock(unlock: DuressUnlock) = VaultCrypto.zero(unlock.key)372373    /**374     * Configure the duress vault (MF-6): seal a fresh, empty decoy payload under an375     * Argon2id key derived from [duressPassphrase] (fresh salt) into slot B. The376     * passphrase is never stored — only its ability to decrypt slot B proves it.377     * Requires the real vault to be unlocked and not itself a decoy session.378     */379    suspend fun setDuressPassphrase(duressPassphrase: String): Boolean = mutex.withLock {380        if (derivedKey == null || decoyMode) return false381        // Reject a duress passphrase that also opens the real vault: it would make the382        // lock screen ambiguous (both slots would decrypt for the same input).383        tryUnlockSlotA(duressPassphrase)?.let { discardSlotAUnlock(it); return false }384        return try {385            val salt = VaultCrypto.generateSalt()386            val key = VaultCrypto.deriveKey(duressPassphrase, salt)387            // An empty decoy vault with its own fresh sync root key — nothing real leaks.388            val decoyPayload = VaultPayload(entries = emptyList(), rootKeyB64 = b64(VaultCrypto.generateRootKey()))389            val plaintext = VaultCodec.encode(decoyPayload)390            val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))391            VaultCrypto.zero(key)392            VaultCrypto.zero(plaintext)393            val ok = store.writeDecoySlot(StoredVault(version = 1, salt = b64(salt), blob = blob))394            if (ok) {395                duressConfigured = true396                runCatching { persistSlotA(bumpVersion = false) }397            }398            ok399        } catch (_: Exception) {400            false401        }402    }403404    /** Tear down the duress vault: drop slot B and the duress flag on the real payload. */405    suspend fun clearDuress(): Boolean = mutex.withLock {406        store.clearDecoySlot()407        if (derivedKey != null && !decoyMode) {408            duressConfigured = false409            runCatching { persistSlotA(bumpVersion = false) }410        }411        true412    }413414    /** Unlock with an already-derived AES-256 key (biometric path). */415    suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {416        val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")417        return try {418            val payload = VaultCodec.decode(419                VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A),420            )421            derivedKey = key.copyOf()422            decoyMode = false423            entryList = payload.entries.toMutableList()424            duressConfigured = payload.duressConfigured425            recoveryWordHash = payload.recoveryWordHash426            recoveryWordsSet = payload.recoveryWordsSet427            _settings.value = store.loadSettings()428            ensureRootKey(payload)429            autoPurgeExpiredTrash()430            publish()431            _isUnlocked.value = true432            UnlockResult.Success433        } catch (_: Exception) {434            UnlockResult.WrongPassword435        }436    }437438    fun lock() {439        derivedKey?.let(VaultCrypto::zero)440        rootKey?.let(VaultCrypto::zero)441        derivedKey = null442        rootKey = null443        entryList = mutableListOf()444        duressConfigured = false445        recoveryWordHash = null446        recoveryWordsSet = false447        decoyMode = false448        _entries.value = emptyList()449        _isUnlocked.value = false450    }451452    // ---- Sync identity ----------------------------------------------------453454    /**455     * The vault's stable sync master key (a copy). Caller must zero it. Backs456     * vault_id, the Noise static key, the Ed25519 manifest key, and per-entry457     * envelope keys. Null when locked. See [VaultPayload.rootKeyB64].458     */459    fun syncMasterKey(): ByteArray? = rootKey?.copyOf()460461    /** Stable per-vault id two paired devices must share to sync. Null when locked. */462    fun syncVaultId(): String? = rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }463464    /**465     * Browser parity (MV-8): rotate the sync identity by replacing the stable466     * root key. Entries remain under the master-password key, while sync467     * credentials, vault_id, and recovery words all change.468     */469    suspend fun rotateSyncIdentity(): Boolean = mutex.withLock {470        val key = derivedKey ?: return false471        if (decoyMode) return false472        val priorSlot = store.loadSlotA() ?: return false473        val priorRootKey = rootKey ?: return false474        val priorRecoveryHash = recoveryWordHash475        val priorRecoverySet = recoveryWordsSet476        val nextRootKey = generateRecoverableRootKey()477        val nextWords = rootKeyToWords(nextRootKey)478479        try {480            takeVaultSnapshot("local_save")481            rootKey = nextRootKey482            recoveryWordHash = recoveryWordsHash(nextWords)483            recoveryWordsSet = false484485            val nextRecoveryEscrow = buildRecoveryEscrow(nextWords)486                ?: throw IllegalStateException("recovery_escrow_failed")487            val nextRootKeyEscrow = buildRootKeyEscrow(nextWords)488                ?: throw IllegalStateException("root_escrow_failed")489            val plaintext = VaultCodec.encode(currentPayload())490            val blob = try {491                b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))492            } finally {493                VaultCrypto.zero(plaintext)494            }495            val nextSlot = priorSlot.copy(496                blob = blob,497                recoveryEscrow = nextRecoveryEscrow,498                rootKeyEscrow = nextRootKeyEscrow,499            )500            if (!store.writeSlotA(nextSlot)) throw IllegalStateException("storage_write_failed")501            try {502                writeMatchingNoiseSlotB(nextSlot)503                store.stampLocalMutation()504            } catch (e: Exception) {505                store.writeSlotA(priorSlot)506                throw e507            }508            VaultCrypto.zero(priorRootKey)509            publish()510            true511        } catch (_: Exception) {512            rootKey = priorRootKey513            recoveryWordHash = priorRecoveryHash514            recoveryWordsSet = priorRecoverySet515            VaultCrypto.zero(nextRootKey)516            store.writeSlotA(priorSlot)517            false518        }519    }520521    /**522     * A copy of the live Argon2id-derived vault key, for biometric escrow only523     * (wrapped under a hardware KeyStore key on biometric enable). Null when524     * locked. Caller must [VaultCrypto.zero] it after use.525     */526    fun currentVaultKey(): ByteArray? = derivedKey?.copyOf()527528    suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {529        val slotA = store.loadSlotA() ?: return false530        return try {531            val oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))532            val payload = VaultCodec.decode(533                VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A),534            )535            val newSalt = VaultCrypto.generateSalt()536            val newKey = VaultCrypto.deriveKey(newPassword, newSalt)537            // Re-seal the existing payload under the new key/salt.538            val plaintext = VaultCodec.encode(payload)539            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))540            // The escrow seals the slot-A PLAINTEXT, which a password change does not541            // alter — only the wrapping changes — so carry it forward; rebuilding the542            // StoredVault from scratch would silently drop it.543            // Carry BOTH escrows forward unchanged: each seals plaintext/root-key544            // content that a password change does not alter — only the slot-A545            // wrapping rotates. The root-key escrow staying stable across password546            // changes matches the browser (`vault.ts:363-364`).547            val next = StoredVault(548                version = slotA.version,549                salt = b64(newSalt),550                blob = blob,551                recoveryEscrow = slotA.recoveryEscrow,552                rootKeyEscrow = slotA.rootKeyEscrow,553            )554            if (!store.writeSlotA(next)) return false555            writeMatchingNoiseSlotB(next)556            store.stampLocalMutation()557            VaultCrypto.zero(oldKey)558            derivedKey?.let(VaultCrypto::zero)559            derivedKey = newKey560            true561        } catch (_: Exception) {562            false563        }564    }565566    /**567     * Irreversible wipe. Locks the session and clears every vault key. The Pro568     * license is in a separate store and is preserved by construction.569     */570    suspend fun destroyVault() = mutex.withLock {571        lock()572        store.clearVault()573        store.clearDecoySlot()574    }575576    // ---- Entry CRUD -------------------------------------------------------577578    suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {579        requireUnlocked()580        val stamp = VaultCrypto.monotonicEntryTimestamp()581        val now = System.currentTimeMillis()582        val entry = withDerivedLast4(draft.copy(583            id = draft.id.ifBlank { UUID.randomUUID().toString() },584            createdAt = if (draft.createdAt > 0) draft.createdAt else now,585            modifiedAt = stamp,586            passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,587        ))588        val rollback = entryList.toMutableList()589        entryList.add(entry)590        persistOrRollback(rollback)591        entry592    }593594    suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {595        requireUnlocked()596        val idx = entryList.indexOfFirst { it.id == patch.id }597        if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")598        val current = entryList[idx]599        val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)600        // Only refresh passwordChangedAt when the password value actually changes.601        val passwordChanged = patch.password != null && patch.password != current.password602        // Capture the outgoing password (newest first) so the user can reveal/copy/603        // restore it later. History is computed authoritatively from `current`, not604        // the patch — updateEntry is a full-entry replace, so trusting patch's value605        // would let a stale form clobber the real history. Record the age the old606        // password carried, skip an empty prior, and skip an immediate exact dupe607        // (e.g. restore-then-restore). Capped at PASSWORD_HISTORY_MAX.608        val priorPassword = current.password609        val shouldCapture = passwordChanged &&610            !priorPassword.isNullOrEmpty() &&611            current.passwordHistory?.firstOrNull()?.password != priorPassword612        val nextHistory = if (shouldCapture) {613            (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +614                (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)615        } else {616            current.passwordHistory617        }618        val updated = withDerivedLast4(patch.copy(619            createdAt = current.createdAt,620            modifiedAt = stamp,621            passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,622            passwordHistory = nextHistory,623        ))624        val rollback = entryList.toMutableList()625        entryList[idx] = updated626        persistOrRollback(rollback)627        updated628    }629630    /** Soft-delete: writes a tombstone whose timestamp beats any in-flight edit. */631    suspend fun deleteEntry(id: String) = mutex.withLock {632        requireUnlocked()633        val idx = entryList.indexOfFirst { it.id == id }634        if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")635        val current = entryList[idx]636        val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)637        val rollback = entryList.toMutableList()638        entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)639        persistOrRollback(rollback)640    }641642    suspend fun restoreEntry(id: String) = mutex.withLock {643        requireUnlocked()644        val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }645        if (idx == -1) throw IllegalStateException("deleted entry not found")646        val current = entryList[idx]647        val rollback = entryList.toMutableList()648        entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))649        persistOrRollback(rollback)650    }651652    /** Permanent delete — no tombstone, no recovery. */653    suspend fun purgeEntry(id: String) = mutex.withLock {654        requireUnlocked()655        val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }656        if (idx == -1) throw IllegalStateException("deleted entry not found")657        val rollback = entryList.toMutableList()658        entryList.removeAt(idx)659        persistOrRollback(rollback)660    }661662    /** Permanently empty the trash — hard-deletes every soft-deleted entry. */663    suspend fun purgeDeletedEntries(): Int = mutex.withLock {664        requireUnlocked()665        val rollback = entryList.toMutableList()666        val before = entryList.size667        entryList.removeAll { it.deletedAt != null }668        val removed = before - entryList.size669        if (removed > 0) persistOrRollback(rollback)670        removed671    }672673    /** Browser parity: number of active entries that dedupe would move to trash. */674    suspend fun countDuplicateEntries(): Int = mutex.withLock {675        requireUnlocked()676        countDuplicateEntriesLocked()677    }678679    /**680     * Browser parity: soft-delete duplicate entries, keeping the most recently681     * modified member of each group. Refuse in decoy mode so the duress vault is682     * not reshaped into a forensically distinct state.683     */684    suspend fun deduplicateEntries(): Int = mutex.withLock {685        requireUnlocked()686        if (decoyMode) throw IllegalStateException("deduplicate disabled in decoy mode")687        val active = entryList.filter { it.deletedAt == null }688        val keepIds = mutableSetOf<String>()689        active.groupBy { it.duplicateKey() }.values.forEach { group ->690            keepIds += group.maxBy { it.modifiedAt.takeIf { ts -> ts > 0 } ?: it.createdAt }.id691        }692693        val rollback = entryList.toMutableList()694        var removed = 0695        entryList = entryList.map { entry ->696            if (entry.deletedAt == null && entry.id !in keepIds) {697                removed++698                val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)699                entry.copy(deletedAt = stamp, modifiedAt = stamp)700            } else {701                entry702            }703        }.toMutableList()704        if (removed > 0) persistOrRollback(rollback)705        removed706    }707708    fun getEntries(): List<VaultEntry> = entryList.filter { it.deletedAt == null }709    fun getEntry(id: String): VaultEntry? = entryList.firstOrNull { it.id == id && it.deletedAt == null }710    fun getDeletedEntries(): List<VaultEntry> =711        entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }712713    /** Active entries, optionally narrowed to those carrying [tagFilter]. */714    fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {715        val active = entryList.filter { it.deletedAt == null }716        if (tagFilter == null) return active717        val needle = tagFilter.trim().lowercase()718        return active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }719    }720721    /** Sorted, de-duplicated tags across all active entries. */722    fun getDistinctTags(): List<String> =723        entryList.asSequence()724            .filter { it.deletedAt == null }725            .flatMap { it.tags?.asSequence() ?: emptySequence() }726            .map { it.trim().lowercase() }727            .filter { it.isNotEmpty() }728            .distinct()729            .sorted()730            .toList()731732    /**733     * Distinct non-blank values for an identity field across active entries,734     * most-frequently-used first. Supports "username" and "email"; unknown field735     * names return an empty list. Values keep original casing (deduped736     * case-insensitively) so a suggestion matches what the user typed.737     */738    fun getDistinctFieldValues(field: String): List<String> {739        val select: (VaultEntry) -> String? = when (field) {740            "username" -> { e -> e.username }741            "email" -> { e -> e.email }742            else -> return emptyList()743        }744        return entryList.asSequence()745            .filter { it.deletedAt == null }746            .mapNotNull { select(it)?.trim() }747            .filter { it.isNotEmpty() }748            .groupingBy { it.lowercase() }749            .aggregate { _, acc: Pair<String, Int>?, value, _ ->750                Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)751            }752            .values753            .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })754            .map { it.first }755    }756757    fun getTombstones(): List<Tombstone> =758        entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }759    fun getVaultVersion(): Long = store.version()760    fun getVaultHistory(): List<VaultSnapshot> = store.loadVaultHistory().snapshots761762    suspend fun restoreVaultSnapshot(snapshotId: String): Boolean = mutex.withLock {763        val snapshot = store.loadVaultHistory().snapshots.firstOrNull { it.id == snapshotId } ?: return false764        val restoredA = VaultCodec.decodeSlot(snapshot.vault_a) ?: return false765        takeVaultSnapshot("restore")766        if (!store.writeSlotA(restoredA)) return false767        if (!store.writeSlotB(snapshot.vault_b)) return false768        store.stampLocalMutation()769        lock()770        true771    }772773    // ---- Sync apply (does NOT advance the version) ------------------------774775    /**776     * Apply remote entryList + tombstones with per-entry last-write-wins. Persists777     * WITHOUT bumping the version counter, so a sync round cannot cascade into778     * another outbound sync. Returns the number of locally-applied changes.779     */780    suspend fun applyMergedRemoteEntries(781        remoteEntries: List<VaultEntry>,782        remoteTombstones: List<Tombstone>,783    ): Int = mutex.withLock {784        requireUnlocked()785        val tombMap = remoteTombstones.associate { it.id to it.deletedAt }786        var applied = 0787        val byId = entryList.associateBy { it.id }.toMutableMap()788789        for (remote in remoteEntries) {790            val tomb = tombMap[remote.id]791            if (tomb != null && tomb >= remote.modifiedAt) continue792            val local = byId[remote.id]793            if (local == null) {794                entryList.add(remote); byId[remote.id] = remote; applied++795            } else if (remote.modifiedAt > local.modifiedAt) {796                val i = entryList.indexOfFirst { it.id == local.id }797                if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; applied++ }798            }799        }800801        for ((id, deletedAt) in tombMap) {802            val local = byId[id] ?: continue803            if (local.deletedAt != null && local.deletedAt >= deletedAt) continue804            if (deletedAt < local.modifiedAt) continue805            val i = entryList.indexOfFirst { it.id == id }806            if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); applied++ }807        }808809        if (applied > 0) {810            persistSlotA(bumpVersion = false, snapshotReason = "sync_received")811            publish()812        }813        applied814    }815816    suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {817        _settings.value = settings818        store.writeSettings(settings)819    }820821    // ---- Recovery words (vault metadata) ----------------------------------822823    /** True once the user has confirmed their recovery words for this vault. */824    fun isRecoveryWordsSet(): Boolean = recoveryWordsSet825826    /**827     * Record the BLAKE3 hash of the confirmed recovery words and mark them set.828     * Persisted without bumping the version — recovery metadata is local-only and829     * is not an entry mutation paired devices should sync against.830     */831    suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {832        requireUnlocked()833        recoveryWordHash = recoveryWordsHash(words)834        recoveryWordsSet = true835        // Seal TWO escrows (MF-1): the browser-byte-compatible root-key escrow836        // (cross-platform recovery of the sync root key) and Android's whole-payload837        // escrow (offline forgot-password restore of entries). Both derive their key838        // from the same `wordsToRootKeyMaterial` IKM but use distinct AADs.839        runCatching {840            persistSlotAWithEscrows(buildRecoveryEscrow(words), buildRootKeyEscrow(words))841        }.getOrDefault(false)842    }843844    /** Verify entered words against the stored recovery hash. */845    fun verifyRecoveryWords(words: List<String>): Boolean {846        val stored = recoveryWordHash ?: return false847        return stored == recoveryWordsHash(words)848    }849850    // ---- Recovery escrow (forgot-password) --------------------------------851852    /** True at rest if this vault has any recovery escrow the recovery flow can use. */853    fun hasRecoveryEscrow(): Boolean =854        store.loadSlotA()?.let { it.recoveryEscrow != null || it.rootKeyEscrow != null } ?: false855856    /**857     * Attempt to unlock the vault using the 12 BIP39 recovery [words] instead of858     * the master password. On success the slot-A plaintext sealed in the escrow is859     * adopted as the live session (entries, rootKey, settings), but no Argon2id860     * password key exists yet — call [resetPasswordWithRecoveryWords] next to set a861     * new password and finish unlocking. Returns false when there is no escrow, the862     * words fail the BIP39 checksum, or the words are wrong (GCM tag mismatch).863     *864     * Unlike the brief's `unlockWithRecoveryWords(): ByteArray?`, there is no865     * detached vault key to return here — slot A is wrapped under the rotating866     * Argon2id key — so this opens the escrowed payload directly.867     */868    suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {869        val slotA = store.loadSlotA() ?: return false870        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false871872        // Prefer Android's whole-payload escrow: a full offline restore of entries,873        // root key, and settings. Present for Android-created vaults.874        slotA.recoveryEscrow?.let { escrow ->875            val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return@let876            val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))877            val keyBytes = recoveryKey.encoded878            try {879                val plaintext = VaultCrypto.decrypt(unb64(escrow.blob), keyBytes, VaultCrypto.AAD_RECOVERY)880                val payload = VaultCodec.decode(plaintext)881                decoyMode = false882                entryList = payload.entries.toMutableList()883                duressConfigured = payload.duressConfigured884                recoveryWordHash = payload.recoveryWordHash885                recoveryWordsSet = payload.recoveryWordsSet886                rootKey = if (payload.rootKeyB64.isNotBlank()) unb64(payload.rootKeyB64)887                          else generateRecoverableRootKey()888                _settings.value = store.loadSettings()889                VaultCrypto.zero(plaintext)890                return true891            } catch (_: Exception) {892                // Wrong words against this escrow — fall through to the root-key escrow.893            } finally {894                VaultCrypto.zero(material)895                VaultCrypto.zero(keyBytes)896            }897        }898899        // Browser-format vault (only the root-key escrow): recover the 32-byte root900        // key (sync identity) and reset the password; entries return via sync. This901        // is exactly the browser's recovery semantics (`messages.ts:312-347`).902        slotA.rootKeyEscrow?.let { escrow ->903            val rk = unsealRootKeyEscrow(words, escrow) ?: return false904            decoyMode = false905            entryList = mutableListOf()906            duressConfigured = false907            recoveryWordHash = recoveryWordsHash(words)908            recoveryWordsSet = true909            rootKey = rk910            _settings.value = store.loadSettings()911            return true912        }913        return false914    }915916    /**917     * After [unlockWithRecoveryWords] succeeds, set a brand-new master password:918     * re-seal slot A under a fresh Argon2id key, rotate the escrow under the same919     * words, mark the session fully unlocked, and publish. Returns false if called920     * without a prior successful recovery unlock (no in-memory root key).921     *922     * Folds the brief's `resetPasswordWithRecoveryKey(vaultKey, …)` + `unlock(…)`923     * into one step, since there is no detached vault key here.924     */925    suspend fun resetPasswordWithRecoveryWords(926        words: List<String>,927        newPassword: String,928    ): Boolean = mutex.withLock {929        if (rootKey == null) return false // must have recovered first930        return try {931            val newSalt = VaultCrypto.generateSalt()932            val newKey = VaultCrypto.deriveKey(newPassword, newSalt)933            val plaintext = VaultCodec.encode(currentPayload())934            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))935            val prior = store.loadSlotA()936            // Rebuild both escrows against the recovered session so their salts rotate937            // with the password reset; fall back to the prior escrows if rebuild fails938            // (e.g. a checksum-invalid phrase). The same 12 words keep working.939            val valid = words.size == 12 && findInvalidWords(words).isEmpty()940            val freshRecovery = if (valid) buildRecoveryEscrow(words) ?: prior?.recoveryEscrow else prior?.recoveryEscrow941            val freshRootKey = if (valid) buildRootKeyEscrow(words) ?: prior?.rootKeyEscrow else prior?.rootKeyEscrow942            val next = StoredVault(943                version = prior?.version ?: 1,944                salt = b64(newSalt),945                blob = blob,946                recoveryEscrow = freshRecovery,947                rootKeyEscrow = freshRootKey,948            )949            if (!store.writeSlotA(next)) return false950            writeMatchingNoiseSlotB(next)951            store.stampLocalMutation()952            derivedKey?.let(VaultCrypto::zero)953            derivedKey = newKey954            VaultCrypto.zero(plaintext)955            publish()956            _isUnlocked.value = true957            true958        } catch (_: Exception) {959            false960        }961    }962963    /**964     * Seal the current slot-A plaintext under a key derived from the 12 BIP39965     * recovery [words] (Android offline-restore escrow). IKM is the browser's966     * `wordsToRootKeyMaterial` (MF-1), AAD is the string [VaultCrypto.AAD_RECOVERY].967     * Returns null for a checksum-invalid phrase.968     */969    private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {970        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null971        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null972        val salt = VaultCrypto.generateSalt()973        val recoveryKey = deriveRecoveryKey(material, salt)974        val keyBytes = recoveryKey.encoded975        val plaintext = VaultCodec.encode(currentPayload())976        return try {977            val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)978            RecoveryEscrow(salt = b64(salt), blob = b64(sealed))979        } finally {980            VaultCrypto.zero(material)981            VaultCrypto.zero(keyBytes)982            VaultCrypto.zero(plaintext)983        }984    }985986    /**987     * Seal ONLY the 32-byte root key under a key the recovery [words] derive,988     * byte-for-byte the browser algorithm (MF-1): plaintext = lowercase ASCII hex989     * of the root key, IKM = `wordsToRootKeyMaterial`, HKDF salt random-16,990     * info `peach-recovery-v1`, AES-256-GCM AAD = 0x01. The same 12 words unwrap991     * the same root key on the browser. Returns null with no in-memory root key or992     * a checksum-invalid phrase.993     */994    private fun buildRootKeyEscrow(words: List<String>): RootKeyEscrow? {995        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null996        val rk = rootKey ?: return null997        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null998        val salt = VaultCrypto.generateSalt()999        val recoveryKey = deriveRecoveryKey(material, salt)1000        val keyBytes = recoveryKey.encoded1001        val plaintext = rootKeyToHex(rk).toByteArray(Charsets.US_ASCII)1002        return try {1003            // combined = nonce(12) || ciphertext || tag(16)1004            val combined = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)1005            val nonce = combined.copyOfRange(0, VaultCrypto.NONCE_SIZE)1006            val ctTag = combined.copyOfRange(VaultCrypto.NONCE_SIZE, combined.size)1007            val tag = ctTag.copyOfRange(ctTag.size - 16, ctTag.size)1008            val ct = ctTag.copyOfRange(0, ctTag.size - 16)1009            RootKeyEscrow(salt = b64(salt), wrappedRootKey = b64(ct), nonce = b64(nonce), tag = b64(tag))1010        } finally {1011            VaultCrypto.zero(material)1012            VaultCrypto.zero(keyBytes)1013            VaultCrypto.zero(plaintext)1014        }1015    }10161017    /** Unwrap the 32-byte root key from a browser-compatible [escrow]; null on wrong words. */1018    private fun unsealRootKeyEscrow(words: List<String>, escrow: RootKeyEscrow): ByteArray? {1019        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null1020        val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))1021        val keyBytes = recoveryKey.encoded1022        return try {1023            val combined = unb64(escrow.nonce) + unb64(escrow.wrappedRootKey) + unb64(escrow.tag)1024            val pt = VaultCrypto.decrypt(combined, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)1025            hexToRootKey(String(pt, Charsets.US_ASCII))1026        } catch (_: Exception) {1027            null1028        } finally {1029            VaultCrypto.zero(material)1030            VaultCrypto.zero(keyBytes)1031        }1032    }10331034    /**1035     * Re-seal slot A from the current in-memory state under the live key, carrying1036     * both [recoveryEscrow] and [rootKeyEscrow] onto the written record. Never runs1037     * in decoy mode (recovery is never offered for the decoy) and persists without1038     * a version bump, like the recovery-words metadata write it replaces.1039     */1040    private fun persistSlotAWithEscrows(1041        recoveryEscrow: RecoveryEscrow?,1042        rootKeyEscrow: RootKeyEscrow?,1043    ): Boolean {1044        val key = derivedKey ?: throw IllegalStateException("vault_locked")1045        if (decoyMode) return false1046        val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")1047        val plaintext = VaultCodec.encode(currentPayload())1048        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))1049        val next = prior.copy(1050            blob = blob,1051            recoveryEscrow = recoveryEscrow ?: prior.recoveryEscrow,1052            rootKeyEscrow = rootKeyEscrow ?: prior.rootKeyEscrow,1053        )1054        if (!store.writeSlotA(next)) return false1055        try {1056            writeMatchingNoiseSlotB(next)1057        } catch (e: Exception) {1058            store.writeSlotA(prior)1059            throw e1060        }1061        return true1062    }10631064    // ---- Internals --------------------------------------------------------10651066    private fun requireUnlocked() {1067        if (derivedKey == null) throw IllegalStateException("vault_locked")1068    }10691070    private fun countDuplicateEntriesLocked(): Int {1071        val seen = mutableMapOf<String, VaultEntry>()1072        var duplicates = 01073        for (entry in entryList.filter { it.deletedAt == null }) {1074            val key = entry.duplicateKey()1075            val existing = seen[key]1076            if (existing == null) {1077                seen[key] = entry1078            } else {1079                duplicates++1080                val entryStamp = entry.modifiedAt.takeIf { it > 0 } ?: entry.createdAt1081                val existingStamp = existing.modifiedAt.takeIf { it > 0 } ?: existing.createdAt1082                if (entryStamp > existingStamp) seen[key] = entry1083            }1084        }1085        return duplicates1086    }10871088    private fun VaultEntry.duplicateKey(): String {1089        if (type == "note") return "note|${title.lowercase()}"1090        val passkeyData = passkey1091        if (passkeyData != null) {1092            return "passkey|${passkeyData.rpId.lowercase()}|${passkeyData.userName.lowercase()}"1093        }1094        return "login|${title.lowercase()}|${url.orEmpty().lowercase()}|${username.orEmpty().lowercase()}"1095    }10961097    private fun takeVaultSnapshot(reason: String) {1098        runCatching {1099            val slotA = store.loadSlotA() ?: return1100            val vaultA = VaultCodec.encodeSlot(slotA)1101            val vaultB = store.loadSlotB() ?: slotA.blob1102            val history = store.loadVaultHistory()1103            val latest = history.snapshots.firstOrNull()1104            if (latest?.vault_a == vaultA && latest.vault_b == vaultB) return1105            val entryCount = if (derivedKey != null && !decoyMode) {1106                bucketEntryCount(entryList.count { it.deletedAt == null })1107            } else {1108                null1109            }1110            val snapshot = VaultSnapshot(1111                id = UUID.randomUUID().toString(),1112                savedAt = System.currentTimeMillis(),1113                reason = reason,1114                vault_a = vaultA,1115                vault_b = vaultB,1116                entryCount = entryCount,1117            )1118            store.writeVaultHistory(1119                history.copy(snapshots = (listOf(snapshot) + history.snapshots).take(VAULT_HISTORY_MAX)),1120            )1121        }1122    }11231124    private fun bucketEntryCount(n: Int): Int = when {1125        n <= 0 -> 01126        n <= 10 -> 101127        n <= 25 -> 251128        n <= 50 -> 501129        n <= 100 -> 1001130        n <= 250 -> 2501131        n <= 500 -> 5001132        else -> ((n + 499) / 500) * 5001133    }11341135    /**1136     * Keep [VaultEntry.last4] in sync with the card number for card entries (MF-3),1137     * so it is stored explicitly and survives the sync wire format rather than being1138     * re-derived at render time. Non-card entries pass through unchanged.1139     */1140    private fun withDerivedLast4(entry: VaultEntry): VaultEntry {1141        if (!entry.isCard()) return entry1142        val digits = entry.cardNumber?.filter { it.isDigit() } ?: ""1143        return entry.copy(last4 = if (digits.length >= 4) digits.takeLast(4) else null)1144    }11451146    /**1147     * On unlock, hard-delete trashed entries older than the retention window.1148     * A null or non-positive [VaultSettings.trashRetentionDays] means "never"1149     * (the app's "Never" option), so nothing is purged. Persists without a1150     * version bump and without touching the publish state (caller publishes).1151     */1152    private fun autoPurgeExpiredTrash() {1153        val days = _settings.value.trashRetentionDays ?: return1154        if (days <= 0) return1155        val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L1156        val before = entryList.size1157        entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }1158        if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }1159    }11601161    /** The slot-A plaintext envelope for the current in-memory session. */1162    private fun currentPayload(): VaultPayload =1163        VaultPayload(1164            entries = entryList.toList(),1165            duressConfigured = duressConfigured,1166            rootKeyB64 = rootKey?.let(::b64) ?: "",1167            recoveryWordHash = recoveryWordHash,1168            recoveryWordsSet = recoveryWordsSet,1169        )11701171    /**1172     * Adopt the payload's root key, lazily minting one for legacy payloads.1173     * A freshly-minted key is persisted WITHOUT bumping the version — adopting1174     * a root key is not a mutation paired devices should sync against.1175     */1176    private fun ensureRootKey(payload: VaultPayload) {1177        if (payload.rootKeyB64.isNotBlank()) {1178            rootKey = unb64(payload.rootKeyB64)1179            return1180        }1181        rootKey = generateRecoverableRootKey()1182        runCatching { persistSlotA(bumpVersion = false) }1183    }11841185    private fun publish() {1186        _entries.value = entryList.filter { it.deletedAt == null }1187    }11881189    private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {1190        val plaintext = VaultCodec.encode(currentPayload())1191        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))1192        return StoredVault(version = 1, salt = b64(salt), blob = blob)1193    }11941195    private fun writeMatchingNoiseSlotB(slotA: StoredVault) {1196        // Size the noise so its base64 length matches slot A's blob (MN-1): with the1197        // plaintext now bucket-padded, an at-rest observer sees two equal-length slots1198        // and cannot pick the real one by size. b64(N bytes) ≈ N*4/3 chars.1199        val approxBytes = (slotA.blob.length * 3 / 4).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)1200        val noise = ByteArray(approxBytes).also(rng::nextBytes)1201        store.writeSlotB(b64(noise))1202    }12031204    /** Re-seal slot A from the current in-memory state under the live key. */1205    private fun persistSlotA(bumpVersion: Boolean, snapshotReason: String? = "local_save"): Boolean {1206        val key = derivedKey ?: throw IllegalStateException("vault_locked")1207        // Decoy sessions persist to the decoy slot only — never touch the real slot A.1208        if (decoyMode) {1209            val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")1210            val plaintext = VaultCodec.encode(currentPayload())1211            val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))1212            return store.writeDecoySlot(prior.copy(blob = blob))1213        }1214        val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")1215        if (snapshotReason != null) takeVaultSnapshot(snapshotReason)1216        val plaintext = VaultCodec.encode(currentPayload())1217        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))1218        val next = prior.copy(blob = blob)1219        if (!store.writeSlotA(next)) return false1220        // Slot A committed — keep slot B size-matched, then advance the version1221        // for local writes only. Restore slot A if a later step fails.1222        try {1223            writeMatchingNoiseSlotB(next)1224            if (bumpVersion) store.stampLocalMutation()1225        } catch (e: Exception) {1226            store.writeSlotA(prior)1227            throw e1228        }1229        return true1230    }12311232    /** Persist a local mutation, rolling the in-memory list back on failure. */1233    private fun persistOrRollback(rollback: MutableList<VaultEntry>) {1234        try {1235            if (!persistSlotA(bumpVersion = true)) {1236                entryList = rollback1237                throw IllegalStateException("storage_write_failed")1238            }1239        } catch (e: Exception) {1240            entryList = rollback1241            throw e1242        }1243        publish()1244    }1245}