VaultRepository.kt

85.4 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 kotlinx.serialization.json.Json11import android.util.Log12import com.peachpasswords.BuildConfig13import com.peachpasswords.sync.SyncLimits14import kotlinx.serialization.json.JsonElement15import kotlinx.serialization.json.JsonNull16import kotlinx.serialization.json.JsonObject17import kotlinx.serialization.json.JsonPrimitive18import java.util.Base6419import java.util.UUID20import java.util.concurrent.locks.ReentrantLock21import javax.inject.Inject22import javax.inject.Singleton2324/** Lenient parser for the Codex vault-blob wrapper only. */25private val CodexJson = Json { ignoreUnknownKeys = true; isLenient = true }2627private fun b64(bytes: ByteArray): String = Base64.getEncoder().withoutPadding().encodeToString(bytes)28private fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s)2930/** Cap on retained past passwords per entry. Mirrors the browser PASSWORD_HISTORY_MAX. */31private const val PASSWORD_HISTORY_MAX = 5032private const val VAULT_HISTORY_MAX = 53334sealed interface UnlockResult {35    data object Success : UnlockResult36    data object WrongPassword : UnlockResult37    data class Error(val reason: String) : UnlockResult38}3940sealed interface CreateVaultResult {41    data object Success : CreateVaultResult42    data class Error(val reason: String) : CreateVaultResult43}4445sealed interface AdoptVaultResult {46    data class Success(val vaultId: String) : AdoptVaultResult47    data class Error(val reason: String) : AdoptVaultResult48}4950/**51 * In-memory vault session backed by [VaultStore]. Faithful port of the browser52 * `vault.ts` semantics that matter for correctness:53 *54 *  - Two-slot at rest: slot A is the real (encrypted) vault, slot B a size-matched55 *    noise blob so a fresh install shows two similarly-shaped records.56 *  - Every modifiedAt/deletedAt uses [VaultCrypto.monotonicEntryTimestamp] so a57 *    deletion always wins last-write-wins against an in-flight edit.58 *  - Local writes bump the version counter; sync-applied writes do NOT (so a59 *    sync round never cascades into another outbound sync).60 *  - add/update/delete roll back in-memory state if the disk write fails.61 *  - destroyVault never touches the Pro license (separate store).62 */63@Singleton64class VaultRepository @Inject constructor(65    private val store: VaultStorage,66) {67    private val mutex = Mutex()68    // H-03: lock() and requireUnlocked() cannot take [mutex] from non-suspend69    // callers (ProcessLifecycleOwner, ViewModels, VaultLockTimer). This sync70    // lock guards ONLY the brief read/write of derivedKey/rootKey/entryList so71    // lock() can serialize against an in-flight suspend op without blocking on72    // Argon2id or store I/O. Suspend ops hold [mutex] for their full body and73    // take [stateLock] only around the state-write portions. Acquisition order74    // is always mutex → stateLock.75    private val stateLock = ReentrantLock()76    private val rng = SecureRandom()7778    /**79     * Run [block] with [stateLock] held. Used to fence the small state-write80     * portions of suspend operations against [lock] and [requireUnlocked]81     * racing from another thread.82     */83    private inline fun <T> mutateState(block: () -> T): T {84        stateLock.lock()85        return try { block() } finally { stateLock.unlock() }86    }8788    private var derivedKey: ByteArray? = null89    private var rootKey: ByteArray? = null90    private var entryList: MutableList<VaultEntry> = mutableListOf()91    private var duressConfigured: Boolean = false92    private var recoveryWordHash: String? = null93    private var recoveryWordsSet: Boolean = false94    /** True while a decoy (duress) session is active — persistence targets the decoy slot. */95    private var decoyMode: Boolean = false9697    private val _isUnlocked = MutableStateFlow(false)98    val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()99100    private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())101    /** Active (non-deleted) entryList. */102    val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()103104    private val _settings = MutableStateFlow(VaultSettings())105    val settings: StateFlow<VaultSettings> = _settings.asStateFlow()106107    fun hasVault(): Boolean = store.hasVault()108109    // ---- Codex (printed paper backup) -------------------------------------110111    /**112     * The at-rest slot-A envelope as base64 JSON `{"a": <StoredVault>}` — the113     * Codex payload's vaultBlob. Slot B is noise, so it is omitted. Restorable114     * on any device that has the master password. Null when no vault exists.115     */116    fun codexVaultBlobBase64(): String? {117        val slotA = store.loadSlotA() ?: return null118        val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)}}"""119        return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))120    }121122    /**123     * Replace the local vault from a Codex blob, then unlock with [password].124     * Writes slot A (and a size-matched noise slot B) before unlocking so the125     * restored vault is at rest exactly as a freshly-created one would be.126     */127    /** A slot is stored either as a JSON string (browser) or inline object (Android). */128    private fun JsonElement?.asSlotJson(): String? = when {129        this == null || this is JsonNull -> null130        this is JsonPrimitive && isString -> content131        else -> toString()132    }133134    suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {135        var candidateKey: ByteArray? = null136        var plaintext: ByteArray? = null137        return try {138            val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)139            // Parsed as JSON, not matched with a regex. The wrapper is140            // `{ "a": <slot>, "b": <slot|null> }` and the browser — which141            // generates most real Codexes — writes each slot as a JSON142            // *string*, with "b" present. A regex looking for an object143            // literal under "a" at the very end of the wrapper matches144            // neither of those, so every browser-generated Codex failed here145            // with "invalid_codex_blob" after decoding perfectly.146            val wrapper = CodexJson.parseToJsonElement(wrapperJson) as? JsonObject147                ?: return UnlockResult.Error("invalid_codex_blob")148            val slotJson = wrapper["a"].asSlotJson() ?: return UnlockResult.Error("invalid_codex_blob")149            // A Codex printed from the browser carries a browser-shaped slot,150            // which is the common case — most Codexes are printed there. It is151            // translated to Android's shape (see BrowserSlot) rather than152            // rejected. A translation failure is a wrong password, not a bad153            // blob: the codes decoded fine, the password just didn't open them.154            val slotA = VaultCodec.decodeSlot(slotJson)155                ?: BrowserSlot.parse(slotJson)?.let {156                    BrowserSlot.toAndroidSlot(it, password) ?: return UnlockResult.WrongPassword157                }158                ?: return UnlockResult.Error("invalid_codex_blob")159            // C-01: authenticate the candidate ENTIRELY in memory before touching160            // storage. VaultCodec.decodeSlot is structural — an Android-shaped161            // Codex parses under ANY password — so writing slot A first and162            // unlocking afterwards destroyed the device's existing vault every163            // time the user mistyped the password.164            candidateKey = VaultCrypto.deriveKey(password, unb64(slotA.salt))165            plaintext = decryptSlotABlob(slotA, candidateKey)166            // LV-1: a Codex printed from a vault sealed before NFC normalization167            // opens only under the raw password bytes. unlockLocked used to supply168            // this fallback; authenticating up front here has to keep it, or those169            // Codexes become unrestorable.170            if (plaintext == null && password != Normalizer.normalize(password, Normalizer.Form.NFC)) {171                VaultCrypto.zero(candidateKey)172                candidateKey = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))173                plaintext = decryptSlotABlob(slotA, candidateKey)174            }175            if (plaintext == null) return UnlockResult.WrongPassword176            val payload = try {177                VaultCodec.decode(plaintext)178            } catch (_: Exception) {179                return UnlockResult.Error("invalid_codex_blob")180            }181182            val priorA = store.loadSlotA()183            val priorB = store.loadSlotB()184            // Carry the real slot B across when the Codex has one — it holds a185            // duress vault, which noise would silently destroy.186            val codexSlotB = wrapper["b"].asSlotJson()187188            if (!store.writeSlotA(slotA)) return UnlockResult.Error("storage_write_failed")189            val committed = runCatching {190                val wroteB = if (codexSlotB != null) {191                    store.writeSlotB(Base64.getEncoder().encodeToString(codexSlotB.toByteArray(Charsets.UTF_8)))192                } else {193                    writeMatchingNoiseSlotB(slotA)194                }195                if (!wroteB) throw IllegalStateException("storage_write_failed")196                store.stampLocalMutation()197            }.isSuccess198            if (!committed) {199                rollbackRestore(priorA, priorB)200                return UnlockResult.Error("storage_write_failed")201            }202203            val ownedKey = candidateKey!!204            candidateKey = null // the session owns the key from here on205            adoptSlotA(ownedKey, payload)206        } catch (e: Exception) {207            // A raw kotlinx parse error ("Unexpected JSON token at offset N")208            // reaching the user says nothing about WHICH json failed — the209            // wrapper, or the payload decrypted out of it. Codex screens are210            // FLAG_SECURE so this can't be screenshotted either. Debug builds211            // log the structure around the failure; alphanumerics are masked so212            // no ciphertext or vault content lands in a log.213            if (BuildConfig.DEBUG) Log.w("PeachCodex", codexFailureShape(vaultBlobBase64, e))214            UnlockResult.Error(e.message ?: "restore_failed")215        } finally {216            plaintext?.let(VaultCrypto::zero)217            candidateKey?.let(VaultCrypto::zero)218        }219    }220221    /** Slot-A plaintext under [key], or null when the GCM tag fails (wrong password). */222    private fun decryptSlotABlob(slot: StoredVault, key: ByteArray): ByteArray? =223        runCatching { VaultCrypto.decrypt(unb64(slot.blob), key, VaultCrypto.AAD_SLOT_A) }.getOrNull()224225    /**226     * Undo a partially-committed Codex restore. Every step is attempted227     * independently so one failure cannot strand the others. With no prior vault228     * the accurate inverse is having none at all, rather than a half-written229     * slot A that [hasVault] would report as a real vault.230     */231    private fun rollbackRestore(priorA: StoredVault?, priorB: String?) {232        val failures = mutableListOf<String>()233        if (priorA == null) {234            runCatching { store.clearVault() }.onFailure { failures += "clearVault: $it" }235        } else {236            runCatching { if (!store.writeSlotA(priorA)) failures += "writeSlotA returned false" }237                .onFailure { failures += "writeSlotA: $it" }238            if (priorB != null) {239                runCatching { if (!store.writeSlotB(priorB)) failures += "writeSlotB returned false" }240                    .onFailure { failures += "writeSlotB: $it" }241            }242        }243        // Log is a throwing stub off-device, and a failed log must never mask244        // the rollback result the caller is about to report.245        if (failures.isNotEmpty()) runCatching { Log.w("PeachCodex", "codex rollback incomplete: $failures") }246    }247248    /** Debug-only: structure of a failed Codex restore, with content masked. */249    private fun codexFailureShape(vaultBlobBase64: String, e: Exception): String = runCatching {250        val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)251        val offset = Regex("offset (\\d+)").find(e.message.orEmpty())?.groupValues?.get(1)?.toIntOrNull()252        val window = offset?.let {253            val from = (it - 40).coerceAtLeast(0)254            val to = (it + 40).coerceAtMost(wrapperJson.length)255            wrapperJson.substring(from, to).replace(Regex("[A-Za-z0-9+/=_-]"), "x")256        }257        val wrapper = runCatching { CodexJson.parseToJsonElement(wrapperJson) as? JsonObject }.getOrNull()258        val slot = wrapper?.get("a")259        buildString {260            append("codex restore failed: ").append(e::class.simpleName).append(": ").append(e.message)261            append(" | blobBase64=").append(vaultBlobBase64.length)262            append(" wrapperChars=").append(wrapperJson.length)263            append(" wrapperParses=").append(wrapper != null)264            append(" keys=").append(wrapper?.keys)265            append(" slotAKind=").append(266                when {267                    slot == null -> "absent"268                    slot is JsonPrimitive && slot.isString -> "string"269                    slot is JsonObject -> "object:" + slot.keys270                    else -> slot::class.simpleName271                },272            )273            if (window != null) append(" masked@").append(offset).append("=").append(window)274        }275    }.getOrElse { "codex restore failed: ${e.message} (shape unavailable: $it)" }276277    suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {278        return try {279            val salt = VaultCrypto.generateSalt()280            val key = VaultCrypto.deriveKey(password, salt)281            mutateState {282                entryList = mutableListOf()283                duressConfigured = false284                recoveryWordHash = null285                recoveryWordsSet = false286                decoyMode = false287                rootKey = generateRecoverableRootKey()288            }289            val slotA = sealSlotA(key, salt)290            if (!store.writeSlotA(slotA)) return CreateVaultResult.Error("storage_write_failed")291            // P1-3 (codex): every later step must roll the slot pair back if it292            // fails — leaving a half-built vault is worse than refusing to make it.293            val created = try {294                if (!writeMatchingNoiseSlotB(slotA)) throw java.io.IOException("noise_slot_b_commit_failed")295                store.stampLocalMutation()296                if (!store.writeSettings(_settings.value)) throw java.io.IOException("settings_commit_failed")297                true298            } catch (_: Exception) {299                // Half-built vault on disk is worse than no vault — refuse to300                // create if any step past slot A fails.301                store.clearVault()302                false303            }304            if (!created) return CreateVaultResult.Error("storage_write_failed")305            mutateState {306                derivedKey = key307                publish()308                _isUnlocked.value = true309            }310            CreateVaultResult.Success311        } catch (e: Exception) {312            CreateVaultResult.Error(e.message ?: "create_failed")313        }314    }315316    suspend fun createVaultFromRootKey(password: String, rootKeyHex: String): AdoptVaultResult = mutex.withLock {317        if (password.isEmpty()) return AdoptVaultResult.Error("ADOPT_INVALID_PASSWORD")318        if (store.hasVault()) return AdoptVaultResult.Error("ADOPT_VAULT_ALREADY_EXISTS")319        if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {320            return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars")321        }322        var adoptedRootKey: ByteArray? = null323        var nextDerivedKey: ByteArray? = null324        var sessionRootKey: ByteArray? = null325        return try {326            adoptedRootKey = hexToRootKey(rootKeyHex)327            if (adoptedRootKey.size != VaultCrypto.KEY_SIZE) {328                return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes")329            }330            val vaultId = com.peachpasswords.sync.computeVaultId(adoptedRootKey)331            val salt = VaultCrypto.generateSalt()332            nextDerivedKey = VaultCrypto.deriveKey(password, salt)333            sessionRootKey = adoptedRootKey.copyOf()334            val payload = VaultPayload(335                entries = emptyList(),336                duressConfigured = false,337                rootKeyB64 = b64(sessionRootKey),338                recoveryWordHash = null,339                recoveryWordsSet = false,340            )341            val blob = b64(VaultCrypto.encrypt(VaultCodec.encode(payload), nextDerivedKey, VaultCrypto.AAD_SLOT_A))342            val slotA = StoredVault(version = 1, salt = b64(salt), blob = blob)343            if (!store.writeSlotA(slotA)) return AdoptVaultResult.Error("storage_write_failed")344            // P1-3 (codex): same partial-commit guard as createVault — any failure345            // past slot A wipes the half-built vault and refuses adoption.346            val created = try {347                if (!writeMatchingNoiseSlotB(slotA)) throw java.io.IOException("noise_slot_b_commit_failed")348                store.stampLocalMutation()349                if (!store.writeSettings(_settings.value)) throw java.io.IOException("settings_commit_failed")350                true351            } catch (_: Exception) {352                store.clearVault()353                false354            }355            if (!created) return AdoptVaultResult.Error("storage_write_failed")356357            val previousDerivedKey = derivedKey358            val previousRootKey = rootKey359            mutateState {360                derivedKey = nextDerivedKey361                rootKey = sessionRootKey362                nextDerivedKey = null363                sessionRootKey = null364                entryList = mutableListOf()365                duressConfigured = false366                recoveryWordHash = null367                recoveryWordsSet = false368                decoyMode = false369                publish()370                _isUnlocked.value = true371            }372            previousDerivedKey?.let(VaultCrypto::zero)373            previousRootKey?.let(VaultCrypto::zero)374            AdoptVaultResult.Success(vaultId)375        } catch (e: Exception) {376            AdoptVaultResult.Error(e.message ?: "adoption_create_failed")377        } finally {378            adoptedRootKey?.let(VaultCrypto::zero)379            nextDerivedKey?.let(VaultCrypto::zero)380            sessionRootKey?.let(VaultCrypto::zero)381        }382    }383384    suspend fun unlock(password: String): UnlockResult = mutex.withLock { unlockLocked(password) }385386    /** Unlock body without acquiring the mutex — callers must already hold it. */387    private fun unlockLocked(password: String): UnlockResult {388        val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")389        val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))390        val payload = try {391            VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))392        } catch (_: Exception) {393            VaultCrypto.zero(key)394            // LV-1: a vault sealed before NFC normalization with a non-NFC395            // password derives a different key now. If the supplied password is396            // not already in NFC form, retry with the raw (un-normalized) bytes.397            if (password != Normalizer.normalize(password, Normalizer.Form.NFC)) {398                val legacy = tryLegacyRawUnlock(password, slotA)399                if (legacy != null) return legacy400            }401            return UnlockResult.WrongPassword402        }403        return adoptSlotA(key, payload)404    }405406    /**407     * LV-1 legacy fallback: unlock a slot-A vault that was sealed under the raw408     * (un-normalized) password bytes. On success the slot is HEALED — re-sealed409     * under the NFC-normalized key — so every future unlock takes the normal410     * path. Returns null when the raw key also fails (genuinely wrong password)411     * OR when any step of the heal commits fails (the original slot A is restored412     * so disk and session stay aligned).413     */414    private fun tryLegacyRawUnlock(password: String, slotA: StoredVault): UnlockResult? {415        val rawKey = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))416        val payload = try {417            VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), rawKey, VaultCrypto.AAD_SLOT_A))418        } catch (_: Exception) {419            VaultCrypto.zero(rawKey)420            return null421        }422        // Heal: re-seal slot A under the NFC key (mirrors changePassword's423        // re-seal). Escrows carry forward unchanged — only the wrapping rotates.424        val newSalt = VaultCrypto.generateSalt()425        val newKey = VaultCrypto.deriveKey(password, newSalt)426        val blob = b64(VaultCrypto.encrypt(VaultCodec.encode(payload), newKey, VaultCrypto.AAD_SLOT_A))427        val next = StoredVault(428            version = slotA.version,429            salt = b64(newSalt),430            blob = blob,431            recoveryEscrow = slotA.recoveryEscrow,432            rootKeyEscrow = slotA.rootKeyEscrow,433        )434        // P1-1/P1-3/P1-2 (codex): any failure of writeSlotA, writeMatchingNoiseSlotB,435        // or stampLocalMutation must restore the prior slot A AND slot B so disk436        // and the eventual session key never disagree on the wrapping.437        val priorB = store.loadSlotB()438        val healed = if (!store.writeSlotA(next)) {439            false440        } else try {441            if (!writeMatchingNoiseSlotB(next)) {442                runCatching { store.writeSlotA(slotA) }443                if (priorB != null) runCatching { store.writeSlotB(priorB) }444                false445            } else {446                store.stampLocalMutation()447                true448            }449        } catch (_: Exception) {450            runCatching { store.writeSlotA(slotA) }451            if (priorB != null) runCatching { store.writeSlotB(priorB) }452            false453        }454        return if (healed) {455            VaultCrypto.zero(rawKey)456            adoptSlotA(newKey, payload) // session key now matches the re-sealed slot457        } else {458            VaultCrypto.zero(newKey)459            adoptSlotA(rawKey, payload) // heal failed — keep using the raw key460        }461    }462463    /** Adopt a derived slot-A [key]/[payload] as the live (real-vault) session. */464    private fun adoptSlotA(key: ByteArray, payload: VaultPayload): UnlockResult {465        return try {466            mutateState {467                derivedKey = key468                decoyMode = false469                entryList = payload.entries.toMutableList()470                duressConfigured = payload.duressConfigured471                recoveryWordHash = payload.recoveryWordHash472                recoveryWordsSet = payload.recoveryWordsSet473                _settings.value = store.loadSettings()474                ensureRootKey(payload)475                autoPurgeExpiredTrash()476                publish()477                _isUnlocked.value = true478            }479            UnlockResult.Success480        } catch (e: Exception) {481            UnlockResult.Error(e.message ?: "unlock_failed")482        }483    }484485    // ---- Constant-time unlock (MF-5) --------------------------------------486487    /**488     * A slot-A unlock that has been derived but not yet adopted. Holds the live489     * Argon2id key and decoded payload so the caller can derive several candidates490     * concurrently and commit only the winner. The key is owned by this token until491     * [commitSlotAUnlock] adopts it or [discardSlotAUnlock] zeroes it.492     */493    class SlotAUnlock internal constructor(494        internal val key: ByteArray,495        internal val payload: VaultPayload,496    )497498    /**499     * Derive the slot-A key and decrypt its payload WITHOUT mutating session state.500     * Pure computation (no mutex), so it can run concurrently with other candidate501     * derivations before the caller decides which to commit (MF-5). Returns null on502     * no-vault or wrong password (the derived key is zeroed on a tag mismatch).503     */504    fun tryUnlockSlotA(password: String): SlotAUnlock? {505        val slotA = store.loadSlotA() ?: return null506        val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))507        return try {508            val payload = VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))509            SlotAUnlock(key, payload)510        } catch (_: Exception) {511            VaultCrypto.zero(key)512            null513        }514    }515516    /** Adopt a previously-derived [SlotAUnlock] as the live session. */517    suspend fun commitSlotAUnlock(unlock: SlotAUnlock): UnlockResult = mutex.withLock {518        adoptSlotA(unlock.key, unlock.payload)519    }520521    /** Zero a derived [SlotAUnlock] that will not be adopted. */522    fun discardSlotAUnlock(unlock: SlotAUnlock) = VaultCrypto.zero(unlock.key)523524    // ---- Duress slot B (MF-6) ---------------------------------------------525526    /**527     * A duress-slot (slot B) unlock derived but not yet adopted. Holds the live key528     * and decoded decoy payload so it can be derived concurrently with slot A and529     * only committed if the duress passphrase was the one entered (MF-5/MF-6).530     */531    class DuressUnlock internal constructor(532        internal val key: ByteArray,533        internal val payload: VaultPayload,534    )535536    /**537     * Try to decrypt the duress slot (slot B) with [password] WITHOUT mutating the538     * session. Success means the entered password is the duress passphrase that keys539     * slot B — indistinguishable from the real slot A at the lock screen. Pure540     * computation (no mutex), safe to run concurrently with [tryUnlockSlotA].541     * Returns null when no duress slot exists or the password is not the duress one.542     */543    fun tryUnlockDuress(password: String): DuressUnlock? {544        val slot = store.loadDecoySlot() ?: return null545        val key = VaultCrypto.deriveKey(password, unb64(slot.salt))546        return try {547            val payload = VaultCodec.decode(VaultCrypto.decrypt(unb64(slot.blob), key, VaultCrypto.AAD_SLOT_A))548            DuressUnlock(key, payload)549        } catch (_: Exception) {550            VaultCrypto.zero(key)551            null552        }553    }554555    /** Adopt a derived [DuressUnlock] as a live decoy session (edits persist to slot B only). */556    suspend fun commitDuressUnlock(unlock: DuressUnlock): UnlockResult = mutex.withLock {557        return try {558            mutateState {559                derivedKey = unlock.key560                decoyMode = true561                entryList = unlock.payload.entries.toMutableList()562                duressConfigured = false563                recoveryWordHash = unlock.payload.recoveryWordHash564                recoveryWordsSet = unlock.payload.recoveryWordsSet565                rootKey = if (unlock.payload.rootKeyB64.isNotBlank()) unb64(unlock.payload.rootKeyB64)566                          else VaultCrypto.generateRootKey()567                _settings.value = store.loadSettings()568                publish()569                _isUnlocked.value = true570            }571            UnlockResult.Success572        } catch (e: Exception) {573            UnlockResult.Error(e.message ?: "decoy_unlock_failed")574        }575    }576577    /** Zero a derived [DuressUnlock] that will not be adopted. */578    fun discardDuressUnlock(unlock: DuressUnlock) = VaultCrypto.zero(unlock.key)579580    /**581     * Configure the duress vault (MF-6): seal a fresh, empty decoy payload under an582     * Argon2id key derived from [duressPassphrase] (fresh salt) into slot B. The583     * passphrase is never stored — only its ability to decrypt slot B proves it.584     * Requires the real vault to be unlocked and not itself a decoy session.585     */586    suspend fun setDuressPassphrase(duressPassphrase: String): Boolean = mutex.withLock {587        // H-03: read derivedKey/decoyMode atomically with any concurrent lock().588        val unlockedAndReal = mutateState { derivedKey != null && !decoyMode }589        if (!unlockedAndReal) return false590        // Reject a duress passphrase that also opens the real vault: it would make the591        // lock screen ambiguous (both slots would decrypt for the same input).592        tryUnlockSlotA(duressPassphrase)?.let { discardSlotAUnlock(it); return false }593        return try {594            val salt = VaultCrypto.generateSalt()595            val key = VaultCrypto.deriveKey(duressPassphrase, salt)596            // An empty decoy vault with its own fresh sync root key — nothing real leaks.597            val decoyPayload = VaultPayload(entries = emptyList(), rootKeyB64 = b64(VaultCrypto.generateRootKey()))598            val plaintext = VaultCodec.encode(decoyPayload)599            val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))600            VaultCrypto.zero(key)601            VaultCrypto.zero(plaintext)602            val ok = store.writeDecoySlot(StoredVault(version = 1, salt = b64(salt), blob = blob))603            if (ok) {604                mutateState { duressConfigured = true }605                runCatching { persistSlotA(bumpVersion = false) }606            }607            ok608        } catch (_: Exception) {609            false610        }611    }612613    /** Tear down the duress vault: drop slot B and the duress flag on the real payload. */614    suspend fun clearDuress(): Boolean = mutex.withLock {615        store.clearDecoySlot()616        // H-03: stateLock-fence the derivedKey/decoyMode read AND the617        // duressConfigured write so a concurrent lock() cannot land between them.618        val shouldClear = mutateState { derivedKey != null && !decoyMode }619        if (shouldClear) {620            mutateState { duressConfigured = false }621            runCatching { persistSlotA(bumpVersion = false) }622        }623        true624    }625626    /** Unlock with an already-derived AES-256 key (biometric path). */627    suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {628        val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")629        return try {630            val payload = VaultCodec.decode(631                VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A),632            )633            mutateState {634                derivedKey = key.copyOf()635                decoyMode = false636                entryList = payload.entries.toMutableList()637                duressConfigured = payload.duressConfigured638                recoveryWordHash = payload.recoveryWordHash639                recoveryWordsSet = payload.recoveryWordsSet640                _settings.value = store.loadSettings()641                ensureRootKey(payload)642                autoPurgeExpiredTrash()643                publish()644                _isUnlocked.value = true645            }646            UnlockResult.Success647        } catch (_: Exception) {648            UnlockResult.WrongPassword649        }650    }651652    fun lock() {653        // H-03: must observe derivedKey/entryList atomically with any in-flight654        // suspend op (an addEntry mid-encrypt, an unlock adopting the payload,655        // etc.). mutex cannot be acquired from this non-suspend caller; stateLock656        // guards just the brief state reset.657        stateLock.lock()658        try {659            derivedKey?.let(VaultCrypto::zero)660            rootKey?.let(VaultCrypto::zero)661            derivedKey = null662            rootKey = null663            entryList = mutableListOf()664            duressConfigured = false665            recoveryWordHash = null666            recoveryWordsSet = false667            decoyMode = false668            _entries.value = emptyList()669            _isUnlocked.value = false670        } finally {671            stateLock.unlock()672        }673    }674675    @Volatile private var suppressNextBackgroundLock = false676677    /**678     * Call immediately before launching a system Activity (a SAF file679     * picker/save dialog, a share sheet) that briefly takes the whole process680     * out of the foreground as an expected part of an in-app flow — not a681     * genuine user backgrounding. ProcessLifecycleOwner.onStop can't tell the682     * two apart on its own (it fires for both), and without this, exporting or683     * importing a file silently locked and wiped the vault mid-flow the moment684     * the picker took over, before its result ever reached the app.685     */686    fun expectTransientBackground() {687        suppressNextBackgroundLock = true688    }689690    /** Consumed once by the next background-lock check; see [expectTransientBackground]. */691    fun consumeTransientBackgroundSuppression(): Boolean {692        val suppressed = suppressNextBackgroundLock693        suppressNextBackgroundLock = false694        return suppressed695    }696697    // ---- Sync identity ----------------------------------------------------698699    /**700     * The vault's stable sync master key (a copy). Caller must zero it. Backs701     * vault_id, the Noise static key, the Ed25519 manifest key, and per-entry702     * envelope keys. Null when locked. See [VaultPayload.rootKeyB64].703     */704    /**705     * HOLE 5 — the duress vault never syncs.706     *707     * [commitDuressUnlock] gives the decoy session a root key so its own codex708     * and recovery paths work, which means (unlike the browser, where the decoy709     * path simply has no root key) the sync surface has to refuse explicitly.710     * Without this the decoy vault would present a second, different vault_id711     * to a paired device, and a coerced user opening it would make sync visibly712     * fail on their other devices — a duress indicator, which is the one thing713     * a duress vault must never be.714     */715    fun syncMasterKey(): ByteArray? = if (decoyMode) null else rootKey?.copyOf()716717    /**718     * The current session's root key, decoy included. For local-only uses that719     * must behave identically in a decoy session — Codex backup and recovery720     * words — because a feature that errors under duress is itself a duress721     * tell. In a decoy session this is the DECOY's root key (see722     * [commitDuressUnlock]), never the real vault's, so neither surface can723     * leak the real vault. Anything that leaves the device must use724     * [syncMasterKey] instead.725     */726    fun sessionRootKey(): ByteArray? = rootKey?.copyOf()727728    /** Stable per-vault id two paired devices must share to sync. Null when729     *  locked, and never present for the decoy vault (see [syncMasterKey]). */730    fun syncVaultId(): String? =731        if (decoyMode) null else rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }732733    /**734     * Browser parity (MV-8): rotate the sync identity by replacing the stable735     * root key. Entries remain under the master-password key, while sync736     * credentials, vault_id, and recovery words all change.737     */738    suspend fun rotateSyncIdentity(): Boolean = mutex.withLock {739        installRootKey(generateRecoverableRootKey())740    }741742    /**743     * Join the vault behind [rootKeyHex]: adopt that vault's identity while744     * keeping every local entry.745     *746     * Sync identity (vault id, signing keys) derives from the root key, and747     * `sync-coordinator` refuses a `vault_id_mismatch`, so two independently748     * created vaults can never reconcile. Taking the other side's root key is749     * what makes them one vault; from the next sync on, both entry sets merge.750     *751     * Entries survive because they are sealed under the password-derived key,752     * not the root key — the same property [rotateSyncIdentity] relies on.753     *754     * CONSEQUENCE, which the caller must have disclosed and had confirmed:755     * this device's previous recovery words stop working for good, and its new756     * words are the source vault's words, because words are a deterministic757     * encoding of the root key.758     */759    suspend fun joinVault(rootKeyHex: String): AdoptVaultResult = mutex.withLock {760        if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {761            return AdoptVaultResult.Error("JOIN_INVALID_ROOT_KEY: expected 64 lowercase hex chars")762        }763        if (derivedKey == null) return AdoptVaultResult.Error("vault_locked")764        if (decoyMode) return AdoptVaultResult.Error("JOIN_DECOY_MODE")765        if (!store.hasVault()) return AdoptVaultResult.Error("JOIN_NO_LOCAL_VAULT")766767        val incoming = hexToRootKey(rootKeyHex)768        if (incoming.size != VaultCrypto.KEY_SIZE) {769            VaultCrypto.zero(incoming)770            return AdoptVaultResult.Error("JOIN_INVALID_ROOT_KEY: expected 32 bytes")771        }772        // Refuse before committing rather than leave this device holding a vault773        // whose recovery words cannot be typed back. generateRecoverableRootKey774        // screens its own keys for this; a key arriving from a peer has not been.775        val roundTrips = runCatching { wordsToRootKeyMaterial(rootKeyToWords(incoming)) }.isSuccess776        if (!roundTrips) {777            VaultCrypto.zero(incoming)778            return AdoptVaultResult.Error("JOIN_UNRECOVERABLE_ROOT_KEY")779        }780781        val vaultId = com.peachpasswords.sync.computeVaultId(incoming)782        return if (installRootKey(incoming)) {783            AdoptVaultResult.Success(vaultId)784        } else {785            AdoptVaultResult.Error("JOIN_INSTALL_FAILED")786        }787    }788789    /**790     * The recovery words [rootKeyHex] will produce once joined, or null if it is791     * not a usable root key. Lets the join flow show the user the words that are792     * about to replace theirs *before* anything is committed.793     */794    fun previewRecoveryWords(rootKeyHex: String): List<String>? {795        if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) return null796        val bytes = hexToRootKey(rootKeyHex)797        return try {798            val words = rootKeyToWords(bytes)799            if (runCatching { wordsToRootKeyMaterial(words) }.isSuccess) words else null800        } catch (_: Exception) {801            null802        } finally {803            VaultCrypto.zero(bytes)804        }805    }806807    /**808     * Swap the vault's root key, keeping every entry, and re-escrow under the809     * words the new key encodes. Takes ownership of [nextRootKey]. Caller holds810     * [mutex].811     */812    private suspend fun installRootKey(nextRootKey: ByteArray): Boolean {813        // H-03: snapshot the live fields under stateLock so the success and the814        // rollback paths both see consistent prior/new state. Writing the new815        // rootKey/recovery fields is inside its own mutateState at the end.816        // H-03 (P1-3 codex): the snapshot must COPY the live key/rootKey arrays817        // — holding live references would let a zero-on-failure operation also818        // wipe the session's still-live key arrays.819        data class Snapshot(820            val key: ByteArray,821            val priorRootKey: ByteArray,822            val priorRecoveryHash: String?,823            val priorRecoverySet: Boolean,824        )825        val snap = mutateState {826            val k = derivedKey ?: return false827            if (decoyMode) return false828            val priorRoot = rootKey ?: return false829            Snapshot(k.copyOf(), priorRoot.copyOf(), recoveryWordHash, recoveryWordsSet)830        } as Snapshot? ?: return false831        val priorSlot = store.loadSlotA() ?: run {832            VaultCrypto.zero(snap.priorRootKey)833            return false834        }835        val nextWords = rootKeyToWords(nextRootKey)836837        return try {838            takeVaultSnapshot("local_save")839            mutateState {840                rootKey = nextRootKey841                recoveryWordHash = recoveryWordsHash(nextWords)842                recoveryWordsSet = false843            }844845            val nextRecoveryEscrow = buildRecoveryEscrow(nextWords)846                ?: throw IllegalStateException("recovery_escrow_failed")847            val nextRootKeyEscrow = buildRootKeyEscrow(nextWords)848                ?: throw IllegalStateException("root_escrow_failed")849            val plaintext = VaultCodec.encode(currentPayload())850            val blob = try {851                b64(VaultCrypto.encrypt(plaintext, snap.key, VaultCrypto.AAD_SLOT_A))852            } finally {853                VaultCrypto.zero(plaintext)854            }855            val nextSlot = priorSlot.copy(856                blob = blob,857                recoveryEscrow = nextRecoveryEscrow,858                rootKeyEscrow = nextRootKeyEscrow,859            )860            if (!store.writeSlotA(nextSlot)) throw IllegalStateException("storage_write_failed")861            try {862                writeMatchingNoiseSlotB(nextSlot)863                store.stampLocalMutation()864            } catch (e: Exception) {865                store.writeSlotA(priorSlot)866                throw e867            }868            VaultCrypto.zero(snap.priorRootKey)869            mutateState { publish() }870            true871        } catch (_: Exception) {872            mutateState {873                rootKey = snap.priorRootKey874                recoveryWordHash = snap.priorRecoveryHash875                recoveryWordsSet = snap.priorRecoverySet876            }877            VaultCrypto.zero(nextRootKey)878            store.writeSlotA(priorSlot)879            false880        }881    }882883    /**884     * A copy of the live Argon2id-derived vault key, for biometric escrow only885     * (wrapped under a hardware KeyStore key on biometric enable). Null when886     * locked. Caller must [VaultCrypto.zero] it after use.887     */888    fun currentVaultKey(): ByteArray? = derivedKey?.copyOf()889890    suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {891        val slotA = store.loadSlotA() ?: return false892        var oldKey: ByteArray? = null893        var newKey: ByteArray? = null894        var plaintext: ByteArray? = null895        return try {896            oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))897            val payload = VaultCodec.decode(898                VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A),899            )900            val newSalt = VaultCrypto.generateSalt()901            newKey = VaultCrypto.deriveKey(newPassword, newSalt)902            // Re-seal the existing payload under the new key/salt.903            plaintext = VaultCodec.encode(payload)904            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))905            // The escrow seals the slot-A PLAINTEXT, which a password change does not906            // alter — only the wrapping changes — so carry it forward; rebuilding the907            // StoredVault from scratch would silently drop it.908            // Carry BOTH escrows forward unchanged: each seals plaintext/root-key909            // content that a password change does not alter — only the slot-A910            // wrapping rotates. The root-key escrow staying stable across password911            // changes matches the browser (`vault.ts:363-364`).912            val next = StoredVault(913                version = slotA.version,914                salt = b64(newSalt),915                blob = blob,916                recoveryEscrow = slotA.recoveryEscrow,917                rootKeyEscrow = slotA.rootKeyEscrow,918            )919            // H-01: durably commit slot A + size-matched noise + version stamp920            // before swapping the session key. A partial commit (new A on disk,921            // old key in memory) would have the next save encrypt under the old922            // key while matching disk on the new one.923            val priorB = store.loadSlotB()924            if (!commitVaultRotation(slotA, priorB, next)) return false925            // H-03 (P1-2 codex): zero the OLD live key and assign the NEW one926            // inside the same stateLock critical section, so a concurrent lock()927            // can't observe the in-between (zeroed but not yet reassigned).928            mutateState {929                oldKey?.let(VaultCrypto::zero); oldKey = null930                derivedKey?.let(VaultCrypto::zero)931                derivedKey = newKey; newKey = null932            }933            true934        } catch (_: Exception) {935            false936        } finally {937            oldKey?.let(VaultCrypto::zero)938            newKey?.let(VaultCrypto::zero)939            plaintext?.let(VaultCrypto::zero)940        }941    }942943    /**944     * Irreversible wipe. Locks the session and clears every vault key. The Pro945     * license is in a separate store and is preserved by construction.946     */947    suspend fun destroyVault() = mutex.withLock {948        lock()949        store.clearVault()950        store.clearDecoySlot()951    }952953    // ---- Entry CRUD -------------------------------------------------------954955    suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {956        requireUnlocked()957        val stamp = VaultCrypto.monotonicEntryTimestamp()958        val now = System.currentTimeMillis()959        val entry = withDerivedLast4(draft.copy(960            id = draft.id.ifBlank { UUID.randomUUID().toString() },961            createdAt = if (draft.createdAt > 0) draft.createdAt else now,962            modifiedAt = stamp,963            passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,964        ))965        // H-03: capture rollback AND write entryList under stateLock so a966        // concurrent lock() cannot zero the session between the read and the write.967        val rollback = mutateState {968            val r = entryList.toMutableList()969            entryList.add(entry)970            r971        }972        persistOrRollback(rollback)973        entry974    }975976    /**977     * Insert many entries with a single encrypt-and-write at the end.978     *979     * Importing a real vault through [addEntry] was quadratic: every entry took980     * the lock and re-encrypted and rewrote the whole vault, so an 806-entry981     * restore did 806 full-vault writes and hung the app long enough to ANR.982     * Rolls back to the pre-import list if the one write fails, matching983     * [addEntry]'s all-or-nothing behaviour.984     */985    suspend fun addEntries(drafts: List<VaultEntry>): Int = mutex.withLock {986        requireUnlocked()987        if (drafts.isEmpty()) return 0988        val now = System.currentTimeMillis()989        val ready = drafts.map { draft ->990            val stamp = VaultCrypto.monotonicEntryTimestamp()991            withDerivedLast4(992                draft.copy(993                    id = draft.id.ifBlank { UUID.randomUUID().toString() },994                    createdAt = if (draft.createdAt > 0) draft.createdAt else now,995                    modifiedAt = stamp,996                    passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,997                ),998            )999        }1000        // H-03: capture rollback AND append every entry under stateLock.1001        val rollback = mutateState {1002            val r = entryList.toMutableList()1003            entryList.addAll(ready)1004            r1005        }1006        persistOrRollback(rollback)1007        return drafts.size1008    }10091010    suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {1011        requireUnlocked()1012        // H-03: read entryList, compute the patched entry, and write it under a1013        // single stateLock so a concurrent lock() cannot interleave between the1014        // lookup and the assignment (would IndexOutOfBoundsException on a shrunk1015        // list, or clobber the entry onto the wrong id after a relock).1016        var prepared: Pair<VaultEntry, MutableList<VaultEntry>>? = null1017        mutateState {1018            val idx = entryList.indexOfFirst { it.id == patch.id }1019            if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1020            val current = entryList[idx]1021            val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1022            // Only refresh passwordChangedAt when the password value actually changes.1023            val passwordChanged = patch.password != null && patch.password != current.password1024            // Capture the outgoing password (newest first) so the user can reveal/copy/1025            // restore it later. History is computed authoritatively from `current`, not1026            // the patch — updateEntry is a full-entry replace, so trusting patch's value1027            // would let a stale form clobber the real history. Record the age the old1028            // password carried, skip an empty prior, and skip an immediate exact dupe1029            // (e.g. restore-then-restore). Capped at PASSWORD_HISTORY_MAX.1030            val priorPassword = current.password1031            val shouldCapture = passwordChanged &&1032                !priorPassword.isNullOrEmpty() &&1033                current.passwordHistory?.firstOrNull()?.password != priorPassword1034            val nextHistory = if (shouldCapture) {1035                (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +1036                    (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)1037            } else {1038                current.passwordHistory1039            }1040            val updated = withDerivedLast4(patch.copy(1041                createdAt = current.createdAt,1042                modifiedAt = stamp,1043                passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,1044                passwordHistory = nextHistory,1045            ))1046            val rollback = entryList.toMutableList()1047            entryList[idx] = updated1048            prepared = updated to rollback1049        }1050        val (updated, rollback) = prepared!!1051        persistOrRollback(rollback)1052        updated1053    }10541055    /** Soft-delete: writes a tombstone whose timestamp beats any in-flight edit. */1056    suspend fun deleteEntry(id: String) = mutex.withLock {1057        requireUnlocked()1058        // H-03: lookup + tombstone write under stateLock so lock() cannot shrink1059        // the list out from under the indexOfFirst.1060        var rollback: MutableList<VaultEntry>? = null1061        mutateState {1062            val idx = entryList.indexOfFirst { it.id == id }1063            if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1064            val current = entryList[idx]1065            val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1066            rollback = entryList.toMutableList()1067            entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)1068        }1069        persistOrRollback(rollback!!)1070    }10711072    suspend fun restoreEntry(id: String) = mutex.withLock {1073        requireUnlocked()1074        var rollback: MutableList<VaultEntry>? = null1075        mutateState {1076            val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }1077            if (idx == -1) throw IllegalStateException("deleted entry not found")1078            val current = entryList[idx]1079            rollback = entryList.toMutableList()1080            entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))1081        }1082        persistOrRollback(rollback!!)1083    }10841085    /** Permanent delete — no tombstone, no recovery. */1086    suspend fun purgeEntry(id: String) = mutex.withLock {1087        requireUnlocked()1088        var rollback: MutableList<VaultEntry>? = null1089        mutateState {1090            val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }1091            if (idx == -1) throw IllegalStateException("deleted entry not found")1092            rollback = entryList.toMutableList()1093            entryList.removeAt(idx)1094        }1095        persistOrRollback(rollback!!)1096    }10971098    /** Permanently empty the trash — hard-deletes every soft-deleted entry. */1099    suspend fun purgeDeletedEntries(): Int = mutex.withLock {1100        requireUnlocked()1101        // H-03: read+remove under stateLock so lock() can't reorder the remove.1102        data class R(val rollback: MutableList<VaultEntry>, val removed: Int)1103        val r = mutateState {1104            val rollback = entryList.toMutableList()1105            val before = entryList.size1106            entryList.removeAll { it.deletedAt != null }1107            R(rollback, before - entryList.size)1108        }1109        if (r.removed > 0) persistOrRollback(r.rollback)1110        r.removed1111    }11121113    /** Browser parity: number of active entries that dedupe would move to trash. */1114    suspend fun countDuplicateEntries(): Int = mutex.withLock {1115        requireUnlocked()1116        // countDuplicateEntriesLocked reads entryList; H-03 fences the read so1117        // lock() can't race the read with state writes.1118        mutateState { countDuplicateEntriesLocked() }1119    }11201121    /**1122     * Browser parity: soft-delete duplicate entries, keeping the most recently1123     * modified member of each group. Refuse in decoy mode so the duress vault is1124     * not reshaped into a forensically distinct state.1125     */1126    suspend fun deduplicateEntries(): Int = mutex.withLock {1127        requireUnlocked()1128        // H-03: read the decoyMode flag and the entry list, then reassign1129        // entryList, all under one stateLock.1130        val decoy = mutateState { decoyMode }1131        if (decoy) throw IllegalStateException("deduplicate disabled in decoy mode")1132        data class R(val rollback: MutableList<VaultEntry>, val removed: Int)1133        val ready = mutateState {1134            val active = entryList.filter { it.deletedAt == null }1135            val keepIds = mutableSetOf<String>()1136            active.groupBy { it.duplicateKey() }.values.forEach { group ->1137                keepIds += group.maxBy { it.modifiedAt.takeIf { ts -> ts > 0 } ?: it.createdAt }.id1138            }1139            val rollback = entryList.toMutableList()1140            var removed = 01141            entryList = entryList.map { entry ->1142                if (entry.deletedAt == null && entry.id !in keepIds) {1143                    removed++1144                    val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)1145                    entry.copy(deletedAt = stamp, modifiedAt = stamp)1146                } else {1147                    entry1148                }1149            }.toMutableList()1150            R(rollback, removed)1151        }1152        if (ready.removed > 0) persistOrRollback(ready.rollback)1153        ready.removed1154    }11551156    fun getEntries(): List<VaultEntry> = entryList.filter { it.deletedAt == null }1157    fun getEntry(id: String): VaultEntry? = entryList.firstOrNull { it.id == id && it.deletedAt == null }1158    fun getDeletedEntries(): List<VaultEntry> =1159        entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }11601161    /** Active entries, optionally narrowed to those carrying [tagFilter]. */1162    fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {1163        val active = entryList.filter { it.deletedAt == null }1164        if (tagFilter == null) return active1165        val needle = tagFilter.trim().lowercase()1166        return active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }1167    }11681169    /** Sorted, de-duplicated tags across all active entries. */1170    fun getDistinctTags(): List<String> =1171        entryList.asSequence()1172            .filter { it.deletedAt == null }1173            .flatMap { it.tags?.asSequence() ?: emptySequence() }1174            .map { it.trim().lowercase() }1175            .filter { it.isNotEmpty() }1176            .distinct()1177            .sorted()1178            .toList()11791180    /**1181     * Distinct non-blank values for an identity field across active entries,1182     * most-frequently-used first. Supports "username" and "email"; unknown field1183     * names return an empty list. Values keep original casing (deduped1184     * case-insensitively) so a suggestion matches what the user typed.1185     */1186    fun getDistinctFieldValues(field: String): List<String> {1187        val select: (VaultEntry) -> String? = when (field) {1188            "username" -> { e -> e.username }1189            "email" -> { e -> e.email }1190            else -> return emptyList()1191        }1192        return entryList.asSequence()1193            .filter { it.deletedAt == null }1194            .mapNotNull { select(it)?.trim() }1195            .filter { it.isNotEmpty() }1196            .groupingBy { it.lowercase() }1197            .aggregate { _, acc: Pair<String, Int>?, value, _ ->1198                Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)1199            }1200            .values1201            .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })1202            .map { it.first }1203    }12041205    fun getTombstones(): List<Tombstone> =1206        entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }1207    fun getVaultVersion(): Long = store.version()1208    fun getVaultHistory(): List<VaultSnapshot> = store.loadVaultHistory().snapshots12091210    suspend fun restoreVaultSnapshot(snapshotId: String): Boolean = mutex.withLock {1211        val snapshot = store.loadVaultHistory().snapshots.firstOrNull { it.id == snapshotId } ?: return false1212        val restoredA = VaultCodec.decodeSlot(snapshot.vault_a) ?: return false1213        val priorA = store.loadSlotA()1214        val priorB = store.loadSlotB()1215        // H-02: capture pre-restore state as the recovery snapshot BEFORE any1216        // slot write — the old code took this snapshot, then stranded it on1217        // every failure, polluting history with a "restore" entry that never1218        // restored anything. The history below is rolled back together with1219        // the slots if the commit fails.1220        val priorHistory = store.loadVaultHistory()1221        // P1-4 (codex): the recovery snapshot must land before we commit the1222        // slot pair, otherwise a failed restore cannot be rolled back to the1223        // pre-restore history. If the history write itself fails, refuse to1224        // proceed — the alternative is a successful restore with no undo path.1225        if (!takeVaultSnapshot("restore")) {1226            return false1227        }1228        if (!commitRestoreAtomic(restoredA, snapshot.vault_b, priorA, priorB)) {1229            store.writeVaultHistory(priorHistory)1230            return false1231        }1232        lock()1233        true1234    }12351236    /**1237     * H-02: atomic slot-A + slot-B + version stamp for a snapshot restore.1238     * Mirrors [commitVaultRotation] but writes the snapshot's EXACT slot B1239     * (a restore preserves the duress-shaped blob from history), not a fresh1240     * noise record. Any failure rolls back so the at-rest pair never holds a1241     * restored slot A against a pre-restore slot B. Caller is responsible for1242     * restoring the pre-snapshot history on a false return.1243     */1244    private fun commitRestoreAtomic(1245        nextA: StoredVault,1246        nextB: String,1247        priorA: StoredVault?,1248        priorB: String?,1249    ): Boolean {1250        if (!store.writeSlotA(nextA)) return false1251        // P1-2 (codex): writeSlotB's boolean AND any thrown exception from it1252        // must trigger rollback; previously a throw escaped without restoring1253        // the prior slot A and history.1254        try {1255            if (!store.writeSlotB(nextB)) throw java.io.IOException("slot_b_commit_failed")1256            store.stampLocalMutation()1257        } catch (_: Exception) {1258            rollbackRestore(priorA, priorB)1259            return false1260        }1261        return true1262    }12631264    // ---- Sync apply (does NOT advance the version) ------------------------12651266    /**1267     * Apply remote entryList + tombstones with per-entry last-write-wins. Persists1268     * WITHOUT bumping the version counter, so a sync round cannot cascade into1269     * another outbound sync. Returns the number of locally-applied changes.1270     */1271    suspend fun applyMergedRemoteEntries(1272        remoteEntries: List<VaultEntry>,1273        remoteTombstones: List<Tombstone>,1274    ): Int = mutex.withLock {1275        requireUnlocked()1276        // HV-1: clamp every peer-supplied timestamp to now + MAX_CLOCK_SKEW_MS1277        // BEFORE any comparison against a local one. Without this a peer can1278        // send a far-future modifiedAt and permanently pin its version of an1279        // entry against every honest local edit. The browser clamps in the1280        // matching place (vault.ts applyMergedRemoteEntries).1281        val mergeNow = System.currentTimeMillis()1282        val clamped = remoteEntries.map { entry ->1283            entry.copy(1284                modifiedAt = SyncLimits.clampSyncTimestamp(entry.modifiedAt, mergeNow),1285                deletedAt = entry.deletedAt?.let {1286                    SyncLimits.clampSyncTimestamp(it, mergeNow)1287                },1288            )1289        }1290        val tombMap = remoteTombstones.associate {1291            it.id to SyncLimits.clampSyncTimestamp(it.deletedAt, mergeNow)1292        }1293        // H-03: build the new entryList under stateLock so a concurrent lock()1294        // cannot zero derivedKey/entryList between the byId read and the merge.1295        val applied = mutateState {1296            var n = 01297            val byId = entryList.associateBy { it.id }.toMutableMap()12981299            for (remote in clamped) {1300                val tomb = tombMap[remote.id]1301                if (tomb != null && tomb >= remote.modifiedAt) continue1302                val local = byId[remote.id]1303                if (local == null) {1304                    entryList.add(remote); byId[remote.id] = remote; n++1305                } else if (remote.modifiedAt > local.modifiedAt) {1306                    val i = entryList.indexOfFirst { it.id == local.id }1307                    if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; n++ }1308                }1309            }13101311            for ((id, deletedAt) in tombMap) {1312                val local = byId[id] ?: continue1313                if (local.deletedAt != null && local.deletedAt >= deletedAt) continue1314                if (deletedAt < local.modifiedAt) continue1315                val i = entryList.indexOfFirst { it.id == id }1316                if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); n++ }1317            }1318            n1319        }13201321        if (applied > 0) {1322            persistSlotA(bumpVersion = false, snapshotReason = "sync_received")1323            mutateState { publish() }1324        }1325        applied1326    }13271328    suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {1329        // _settings is a StateFlow (atomic write), but publish under stateLock so1330        // any concurrent lock() observes either the old or the new value — not1331        // ordering with the in-memory entries flip.1332        mutateState { _settings.value = settings }1333        store.writeSettings(settings)1334    }13351336    // ---- Recovery words (vault metadata) ----------------------------------13371338    /** True once the user has confirmed their recovery words for this vault. */1339    fun isRecoveryWordsSet(): Boolean = recoveryWordsSet13401341    /**1342     * Record the BLAKE3 hash of the confirmed recovery words and mark them set.1343     * Persisted without bumping the version — recovery metadata is local-only and1344     * is not an entry mutation paired devices should sync against.1345     */1346    suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {1347        requireUnlocked()1348        // H-03: hash + escrow-related state fields set under stateLock so a1349        // concurrent lock() cannot zero them in the middle of buildRecoveryEscrow.1350        mutateState {1351            recoveryWordHash = recoveryWordsHash(words)1352            recoveryWordsSet = true1353        }1354        // Seal TWO escrows (MF-1): the browser-byte-compatible root-key escrow1355        // (cross-platform recovery of the sync root key) and Android's whole-payload1356        // escrow (offline forgot-password restore of entries). Both derive their key1357        // from the same `wordsToRootKeyMaterial` IKM but use distinct AADs.1358        runCatching {1359            persistSlotAWithEscrows(buildRecoveryEscrow(words), buildRootKeyEscrow(words))1360        }.getOrDefault(false)1361    }13621363    /** Verify entered words against the stored recovery hash. */1364    fun verifyRecoveryWords(words: List<String>): Boolean {1365        val stored = recoveryWordHash ?: return false1366        return stored == recoveryWordsHash(words)1367    }13681369    // ---- Recovery escrow (forgot-password) --------------------------------13701371    /** True at rest if this vault has any recovery escrow the recovery flow can use. */1372    fun hasRecoveryEscrow(): Boolean =1373        store.loadSlotA()?.let { it.recoveryEscrow != null || it.rootKeyEscrow != null } ?: false13741375    /**1376     * Attempt to unlock the vault using the 12 BIP39 recovery [words] instead of1377     * the master password. On success the slot-A plaintext sealed in the escrow is1378     * adopted as the live session (entries, rootKey, settings), but no Argon2id1379     * password key exists yet — call [resetPasswordWithRecoveryWords] next to set a1380     * new password and finish unlocking. Returns false when there is no escrow, the1381     * words fail the BIP39 checksum, or the words are wrong (GCM tag mismatch).1382     *1383     * Unlike the brief's `unlockWithRecoveryWords(): ByteArray?`, there is no1384     * detached vault key to return here — slot A is wrapped under the rotating1385     * Argon2id key — so this opens the escrowed payload directly.1386     */1387    suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {1388        val slotA = store.loadSlotA() ?: return false1389        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false13901391        // Prefer Android's whole-payload escrow: a full offline restore of entries,1392        // root key, and settings. Present for Android-created vaults.1393        slotA.recoveryEscrow?.let { escrow ->1394            val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return@let1395            val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))1396            val keyBytes = recoveryKey.encoded1397            try {1398                val plaintext = VaultCrypto.decrypt(unb64(escrow.blob), keyBytes, VaultCrypto.AAD_RECOVERY)1399                val payload = VaultCodec.decode(plaintext)1400                // H-03: adoption is one atomic state-write — lock() cannot interleave.1401                mutateState {1402                    decoyMode = false1403                    entryList = payload.entries.toMutableList()1404                    duressConfigured = payload.duressConfigured1405                    recoveryWordHash = payload.recoveryWordHash1406                    recoveryWordsSet = payload.recoveryWordsSet1407                    rootKey = if (payload.rootKeyB64.isNotBlank()) unb64(payload.rootKeyB64)1408                              else generateRecoverableRootKey()1409                    _settings.value = store.loadSettings()1410                }1411                VaultCrypto.zero(plaintext)1412                return true1413            } catch (_: Exception) {1414                // Wrong words against this escrow — fall through to the root-key escrow.1415            } finally {1416                VaultCrypto.zero(material)1417                VaultCrypto.zero(keyBytes)1418            }1419        }14201421        // Browser-format vault (only the root-key escrow): recover the 32-byte root1422        // key (sync identity) and reset the password; entries return via sync. This1423        // is exactly the browser's recovery semantics (`messages.ts:312-347`).1424        slotA.rootKeyEscrow?.let { escrow ->1425            val rk = unsealRootKeyEscrow(words, escrow) ?: return false1426            mutateState {1427                decoyMode = false1428                entryList = mutableListOf()1429                duressConfigured = false1430                recoveryWordHash = recoveryWordsHash(words)1431                recoveryWordsSet = true1432                rootKey = rk1433                _settings.value = store.loadSettings()1434            }1435            return true1436        }1437        return false1438    }14391440    /**1441     * After [unlockWithRecoveryWords] succeeds, set a brand-new master password:1442     * re-seal slot A under a fresh Argon2id key, rotate the escrow under the same1443     * words, mark the session fully unlocked, and publish. Returns false if called1444     * without a prior successful recovery unlock (no in-memory root key).1445     *1446     * Folds the brief's `resetPasswordWithRecoveryKey(vaultKey, …)` + `unlock(…)`1447     * into one step, since there is no detached vault key here.1448     */1449    suspend fun resetPasswordWithRecoveryWords(1450        words: List<String>,1451        newPassword: String,1452    ): Boolean = mutex.withLock {1453        // H-03: read rootKey + entryList under stateLock before computing the new1454        // plaintext, then re-publish + swap the derived key under stateLock so a1455        // concurrent lock() cannot straddle the two fences.1456        if (!mutateState { rootKey != null }) return false1457        val priorA = store.loadSlotA() ?: return false1458        var newKey: ByteArray? = null1459        var plaintext: ByteArray? = null1460        return try {1461            val newSalt = VaultCrypto.generateSalt()1462            newKey = VaultCrypto.deriveKey(newPassword, newSalt)1463            plaintext = VaultCodec.encode(currentPayload())1464            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))1465            // Rebuild both escrows against the recovered session so their salts rotate1466            // with the password reset; fall back to the prior escrows if rebuild fails1467            // (e.g. a checksum-invalid phrase). The same 12 words keep working.1468            val valid = words.size == 12 && findInvalidWords(words).isEmpty()1469            val freshRecovery = if (valid) buildRecoveryEscrow(words) ?: priorA.recoveryEscrow else priorA.recoveryEscrow1470            val freshRootKey = if (valid) buildRootKeyEscrow(words) ?: priorA.rootKeyEscrow else priorA.rootKeyEscrow1471            val next = StoredVault(1472                version = priorA.version,1473                salt = b64(newSalt),1474                blob = blob,1475                recoveryEscrow = freshRecovery,1476                rootKeyEscrow = freshRootKey,1477            )1478            // H-01: see changePassword — both rotations share the same1479            // commit-or-keep-old-key contract so a partial write can't strand1480            // the session on a key that no longer matches disk.1481            val priorB = store.loadSlotB()1482            if (!commitVaultRotation(priorA, priorB, next)) return false1483            // H-03 (P1-2 codex): zero the old live key and install the new one1484            // inside the same stateLock critical section so a concurrent lock()1485            // can't observe the in-between.1486            mutateState {1487                derivedKey?.let(VaultCrypto::zero)1488                derivedKey = newKey; newKey = null1489                publish()1490                _isUnlocked.value = true1491            }1492            true1493        } catch (_: Exception) {1494            false1495        } finally {1496            newKey?.let(VaultCrypto::zero)1497            plaintext?.let(VaultCrypto::zero)1498        }1499    }15001501    /**1502     * Seal the current slot-A plaintext under a key derived from the 12 BIP391503     * recovery [words] (Android offline-restore escrow). IKM is the browser's1504     * `wordsToRootKeyMaterial` (MF-1), AAD is the string [VaultCrypto.AAD_RECOVERY].1505     * Returns null for a checksum-invalid phrase.1506     */1507    private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {1508        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null1509        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null1510        val salt = VaultCrypto.generateSalt()1511        val recoveryKey = deriveRecoveryKey(material, salt)1512        val keyBytes = recoveryKey.encoded1513        val plaintext = VaultCodec.encode(currentPayload())1514        return try {1515            val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)1516            RecoveryEscrow(salt = b64(salt), blob = b64(sealed))1517        } finally {1518            VaultCrypto.zero(material)1519            VaultCrypto.zero(keyBytes)1520            VaultCrypto.zero(plaintext)1521        }1522    }15231524    /**1525     * Seal ONLY the 32-byte root key under a key the recovery [words] derive,1526     * byte-for-byte the browser algorithm (MF-1): plaintext = lowercase ASCII hex1527     * of the root key, IKM = `wordsToRootKeyMaterial`, HKDF salt random-16,1528     * info `peach-recovery-v1`, AES-256-GCM AAD = 0x01. The same 12 words unwrap1529     * the same root key on the browser. Returns null with no in-memory root key or1530     * a checksum-invalid phrase.1531     */1532    private fun buildRootKeyEscrow(words: List<String>): RootKeyEscrow? {1533        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null1534        val rk = rootKey ?: return null1535        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null1536        val salt = VaultCrypto.generateSalt()1537        val recoveryKey = deriveRecoveryKey(material, salt)1538        val keyBytes = recoveryKey.encoded1539        val plaintext = rootKeyToHex(rk).toByteArray(Charsets.US_ASCII)1540        return try {1541            // combined = nonce(12) || ciphertext || tag(16)1542            val combined = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)1543            val nonce = combined.copyOfRange(0, VaultCrypto.NONCE_SIZE)1544            val ctTag = combined.copyOfRange(VaultCrypto.NONCE_SIZE, combined.size)1545            val tag = ctTag.copyOfRange(ctTag.size - 16, ctTag.size)1546            val ct = ctTag.copyOfRange(0, ctTag.size - 16)1547            RootKeyEscrow(salt = b64(salt), wrappedRootKey = b64(ct), nonce = b64(nonce), tag = b64(tag))1548        } finally {1549            VaultCrypto.zero(material)1550            VaultCrypto.zero(keyBytes)1551            VaultCrypto.zero(plaintext)1552        }1553    }15541555    /** Unwrap the 32-byte root key from a browser-compatible [escrow]; null on wrong words. */1556    private fun unsealRootKeyEscrow(words: List<String>, escrow: RootKeyEscrow): ByteArray? {1557        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null1558        val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))1559        val keyBytes = recoveryKey.encoded1560        return try {1561            val combined = unb64(escrow.nonce) + unb64(escrow.wrappedRootKey) + unb64(escrow.tag)1562            val pt = VaultCrypto.decrypt(combined, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)1563            hexToRootKey(String(pt, Charsets.US_ASCII))1564        } catch (_: Exception) {1565            null1566        } finally {1567            VaultCrypto.zero(material)1568            VaultCrypto.zero(keyBytes)1569        }1570    }15711572    /**1573     * Re-seal slot A from the current in-memory state under the live key, carrying1574     * both [recoveryEscrow] and [rootKeyEscrow] onto the written record. Never runs1575     * in decoy mode (recovery is never offered for the decoy) and persists without1576     * a version bump, like the recovery-words metadata write it replaces.1577     */1578    private fun persistSlotAWithEscrows(1579        recoveryEscrow: RecoveryEscrow?,1580        rootKeyEscrow: RootKeyEscrow?,1581    ): Boolean {1582        val key = derivedKey ?: throw IllegalStateException("vault_locked")1583        if (decoyMode) return false1584        val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")1585        val plaintext = VaultCodec.encode(currentPayload())1586        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))1587        val next = prior.copy(1588            blob = blob,1589            recoveryEscrow = recoveryEscrow ?: prior.recoveryEscrow,1590            rootKeyEscrow = rootKeyEscrow ?: prior.rootKeyEscrow,1591        )1592        if (!store.writeSlotA(next)) return false1593        try {1594            writeMatchingNoiseSlotB(next)1595        } catch (e: Exception) {1596            store.writeSlotA(prior)1597            throw e1598        }1599        return true1600    }16011602    // ---- Internals --------------------------------------------------------16031604    private fun requireUnlocked() {1605        // H-03: read derivedKey atomically with [lock]'s reset; without it,1606        // [lock] from a background lifecycle event can run between this read1607        // and the caller's first state touch.1608        stateLock.lock()1609        try {1610            if (derivedKey == null) throw IllegalStateException("vault_locked")1611        } finally {1612            stateLock.unlock()1613        }1614    }16151616    private fun countDuplicateEntriesLocked(): Int {1617        val seen = mutableMapOf<String, VaultEntry>()1618        var duplicates = 01619        for (entry in entryList.filter { it.deletedAt == null }) {1620            val key = entry.duplicateKey()1621            val existing = seen[key]1622            if (existing == null) {1623                seen[key] = entry1624            } else {1625                duplicates++1626                val entryStamp = entry.modifiedAt.takeIf { it > 0 } ?: entry.createdAt1627                val existingStamp = existing.modifiedAt.takeIf { it > 0 } ?: existing.createdAt1628                if (entryStamp > existingStamp) seen[key] = entry1629            }1630        }1631        return duplicates1632    }16331634    private fun VaultEntry.duplicateKey(): String {1635        if (type == "note") return "note|${title.lowercase()}"1636        val passkeyData = passkey1637        if (passkeyData != null) {1638            return "passkey|${passkeyData.rpId.lowercase()}|${passkeyData.userName.lowercase()}"1639        }1640        return "login|${title.lowercase()}|${url.orEmpty().lowercase()}|${username.orEmpty().lowercase()}"1641    }16421643    /**1644     * Capture the current slot pair (and metadata) into the history list.1645     * Returns true when the history write landed, false when it didn't — callers1646     * that depend on the snapshot existing (notably [restoreVaultSnapshot])1647     * must check the result and roll back if it does not.1648     */1649    private fun takeVaultSnapshot(reason: String): Boolean {1650        val slotA = store.loadSlotA() ?: return false1651        val vaultA = VaultCodec.encodeSlot(slotA)1652        val vaultB = store.loadSlotB() ?: slotA.blob1653        val history = store.loadVaultHistory()1654        val latest = history.snapshots.firstOrNull()1655        if (latest?.vault_a == vaultA && latest.vault_b == vaultB) return true1656        val entryCount = if (derivedKey != null && !decoyMode) {1657            bucketEntryCount(entryList.count { it.deletedAt == null })1658        } else {1659            null1660        }1661        return try {1662            val snapshot = VaultSnapshot(1663                id = UUID.randomUUID().toString(),1664                savedAt = System.currentTimeMillis(),1665                reason = reason,1666                vault_a = vaultA,1667                vault_b = vaultB,1668                entryCount = entryCount,1669            )1670            // P1-4 (codex): return the history-write boolean to callers so a1671            // false return no longer leaves the snapshot out of history while1672            // callers (notably restoreVaultSnapshot) proceed as if it succeeded.1673            store.writeVaultHistory(1674                history.copy(snapshots = (listOf(snapshot) + history.snapshots).take(VAULT_HISTORY_MAX)),1675            )1676        } catch (_: Exception) {1677            false1678        }1679    }16801681    private fun bucketEntryCount(n: Int): Int = when {1682        n <= 0 -> 01683        n <= 10 -> 101684        n <= 25 -> 251685        n <= 50 -> 501686        n <= 100 -> 1001687        n <= 250 -> 2501688        n <= 500 -> 5001689        else -> ((n + 499) / 500) * 5001690    }16911692    /**1693     * Keep [VaultEntry.last4] in sync with the card number for card entries (MF-3),1694     * so it is stored explicitly and survives the sync wire format rather than being1695     * re-derived at render time. Non-card entries pass through unchanged.1696     */1697    private fun withDerivedLast4(entry: VaultEntry): VaultEntry {1698        if (!entry.isCard()) return entry1699        val digits = entry.cardNumber?.filter { it.isDigit() } ?: ""1700        return entry.copy(last4 = if (digits.length >= 4) digits.takeLast(4) else null)1701    }17021703    /**1704     * On unlock, hard-delete trashed entries older than the retention window.1705     * A null or non-positive [VaultSettings.trashRetentionDays] means "never"1706     * (the app's "Never" option), so nothing is purged. Persists without a1707     * version bump and without touching the publish state (caller publishes).1708     */1709    private fun autoPurgeExpiredTrash() {1710        val days = _settings.value.trashRetentionDays ?: return1711        if (days <= 0) return1712        val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L1713        val before = entryList.size1714        entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }1715        if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }1716    }17171718    /** The slot-A plaintext envelope for the current in-memory session. */1719    private fun currentPayload(): VaultPayload =1720        VaultPayload(1721            entries = entryList.toList(),1722            duressConfigured = duressConfigured,1723            rootKeyB64 = rootKey?.let(::b64) ?: "",1724            recoveryWordHash = recoveryWordHash,1725            recoveryWordsSet = recoveryWordsSet,1726        )17271728    /**1729     * Adopt the payload's root key, lazily minting one for legacy payloads.1730     * A freshly-minted key is persisted WITHOUT bumping the version — adopting1731     * a root key is not a mutation paired devices should sync against.1732     */1733    private fun ensureRootKey(payload: VaultPayload) {1734        if (payload.rootKeyB64.isNotBlank()) {1735            rootKey = unb64(payload.rootKeyB64)1736            return1737        }1738        rootKey = generateRecoverableRootKey()1739        runCatching { persistSlotA(bumpVersion = false) }1740    }17411742    private fun publish() {1743        _entries.value = entryList.filter { it.deletedAt == null }1744    }17451746    private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {1747        val plaintext = VaultCodec.encode(currentPayload())1748        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))1749        return StoredVault(version = 1, salt = b64(salt), blob = blob)1750    }17511752    private fun writeMatchingNoiseSlotB(slotA: StoredVault): Boolean {1753        // Size the noise so its base64 length matches slot A's blob (MN-1): with the1754        // plaintext now bucket-padded, an at-rest observer sees two equal-length slots1755        // and cannot pick the real one by size. b64(N bytes) ≈ N*4/3 chars.1756        val approxBytes = (slotA.blob.length * 3 / 4).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)1757        val noise = ByteArray(approxBytes).also(rng::nextBytes)1758        return store.writeSlotB(b64(noise))1759    }17601761    /** Re-seal slot A from the current in-memory state under the live key. */1762    private fun persistSlotA(bumpVersion: Boolean, snapshotReason: String? = "local_save"): Boolean {1763        val key = derivedKey ?: throw IllegalStateException("vault_locked")1764        // Decoy sessions persist to the decoy slot only — never touch the real slot A.1765        if (decoyMode) {1766            val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")1767            val plaintext = VaultCodec.encode(currentPayload())1768            val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))1769            return store.writeDecoySlot(prior.copy(blob = blob))1770        }1771        val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")1772        // H-01: captured BEFORE the noise write so a stamp failure can restore1773        // the prior slot B alongside the prior slot A. Slot B is always1774        // overwritten by writeMatchingNoiseSlotB below, so a stamp failure1775        // leaves (new A, new B, old version) on disk — partial commit.1776        val priorB = store.loadSlotB()1777        if (snapshotReason != null) takeVaultSnapshot(snapshotReason)1778        val plaintext = VaultCodec.encode(currentPayload())1779        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))1780        val next = prior.copy(blob = blob)1781        if (!store.writeSlotA(next)) return false1782        // Slot A committed — keep slot B size-matched, then advance the version1783        // for local writes only. Restore both A and B if a later step fails.1784        // P1-1 (codex): the noise write's boolean AND any thrown exception from1785        // it must trigger rollback; previously the call sat outside the try.1786        try {1787            if (!writeMatchingNoiseSlotB(next)) throw java.io.IOException("noise_slot_b_commit_failed")1788            if (bumpVersion) store.stampLocalMutation()1789        } catch (e: Exception) {1790            store.writeSlotA(prior)1791            if (priorB != null) runCatching { store.writeSlotB(priorB) }1792            throw e1793        }1794        return true1795    }17961797    /**1798     * H-01: durably commit a slot-A rotation by writing slot A, its1799     * size-matched noise slot B, and the local-mutation stamp in order. Any1800     * failure rolls the previously-committed steps back so the at-rest pair1801     * matches what was there before the call. Returns true only when every1802     * step succeeded — callers must NOT swap their session key on false.1803     */1804    private fun commitVaultRotation(1805        priorA: StoredVault,1806        priorB: String?,1807        nextA: StoredVault,1808    ): Boolean {1809        if (!store.writeSlotA(nextA)) return false1810        // P1-1 (codex): the noise write's boolean AND any thrown exception from1811        // it must trigger rollback; previously a throw from writeMatchingNoiseSlotB1812        // escaped the helper and left slot A committed.1813        try {1814            if (!writeMatchingNoiseSlotB(nextA)) throw java.io.IOException("noise_slot_b_commit_failed")1815            store.stampLocalMutation()1816        } catch (_: Exception) {1817            rollbackRotation(priorA, priorB)1818            return false1819        }1820        return true1821    }18221823    /**1824     * Best-effort undo of the writes [commitVaultRotation] may have committed.1825     * Each step runs independently — a failed rollback must not mask the1826     * original commit failure. Log is a throwing stub off-device.1827     */1828    private fun rollbackRotation(priorA: StoredVault, priorB: String?) {1829        val failures = mutableListOf<String>()1830        runCatching { if (!store.writeSlotA(priorA)) failures += "writeSlotA returned false" }1831            .onFailure { failures += "writeSlotA: $it" }1832        if (priorB != null) {1833            runCatching { if (!store.writeSlotB(priorB)) failures += "writeSlotB returned false" }1834                .onFailure { failures += "writeSlotB: $it" }1835        }1836        if (failures.isNotEmpty()) runCatching { Log.w("PeachVault", "vault rotation rollback incomplete: $failures") }1837    }18381839    /** Persist a local mutation, rolling the in-memory list back on failure. */1840    private fun persistOrRollback(rollback: MutableList<VaultEntry>) {1841        try {1842            if (!persistSlotA(bumpVersion = true)) {1843                mutateState { entryList = rollback }1844                throw IllegalStateException("storage_write_failed")1845            }1846        } catch (e: Exception) {1847            mutateState { entryList = rollback }1848            throw e1849        }1850        mutateState { publish() }1851    }1852}