VaultRepository.kt

142.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.MessageDigest9import java.security.SecureRandom10import java.text.Normalizer11import kotlinx.serialization.json.Json12import android.os.SystemClock13import android.util.Log14import androidx.annotation.VisibleForTesting15import com.peachpasswords.BuildConfig16import com.peachpasswords.sync.SyncLimits17import com.peachpasswords.sync.LockedSyncSpoolHooks18import kotlinx.serialization.json.JsonElement19import kotlinx.serialization.json.JsonNull20import kotlinx.serialization.json.JsonObject21import kotlinx.serialization.json.JsonPrimitive22import java.util.Base6423import java.util.UUID24import java.util.concurrent.locks.ReentrantLock25import javax.inject.Inject26import javax.inject.Singleton2728/** Lenient parser for the Codex vault-blob wrapper only. */29private val CodexJson = Json { ignoreUnknownKeys = true; isLenient = true }3031private fun b64(bytes: ByteArray): String = Base64.getEncoder().withoutPadding().encodeToString(bytes)32private fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s)3334/** Cap on retained past passwords per entry. Mirrors the browser PASSWORD_HISTORY_MAX. */35private const val PASSWORD_HISTORY_MAX = 5036private const val VAULT_HISTORY_MAX = 53738// How long the transient-background-lock suppression stays valid. If the39// launched system Activity never reports the expected lifecycle stop (picker40// crashed, user backed out into another app, OEM killed the picker process),41// the flag expires and the next genuine background event locks the vault42// rather than consuming a stale suppression.43private const val BACKGROUND_LOCK_SUPPRESSION_TIMEOUT_MS = 30_000L4445sealed interface UnlockResult {46    data object Success : UnlockResult47    data object WrongPassword : UnlockResult48    data class Error(val reason: String) : UnlockResult49}5051sealed interface CreateVaultResult {52    data object Success : CreateVaultResult53    data class Error(val reason: String) : CreateVaultResult54}5556sealed interface AdoptVaultResult {57    data class Success(val vaultId: String) : AdoptVaultResult58    data class Error(val reason: String) : AdoptVaultResult59}6061/**62 * In-memory vault session backed by [VaultStore]. Faithful port of the browser63 * `vault.ts` semantics that matter for correctness:64 *65 *  - Two-slot at rest: slot A is the real (encrypted) vault, slot B a size-matched66 *    noise blob so a fresh install shows two similarly-shaped records.67 *  - Every modifiedAt/deletedAt uses [VaultCrypto.monotonicEntryTimestamp] so a68 *    deletion always wins last-write-wins against an in-flight edit.69 *  - Local writes bump the version counter; sync-applied writes do NOT (so a70 *    sync round never cascades into another outbound sync).71 *  - add/update/delete roll back in-memory state if the disk write fails.72 *  - destroyVault never touches the Pro license (separate store).73 */74@Singleton75class VaultRepository @Inject constructor(76    private val store: VaultStorage,77) {78    private val mutex = Mutex()79    // H-03: lock() and requireUnlocked() cannot take [mutex] from non-suspend80    // callers (ProcessLifecycleOwner, ViewModels, VaultLockTimer). This sync81    // lock guards ONLY the brief read/write of derivedKey/rootKey/entryList so82    // lock() can serialize against an in-flight suspend op without blocking on83    // Argon2id or store I/O. Suspend ops hold [mutex] for their full body and84    // take [stateLock] only around the state-write portions. Acquisition order85    // is always mutex → stateLock.86    private val stateLock = ReentrantLock()87    private val rng = SecureRandom()8889    /**90     * Monotonic session generation.  [lock] advances this before clearing any91     * secret state; work that captured the previous generation is therefore92     * stale even if it is still running its (non-suspending) storage step.93     */94    private var sessionEpoch: Long = 0L9596    private fun nextSessionEpoch(epoch: Long): Long =97        if (epoch == Long.MAX_VALUE) 0L else epoch + 1L9899    /** Test seam for deterministic "lock while waiting to commit" races. */100    @VisibleForTesting101    internal var beforeDurableCommit: () -> Unit = {}102103    /** Test seam after a failed Codex rollback, while the epoch fence is held. */104    @VisibleForTesting105    internal var afterCodexRollback: () -> Unit = {}106107    /**108     * Run [block] with [stateLock] held. Used to fence the small state-write109     * portions of suspend operations against [lock] and [requireUnlocked]110     * racing from another thread.111     */112    private inline fun <T> mutateState(block: () -> T): T {113        stateLock.lock()114        return try { block() } finally { stateLock.unlock() }115    }116117    /** Run a durable commit only while the session generation is still live. */118    private inline fun <T> withEpochCommit(epoch: Long, block: () -> T): T? {119        stateLock.lock()120        return try {121            if (sessionEpoch != epoch) null else block()122        } finally {123            stateLock.unlock()124        }125    }126127    /** Test seam for a caller that must stage work before the epoch fence. */128    @VisibleForTesting129    internal var beforeSessionEpochCommit: () -> Unit = {}130131    /**132     * Test seam for the narrower H-03 race: a suspend mutation has authenticated133     * the session and staged its candidate state, but has not yet entered the134     * epoch-fenced in-memory write. Production callers leave this as a no-op.135     */136    @VisibleForTesting137    internal var beforeSessionStateMutation: () -> Unit = {}138139    /**140     * Run an external session-bound commit while the repository's epoch fence is141     * held. The callback is deliberately non-suspending: [lock] cannot advance142     * the epoch until the whole external batch has reached its linearization143     * point.144     */145    internal fun <T> withSessionEpochCommit(epoch: Long, block: () -> T): T? {146        beforeSessionEpochCommit()147        return withEpochCommit(epoch, block)148    }149150    private fun currentEpoch(): Long = mutateState { sessionEpoch }151152    private inline fun <T> mutateIfCurrentEpoch(epoch: Long, block: () -> T): T? =153        mutateState { if (sessionEpoch == epoch) block() else null }154155    /** Invoke the pre-state-write seam, then linearize only in the same epoch. */156    private inline fun <T> mutateCurrentSession(epoch: Long, block: () -> T): T? {157        beforeSessionStateMutation()158        return mutateIfCurrentEpoch(epoch, block)159    }160161    private data class PersistSnapshot(162        val epoch: Long,163        val key: ByteArray,164        val payload: VaultPayload,165        val decoy: Boolean,166    )167168    /** Copy all session material while fenced; callers own and must zero [key]. */169    private fun snapshotForPersist(expectedEpoch: Long? = null): PersistSnapshot? = mutateState {170        if (expectedEpoch != null && sessionEpoch != expectedEpoch) return@mutateState null171        val liveKey = derivedKey ?: return@mutateState null172        PersistSnapshot(173            epoch = sessionEpoch,174            key = liveKey.copyOf(),175            payload = currentPayloadLocked(),176            decoy = decoyMode,177        )178    }179180    private var derivedKey: ByteArray? = null181    private var rootKey: ByteArray? = null182    private var entryList: MutableList<VaultEntry> = mutableListOf()183    private var authenticatedDuressConfigured: Boolean = false184    private var recoveryWordHash: String? = null185    private var recoveryWordsSet: Boolean = false186    /** True when an authenticated vault payload is available for local reads. */187    private var sessionDataAvailable: Boolean = false188    /** True while a decoy (duress) session is active — persistence targets the decoy slot. */189    private var decoyMode: Boolean = false190191    private val _isUnlocked = MutableStateFlow(false)192    val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()193194    private val _duressConfigured = MutableStateFlow(false)195    /** Authenticated payload state; never loaded from plaintext settings. */196    val duressConfigured: StateFlow<Boolean> = _duressConfigured.asStateFlow()197198199    /**200     * UI-only gate for sync-retained background mode. The vault stays unlocked201     * in memory (sync can proceed) but the UI shows the lock screen until the202     * user authenticates on resume. Cleared by a full [lock] or an explicit203     * [clearUiGate] from the lock screen.204     */205    private val _uiGateLocked = MutableStateFlow(false)206    val uiGateLocked: StateFlow<Boolean> = _uiGateLocked.asStateFlow()207208    private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())209    /** Active (non-deleted) entryList. */210    val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()211212    // Settings live in plain prefs, not inside the sealed vault — they hold no213    // secrets — so they are readable before unlock. Loading them here keeps the214    // lock screen at the user's chosen appearance instead of the defaults, which215    // otherwise snap to the real values the moment they authenticate.216    private val _settings = MutableStateFlow(store.loadSettings())217    val settings: StateFlow<VaultSettings> = _settings.asStateFlow()218219    /** Clear every in-memory session field while [stateLock] is held. */220    private fun clearSessionStateLocked() {221        derivedKey?.let(VaultCrypto::zero)222        rootKey?.let(VaultCrypto::zero)223        derivedKey = null224        rootKey = null225        entryList = mutableListOf()226        authenticatedDuressConfigured = false227        _duressConfigured.value = false228        recoveryWordHash = null229        recoveryWordsSet = false230        sessionDataAvailable = false231        decoyMode = false232        _settings.value = store.loadSettings()233        _entries.value = emptyList()234        _isUnlocked.value = false235    }236237    fun hasVault(): Boolean = store.hasVault()238239    // ---- Codex (printed paper backup) -------------------------------------240241    /**242     * The at-rest slot pair as base64 JSON `{"a": <StoredVault>, "b": <StoredVault>}` — the243     * Codex payload's vaultBlob. "b" is the duress slot (matching the browser's244     * A/B naming where slot B is the duress decoy); the noise slot is local-only245     * and never crosses devices. Restorable on any device that has the master246     * password. Null when no vault exists.247     */248    fun codexVaultBlobBase64(): String? {249        val slotA = store.loadSlotA() ?: return null250        // H-04: duress slot is always present after createVault (real or fake),251        // so the wrapper can rely on it being loadable.252        val slotD = store.loadDecoySlot() ?: return null253        val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)},"b":${VaultCodec.encodeSlot(slotD)}}"""254        return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))255    }256257    /**258     * Replace the local vault from a Codex blob, then unlock with [password].259     * Writes slot A (and a size-matched noise slot B) before unlocking so the260     * restored vault is at rest exactly as a freshly-created one would be.261     */262    /** A slot is stored either as a JSON string (browser) or inline object (Android). */263    private fun JsonElement?.asSlotJson(): String? = when {264        this == null || this is JsonNull -> null265        this is JsonPrimitive && isString -> content266        else -> toString()267    }268269    suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {270        val expectedEpoch = currentEpoch()271        var candidateKey: ByteArray? = null272        var plaintext: ByteArray? = null273        return try {274            val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)275            // Parsed as JSON, not matched with a regex. The wrapper is276            // `{ "a": <slot>, "b": <slot|null> }` and the browser — which277            // generates most real Codexes — writes each slot as a JSON278            // *string*, with "b" present. A regex looking for an object279            // literal under "a" at the very end of the wrapper matches280            // neither of those, so every browser-generated Codex failed here281            // with "invalid_codex_blob" after decoding perfectly.282            val wrapper = CodexJson.parseToJsonElement(wrapperJson) as? JsonObject283                ?: return UnlockResult.Error("invalid_codex_blob")284            val slotJson = wrapper["a"].asSlotJson() ?: return UnlockResult.Error("invalid_codex_blob")285            // A Codex printed from the browser carries a browser-shaped slot,286            // which is the common case — most Codexes are printed there. It is287            // translated to Android's shape (see BrowserSlot) rather than288            // rejected. A translation failure is a wrong password, not a bad289            // blob: the codes decoded fine, the password just didn't open them.290            val slotA = VaultCodec.decodeSlot(slotJson)291                ?: BrowserSlot.parse(slotJson)?.let {292                    BrowserSlot.toAndroidSlot(it, password) ?: return UnlockResult.WrongPassword293                }294                ?: return UnlockResult.Error("invalid_codex_blob")295            // C-01: authenticate the candidate ENTIRELY in memory before touching296            // storage. VaultCodec.decodeSlot is structural — an Android-shaped297            // Codex parses under ANY password — so writing slot A first and298            // unlocking afterwards destroyed the device's existing vault every299            // time the user mistyped the password.300            candidateKey = VaultCrypto.deriveKey(password, unb64(slotA.salt))301            plaintext = decryptSlotABlob(slotA, candidateKey)302            // LV-1: a Codex printed from a vault sealed before NFC normalization303            // opens only under the raw password bytes. unlockLocked used to supply304            // this fallback; authenticating up front here has to keep it, or those305            // Codexes become unrestorable.306            if (plaintext == null && password != Normalizer.normalize(password, Normalizer.Form.NFC)) {307                VaultCrypto.zero(candidateKey)308                candidateKey = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))309                plaintext = decryptSlotABlob(slotA, candidateKey)310            }311            if (plaintext == null) return UnlockResult.WrongPassword312            val payload = try {313                VaultCodec.decode(plaintext)314            } catch (_: Exception) {315                return UnlockResult.Error("invalid_codex_blob")316            }317318            val priorA = store.loadSlotA()319            val priorB = store.loadSlotB()320            val priorD = store.loadDecoySlot()321            // Carry the real duress slot across when the Codex has one — the322            // browser writes "b" as its duress-shaped slot, and dropping it323            // here would silently destroy a configured decoy.324            // H-04: write browser B into the duress slot (not the noise slot),325            // translating browser-shaped slots to Android's StoredVault shape.326            val codexDuressJson = wrapper["b"].asSlotJson()327            val codexDuress: StoredVault? = codexDuressJson?.let {328                VaultCodec.decodeSlot(it) ?: BrowserSlot.parse(it)?.let { b ->329                    // H-04: pass-through — the browser duress slot is sealed330                    // under the duress passphrase, not the main password. Trying331                    // to decrypt with the slot-A password fails the GCM tag and332                    // silently drops a real decoy. Re-encode the browser hex333                    // fields as Android base64 salt/blob so tryUnlockDuress can334                    // still open it with the duress passphrase.335                    browserDuressPassthrough(b)336                }337            }338339            beforeDurableCommit()340            val committed = runCatching {341                withEpochCommit(expectedEpoch) {342                    try {343                        // Keep every slot write, including the inverse, under the344                        // same epoch fence. Releasing stateLock after a partial345                        // write and reacquiring it for rollback lets lock() advance346                        // the epoch in between and strand the incoming slot A.347                        if (!store.writeSlotA(slotA)) throw java.io.IOException("slot_a_commit_failed")348                        // Noise slot is always size-matched to slot A — local-only,349                        // never written from a Codex.350                        if (!writeMatchingNoiseSlotB(slotA)) throw IllegalStateException("noise_slot_commit_failed")351                        // H-04: duress slot always present; real one from the Codex or352                        // a fake the size of slot A.353                        val duressOk = if (codexDuress != null) {354                            store.writeDecoySlot(codexDuress)355                        } else {356                            writeFakeDuressSlot(slotA)357                        }358                        if (!duressOk) throw IllegalStateException("duress_slot_commit_failed")359                        store.stampLocalMutation()360                        true361                    } catch (_: Exception) {362                        reportRollbackFailures(rollbackRestoreLocked(priorA, priorB, priorD))363                        // Keep the fence held through the final rollback364                        // observation. A concurrent lock() may queue here, but365                        // cannot invalidate the restored A/B/D triad.366                        afterCodexRollback()367                        false368                    }369                } ?: false370            }.getOrDefault(false)371            if (!committed) {372                return UnlockResult.Error("storage_write_failed")373            }374375            val ownedKey = candidateKey!!376            candidateKey = null // the session owns the key from here on377            adoptSlotA(ownedKey, payload, expectedEpoch)378        } catch (e: Exception) {379            // A raw kotlinx parse error ("Unexpected JSON token at offset N")380            // reaching the user says nothing about WHICH json failed — the381            // wrapper, or the payload decrypted out of it. Codex screens are382            // FLAG_SECURE so this can't be screenshotted either. Debug builds383            // log the structure around the failure; alphanumerics are masked so384            // no ciphertext or vault content lands in a log.385            if (BuildConfig.DEBUG) Log.w("PeachCodex", codexFailureShape(vaultBlobBase64, e))386            UnlockResult.Error(e.message ?: "restore_failed")387        } finally {388            plaintext?.let(VaultCrypto::zero)389            candidateKey?.let(VaultCrypto::zero)390        }391    }392393    /** Slot-A plaintext under [key], or null when the GCM tag fails (wrong password). */394    private fun decryptSlotABlob(slot: StoredVault, key: ByteArray): ByteArray? =395        runCatching { VaultCrypto.decrypt(unb64(slot.blob), key, VaultCrypto.AAD_SLOT_A) }.getOrNull()396397    /**398     * Undo a partially-committed Codex restore while [stateLock] is already held.399     * Every step is attempted independently so one failure cannot strand the400     * others. Callers that need epoch validation must enter through401     * [withEpochCommit] first; this helper deliberately does not reacquire the402     * lock, avoiding a reentrant gap between a failed write and its inverse.403     * With no prior vault the accurate inverse is having none at all, rather404     * than a half-written slot A that [hasVault] would report as a real vault.405     */406    private fun rollbackRestoreLocked(407        priorA: StoredVault?,408        priorB: String?,409        priorD: StoredVault? = null,410    ): List<String> {411        val failures = mutableListOf<String>()412        if (priorA == null) {413            runCatching { store.clearVault() }.onFailure { failures += "clearVault: $it" }414        } else {415            runCatching { if (!store.writeSlotA(priorA)) failures += "writeSlotA returned false" }416                .onFailure { failures += "writeSlotA: $it" }417            if (priorB != null) {418                runCatching { if (!store.writeSlotB(priorB)) failures += "writeSlotB returned false" }419                    .onFailure { failures += "writeSlotB: $it" }420            }421            // H-04: restore the prior duress slot — a half-committed restore that422            // left the duress record on the Codex side and slot A on the prior423            // side would put the at-rest pair in a state that never existed.424            if (priorD != null) {425                runCatching { if (!store.writeDecoySlot(priorD)) failures += "writeDecoySlot returned false" }426                    .onFailure { failures += "writeDecoySlot: $it" }427            } else {428                runCatching { store.clearDecoySlot() }.onFailure { failures += "clearDecoySlot: $it" }429            }430        }431        return failures432    }433434    private fun reportRollbackFailures(failures: List<String>) {435        // Log is a throwing stub off-device, and a failed log must never mask436        // the rollback result the caller is about to report.437        if (failures.isNotEmpty()) runCatching { Log.w("PeachCodex", "codex rollback incomplete: $failures") }438    }439440    /** Debug-only: structure of a failed Codex restore, with content masked. */441    private fun codexFailureShape(vaultBlobBase64: String, e: Exception): String = runCatching {442        val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)443        val offset = Regex("offset (\\d+)").find(e.message.orEmpty())?.groupValues?.get(1)?.toIntOrNull()444        val window = offset?.let {445            val from = (it - 40).coerceAtLeast(0)446            val to = (it + 40).coerceAtMost(wrapperJson.length)447            wrapperJson.substring(from, to).replace(Regex("[A-Za-z0-9+/=_-]"), "x")448        }449        val wrapper = runCatching { CodexJson.parseToJsonElement(wrapperJson) as? JsonObject }.getOrNull()450        val slot = wrapper?.get("a")451        buildString {452            append("codex restore failed: ").append(e::class.simpleName).append(": ").append(e.message)453            append(" | blobBase64=").append(vaultBlobBase64.length)454            append(" wrapperChars=").append(wrapperJson.length)455            append(" wrapperParses=").append(wrapper != null)456            append(" keys=").append(wrapper?.keys)457            append(" slotAKind=").append(458                when {459                    slot == null -> "absent"460                    slot is JsonPrimitive && slot.isString -> "string"461                    slot is JsonObject -> "object:" + slot.keys462                    else -> slot::class.simpleName463                },464            )465            if (window != null) append(" masked@").append(offset).append("=").append(window)466        }467    }.getOrElse { "codex restore failed: ${e.message} (shape unavailable: $it)" }468469    suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {470        val expectedEpoch = currentEpoch()471        var key: ByteArray? = null472        return try {473            val salt = VaultCrypto.generateSalt()474            key = VaultCrypto.deriveKey(password, salt)475            if (mutateIfCurrentEpoch(expectedEpoch) {476                entryList = mutableListOf()477                authenticatedDuressConfigured = false478                _duressConfigured.value = false479                recoveryWordHash = null480                recoveryWordsSet = false481                decoyMode = false482                sessionDataAvailable = false483                rootKey = generateRecoverableRootKey()484            } == null) return CreateVaultResult.Error("stale_create")485            // M-04: the fields above have to be live before sealSlotA, since it486            // seals currentPayload(). That stages a root key the session would487            // otherwise keep after a failed create — [lock] discards the whole488            // staged session on every non-success exit below.489            val slotA = sealSlotA(key!!, salt)490            // P1-3 (codex): every later step must roll the slot pair back if it491            // fails — leaving a half-built vault is worse than refusing to make it.492            beforeDurableCommit()493            val created = withEpochCommit(expectedEpoch) {494                if (!store.writeSlotA(slotA)) return@withEpochCommit false495                try {496                    if (!writeMatchingNoiseSlotB(slotA)) throw java.io.IOException("noise_slot_b_commit_failed")497                    // H-04: duress slot must be present from the start so its498                    // existence on disk is independent of authenticatedDuressConfigured.499                    if (!writeFakeDuressSlot(slotA)) throw java.io.IOException("duress_slot_commit_failed")500                    store.stampLocalMutation()501                    if (!store.writeSettings(_settings.value)) throw java.io.IOException("settings_commit_failed")502                    true503                } catch (_: Exception) {504                    // Half-built vault on disk is worse than no vault — refuse to505                    // create if any step past slot A fails.506                    store.clearVault()507                    false508                }509            } ?: false510            if (!created) {511                lock()512                return CreateVaultResult.Error("storage_write_failed")513            }514            val sessionKey = key ?: return CreateVaultResult.Error("create_key_missing")515            if (mutateIfCurrentEpoch(expectedEpoch) {516                derivedKey = sessionKey517                key = null518                publish()519                _isUnlocked.value = true520                sessionDataAvailable = true521                sessionEpoch = nextSessionEpoch(sessionEpoch)522            } == null) return CreateVaultResult.Error("stale_create")523            CreateVaultResult.Success524        } catch (e: Exception) {525            lock()526            CreateVaultResult.Error(e.message ?: "create_failed")527        } finally {528            key?.let(VaultCrypto::zero)529        }530    }531532    suspend fun createVaultFromRootKey(password: String, rootKeyHex: String): AdoptVaultResult = mutex.withLock {533        val expectedEpoch = currentEpoch()534        if (password.isEmpty()) return AdoptVaultResult.Error("ADOPT_INVALID_PASSWORD")535        if (store.hasVault()) return AdoptVaultResult.Error("ADOPT_VAULT_ALREADY_EXISTS")536        if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {537            return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars")538        }539        var adoptedRootKey: ByteArray? = null540        var nextDerivedKey: ByteArray? = null541        var sessionRootKey: ByteArray? = null542        return try {543            adoptedRootKey = hexToRootKey(rootKeyHex)544            if (adoptedRootKey.size != VaultCrypto.KEY_SIZE) {545                return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes")546            }547            val vaultId = com.peachpasswords.sync.computeVaultId(adoptedRootKey)548            val salt = VaultCrypto.generateSalt()549            nextDerivedKey = VaultCrypto.deriveKey(password, salt)550            sessionRootKey = adoptedRootKey.copyOf()551            val payload = VaultPayload(552                entries = emptyList(),553                duressConfigured = false,554                rootKeyB64 = b64(sessionRootKey),555                recoveryWordHash = null,556                recoveryWordsSet = false,557            )558            val plaintext = VaultCodec.encode(payload)559            val blob = try {560                b64(VaultCrypto.encrypt(plaintext, nextDerivedKey, VaultCrypto.AAD_SLOT_A))561            } finally {562                VaultCrypto.zero(plaintext)563            }564            val slotA = StoredVault(version = 1, salt = b64(salt), blob = blob)565            // P1-3 (codex): same partial-commit guard as createVault — any failure566            // past slot A wipes the half-built vault and refuses adoption.567            beforeDurableCommit()568            val created = withEpochCommit(expectedEpoch) {569                if (!store.writeSlotA(slotA)) return@withEpochCommit false570                try {571                    if (!writeMatchingNoiseSlotB(slotA)) throw java.io.IOException("noise_slot_b_commit_failed")572                    // H-04: duress slot must be present from the start so its573                    // existence on disk is independent of authenticatedDuressConfigured.574                    if (!writeFakeDuressSlot(slotA)) throw java.io.IOException("duress_slot_commit_failed")575                    store.stampLocalMutation()576                    if (!store.writeSettings(_settings.value)) throw java.io.IOException("settings_commit_failed")577                    true578                } catch (_: Exception) {579                    store.clearVault()580                    false581                }582            } ?: false583            if (!created) return AdoptVaultResult.Error("storage_write_failed")584585            val adopted = mutateIfCurrentEpoch(expectedEpoch) {586                val previousDerivedKey = derivedKey587                val previousRootKey = rootKey588                derivedKey = nextDerivedKey589                rootKey = sessionRootKey590                nextDerivedKey = null591                sessionRootKey = null592                entryList = mutableListOf()593                authenticatedDuressConfigured = false594                _duressConfigured.value = false595                recoveryWordHash = null596                recoveryWordsSet = false597                decoyMode = false598                sessionDataAvailable = true599                publish()600                _isUnlocked.value = true601                sessionEpoch = nextSessionEpoch(sessionEpoch)602                previousDerivedKey to previousRootKey603            }604            if (adopted == null) return AdoptVaultResult.Error("stale_adoption")605            val (previousDerivedKey, previousRootKey) = adopted606            previousDerivedKey?.let(VaultCrypto::zero)607            previousRootKey?.let(VaultCrypto::zero)608            // Write the recovery escrow so the forgot-password flow works on609            // this device. The words are deterministic from the root key and610            // were already confirmed on the source device.611            runCatching {612                val words = rootKeyToWords(rootKey!!)613                val escrow = buildRecoveryEscrow(words)614                val rkEscrow = buildRootKeyEscrow(words)615                if (escrow != null || rkEscrow != null) {616                    val prior = store.loadSlotA()617                    if (prior != null) {618                        store.writeSlotA(prior.copy(619                            recoveryEscrow = escrow ?: prior.recoveryEscrow,620                            rootKeyEscrow = rkEscrow ?: prior.rootKeyEscrow,621                        ))622                    }623                    mutateState {624                        recoveryWordHash = recoveryWordsHash(words)625                        recoveryWordsSet = true626                    }627                }628            }629            AdoptVaultResult.Success(vaultId)630        } catch (e: Exception) {631            AdoptVaultResult.Error(e.message ?: "adoption_create_failed")632        } finally {633            adoptedRootKey?.let(VaultCrypto::zero)634            nextDerivedKey?.let(VaultCrypto::zero)635            sessionRootKey?.let(VaultCrypto::zero)636        }637    }638639    suspend fun unlock(password: String): UnlockResult = mutex.withLock {640        val result = unlockLocked(password, currentEpoch())641        if (result is UnlockResult.Success) ensureRecoveryEscrow()642        result643    }644645    /** Unlock body without acquiring the mutex — callers must already hold it. */646    private fun unlockLocked(password: String, expectedEpoch: Long): UnlockResult {647        val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")648        val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))649        val payload = try {650            val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A)651            try {652                VaultCodec.decode(plaintext)653            } finally {654                VaultCrypto.zero(plaintext)655            }656        } catch (_: Exception) {657            VaultCrypto.zero(key)658            // LV-1: a vault sealed before NFC normalization with a non-NFC659            // password derives a different key now. If the supplied password is660            // not already in NFC form, retry with the raw (un-normalized) bytes.661            if (password != Normalizer.normalize(password, Normalizer.Form.NFC)) {662                val legacy = tryLegacyRawUnlock(password, slotA, expectedEpoch)663                if (legacy != null) return legacy664            }665            return UnlockResult.WrongPassword666        }667        return adoptSlotA(key, payload, expectedEpoch)668    }669670    /**671     * LV-1 legacy fallback: unlock a slot-A vault that was sealed under the raw672     * (un-normalized) password bytes. On success the slot is HEALED — re-sealed673     * under the NFC-normalized key — so every future unlock takes the normal674     * path. Returns null when the raw key also fails (genuinely wrong password)675     * OR when any step of the heal commits fails (the original slot A is restored676     * so disk and session stay aligned).677     */678    private fun tryLegacyRawUnlock(password: String, slotA: StoredVault, expectedEpoch: Long): UnlockResult? {679        var rawKey: ByteArray? = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))680        var newKey: ByteArray? = null681        return try {682            val payload = try {683                val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), rawKey!!, VaultCrypto.AAD_SLOT_A)684                try {685                    VaultCodec.decode(plaintext)686                } finally {687                    VaultCrypto.zero(plaintext)688                }689            } catch (_: Exception) {690                return null691            }692            // Heal: re-seal slot A under the NFC key (mirrors changePassword's693            // re-seal). Escrows carry forward unchanged — only the wrapping rotates.694            val newSalt = VaultCrypto.generateSalt()695            newKey = VaultCrypto.deriveKey(password, newSalt)696            val plaintext = VaultCodec.encode(payload)697            val blob = try {698                b64(VaultCrypto.encrypt(plaintext, newKey!!, VaultCrypto.AAD_SLOT_A))699            } finally {700                VaultCrypto.zero(plaintext)701            }702            val next = StoredVault(703                version = slotA.version,704                salt = b64(newSalt),705                blob = blob,706                recoveryEscrow = slotA.recoveryEscrow,707                rootKeyEscrow = slotA.rootKeyEscrow,708            )709            // P1-1/P1-3/P1-2 (codex): any failure of writeSlotA, writeMatchingNoiseSlotB,710            // or stampLocalMutation must restore the prior slot A AND slot B so disk711            // and the eventual session key never disagree on the wrapping.712            val priorB = store.loadSlotB()713            beforeDurableCommit()714            val healed = withEpochCommit(expectedEpoch) {715                if (!store.writeSlotA(next)) {716                    false717                } else try {718                    if (!writeMatchingNoiseSlotB(next)) {719                        runCatching { store.writeSlotA(slotA) }720                        if (priorB != null) runCatching { store.writeSlotB(priorB) }721                        false722                    } else if (!writeCompanionDuressSlot(next)) {723                        runCatching { store.writeSlotA(slotA) }724                        if (priorB != null) runCatching { store.writeSlotB(priorB) }725                        false726                    } else {727                        store.stampLocalMutation()728                        true729                    }730                } catch (_: Exception) {731                    runCatching { store.writeSlotA(slotA) }732                    if (priorB != null) runCatching { store.writeSlotB(priorB) }733                    false734                }735            } ?: false736            if (healed) {737                VaultCrypto.zero(rawKey!!)738                rawKey = null739                val result = adoptSlotA(newKey!!, payload, expectedEpoch) // session key now matches the re-sealed slot740                newKey = null741                result742            } else {743                VaultCrypto.zero(newKey!!)744                newKey = null745                val result = adoptSlotA(rawKey!!, payload, expectedEpoch) // heal failed — keep using the raw key746                rawKey = null747                result748            }749        } finally {750            // Cover codec, encryption, storage, and stale-epoch failures before751            // either candidate key can be transferred into the live session.752            rawKey?.let(VaultCrypto::zero)753            newKey?.let(VaultCrypto::zero)754        }755    }756757    /** Adopt a derived slot-A [key]/[payload] as the live (real-vault) session. */758    private fun adoptSlotA(key: ByteArray, payload: VaultPayload, expectedEpoch: Long): UnlockResult {759        return try {760            // M-04: ensureRootKey and autoPurgeExpiredTrash both persist, so they761            // can throw after the fields above are live. There is no prior session762            // worth restoring — adoption has already replaced it — so a failed763            // adoption discards everything rather than leaving entries and keys764            // resident behind _isUnlocked=false.765            val adopted = mutateIfCurrentEpoch(expectedEpoch) {766                derivedKey = key767                decoyMode = false768                entryList = payload.entries.toMutableList()769                authenticatedDuressConfigured = payload.duressConfigured770                _duressConfigured.value = payload.duressConfigured771                recoveryWordHash = payload.recoveryWordHash772                recoveryWordsSet = payload.recoveryWordsSet773                sessionDataAvailable = true774                _settings.value = store.loadSettings()775                ensureRootKey(payload)776                autoPurgeExpiredTrash()777                consolidatePasskeyEntries()778                publish()779                _isUnlocked.value = true780                // A successful adoption starts a new generation. A sibling781                // SlotAUnlock captured in the prior epoch will fail closed at782                // the next commit instead of replacing this session.783                sessionEpoch = nextSessionEpoch(sessionEpoch)784            }785            if (adopted == null) {786                VaultCrypto.zero(key)787                UnlockResult.Error("stale_unlock")788            } else {789                UnlockResult.Success790            }791        } catch (e: Exception) {792            // Do not call lock() here: a concurrent newer session may already793            // own this repository. Only invalidate the failed epoch's fields.794            mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }795            VaultCrypto.zero(key)796            UnlockResult.Error(e.message ?: "unlock_failed")797        }798    }799800    // ---- Constant-time unlock (MF-5) --------------------------------------801802    /**803     * A slot-A unlock that has been derived but not yet adopted. Holds the live804     * Argon2id key and decoded payload so the caller can derive several candidates805     * concurrently and commit only the winner. The key is owned by this token until806     * [commitSlotAUnlock] adopts it or [discardSlotAUnlock] zeroes it.807     */808    class SlotAUnlock internal constructor(809        key: ByteArray,810        internal val payload: VaultPayload,811        internal val epoch: Long,812    ) {813        private var ownedKey: ByteArray? = key814        private var consumed = false815816        /** Transfer the key exactly once to the adopter. */817        internal fun takeKey(): ByteArray? = synchronized(this) {818            if (consumed) return@synchronized null819            consumed = true820            ownedKey.also { ownedKey = null }821        }822823        /** Discard an uncommitted token without touching a transferred key. */824        internal fun discard() = synchronized(this) {825            if (consumed) return@synchronized826            consumed = true827            ownedKey?.let(VaultCrypto::zero)828            ownedKey = null829        }830    }831832    /**833     * Derive the slot-A key and decrypt its payload WITHOUT mutating session state.834     * Pure computation (no mutex), so it can run concurrently with other candidate835     * derivations before the caller decides which to commit (MF-5). Returns null on836     * no-vault or wrong password (the derived key is zeroed on a tag mismatch).837     */838    fun tryUnlockSlotA(password: String): SlotAUnlock? {839        val epoch = currentEpoch()840        val slotA = store.loadSlotA() ?: return null841        val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))842        return try {843            val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A)844            val payload = try {845                VaultCodec.decode(plaintext)846            } finally {847                VaultCrypto.zero(plaintext)848            }849            SlotAUnlock(key, payload, epoch)850        } catch (_: Exception) {851            VaultCrypto.zero(key)852            null853        }854    }855856    /** Adopt a previously-derived [SlotAUnlock] as the live session. */857    suspend fun commitSlotAUnlock(unlock: SlotAUnlock): UnlockResult = mutex.withLock {858        val key = unlock.takeKey() ?: return@withLock UnlockResult.Error("unlock_token_consumed")859        adoptSlotA(key, unlock.payload, unlock.epoch)860    }861862    /** Zero a derived [SlotAUnlock] that will not be adopted. */863    fun discardSlotAUnlock(unlock: SlotAUnlock) = unlock.discard()864865    // ---- Duress slot B (MF-6) ---------------------------------------------866867    /**868     * A duress-slot (slot B) unlock derived but not yet adopted. Holds the live key869     * and decoded decoy payload so it can be derived concurrently with slot A and870     * only committed if the duress passphrase was the one entered (MF-5/MF-6).871     */872    class DuressUnlock internal constructor(873        key: ByteArray,874        internal val payload: VaultPayload,875        internal val epoch: Long,876    ) {877        private var ownedKey: ByteArray? = key878        private var consumed = false879880        internal fun takeKey(): ByteArray? = synchronized(this) {881            if (consumed) return@synchronized null882            consumed = true883            ownedKey.also { ownedKey = null }884        }885886        internal fun discard() = synchronized(this) {887            if (consumed) return@synchronized888            consumed = true889            ownedKey?.let(VaultCrypto::zero)890            ownedKey = null891        }892    }893894    /**895     * Try to decrypt the duress slot (slot B) with [password] WITHOUT mutating the896     * session. Success means the entered password is the duress passphrase that keys897     * slot B — indistinguishable from the real slot A at the lock screen. Pure898     * computation (no mutex), safe to run concurrently with [tryUnlockSlotA].899     * Returns null when no duress slot exists or the password is not the duress one.900     */901    fun tryUnlockDuress(password: String): DuressUnlock? {902        val epoch = currentEpoch()903        val slot = store.loadDecoySlot() ?: return null904        val key = VaultCrypto.deriveKey(password, unb64(slot.salt))905        return try {906            val plaintext = VaultCrypto.decrypt(unb64(slot.blob), key, VaultCrypto.AAD_SLOT_A)907            val payload = try {908                VaultCodec.decode(plaintext)909            } finally {910                VaultCrypto.zero(plaintext)911            }912            DuressUnlock(key, payload, epoch)913        } catch (_: Exception) {914            VaultCrypto.zero(key)915            null916        }917    }918919    /** Adopt a derived [DuressUnlock] as a live decoy session (edits persist to slot B only). */920    suspend fun commitDuressUnlock(unlock: DuressUnlock): UnlockResult = mutex.withLock {921        val key = unlock.takeKey() ?: return@withLock UnlockResult.Error("unlock_token_consumed")922        if (currentEpoch() != unlock.epoch) {923            VaultCrypto.zero(key)924            return@withLock UnlockResult.Error("stale_unlock")925        }926        return try {927            val adopted = mutateIfCurrentEpoch(unlock.epoch) {928                derivedKey = key929                decoyMode = true930                entryList = unlock.payload.entries.toMutableList()931                authenticatedDuressConfigured = false932                _duressConfigured.value = false933                recoveryWordHash = unlock.payload.recoveryWordHash934                recoveryWordsSet = unlock.payload.recoveryWordsSet935                sessionDataAvailable = true936                rootKey = if (unlock.payload.rootKeyB64.isNotBlank()) unb64(unlock.payload.rootKeyB64)937                          else VaultCrypto.generateRootKey()938                _settings.value = store.loadSettings()939                publish()940                _isUnlocked.value = true941                sessionEpoch = nextSessionEpoch(sessionEpoch)942            }943            if (adopted == null) {944                VaultCrypto.zero(key)945                UnlockResult.Error("stale_unlock")946            } else {947                UnlockResult.Success948            }949        } catch (e: Exception) {950            // A payload/root/settings failure can occur after the candidate key951            // has been assigned to derivedKey. Tear down only this epoch so a952            // newer session is not disturbed, and scrub the token reference on953            // every error path.954            mutateIfCurrentEpoch(unlock.epoch) { clearSessionStateLocked() }955            VaultCrypto.zero(key)956            UnlockResult.Error(e.message ?: "decoy_unlock_failed")957        }958    }959960    /** Zero a derived [DuressUnlock] that will not be adopted. */961    fun discardDuressUnlock(unlock: DuressUnlock) = unlock.discard()962963    /**964     * Configure the duress vault (MF-6): seal a fresh, empty decoy payload under an965     * Argon2id key derived from [duressPassphrase] (fresh salt) into slot B. The966     * passphrase is never stored — only its ability to decrypt slot B proves it.967     * Requires the real vault to be unlocked and not itself a decoy session.968     */969    suspend fun setDuressPassphrase(duressPassphrase: String): Boolean = mutex.withLock {970        // H-03: read derivedKey/decoyMode atomically with any concurrent lock().971        val expectedEpoch = mutateState {972            if (derivedKey != null && !decoyMode) sessionEpoch else null973        } ?: return false974        // Reject a duress passphrase that also opens the real vault: it would make the975        // lock screen ambiguous (both slots would decrypt for the same input).976        tryUnlockSlotA(duressPassphrase)?.let { discardSlotAUnlock(it); return false }977        var key: ByteArray? = null978        var basePlaintext: ByteArray? = null979        return try {980            val salt = VaultCrypto.generateSalt()981            key = VaultCrypto.deriveKey(duressPassphrase, salt)982            // An empty decoy vault with its own fresh sync root key — nothing real leaks.983            val decoyRoot = VaultCrypto.generateRootKey()984            val decoyRootB64 = try { b64(decoyRoot) } finally { VaultCrypto.zero(decoyRoot) }985            val decoyPayload = VaultPayload(entries = emptyList(), rootKeyB64 = decoyRootB64)986            basePlaintext = VaultCodec.encode(decoyPayload)987            // H-04: pad the duress plaintext to slot A's ciphertext length so the988            // duress blob matches slot A's blob on disk. VaultCodec.decode strips989            // trailing NULs, so the extra padding survives encrypt but never990            // reaches the JSON parser.991            // This decoy plaintext length is frozen from here on: re-sealing it992            // on later growth would need the duress passphrase, which is never993            // retained. VaultStore compensates by re-padding the two slot994            // RECORDS to the longer of the two on every write, so the frozen995            // blob no longer shows up as a length difference at rest.996            val slotA = store.loadSlotA()997            val targetSize = slotA?.let(::matchingCiphertextLength) ?: 0998            val plaintext = if (targetSize > basePlaintext!!.size) basePlaintext!!.copyOf(targetSize) else basePlaintext!!999            val blob = try {1000                b64(VaultCrypto.encrypt(plaintext, key!!, VaultCrypto.AAD_SLOT_A))1001            } finally {1002                VaultCrypto.zero(plaintext)1003                // Padding creates a second array; scrub the original encoded1004                // payload too rather than dropping its last reference untouched.1005                if (plaintext !== basePlaintext) basePlaintext?.let(VaultCrypto::zero)1006                basePlaintext = null1007                key?.let(VaultCrypto::zero)1008                key = null1009            }1010            beforeDurableCommit()1011            val ok = withEpochCommit(expectedEpoch) {1012                store.writeDecoySlot(StoredVault(version = 1, salt = b64(salt), blob = blob))1013            } ?: false1014            if (ok && mutateIfCurrentEpoch(expectedEpoch) {1015                authenticatedDuressConfigured = true1016                _duressConfigured.value = true1017            } != null) {1018                runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }1019            } else if (ok) {1020                return false1021            }1022            ok1023        } catch (_: Exception) {1024            false1025        } finally {1026            // Cover failures before the encrypt block is entered (for example a1027            // codec/copy exception) as well as any early return after key derivation.1028            key?.let(VaultCrypto::zero)1029            basePlaintext?.let(VaultCrypto::zero)1030        }1031    }103210331034    /**1035     * Export the decoy slot as browser-shaped JSON for adoption snapshots.1036     *1037     * Returns the sealed slot as `{version, salt, nonce, ciphertext, tag}` all1038     * lowercase hex — identical to the browser's `duress_slot` wire format — so1039     * any receiver (browser or Android) can install it via the existing1040     * passthrough. Returns null when duress is not configured, no decoy exists,1041     * or any conversion failure occurs. Never decrypts.1042     */1043    suspend fun exportDuressSlotForAdoption(): String? = mutex.withLock {1044        if (!authenticatedDuressConfigured) return null1045        val slot = store.loadDecoySlot() ?: return null1046        return runCatching { androidDuressSlotToBrowserJson(slot) }.getOrNull()1047    }10481049    /**1050     * Convert an Android [StoredVault] decoy slot to browser-shaped JSON.1051     *1052     * Mirrors the inverse of [installAdoptedDuressSlot]: base64 salt/blob are1053     * split into lowercase hex fields matching [BrowserSlotA]. Intermediate1054     * byte arrays are zeroed in finally.1055     */1056    private fun androidDuressSlotToBrowserJson(slot: StoredVault): String {1057        // Build the wire JSON directly with JsonObject so `version: 1` is ALWAYS1058        // serialized — kotlinx-serialization's encodeDefaults = false would1059        // otherwise omit BrowserSlotA.version (its Kotlin default), and the1060        // browser's hasValidVaultSchema strictly requires `r.version === 1`,1061        // silently dropping the duress slot on Android→browser adoptions.1062        var salt: ByteArray? = null1063        var blob: ByteArray? = null1064        var nonce: ByteArray? = null1065        var ctAndTag: ByteArray? = null1066        var ct: ByteArray? = null1067        var tag: ByteArray? = null1068        try {1069            salt = unb64(slot.salt)1070            blob = unb64(slot.blob)1071            nonce = blob.copyOfRange(0, VaultCrypto.NONCE_SIZE)1072            ctAndTag = blob.copyOfRange(VaultCrypto.NONCE_SIZE, blob.size)1073            ct = ctAndTag.copyOfRange(0, ctAndTag.size - 16)1074            tag = ctAndTag.copyOfRange(ctAndTag.size - 16, ctAndTag.size)1075            val obj = JsonObject(mapOf(1076                "version" to JsonPrimitive(1),1077                "salt" to JsonPrimitive(salt.joinToString("") { "%02x".format(it) }),1078                "nonce" to JsonPrimitive(nonce.joinToString("") { "%02x".format(it) }),1079                "ciphertext" to JsonPrimitive(ct.joinToString("") { "%02x".format(it) }),1080                "tag" to JsonPrimitive(tag.joinToString("") { "%02x".format(it) }),1081            ))1082            return obj.toString()1083        } finally {1084            salt?.let(VaultCrypto::zero)1085            blob?.let(VaultCrypto::zero)1086            nonce?.let(VaultCrypto::zero)1087            ctAndTag?.let(VaultCrypto::zero)1088            ct?.let(VaultCrypto::zero)1089            tag?.let(VaultCrypto::zero)1090        }1091    }10921093    /**1094     * Install a browser-shaped duress slot received through adoption.1095     *1096     * Parses [json] as a [BrowserSlotA], re-encodes it to Android's1097     * [StoredVault] via [browserDuressPassthrough] (no decryption), and1098     * writes the result to the decoy slot. Epoch-fenced like the Codex1099     * restore path so a concurrent lock() cannot strand the write.1100     *1101     * Returns false on invalid input, no live session, or write failure.1102     */1103    suspend fun installAdoptedDuressSlot(json: String): Boolean = mutex.withLock {1104        val b = BrowserSlot.parse(json) ?: return false1105        var stored: StoredVault? = null1106        var salt: ByteArray? = null1107        var nonce: ByteArray? = null1108        var ct: ByteArray? = null1109        var tag: ByteArray? = null1110        var blob: ByteArray? = null1111        try {1112            salt = unhex(b.salt)1113            nonce = unhex(b.nonce)1114            ct = unhex(b.ciphertext)1115            tag = unhex(b.tag)1116            blob = ByteArray(nonce.size + ct.size + tag.size).also {1117                System.arraycopy(nonce, 0, it, 0, nonce.size)1118                System.arraycopy(ct, 0, it, nonce.size, ct.size)1119                System.arraycopy(tag, 0, it, nonce.size + ct.size, tag.size)1120            }1121            stored = StoredVault(version = 1, salt = b64(salt), blob = b64(blob))1122            val expectedEpoch = sessionEpoch1123            beforeDurableCommit()1124            withEpochCommit(expectedEpoch) {1125                store.writeDecoySlot(stored)1126            } ?: false1127        } catch (_: Exception) {1128            false1129        } finally {1130            salt?.let(VaultCrypto::zero)1131            nonce?.let(VaultCrypto::zero)1132            ct?.let(VaultCrypto::zero)1133            tag?.let(VaultCrypto::zero)1134            blob?.let(VaultCrypto::zero)1135        }1136    }11371138    /** Tear down the duress vault: drop slot B and the duress flag on the real payload. */1139    suspend fun clearDuress(): Boolean = mutex.withLock {1140        // H-04: presence-indistinguishable — replace the real decoy with a fake1141        // blob of slot A's size rather than removing the duress record. The1142        // record stays on disk at the same length, so an at-rest observer1143        // cannot tell "duress cleared" from "no duress ever configured".1144        val expectedEpoch = currentEpoch()1145        val replaced = withEpochCommit(expectedEpoch) {1146            store.loadSlotA()?.let { slotA -> runCatching { writeFakeDuressSlot(slotA) }.getOrDefault(false) }1147                ?: runCatching { store.clearDecoySlot(); true }.getOrDefault(false)1148        } ?: false1149        if (!replaced) return@withLock false1150        // H-03: stateLock-fence the derivedKey/decoyMode read AND the1151        // authenticatedDuressConfigured write so a concurrent lock() cannot land between them.1152        if (!isSessionEpochCurrent(expectedEpoch)) return false1153        val shouldClear = mutateIfCurrentEpoch(expectedEpoch) { derivedKey != null && !decoyMode } == true1154        if (shouldClear && mutateIfCurrentEpoch(expectedEpoch) {1155            authenticatedDuressConfigured = false1156            _duressConfigured.value = false1157        } != null) {1158            runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }1159        }1160        true1161    }11621163    /** True for the provider-specific exception used for a valid GCM blob/key mismatch. */1164    private fun isGcmAuthenticationFailure(error: Throwable): Boolean {1165        var current: Throwable? = error1166        while (current != null) {1167            if (current is javax.crypto.AEADBadTagException) return true1168            // Some Android providers expose a GCM tag failure as the parent1169            // BadPaddingException rather than the AEAD-specific subtype.  A1170            // short ciphertext is an IllegalBlockSizeException and therefore1171            // remains an internal/malformed-payload Error below.1172            if (current is javax.crypto.BadPaddingException) return true1173            current = current.cause1174        }1175        return false1176    }11771178    /** Unlock with an already-derived AES-256 key (biometric path). */1179    suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {1180        val expectedEpoch = currentEpoch()1181        val slotA = try {1182            store.loadSlotA()1183        } catch (_: Exception) {1184            return@withLock UnlockResult.Error("unlock_key_storage_failed")1185        } ?: return@withLock UnlockResult.Error("no_vault")1186        // Keep the caller-owned key separate from the staged session key. The1187        // biometric caller always zeroes its input in a finally block; adoption1188        // must therefore own a copy and use the same all-or-nothing path as a1189        // password unlock rather than publishing a partially decoded session.1190        var stagedKey: ByteArray? = key.copyOf()1191        return try {1192            val encrypted = try {1193                unb64(slotA.blob)1194            } catch (_: Exception) {1195                return@withLock UnlockResult.Error("invalid_vault_blob")1196            }1197            // A GCM record must include nonce + authentication tag.  Providers1198            // differ on whether a shorter record is reported as BadPadding or1199            // AEADBadTag; reject it before decrypt so malformed storage cannot be1200            // misreported as a user-entered wrong key.1201            if (encrypted.size < VaultCrypto.NONCE_SIZE + (VaultCrypto.TAG_LENGTH_BITS / 8)) {1202                return@withLock UnlockResult.Error("invalid_vault_blob")1203            }1204            val plaintext = try {1205                VaultCrypto.decrypt(encrypted, stagedKey!!, VaultCrypto.AAD_SLOT_A)1206            } catch (e: Exception) {1207                if (isGcmAuthenticationFailure(e)) {1208                    return@withLock UnlockResult.WrongPassword1209                }1210                return@withLock UnlockResult.Error("unlock_key_decrypt_failed")1211            }1212            val payload = try {1213                VaultCodec.decode(plaintext)1214            } catch (_: Exception) {1215                return@withLock UnlockResult.Error("invalid_vault_payload")1216            } finally {1217                VaultCrypto.zero(plaintext)1218            }1219            val candidate = stagedKey ?: return UnlockResult.Error("unlock_key_missing")1220            val result = adoptSlotA(candidate, payload, expectedEpoch)1221            if (result is UnlockResult.Success) { stagedKey = null; ensureRecoveryEscrow() }1222            result1223        } finally {1224            stagedKey?.let(VaultCrypto::zero)1225        }1226    }12271228    fun lock() {1229        // Never snapshot a mutation that has changed entryList but has not yet1230        // crossed its durable epoch fence. Successful writes refresh the spool1231        // before releasing this mutex; an in-flight writer therefore makes this1232        // lock skip the convenience refresh and fail closed to the prior cache.1233        if (mutex.tryLock()) {1234            try {1235                runCatching { LockedSyncSpoolHooks.refresh(this) }1236            } finally {1237                mutex.unlock()1238            }1239        }1240        // H-03: must observe derivedKey/entryList atomically with any in-flight1241        // suspend op (an addEntry mid-encrypt, an unlock adopting the payload,1242        // etc.). mutex cannot be acquired from this non-suspend caller; stateLock1243        // guards just the brief state reset. Advancing the epoch first invalidates1244        // every operation that captured this session before it reaches a later1245        // durable commit or publication.1246        stateLock.lock()1247        try {1248            sessionEpoch = nextSessionEpoch(sessionEpoch)1249            clearSessionStateLocked()1250            _uiGateLocked.value = false1251        } finally {1252            stateLock.unlock()1253        }1254    }12551256    /**1257     * Enter sync-retained background mode: the UI shows the lock screen but the1258     * vault stays fully unlocked in memory so [PeachSyncService] can complete1259     * sync sessions. Called from [PeachApplication.onStop] when background sync1260     * is enabled. A subsequent full [lock] (auto-lock timer, manual lock)1261     * supersedes this and zeroes everything.1262     */1263    fun lockUiGate() {1264        if (_isUnlocked.value) _uiGateLocked.value = true1265    }12661267    /** Dismiss the UI gate after the user authenticates on resume. */1268    fun clearUiGate() {1269        _uiGateLocked.value = false1270    }12711272    @Volatile private var suppressNextBackgroundLockUntil: Long = 0L12731274    // Test seam so the expiry branch is reachable from plain JUnit (SystemClock1275    // is a stub off-device).1276    @VisibleForTesting1277    internal var nowMs: () -> Long = { SystemClock.elapsedRealtime() }12781279    /**1280     * Call immediately before launching a system Activity (a SAF file1281     * picker/save dialog, a share sheet) that briefly takes the whole process1282     * out of the foreground as an expected part of an in-app flow — not a1283     * genuine user backgrounding. ProcessLifecycleOwner.onStop can't tell the1284     * two apart on its own (it fires for both), and without this, exporting or1285     * importing a file silently locked and wiped the vault mid-flow the moment1286     * the picker took over, before its result ever reached the app.1287     *1288     * The suppression auto-expires after [BACKGROUND_LOCK_SUPPRESSION_TIMEOUT_MS]1289     * (M-07); a never-consumed stale flag cannot suppress a later real lock.1290     */1291    fun expectTransientBackground() {1292        suppressNextBackgroundLockUntil = nowMs() + BACKGROUND_LOCK_SUPPRESSION_TIMEOUT_MS1293    }12941295    /**1296     * Consumed once by the next background-lock check; see [expectTransientBackground].1297     * Returns false (and clears the flag) if the suppression has expired or was1298     * never set — a genuine background event must always lock.1299     */1300    fun consumeTransientBackgroundSuppression(): Boolean {1301        val until = suppressNextBackgroundLockUntil1302        val active = until != 0L && nowMs() < until1303        suppressNextBackgroundLockUntil = 0L1304        return active1305    }13061307    // ---- Sync identity ----------------------------------------------------13081309    /**1310     * The vault's stable sync master key (a copy). Caller must zero it. Backs1311     * vault_id, the Noise static key, the Ed25519 manifest key, and per-entry1312     * envelope keys. Null when locked. See [VaultPayload.rootKeyB64].1313     */1314    /**1315     * HOLE 5 — the duress vault never syncs.1316     *1317     * [commitDuressUnlock] gives the decoy session a root key so its own codex1318     * and recovery paths work, which means (unlike the browser, where the decoy1319     * path simply has no root key) the sync surface has to refuse explicitly.1320     * Without this the decoy vault would present a second, different vault_id1321     * to a paired device, and a coerced user opening it would make sync visibly1322     * fail on their other devices — a duress indicator, which is the one thing1323     * a duress vault must never be.1324     */1325    // M-04: the "null when locked" half of the contract was documented but never1326    // enforced — a rootKey outlives _isUnlocked in the recovery half-unlock (see1327    // [unlockWithRecoveryWords], which installs a root key with no password key1328    // yet) and in a create that failed after staging. Sync must fail closed1329    // there, so the authoritative unlocked flag gates it, not just decoyMode.1330    internal data class SyncMasterKeySnapshot(val epoch: Long, val key: ByteArray)13311332    internal fun syncMasterKeySnapshot(): SyncMasterKeySnapshot? = mutateState {1333        if (decoyMode || !_isUnlocked.value) null1334        else rootKey?.copyOf()?.let { SyncMasterKeySnapshot(sessionEpoch, it) }1335    }13361337    internal fun isSessionEpochCurrent(epoch: Long): Boolean =1338        mutateState { sessionEpoch == epoch }13391340    internal fun unlockedSessionEpoch(): Long? = mutateState {1341        if (derivedKey != null && _isUnlocked.value) sessionEpoch else null1342    }13431344    fun syncMasterKey(): ByteArray? = syncMasterKeySnapshot()?.key13451346    /**1347     * The current session's root key, decoy included. For local-only uses that1348     * must behave identically in a decoy session — Codex backup and recovery1349     * words — because a feature that errors under duress is itself a duress1350     * tell. In a decoy session this is the DECOY's root key (see1351     * [commitDuressUnlock]), never the real vault's, so neither surface can1352     * leak the real vault. Anything that leaves the device must use1353     * [syncMasterKey] instead.1354     */1355    fun sessionRootKey(): ByteArray? = mutateState {1356        if (!sessionDataAvailable) null else rootKey?.copyOf()1357    }13581359    /** Stable per-vault id two paired devices must share to sync. Null when1360     *  locked, and never present for the decoy vault (see [syncMasterKey]). */1361    fun syncVaultId(): String? = mutateState {1362        if (decoyMode || !_isUnlocked.value) null1363        else rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }1364    }13651366    /**1367     * Browser parity (MV-8): rotate the sync identity by replacing the stable1368     * root key. Entries remain under the master-password key, while sync1369     * credentials, vault_id, and recovery words all change.1370     */1371    suspend fun rotateSyncIdentity(): Boolean = mutex.withLock {1372        val expectedEpoch = mutateState { if (derivedKey != null && !decoyMode) sessionEpoch else null }1373            ?: return false1374        installRootKey(generateRecoverableRootKey(), expectedEpoch)1375    }13761377    /**1378     * Join the vault behind [rootKeyHex]: adopt that vault's identity while1379     * keeping every local entry.1380     *1381     * Sync identity (vault id, signing keys) derives from the root key, and1382     * `sync-coordinator` refuses a `vault_id_mismatch`, so two independently1383     * created vaults can never reconcile. Taking the other side's root key is1384     * what makes them one vault; from the next sync on, both entry sets merge.1385     *1386     * Entries survive because they are sealed under the password-derived key,1387     * not the root key — the same property [rotateSyncIdentity] relies on.1388     *1389     * CONSEQUENCE, which the caller must have disclosed and had confirmed:1390     * this device's previous recovery words stop working for good, and its new1391     * words are the source vault's words, because words are a deterministic1392     * encoding of the root key.1393     */1394    suspend fun joinVault(rootKeyHex: String): AdoptVaultResult = mutex.withLock {1395        if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {1396            return AdoptVaultResult.Error("JOIN_INVALID_ROOT_KEY: expected 64 lowercase hex chars")1397        }1398        val expectedEpoch = mutateState {1399            when {1400                derivedKey == null -> null1401                decoyMode -> Long.MIN_VALUE1402                else -> sessionEpoch1403            }1404        }1405        if (expectedEpoch == null) return AdoptVaultResult.Error("vault_locked")1406        if (expectedEpoch == Long.MIN_VALUE) return AdoptVaultResult.Error("JOIN_DECOY_MODE")1407        if (!store.hasVault()) return AdoptVaultResult.Error("JOIN_NO_LOCAL_VAULT")14081409        val incoming = hexToRootKey(rootKeyHex)1410        if (incoming.size != VaultCrypto.KEY_SIZE) {1411            VaultCrypto.zero(incoming)1412            return AdoptVaultResult.Error("JOIN_INVALID_ROOT_KEY: expected 32 bytes")1413        }1414        // Refuse before committing rather than leave this device holding a vault1415        // whose recovery words cannot be typed back. generateRecoverableRootKey1416        // screens its own keys for this; a key arriving from a peer has not been.1417        val roundTrips = runCatching { wordsToRootKeyMaterial(rootKeyToWords(incoming)) }.isSuccess1418        if (!roundTrips) {1419            VaultCrypto.zero(incoming)1420            return AdoptVaultResult.Error("JOIN_UNRECOVERABLE_ROOT_KEY")1421        }14221423        val vaultId = com.peachpasswords.sync.computeVaultId(incoming)1424        return if (installRootKey(incoming, expectedEpoch)) {1425            AdoptVaultResult.Success(vaultId)1426        } else {1427            AdoptVaultResult.Error("JOIN_INSTALL_FAILED")1428        }1429    }14301431    /**1432     * The recovery words [rootKeyHex] will produce once joined, or null if it is1433     * not a usable root key. Lets the join flow show the user the words that are1434     * about to replace theirs *before* anything is committed.1435     */1436    fun previewRecoveryWords(rootKeyHex: String): List<String>? {1437        if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) return null1438        val bytes = hexToRootKey(rootKeyHex)1439        return try {1440            val words = rootKeyToWords(bytes)1441            if (runCatching { wordsToRootKeyMaterial(words) }.isSuccess) words else null1442        } catch (_: Exception) {1443            null1444        } finally {1445            VaultCrypto.zero(bytes)1446        }1447    }14481449    /**1450     * Swap the vault's root key, keeping every entry, and re-escrow under the1451     * words the new key encodes. Takes ownership of [nextRootKey]. Caller holds1452     * [mutex].1453     */1454    private suspend fun installRootKey(nextRootKey: ByteArray, expectedEpoch: Long): Boolean {1455        // H-03: snapshot the live fields under stateLock so the success and the1456        // rollback paths both see consistent prior/new state. Writing the new1457        // rootKey/recovery fields is inside its own mutateState at the end.1458        // H-03 (P1-3 codex): the snapshot must COPY the live key/rootKey arrays1459        // — holding live references would let a zero-on-failure operation also1460        // wipe the session's still-live key arrays.1461        data class Snapshot(1462            val key: ByteArray,1463            val priorRootKey: ByteArray,1464            val priorRecoveryHash: String?,1465            val priorRecoverySet: Boolean,1466        )1467        val snap = mutateIfCurrentEpoch(expectedEpoch) {1468            val k = derivedKey ?: return@mutateIfCurrentEpoch null1469            if (decoyMode) return@mutateIfCurrentEpoch null1470            val priorRoot = rootKey ?: return@mutateIfCurrentEpoch null1471            Snapshot(k.copyOf(), priorRoot.copyOf(), recoveryWordHash, recoveryWordsSet)1472        } ?: run {1473            VaultCrypto.zero(nextRootKey)1474            return false1475        }1476        val priorSlot = store.loadSlotA() ?: run {1477            VaultCrypto.zero(snap.key)1478            VaultCrypto.zero(snap.priorRootKey)1479            VaultCrypto.zero(nextRootKey)1480            return false1481        }1482        val nextWords = rootKeyToWords(nextRootKey)14831484        return try {1485            beforeDurableCommit()1486            if (!takeVaultSnapshot("local_save", expectedEpoch)) throw IllegalStateException("snapshot_failed")1487            if (mutateIfCurrentEpoch(expectedEpoch) {1488                rootKey = nextRootKey1489                recoveryWordHash = recoveryWordsHash(nextWords)1490                recoveryWordsSet = false1491            } == null) throw IllegalStateException("stale_root_rotation")14921493            val nextRecoveryEscrow = buildRecoveryEscrow(nextWords)1494                ?: throw IllegalStateException("recovery_escrow_failed")1495            val nextRootKeyEscrow = buildRootKeyEscrow(nextWords)1496                ?: throw IllegalStateException("root_escrow_failed")1497            val plaintext = VaultCodec.encode(currentPayload())1498            val blob = try {1499                b64(VaultCrypto.encrypt(plaintext, snap.key, VaultCrypto.AAD_SLOT_A))1500            } finally {1501                VaultCrypto.zero(plaintext)1502            }1503            val nextSlot = priorSlot.copy(1504                blob = blob,1505                recoveryEscrow = nextRecoveryEscrow,1506                rootKeyEscrow = nextRootKeyEscrow,1507            )1508            val committed = withEpochCommit(expectedEpoch) {1509                if (!store.writeSlotA(nextSlot)) return@withEpochCommit false1510                try {1511                    if (!writeMatchingNoiseSlotB(nextSlot)) throw IllegalStateException("noise_slot_b_commit_failed")1512                    // H-04: a root-key rotation re-seals slot A, so the duress slot1513                    // (real or fake) must be re-padded to the new ciphertext length.1514                    if (!writeCompanionDuressSlot(nextSlot)) throw IllegalStateException("duress_slot_commit_failed")1515                    store.stampLocalMutation()1516                } catch (_: Exception) {1517                    store.writeSlotA(priorSlot)1518                    return@withEpochCommit false1519                }1520                true1521            } ?: false1522            if (!committed) throw IllegalStateException("storage_write_failed")1523            mutateIfCurrentEpoch(expectedEpoch) { publish() }1524            true1525        } catch (_: Exception) {1526            val restored = mutateIfCurrentEpoch(expectedEpoch) {1527                rootKey?.let(VaultCrypto::zero)1528                rootKey = snap.priorRootKey.copyOf()1529                recoveryWordHash = snap.priorRecoveryHash1530                recoveryWordsSet = snap.priorRecoverySet1531            }1532            if (restored != null) {1533                withEpochCommit(expectedEpoch) { store.writeSlotA(priorSlot) }1534            }1535            false1536        } finally {1537            VaultCrypto.zero(snap.key)1538            VaultCrypto.zero(snap.priorRootKey)1539            // On success nextRootKey is owned by rootKey. On every other path1540            // it is not, including a stale epoch after lock(); scrub it while1541            // the local reference is still available.1542            val stillOwnedBySession = mutateState {1543                sessionEpoch == expectedEpoch && rootKey === nextRootKey1544            }1545            if (!stillOwnedBySession) VaultCrypto.zero(nextRootKey)1546        }1547    }15481549    /**1550     * A copy of the live Argon2id-derived vault key, for biometric escrow only1551     * (wrapped under a hardware KeyStore key on biometric enable). Null when1552     * locked. Caller must [VaultCrypto.zero] it after use.1553     */1554    fun currentVaultKey(): ByteArray? = mutateState {1555        if (!isFullyUnlockedLocked()) null else derivedKey?.copyOf()1556    }15571558    suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {1559        val expectedEpoch = currentEpoch()1560        val slotA = store.loadSlotA() ?: return false1561        var oldKey: ByteArray? = null1562        var newKey: ByteArray? = null1563        var plaintext: ByteArray? = null1564        return try {1565            oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))1566            // Keep ownership of the decrypted vault plaintext until decoding has1567            // finished.  Passing decrypt() inline made the byte array unreachable1568            // before the finally block, so a successful or failed password change1569            // could leave the full plaintext resident in the heap.1570            val decrypted = VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A)1571            val payload = try {1572                VaultCodec.decode(decrypted)1573            } finally {1574                VaultCrypto.zero(decrypted)1575            }1576            val newSalt = VaultCrypto.generateSalt()1577            newKey = VaultCrypto.deriveKey(newPassword, newSalt)1578            // Re-seal the existing payload under the new key/salt.1579            plaintext = VaultCodec.encode(payload)1580            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))1581            // The escrow seals the slot-A PLAINTEXT, which a password change does not1582            // alter — only the wrapping changes — so carry it forward; rebuilding the1583            // StoredVault from scratch would silently drop it.1584            // Carry BOTH escrows forward unchanged: each seals plaintext/root-key1585            // content that a password change does not alter — only the slot-A1586            // wrapping rotates. The root-key escrow staying stable across password1587            // changes matches the browser (`vault.ts:363-364`).1588            val next = StoredVault(1589                version = slotA.version,1590                salt = b64(newSalt),1591                blob = blob,1592                recoveryEscrow = slotA.recoveryEscrow,1593                rootKeyEscrow = slotA.rootKeyEscrow,1594            )1595            // H-01: durably commit slot A + size-matched noise + version stamp1596            // before swapping the session key. A partial commit (new A on disk,1597            // old key in memory) would have the next save encrypt under the old1598            // key while matching disk on the new one.1599            val priorB = store.loadSlotB()1600            if (!commitVaultRotation(slotA, priorB, next, expectedEpoch)) return false1601            // H-03 (P1-2 codex): zero the OLD live key and assign the NEW one1602            // inside the same stateLock critical section, so a concurrent lock()1603            // can't observe the in-between (zeroed but not yet reassigned).1604            if (mutateIfCurrentEpoch(expectedEpoch) {1605                oldKey?.let(VaultCrypto::zero); oldKey = null1606                derivedKey?.let(VaultCrypto::zero)1607                derivedKey = newKey; newKey = null1608            } == null) return false1609            true1610        } catch (_: Exception) {1611            false1612        } finally {1613            oldKey?.let(VaultCrypto::zero)1614            newKey?.let(VaultCrypto::zero)1615            plaintext?.let(VaultCrypto::zero)1616        }1617    }16181619    /**1620     * Irreversible wipe. Locks the session and clears every vault key. The Pro1621     * license is in a separate store and is preserved by construction.1622     */1623    suspend fun destroyVault() = mutex.withLock {1624        lock()1625        store.clearVault()1626        store.clearDecoySlot()1627    }16281629    // ---- Entry CRUD -------------------------------------------------------16301631    /**1632     * A Peach entry id is a UUID. Import and restore carry ids from foreign1633     * files (another Peach install, a vendor export, a hand-written backup) and1634     * no reader bounds them, so an id that is not a well-formed Peach id is1635     * replaced here rather than trusted.1636     *1637     * This is the naturalisation seam, and it is deliberately the only place it1638     * happens. Minting costs at most one duplicate if the same vault is later1639     * restored on a device that still holds the old id — visible and fixable.1640     * The sync path must NOT do this: adopting a peer's id verbatim is the only1641     * thing that keeps two devices agreeing on which entry they are discussing,1642     * so reminting there would fork identity on every device, on every round.1643     */1644    private val entryIdShape = Regex("[A-Za-z0-9_-]{1,64}")16451646    private fun String?.normalizedEntryId(): String =1647        if (this != null && entryIdShape.matches(this)) this else UUID.randomUUID().toString()16481649    suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {1650        val epoch = requireUnlocked()1651        val stamp = VaultCrypto.monotonicEntryTimestamp()1652        val now = System.currentTimeMillis()1653        val entry = withDerivedLast4(draft.copy(1654            id = draft.id.normalizedEntryId(),1655            createdAt = if (draft.createdAt > 0) draft.createdAt else now,1656            modifiedAt = stamp,1657            passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1658        ))1659        // H-03: capture rollback AND write entryList under stateLock so a1660        // concurrent lock() cannot zero the session between the read and the write.1661        val rollback = mutateCurrentSession(epoch) {1662            val r = entryList.toMutableList()1663            entryList.add(entry)1664            r1665        } ?: throw IllegalStateException("vault_locked")1666        persistOrRollback(rollback, epoch)1667        entry1668    }16691670    /**1671     * Insert many entries with a single encrypt-and-write at the end.1672     *1673     * Importing a real vault through [addEntry] was quadratic: every entry took1674     * the lock and re-encrypted and rewrote the whole vault, so an 806-entry1675     * restore did 806 full-vault writes and hung the app long enough to ANR.1676     * Rolls back to the pre-import list if the one write fails, matching1677     * [addEntry]'s all-or-nothing behaviour.1678     */1679    suspend fun addEntries(drafts: List<VaultEntry>): Int = mutex.withLock {1680        val epoch = requireUnlocked()1681        if (drafts.isEmpty()) return 01682        val now = System.currentTimeMillis()1683        val ready = drafts.map { draft ->1684            val stamp = VaultCrypto.monotonicEntryTimestamp()1685            withDerivedLast4(1686                draft.copy(1687                    id = draft.id.normalizedEntryId(),1688                    createdAt = if (draft.createdAt > 0) draft.createdAt else now,1689                    modifiedAt = stamp,1690                    passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1691                ),1692            )1693        }1694        // H-03: capture rollback AND append every entry under stateLock.1695        val rollback = mutateCurrentSession(epoch) {1696            val r = entryList.toMutableList()1697            entryList.addAll(ready)1698            r1699        } ?: throw IllegalStateException("vault_locked")1700        persistOrRollback(rollback, epoch)1701        return drafts.size1702    }17031704    /**1705     * M-01: replace the whole active set with [newEntries] in one write.1706     *1707     * Import's REPLACE mode used to soft-delete every current entry one durable1708     * write at a time (swallowing each failure) and then batch-add, so a failed1709     * add left the old entries stranded in Trash with nothing restored. Staging1710     * the entire next list in memory and committing it through1711     * [persistOrRollback] makes the swap all-or-nothing: on any failure the1712     * pre-import list — active entries included — is restored.1713     *1714     * Existing tombstones are preserved so paired devices still see the1715     * deletions they already know about.1716     */1717    suspend fun replaceEntries(newEntries: List<VaultEntry>): Int = mutex.withLock {1718        val epoch = requireUnlocked()1719        val now = System.currentTimeMillis()1720        val ready = newEntries.map { draft ->1721            val stamp = VaultCrypto.monotonicEntryTimestamp()1722            withDerivedLast4(1723                draft.copy(1724                    id = draft.id.normalizedEntryId(),1725                    createdAt = if (draft.createdAt > 0) draft.createdAt else now,1726                    modifiedAt = stamp,1727                    passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1728                ),1729            )1730        }1731        // M-03: an incoming entry that shares an id with an existing live entry1732        // is meant to *replace* it (PEACHSCRIPT REPLACE restore). Tombstoning1733        // the old one and then appending the new one would leave the list with1734        // two entries of the same id — the tombstoned one would be returned by1735        // updateEntry's indexOfFirst and trip entry_not_found. Drop the to-be-1736        // superseded entries from the tombstone set instead.1737        val incomingIds = ready.map { it.id }.toHashSet()1738        val rollback = mutateCurrentSession(epoch) {1739            val r = entryList.toMutableList()1740            val replaced = entryList.map { entry ->1741                if (entry.deletedAt != null) return@map entry1742                if (entry.id in incomingIds) return@map null1743                val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)1744                entry.copy(deletedAt = stamp, modifiedAt = stamp)1745            }.filterNotNull()1746            entryList = (replaced + ready).toMutableList()1747            r1748        } ?: throw IllegalStateException("vault_locked")1749        persistOrRollback(rollback, epoch)1750        return ready.size1751    }17521753    suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {1754        val epoch = requireUnlocked()1755        // H-03: read entryList, compute the patched entry, and write it under a1756        // single stateLock so a concurrent lock() cannot interleave between the1757        // lookup and the assignment (would IndexOutOfBoundsException on a shrunk1758        // list, or clobber the entry onto the wrong id after a relock).1759        val prepared = mutateCurrentSession(epoch) {1760            val idx = entryList.indexOfFirst { it.id == patch.id }1761            if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1762            val current = entryList[idx]1763            val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1764            // Only refresh passwordChangedAt when the password value actually changes.1765            val passwordChanged = patch.password != null && patch.password != current.password1766            // Capture the outgoing password (newest first) so the user can reveal/copy/1767            // restore it later. History is computed authoritatively from `current`, not1768            // the patch — updateEntry is a full-entry replace, so trusting patch's value1769            // would let a stale form clobber the real history. Record the age the old1770            // password carried, skip an empty prior, and skip an immediate exact dupe1771            // (e.g. restore-then-restore). Capped at PASSWORD_HISTORY_MAX.1772            val priorPassword = current.password1773            val shouldCapture = passwordChanged &&1774                !priorPassword.isNullOrEmpty() &&1775                current.passwordHistory?.firstOrNull()?.password != priorPassword1776            val nextHistory = if (shouldCapture) {1777                (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +1778                    (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)1779            } else {1780                current.passwordHistory1781            }1782            val updated = withDerivedLast4(patch.copy(1783                createdAt = current.createdAt,1784                modifiedAt = stamp,1785                passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,1786                passwordHistory = nextHistory,1787            ))1788            val rollback = entryList.toMutableList()1789            entryList[idx] = updated1790            updated to rollback1791        } ?: throw IllegalStateException("vault_locked")1792        val (updated, rollback) = prepared1793        persistOrRollback(rollback, epoch)1794        updated1795    }17961797    /** Soft-delete: writes a tombstone whose timestamp beats any in-flight edit. */1798    suspend fun deleteEntry(id: String) = mutex.withLock {1799        val epoch = requireUnlocked()1800        // H-03: lookup + tombstone write under stateLock so lock() cannot shrink1801        // the list out from under the indexOfFirst.1802        val rollback = mutateCurrentSession(epoch) {1803            val idx = entryList.indexOfFirst { it.id == id }1804            if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1805            val current = entryList[idx]1806            val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1807            val prior = entryList.toMutableList()1808            entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)1809            prior1810        } ?: throw IllegalStateException("vault_locked")1811        persistOrRollback(rollback, epoch)1812    }18131814    suspend fun restoreEntry(id: String) = mutex.withLock {1815        val epoch = requireUnlocked()1816        val rollback = mutateCurrentSession(epoch) {1817            val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }1818            if (idx == -1) throw IllegalStateException("deleted entry not found")1819            val current = entryList[idx]1820            val prior = entryList.toMutableList()1821            entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))1822            prior1823        } ?: throw IllegalStateException("vault_locked")1824        persistOrRollback(rollback, epoch)1825    }18261827    /** Permanent delete — no tombstone, no recovery. */1828    suspend fun purgeEntry(id: String) = mutex.withLock {1829        val epoch = requireUnlocked()1830        val rollback = mutateCurrentSession(epoch) {1831            val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }1832            if (idx == -1) throw IllegalStateException("deleted entry not found")1833            val prior = entryList.toMutableList()1834            entryList.removeAt(idx)1835            prior1836        } ?: throw IllegalStateException("vault_locked")1837        persistOrRollback(rollback, epoch)1838    }18391840    /** Permanently empty the trash — hard-deletes every soft-deleted entry. */1841    suspend fun purgeDeletedEntries(): Int = mutex.withLock {1842        val epoch = requireUnlocked()1843        // H-03: read+remove under stateLock so lock() can't reorder the remove.1844        data class R(val rollback: MutableList<VaultEntry>, val removed: Int)1845        val r = mutateCurrentSession(epoch) {1846            val rollback = entryList.toMutableList()1847            val before = entryList.size1848            entryList.removeAll { it.deletedAt != null }1849            R(rollback, before - entryList.size)1850        } ?: throw IllegalStateException("vault_locked")1851        if (r.removed > 0) persistOrRollback(r.rollback, epoch)1852        r.removed1853    }18541855    /** Browser parity: number of active entries that dedupe would move to trash. */1856    suspend fun countDuplicateEntries(): Int = mutex.withLock {1857        val epoch = requireUnlocked()1858        // countDuplicateEntriesLocked reads entryList; H-03 fences the read so1859        // lock() can't race the read with state writes.1860        mutateCurrentSession(epoch) { countDuplicateEntriesLocked() }1861            ?: throw IllegalStateException("vault_locked")1862    }18631864    /**1865     * Browser parity: soft-delete duplicate entries, keeping the most recently1866     * modified member of each group. Refuse in decoy mode so the duress vault is1867     * not reshaped into a forensically distinct state.1868     */1869    suspend fun deduplicateEntries(): Int = mutex.withLock {1870        val epoch = requireUnlocked()1871        data class R(val rollback: MutableList<VaultEntry>, val removed: Int)1872        val ready = mutateCurrentSession(epoch) {1873            if (decoyMode) throw IllegalStateException("deduplicate disabled in decoy mode")1874            val active = entryList.filter { it.deletedAt == null }1875            val keepIds = mutableSetOf<String>()1876            active.groupBy { it.duplicateKey() }.values.forEach { group ->1877                keepIds += group.maxBy { it.modifiedAt.takeIf { ts -> ts > 0 } ?: it.createdAt }.id1878            }1879            val rollback = entryList.toMutableList()1880            var removed = 01881            entryList = entryList.map { entry ->1882                if (entry.deletedAt == null && entry.id !in keepIds) {1883                    removed++1884                    val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)1885                    entry.copy(deletedAt = stamp, modifiedAt = stamp)1886                } else {1887                    entry1888                }1889            }.toMutableList()1890            R(rollback, removed)1891        } ?: throw IllegalStateException("vault_locked")1892        if (ready.removed > 0) persistOrRollback(ready.rollback, epoch)1893        ready.removed1894    }18951896    fun getEntries(): List<VaultEntry> = mutateState {1897        if (!sessionDataAvailable) emptyList() else entryList.filter { it.deletedAt == null }1898    }1899    fun getEntry(id: String): VaultEntry? = mutateState {1900        if (!sessionDataAvailable) null else entryList.firstOrNull { it.id == id && it.deletedAt == null }1901    }1902    fun getDeletedEntries(): List<VaultEntry> = mutateState {1903        if (!sessionDataAvailable) emptyList()1904        else entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }1905    }19061907    /** Active entries, optionally narrowed to those carrying [tagFilter]. */1908    fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {1909        return mutateState {1910            if (!sessionDataAvailable) return@mutateState emptyList()1911            val active = entryList.filter { it.deletedAt == null }1912            if (tagFilter == null) return@mutateState active1913            val needle = tagFilter.trim().lowercase()1914            active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }1915        }1916    }19171918    /** Sorted, de-duplicated tags across all active entries. */1919    fun getDistinctTags(): List<String> = mutateState {1920        if (!sessionDataAvailable) return@mutateState emptyList()1921        entryList.asSequence()1922            .filter { it.deletedAt == null }1923            .flatMap { it.tags?.asSequence() ?: emptySequence() }1924            .map { it.trim().lowercase() }1925            .filter { it.isNotEmpty() }1926            .distinct()1927            .sorted()1928            .toList()1929    }19301931    /**1932     * Distinct non-blank values for an identity field across active entries,1933     * most-frequently-used first. Supports "username" and "email"; unknown field1934     * names return an empty list. Values keep original casing (deduped1935     * case-insensitively) so a suggestion matches what the user typed.1936     */1937    fun getDistinctFieldValues(field: String): List<String> {1938        val select: (VaultEntry) -> String? = when (field) {1939            "username" -> { e -> e.username }1940            "email" -> { e -> e.email }1941            else -> return emptyList()1942        }1943        return mutateState {1944            if (!sessionDataAvailable) return@mutateState emptyList()1945            entryList.asSequence()1946                .filter { it.deletedAt == null }1947                .mapNotNull { select(it)?.trim() }1948                .filter { it.isNotEmpty() }1949                .groupingBy { it.lowercase() }1950                .aggregate { _, acc: Pair<String, Int>?, value, _ ->1951                    Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)1952                }1953                .values1954                .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })1955                .map { it.first }1956        }1957    }19581959    fun getTombstones(): List<Tombstone> = mutateState {1960        if (!sessionDataAvailable) emptyList()1961        else entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }1962    }1963    fun getVaultVersion(): Long = store.version()1964    fun getVaultHistory(): List<VaultSnapshot> = store.loadVaultHistory().snapshots19651966    suspend fun restoreVaultSnapshot(snapshotId: String): Boolean = mutex.withLock {1967        val expectedEpoch = currentEpoch()1968        val snapshot = store.loadVaultHistory().snapshots.firstOrNull { it.id == snapshotId } ?: return false1969        val restoredA = VaultCodec.decodeSlot(snapshot.vault_a) ?: return false1970        // H-04: snapshots now carry the duress slot too — restore preserves1971        // the at-rest triad (A/B/D), not just the A/B pair.1972        val restoredD: StoredVault? = snapshot.vault_d?.let(VaultCodec::decodeSlot)1973        val priorA = store.loadSlotA()1974        val priorB = store.loadSlotB()1975        val priorD = store.loadDecoySlot()1976        // H-02: capture pre-restore state as the recovery snapshot BEFORE any1977        // slot write — the old code took this snapshot, then stranded it on1978        // every failure, polluting history with a "restore" entry that never1979        // restored anything. The history below is rolled back together with1980        // the slots if the commit fails.1981        val priorHistory = store.loadVaultHistory()1982        // P1-4 (codex): the recovery snapshot must land before we commit the1983        // slot pair, otherwise a failed restore cannot be rolled back to the1984        // pre-restore history. If the history write itself fails, refuse to1985        // proceed — the alternative is a successful restore with no undo path.1986        beforeDurableCommit()1987        if (!takeVaultSnapshot("restore", expectedEpoch)) {1988            return false1989        }1990        // H-04: legacy snapshots without vault_d, or vault_d that fails to1991        // decode, fall back to a fake duress of slot A's size — presence-1992        // indistinguishable from any other freshly-restored vault.1993        val nextD: StoredVault = restoredD ?: run {1994            val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(restoredA) + 161995            val fakeBlob = ByteArray(target).also(rng::nextBytes)1996            val fakeSalt = VaultCrypto.generateSalt()1997            StoredVault(version = 1, salt = b64(fakeSalt), blob = b64(fakeBlob))1998        }1999        if (!commitRestoreAtomic(restoredA, snapshot.vault_b, nextD, priorA, priorB, priorD, expectedEpoch)) {2000            withEpochCommit(expectedEpoch) { store.writeVaultHistory(priorHistory) }2001            return false2002        }2003        lock()2004        true2005    }20062007    /**2008     * H-02: atomic slot-A + slot-B + version stamp for a snapshot restore.2009     * Mirrors [commitVaultRotation] but writes the snapshot's EXACT slot B2010     * (a restore preserves the duress-shaped blob from history), not a fresh2011     * noise record. Any failure rolls back so the at-rest pair never holds a2012     * restored slot A against a pre-restore slot B. Caller is responsible for2013     * restoring the pre-snapshot history on a false return.2014     *2015     * H-04: duress slot is now part of the atomic triad — restored last so2016     * a duress-write failure rolls the A/B pair back too.2017     */2018    private fun commitRestoreAtomic(2019        nextA: StoredVault,2020        nextB: String,2021        nextD: StoredVault,2022        priorA: StoredVault?,2023        priorB: String?,2024        priorD: StoredVault?,2025        expectedEpoch: Long,2026    ): Boolean {2027        return withEpochCommit(expectedEpoch) {2028            if (!store.writeSlotA(nextA)) return@withEpochCommit false2029            // P1-2 (codex): writeSlotB's boolean AND any thrown exception from it2030            // must trigger rollback; previously a throw escaped without restoring2031            // the prior slot A and history.2032            try {2033                if (!store.writeSlotB(nextB)) throw java.io.IOException("slot_b_commit_failed")2034                // H-04: duress slot is part of the restore triad. Failures here2035                // roll A+B back so the at-rest state stays consistent.2036                if (!store.writeDecoySlot(nextD)) throw java.io.IOException("duress_slot_commit_failed")2037                store.stampLocalMutation()2038            } catch (_: Exception) {2039                reportRollbackFailures(rollbackRestoreLocked(priorA, priorB, priorD))2040                return@withEpochCommit false2041            }2042            true2043        } ?: false2044    }20452046    // ---- Sync apply (does NOT advance the version) ------------------------20472048    /**2049     * Apply remote entryList + tombstones with per-entry last-write-wins. Persists2050     * WITHOUT bumping the version counter, so a sync round cannot cascade into2051     * another outbound sync. Returns the number of locally-applied changes.2052     */2053    suspend fun applyMergedRemoteEntries(2054        remoteEntries: List<VaultEntry>,2055        remoteTombstones: List<Tombstone>,2056        expectedEpoch: Long? = null,2057    ): Int = mutex.withLock {2058        val epoch = expectedEpoch ?: requireUnlocked()2059        if (expectedEpoch != null && mutateIfCurrentEpoch(epoch) { true } != true) return@withLock 02060        // HV-1: clamp every peer-supplied timestamp to now + MAX_CLOCK_SKEW_MS2061        // BEFORE any comparison against a local one. Without this a peer can2062        // send a far-future modifiedAt and permanently pin its version of an2063        // entry against every honest local edit. The browser clamps in the2064        // matching place (vault.ts applyMergedRemoteEntries).2065        val mergeNow = System.currentTimeMillis()2066        val clamped = remoteEntries.mapNotNull { entry ->2067            // MN-3: drop peer entries that decode cleanly but are semantically2068            // hollow (blank title, credential-less login, husk passkey) and2069            // re-cap passwordHistory before anything merges into the vault.2070            SyncEntrySanitizer.sanitize(entry, PASSWORD_HISTORY_MAX)?.copy(2071                modifiedAt = SyncLimits.clampSyncTimestamp(entry.modifiedAt, mergeNow),2072                deletedAt = entry.deletedAt?.let {2073                    SyncLimits.clampSyncTimestamp(it, mergeNow)2074                },2075            )2076        }2077        val tombMap = remoteTombstones.associate {2078            it.id to SyncLimits.clampSyncTimestamp(it.deletedAt, mergeNow)2079        }2080        // H-03: build the new entryList under stateLock so a concurrent lock()2081        // cannot zero derivedKey/entryList between the byId read and the merge.2082        val applied = mutateCurrentSession(epoch) {2083            var n = 02084            val byId = entryList.associateBy { it.id }.toMutableMap()20852086            for (remote in clamped) {2087                val tomb = tombMap[remote.id]2088                if (tomb != null && tomb >= remote.modifiedAt) continue2089                val local = byId[remote.id]2090                if (local == null) {2091                    entryList.add(remote); byId[remote.id] = remote; n++2092                } else if (remote.modifiedAt > local.modifiedAt) {2093                    val i = entryList.indexOfFirst { it.id == local.id }2094                    if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; n++ }2095                }2096            }20972098            for ((id, deletedAt) in tombMap) {2099                val local = byId[id] ?: continue2100                if (local.deletedAt != null && local.deletedAt >= deletedAt) continue2101                if (deletedAt < local.modifiedAt) continue2102                val i = entryList.indexOfFirst { it.id == id }2103                if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); n++ }2104            }2105            n2106        } ?: return@withLock 021072108        if (applied > 0) {2109            persistSlotA(bumpVersion = false, snapshotReason = "sync_received", expectedEpoch = epoch)2110            mutateIfCurrentEpoch(epoch) { publish() }2111            runCatching { LockedSyncSpoolHooks.refresh(this) }2112        }2113        applied2114    }21152116    suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {2117        // Require a fully live session before exposing a settings mutation.  The2118        // epoch is captured with the read so a lock/new-session boundary cannot2119        // let stale work publish into the replacement session.2120        val epoch = requireUnlocked()2121        val prior = mutateCurrentSession(epoch) {2122            val old = _settings.value2123            _settings.value = settings2124            old2125        } ?: throw IllegalStateException("vault_locked")21262127        val committed = try {2128            beforeDurableCommit()2129            // The durable write is inside the same epoch fence as the in-memory2130            // publication.  If lock() won first, this returns null and no stale2131            // settings reach storage or the public StateFlow.2132            withSessionEpochCommit(epoch) { store.writeSettings(settings) } == true2133        } catch (_: Exception) {2134            false2135        }2136        if (!committed) {2137            // A live-session storage failure rolls back the public value.  A2138            // stale epoch is already reset by lock()/the new session and must2139            // not be allowed to overwrite that safe state.2140            mutateIfCurrentEpoch(epoch) { _settings.value = prior }2141            throw IllegalStateException("settings_write_failed")2142        }2143    }21442145    // ---- Recovery words (vault metadata) ----------------------------------21462147    /** True once the user has confirmed their recovery words for this vault. */2148    fun isRecoveryWordsSet(): Boolean = mutateState { recoveryWordsSet }21492150    /**2151     * Record the BLAKE3 hash of the confirmed recovery words and mark them set.2152     * Persisted without bumping the version — recovery metadata is local-only and2153     * is not an entry mutation paired devices should sync against.2154     */2155    suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {2156        val epoch = requireUnlocked()2157        // H-03: hash + escrow-related state fields set under stateLock so a2158        // concurrent lock() cannot zero them in the middle of buildRecoveryEscrow.2159        // M-04: the flags have to be live before the escrows are built — both seal2160        // currentPayload() — so capture the prior pair and put it back if the write2161        // never lands. Otherwise the session reports words set against a slot A2162        // that still holds no escrow, and the recovery screen never offers a retry.2163        val prior = mutateCurrentSession(epoch) {2164            val priorPair = recoveryWordHash to recoveryWordsSet2165            recoveryWordHash = recoveryWordsHash(words)2166            recoveryWordsSet = true2167            priorPair2168        } ?: return@withLock false2169        // Seal TWO escrows (MF-1): the browser-byte-compatible root-key escrow2170        // (cross-platform recovery of the sync root key) and Android's whole-payload2171        // escrow (offline forgot-password restore of entries). Both derive their key2172        // from the same `wordsToRootKeyMaterial` IKM but use distinct AADs.2173        val persisted = runCatching {2174            persistSlotAWithEscrows(2175                buildRecoveryEscrow(words),2176                buildRootKeyEscrow(words),2177                expectedEpoch = epoch,2178            )2179        }.getOrDefault(false)2180        if (!persisted) {2181            mutateIfCurrentEpoch(epoch) {2182                recoveryWordHash = prior.first2183                recoveryWordsSet = prior.second2184            }2185        }2186        persisted2187    }21882189    /** Verify entered words against the stored recovery hash. */2190    fun verifyRecoveryWords(words: List<String>): Boolean {2191        return mutateState {2192            val stored = recoveryWordHash ?: return@mutateState false2193            MessageDigest.isEqual(2194                stored.toByteArray(Charsets.UTF_8),2195                recoveryWordsHash(words).toByteArray(Charsets.UTF_8),2196            )2197        }2198    }21992200    // ---- Recovery escrow (forgot-password) --------------------------------22012202    /** True at rest if this vault has any recovery escrow the recovery flow can use. */2203    fun hasRecoveryEscrow(): Boolean =2204        store.loadSlotA()?.let { it.recoveryEscrow != null || it.rootKeyEscrow != null } ?: false22052206    /**2207     * One-time self-heal: if this vault has a root key but no recovery escrow2208     * on disk (adopted vaults created before the escrow fix), build and persist2209     * it now. Called on every successful unlock; no-ops once the escrow exists.2210     */2211    private fun ensureRecoveryEscrow() {2212        if (hasRecoveryEscrow()) return2213        val rk = mutateState { rootKey?.copyOf() } ?: return2214        runCatching {2215            val words = rootKeyToWords(rk)2216            val escrow = buildRecoveryEscrow(words)2217            val rkEscrow = buildRootKeyEscrow(words)2218            if (escrow != null || rkEscrow != null) {2219                val prior = store.loadSlotA() ?: return@runCatching2220                store.writeSlotA(prior.copy(2221                    recoveryEscrow = escrow ?: prior.recoveryEscrow,2222                    rootKeyEscrow = rkEscrow ?: prior.rootKeyEscrow,2223                ))2224                mutateState {2225                    recoveryWordHash = recoveryWordsHash(words)2226                    recoveryWordsSet = true2227                }2228            }2229        }.also { VaultCrypto.zero(rk) }2230    }22312232    /**2233     * Attempt to unlock the vault using the 12 BIP39 recovery [words] instead of2234     * the master password. On success the slot-A plaintext sealed in the escrow is2235     * adopted as the live session (entries, rootKey, settings), but no Argon2id2236     * password key exists yet — call [resetPasswordWithRecoveryWords] next to set a2237     * new password and finish unlocking. Returns false when there is no escrow, the2238     * words fail the BIP39 checksum, or the words are wrong (GCM tag mismatch).2239     *2240     * Unlike the brief's `unlockWithRecoveryWords(): ByteArray?`, there is no2241     * detached vault key to return here — slot A is wrapped under the rotating2242     * Argon2id key — so this opens the escrowed payload directly.2243     */2244    suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {2245        val expectedEpoch = currentEpoch()2246        val slotA = store.loadSlotA() ?: return false2247        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false22482249        // Prefer Android's whole-payload escrow: a full offline restore of entries,2250        // root key, and settings. Present for Android-created vaults.2251        val fullEscrow = slotA.recoveryEscrow2252        if (fullEscrow != null) {2253            val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull()2254            if (material != null) {2255                var keyBytes: ByteArray? = null2256                var plaintext: ByteArray? = null2257                var candidateRoot: ByteArray? = null2258                var stateCommitStarted = false2259                try {2260                    keyBytes = deriveRecoveryKey(material, unb64(fullEscrow.salt)).encoded2261                    plaintext = VaultCrypto.decrypt(unb64(fullEscrow.blob), keyBytes!!, VaultCrypto.AAD_RECOVERY)2262                    val payload = VaultCodec.decode(plaintext)2263                    // Stage every fallible operation before touching live session2264                    // fields.  In particular, a settings/provider/decode failure2265                    // cannot leave entries, flags, or a root key resident while the2266                    // public session remains locked.2267                    val candidateSettings = store.loadSettings()2268                    candidateRoot = if (payload.rootKeyB64.isNotBlank()) {2269                        val decodedRoot = unb64(payload.rootKeyB64)2270                        if (decodedRoot.size != VaultCrypto.KEY_SIZE) {2271                            // Do not let a malformed authenticated payload abandon2272                            // this decoded root-key candidate before the outer2273                            // finally block owns it.2274                            VaultCrypto.zero(decodedRoot)2275                            throw IllegalArgumentException("invalid recovery root key")2276                        }2277                        decodedRoot2278                    } else {2279                        generateRecoverableRootKey()2280                    }2281                    stateCommitStarted = true2282                    val adopted = mutateIfCurrentEpoch(expectedEpoch) {2283                        clearSessionStateLocked()2284                        entryList = payload.entries.toMutableList()2285                        authenticatedDuressConfigured = payload.duressConfigured2286                        _duressConfigured.value = payload.duressConfigured2287                        recoveryWordHash = payload.recoveryWordHash2288                        recoveryWordsSet = payload.recoveryWordsSet2289                        rootKey = candidateRoot2290                        candidateRoot = null2291                        _settings.value = candidateSettings2292                        publish()2293                        // This is the authenticated recovery half-unlock boundary:2294                        // only set it after every candidate field is installed.2295                        sessionDataAvailable = true2296                        _isUnlocked.value = false2297                        true2298                    }2299                    if (adopted == true) return@withLock true2300                } catch (_: Exception) {2301                    // Wrong words, malformed payloads, provider failures, and2302                    // settings failures all fall through to the browser-compatible2303                    // root-key escrow.  If the state commit had started, invalidate2304                    // that epoch so no partial candidate survives.2305                    if (stateCommitStarted) {2306                        mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }2307                    }2308                } finally {2309                    plaintext?.let(VaultCrypto::zero)2310                    VaultCrypto.zero(material)2311                    keyBytes?.let(VaultCrypto::zero)2312                    candidateRoot?.let(VaultCrypto::zero)2313                }2314            }2315        }23162317        // Browser-format vault (only the root-key escrow): recover the 32-byte root2318        // key (sync identity) and reset the password; entries return via sync. This2319        // is exactly the browser's recovery semantics (`messages.ts:312-347`).2320        val rootEscrow = slotA.rootKeyEscrow2321        if (rootEscrow != null) {2322            var candidateRoot: ByteArray? = null2323            var stateCommitStarted = false2324            try {2325                candidateRoot = unsealRootKeyEscrow(words, rootEscrow) ?: return false2326                require(candidateRoot!!.size == VaultCrypto.KEY_SIZE) { "invalid recovery root key" }2327                val candidateSettings = store.loadSettings()2328                stateCommitStarted = true2329                val adopted = mutateIfCurrentEpoch(expectedEpoch) {2330                    clearSessionStateLocked()2331                    entryList = mutableListOf()2332                    authenticatedDuressConfigured = false2333                    _duressConfigured.value = false2334                    recoveryWordHash = recoveryWordsHash(words)2335                    recoveryWordsSet = true2336                    rootKey = candidateRoot2337                    candidateRoot = null2338                    _settings.value = candidateSettings2339                    publish()2340                    sessionDataAvailable = true2341                    _isUnlocked.value = false2342                    true2343                }2344                if (adopted == true) return@withLock true2345            } catch (_: Exception) {2346                if (stateCommitStarted) {2347                    mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }2348                }2349            } finally {2350                candidateRoot?.let(VaultCrypto::zero)2351            }2352        }2353        return false2354    }23552356    /**2357     * After [unlockWithRecoveryWords] succeeds, set a brand-new master password:2358     * re-seal slot A under a fresh Argon2id key, rotate the escrow under the same2359     * words, mark the session fully unlocked, and publish. Returns false if called2360     * without a prior successful recovery unlock (no in-memory root key).2361     *2362     * Folds the brief's `resetPasswordWithRecoveryKey(vaultKey, …)` + `unlock(…)`2363     * into one step, since there is no detached vault key here.2364     */2365    suspend fun resetPasswordWithRecoveryWords(2366        words: List<String>,2367        newPassword: String,2368    ): Boolean = mutex.withLock {2369        val expectedEpoch = currentEpoch()2370        // H-03: read rootKey + entryList under stateLock before computing the new2371        // plaintext, then re-publish + swap the derived key under stateLock so a2372        // concurrent lock() cannot straddle the two fences.2373        if (mutateIfCurrentEpoch(expectedEpoch) { rootKey != null } != true) return false2374        val priorA = store.loadSlotA() ?: return false2375        var newKey: ByteArray? = null2376        var plaintext: ByteArray? = null2377        return try {2378            val newSalt = VaultCrypto.generateSalt()2379            newKey = VaultCrypto.deriveKey(newPassword, newSalt)2380            plaintext = VaultCodec.encode(currentPayload())2381            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))2382            // Rebuild both escrows against the recovered session so their salts rotate2383            // with the password reset; fall back to the prior escrows if rebuild fails2384            // (e.g. a checksum-invalid phrase). The same 12 words keep working.2385            val valid = words.size == 12 && findInvalidWords(words).isEmpty()2386            val freshRecovery = if (valid) buildRecoveryEscrow(words) ?: priorA.recoveryEscrow else priorA.recoveryEscrow2387            val freshRootKey = if (valid) buildRootKeyEscrow(words) ?: priorA.rootKeyEscrow else priorA.rootKeyEscrow2388            val next = StoredVault(2389                version = priorA.version,2390                salt = b64(newSalt),2391                blob = blob,2392                recoveryEscrow = freshRecovery,2393                rootKeyEscrow = freshRootKey,2394            )2395            // H-01: see changePassword — both rotations share the same2396            // commit-or-keep-old-key contract so a partial write can't strand2397            // the session on a key that no longer matches disk.2398            val priorB = store.loadSlotB()2399            if (!commitVaultRotation(priorA, priorB, next, expectedEpoch)) return false2400            // H-03 (P1-2 codex): zero the old live key and install the new one2401            // inside the same stateLock critical section so a concurrent lock()2402            // can't observe the in-between.2403            if (mutateIfCurrentEpoch(expectedEpoch) {2404                derivedKey?.let(VaultCrypto::zero)2405                derivedKey = newKey; newKey = null2406                publish()2407                _isUnlocked.value = true2408            } == null) return false2409            true2410        } catch (_: Exception) {2411            false2412        } finally {2413            newKey?.let(VaultCrypto::zero)2414            plaintext?.let(VaultCrypto::zero)2415        }2416    }24172418    /**2419     * Seal the current slot-A plaintext under a key derived from the 12 BIP392420     * recovery [words] (Android offline-restore escrow). IKM is the browser's2421     * `wordsToRootKeyMaterial` (MF-1), AAD is the string [VaultCrypto.AAD_RECOVERY].2422     * Returns null for a checksum-invalid phrase.2423     */2424    private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {2425        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null2426        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2427        var keyBytes: ByteArray? = null2428        var plaintext: ByteArray? = null2429        return try {2430            val salt = VaultCrypto.generateSalt()2431            val recoveryKey = deriveRecoveryKey(material, salt)2432            keyBytes = recoveryKey.encoded2433            plaintext = VaultCodec.encode(currentPayload())2434            val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)2435            RecoveryEscrow(salt = b64(salt), blob = b64(sealed))2436        } finally {2437            VaultCrypto.zero(material)2438            keyBytes?.let(VaultCrypto::zero)2439            plaintext?.let(VaultCrypto::zero)2440        }2441    }24422443    /**2444     * Seal ONLY the 32-byte root key under a key the recovery [words] derive,2445     * byte-for-byte the browser algorithm (MF-1): plaintext = lowercase ASCII hex2446     * of the root key, IKM = `wordsToRootKeyMaterial`, HKDF salt random-16,2447     * info `peach-recovery-v1`, AES-256-GCM AAD = 0x01. The same 12 words unwrap2448     * the same root key on the browser. Returns null with no in-memory root key or2449     * a checksum-invalid phrase.2450     */2451    private fun buildRootKeyEscrow(words: List<String>): RootKeyEscrow? {2452        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null2453        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2454        val rk = mutateState { rootKey?.copyOf() } ?: run {2455            VaultCrypto.zero(material)2456            return null2457        }2458        var keyBytes: ByteArray? = null2459        var plaintext: ByteArray? = null2460        return try {2461            val salt = VaultCrypto.generateSalt()2462            val recoveryKey = deriveRecoveryKey(material, salt)2463            keyBytes = recoveryKey.encoded2464            plaintext = rootKeyToHex(rk).toByteArray(Charsets.US_ASCII)2465            // combined = nonce(12) || ciphertext || tag(16)2466            val combined = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)2467            val nonce = combined.copyOfRange(0, VaultCrypto.NONCE_SIZE)2468            val ctTag = combined.copyOfRange(VaultCrypto.NONCE_SIZE, combined.size)2469            val tag = ctTag.copyOfRange(ctTag.size - 16, ctTag.size)2470            val ct = ctTag.copyOfRange(0, ctTag.size - 16)2471            RootKeyEscrow(salt = b64(salt), wrappedRootKey = b64(ct), nonce = b64(nonce), tag = b64(tag))2472        } finally {2473            VaultCrypto.zero(rk)2474            VaultCrypto.zero(material)2475            keyBytes?.let(VaultCrypto::zero)2476            plaintext?.let(VaultCrypto::zero)2477        }2478    }24792480    /** Unwrap the 32-byte root key from a browser-compatible [escrow]; null on wrong words. */2481    private fun unsealRootKeyEscrow(words: List<String>, escrow: RootKeyEscrow): ByteArray? {2482        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2483        var keyBytes: ByteArray? = null2484        var pt: ByteArray? = null2485        return try {2486            val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))2487            keyBytes = recoveryKey.encoded2488            val combined = unb64(escrow.nonce) + unb64(escrow.wrappedRootKey) + unb64(escrow.tag)2489            pt = VaultCrypto.decrypt(combined, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)2490            hexToRootKey(String(pt, Charsets.US_ASCII))2491        } catch (_: Exception) {2492            null2493        } finally {2494            // M-05: pt is the lowercase hex of the 32-byte root key — i.e. the2495            // IKM-equivalent of the vault identity. material+keyBytes were2496            // already zeroed; pt was leaking.2497            VaultCrypto.zero(material)2498            keyBytes?.let(VaultCrypto::zero)2499            pt?.let(VaultCrypto::zero)2500        }2501    }25022503    /**2504     * Re-seal slot A from the current in-memory state under the live key, carrying2505     * both [recoveryEscrow] and [rootKeyEscrow] onto the written record. Never runs2506     * in decoy mode (recovery is never offered for the decoy) and persists without2507     * a version bump, like the recovery-words metadata write it replaces.2508     */2509    private fun persistSlotAWithEscrows(2510        recoveryEscrow: RecoveryEscrow?,2511        rootKeyEscrow: RootKeyEscrow?,2512        expectedEpoch: Long? = null,2513    ): Boolean {2514        val snapshot = snapshotForPersist(expectedEpoch)2515            ?: throw IllegalStateException("vault_locked_or_stale")2516        if (snapshot.decoy) {2517            VaultCrypto.zero(snapshot.key)2518            return false2519        }2520        try {2521            val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")2522            val plaintext = VaultCodec.encode(snapshot.payload)2523            val blob = try {2524                b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))2525            } finally {2526                // The escrow path used to drop this reference before zeroing it;2527                // keep it live through the fill on both success and failure.2528                VaultCrypto.zero(plaintext)2529            }2530            val next = prior.copy(2531                blob = blob,2532                recoveryEscrow = recoveryEscrow ?: prior.recoveryEscrow,2533                rootKeyEscrow = rootKeyEscrow ?: prior.rootKeyEscrow,2534            )2535            beforeDurableCommit()2536            return withEpochCommit(snapshot.epoch) {2537                if (!store.writeSlotA(next)) return@withEpochCommit false2538                try {2539                    if (!writeMatchingNoiseSlotB(next)) throw java.io.IOException("noise_slot_b_commit_failed")2540                    // H-04: escrow rebuild changes slot A's plaintext size, so re-pad2541                    // the duress slot too. A real decoy is left alone; a fake is2542                    // re-sized to slot A's new ciphertext length.2543                    if (!writeCompanionDuressSlot(next)) throw java.io.IOException("duress_slot_commit_failed")2544                } catch (e: Exception) {2545                    store.writeSlotA(prior)2546                    throw e2547                }2548                true2549            } ?: false2550        } finally {2551            VaultCrypto.zero(snapshot.key)2552        }2553    }25542555    // ---- Internals --------------------------------------------------------25562557    private fun requireUnlocked(): Long {2558        // H-03: read derivedKey atomically with [lock]'s reset; without it,2559        // [lock] from a background lifecycle event can run between this read2560        // and the caller's first state touch.2561        stateLock.lock()2562        try {2563            if (derivedKey == null) throw IllegalStateException("vault_locked")2564            return sessionEpoch2565        } finally {2566            stateLock.unlock()2567        }2568    }25692570    /** A locked or half-adopted session must not expose secret-bearing fields. */2571    private fun isFullyUnlockedLocked(): Boolean = _isUnlocked.value && derivedKey != null25722573    private fun countDuplicateEntriesLocked(): Int {2574        val seen = mutableMapOf<String, VaultEntry>()2575        var duplicates = 02576        for (entry in entryList.filter { it.deletedAt == null }) {2577            val key = entry.duplicateKey()2578            val existing = seen[key]2579            if (existing == null) {2580                seen[key] = entry2581            } else {2582                duplicates++2583                val entryStamp = entry.modifiedAt.takeIf { it > 0 } ?: entry.createdAt2584                val existingStamp = existing.modifiedAt.takeIf { it > 0 } ?: existing.createdAt2585                if (entryStamp > existingStamp) seen[key] = entry2586            }2587        }2588        return duplicates2589    }25902591    private fun VaultEntry.duplicateKey(): String {2592        if (type == "note") return "note|${title.lowercase()}"2593        val passkeyData = passkey2594        if (passkeyData != null) {2595            return "passkey|${passkeyData.rpId.lowercase()}|${passkeyData.userName.lowercase()}"2596        }2597        return "login|${title.lowercase()}|${url.orEmpty().lowercase()}|${username.orEmpty().lowercase()}"2598    }25992600    /**2601     * Capture the current slot pair (and metadata) into the history list.2602     * Returns true when the history write landed, false when it didn't — callers2603     * that depend on the snapshot existing (notably [restoreVaultSnapshot])2604     * must check the result and roll back if it does not.2605     */2606    private fun takeVaultSnapshot(reason: String, expectedEpoch: Long? = null): Boolean {2607        val epoch = expectedEpoch ?: currentEpoch()2608        if (mutateIfCurrentEpoch(epoch) { true } != true) return false2609        val slotA = store.loadSlotA() ?: return false2610        val vaultA = VaultCodec.encodeSlot(slotA)2611        val vaultB = store.loadSlotB() ?: slotA.blob2612        // H-04: capture the duress slot so a restore preserves the at-rest2613        // triad, not just the A/B pair. The duress slot is always present2614        // (real or fake), so loadDecoySlot() returning null is a logic error2615        // — fall through to a fake duress in that case rather than silently2616        // losing the record from the snapshot.2617        val vaultD = store.loadDecoySlot()?.let(VaultCodec::encodeSlot) ?: run {2618            val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 162619            val fakeBlob = ByteArray(target).also(rng::nextBytes)2620            val fakeSalt = VaultCrypto.generateSalt()2621            VaultCodec.encodeSlot(StoredVault(version = 1, salt = b64(fakeSalt), blob = b64(fakeBlob)))2622        }2623        val history = store.loadVaultHistory()2624        val latest = history.snapshots.firstOrNull()2625        if (latest?.vault_a == vaultA && latest.vault_b == vaultB && latest.vault_d == vaultD) return true2626        val entryCount = mutateIfCurrentEpoch(epoch) {2627            if (derivedKey != null && !decoyMode) {2628                bucketEntryCount(entryList.count { it.deletedAt == null })2629            } else {2630                null2631            }2632        } ?: return false2633        return try {2634            val snapshot = VaultSnapshot(2635                id = UUID.randomUUID().toString(),2636                savedAt = System.currentTimeMillis(),2637                reason = reason,2638                vault_a = vaultA,2639                vault_b = vaultB,2640                vault_d = vaultD,2641                entryCount = entryCount,2642            )2643            // P1-4 (codex): return the history-write boolean to callers so a2644            // false return no longer leaves the snapshot out of history while2645            // callers (notably restoreVaultSnapshot) proceed as if it succeeded.2646            withEpochCommit(epoch) {2647                store.writeVaultHistory(2648                    history.copy(snapshots = (listOf(snapshot) + history.snapshots).take(VAULT_HISTORY_MAX)),2649                )2650            } ?: false2651        } catch (_: Exception) {2652            false2653        }2654    }26552656    private fun bucketEntryCount(n: Int): Int = when {2657        n <= 0 -> 02658        n <= 10 -> 102659        n <= 25 -> 252660        n <= 50 -> 502661        n <= 100 -> 1002662        n <= 250 -> 2502663        n <= 500 -> 5002664        else -> ((n + 499) / 500) * 5002665    }26662667    /**2668     * Keep [VaultEntry.last4] in sync with the card number for card entries (MF-3),2669     * so it is stored explicitly and survives the sync wire format rather than being2670     * re-derived at render time. Non-card entries pass through unchanged.2671     *2672     * M-03: never overwrite a stored last4 with null. A card kept only as last42673     * (e.g. after a PeachScript import that had no PAN) must keep that value;2674     * re-deriving from an absent cardNumber would silently zero the field.2675     */2676    private fun withDerivedLast4(entry: VaultEntry): VaultEntry {2677        if (!entry.isCard()) return entry2678        val digits = entry.cardNumber?.filter { it.isDigit() } ?: ""2679        val derived = if (digits.length >= 4) digits.takeLast(4) else null2680        return entry.copy(last4 = derived ?: entry.last4)2681    }26822683    /**2684     * On unlock, hard-delete trashed entries older than the retention window.2685     * A null or non-positive [VaultSettings.trashRetentionDays] means "never"2686     * (the app's "Never" option), so nothing is purged. Persists without a2687     * version bump and without touching the publish state (caller publishes).2688     */2689    private fun autoPurgeExpiredTrash() {2690        val days = _settings.value.trashRetentionDays ?: return2691        if (days <= 0) return2692        val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L2693        val before = entryList.size2694        entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }2695        if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }2696    }26972698    /**2699     * Browser parity (P1): merge orphaned passkey-only entries into matching2700     * login entries that share the same registrable domain. A passkey-only2701     * entry has passkey fields (rpId + credentialId) but no password. Runs on2702     * unlock so consolidation is idempotent and cheap.2703     */2704    private fun consolidatePasskeyEntries() {2705        val passkeyOnly = entryList.filter { entry ->2706            entry.deletedAt == null &&2707                entry.isLogin() &&2708                entry.password.isNullOrBlank() &&2709                !entry.rpId.isNullOrBlank() &&2710                !entry.credentialId.isNullOrBlank()2711        }2712        if (passkeyOnly.isEmpty()) return2713        var changed = false2714        val now = System.currentTimeMillis()2715        for (pkEntry in passkeyOnly) {2716            val rpId = pkEntry.rpId ?: continue2717            val target = entryList.firstOrNull { candidate ->2718                candidate.deletedAt == null &&2719                    candidate.id != pkEntry.id &&2720                    candidate.isLogin() &&2721                    candidate.passkey == null &&2722                    candidate.credentialId.isNullOrBlank() &&2723                    !candidate.password.isNullOrBlank() &&2724                    listOfNotNull(candidate.url, *candidate.additionalUrls.orEmpty().toTypedArray())2725                        .any { com.peachpasswords.shared.extractDomain(it) == rpId }2726            } ?: continue2727            val idx = entryList.indexOfFirst { it.id == target.id }2728            if (idx < 0) continue2729            entryList[idx] = target.copy(2730                rpId = pkEntry.rpId,2731                rpName = pkEntry.rpName ?: target.rpName,2732                credentialId = pkEntry.credentialId,2733                publicKeyCose = pkEntry.publicKeyCose,2734                privateKeyJwk = pkEntry.privateKeyJwk,2735                userHandle = pkEntry.userHandle,2736                userName = pkEntry.userName,2737                userDisplayName = pkEntry.userDisplayName,2738                algorithm = pkEntry.algorithm,2739                signCount = pkEntry.signCount,2740                lastUsedAt = pkEntry.lastUsedAt,2741                modifiedAt = now,2742            )2743            // Soft-delete the orphan so it lands in trash (recoverable).2744            val pkIdx = entryList.indexOfFirst { it.id == pkEntry.id }2745            if (pkIdx >= 0) entryList[pkIdx] = pkEntry.copy(deletedAt = now)2746            changed = true2747        }2748        if (changed) runCatching { persistSlotA(bumpVersion = false) }2749    }27502751    /** The slot-A plaintext envelope for the current in-memory session. */2752    private fun currentPayload(): VaultPayload = mutateState { currentPayloadLocked() }27532754    private fun currentPayloadLocked(): VaultPayload =2755        VaultPayload(2756            entries = entryList.toList(),2757            duressConfigured = authenticatedDuressConfigured,2758            rootKeyB64 = rootKey?.let(::b64) ?: "",2759            recoveryWordHash = recoveryWordHash,2760            recoveryWordsSet = recoveryWordsSet,2761        )27622763    /**2764     * Adopt the payload's root key, lazily minting one for legacy payloads.2765     * A freshly-minted key is persisted WITHOUT bumping the version — adopting2766     * a root key is not a mutation paired devices should sync against.2767     */2768    private fun ensureRootKey(payload: VaultPayload) {2769        if (payload.rootKeyB64.isNotBlank()) {2770            rootKey = unb64(payload.rootKeyB64)2771            return2772        }2773        rootKey = generateRecoverableRootKey()2774        runCatching { persistSlotA(bumpVersion = false) }2775    }27762777    private fun publish() {2778        _entries.value = entryList.filter { it.deletedAt == null }2779    }27802781    private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {2782        var plaintext = VaultCodec.encode(currentPayload())2783        return try {2784            val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))2785            StoredVault(version = 1, salt = b64(salt), blob = blob)2786        } finally {2787            // M-05: full vault plaintext is allocated here once per createVault.2788            // Zeroing in finally keeps the transient copy off the heap after the2789            // caller either succeeds or rolls back via lock().2790            VaultCrypto.zero(plaintext)2791        }2792    }27932794    private fun writeMatchingNoiseSlotB(slotA: StoredVault): Boolean {2795        // Size the noise so its base64 length matches slot A's blob (MN-1): with the2796        // plaintext now bucket-padded, an at-rest observer sees two equal-length slots2797        // and cannot pick the real one by size. b64(N bytes) ≈ N*4/3 chars.2798        val approxBytes = (slotA.blob.length * 3 / 4).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)2799        val noise = ByteArray(approxBytes).also(rng::nextBytes)2800        return store.writeSlotB(b64(noise))2801    }28022803    /** H-04: the ciphertext length slot A is using right now, so the duress2804     *  slot's blob can match it on disk. AES-GCM is a stream cipher — plaintext2805     *  length equals ciphertext length, so this also matches slot A's plaintext. */2806    private fun matchingCiphertextLength(slotA: StoredVault): Int =2807        (unb64(slotA.blob).size - VaultCrypto.NONCE_SIZE - 16).coerceAtLeast(0)28082809    /** H-04: a decoy-shaped StoredVault with a random blob of [matchingCiphertextLength]2810     *  bytes. Replaces a real decoy when the user clears duress, and is the2811     *  initial duress slot when no decoy is configured — so the record's2812     *  PRESENCE on disk is independent of authenticatedDuressConfigured, and its SIZE2813     *  matches slot A's blob length. */2814    private fun writeFakeDuressSlot(slotA: StoredVault): Boolean {2815        val blobSize = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 162816        val fakeBlob = ByteArray(blobSize).also(rng::nextBytes)2817        val fakeSalt = VaultCrypto.generateSalt()2818        return store.writeDecoySlot(StoredVault(version = 1, salt = b64(fakeSalt), blob = b64(fakeBlob)))2819    }28202821    /** H-04: keep the duress record present on every persist. A real decoy is2822     *  left alone (it was padded at setDuressPassphrase time, and we don't have2823     *  the duress key here to re-seal it) — VaultStore re-pads both slot2824     *  records to the longer of the two on every write, which is what keeps the2825     *  pair the same length after slot A crosses a padding bucket2826     *  (PAI-2026-004). No real decoy → a fresh fake of slot A's size. */2827    private fun writeCompanionDuressSlot(slotA: StoredVault): Boolean {2828        val isConfigured = mutateState { authenticatedDuressConfigured }2829        return if (isConfigured) true else writeFakeDuressSlot(slotA)2830    }28312832    /**2833     * H-04: convert a browser-shaped duress slot to Android StoredVault2834     * without decrypting. The browser seals slot "b" under the duress2835     * passphrase; decrypting with the main password silently drops it.2836     * Concatenates nonce‖ciphertext‖tag into Android's blob and re-encodes2837     * the salt from hex to base64.2838     */2839    private fun browserDuressPassthrough(b: BrowserSlotA): StoredVault {2840        val salt = unhex(b.salt)2841        val nonce = unhex(b.nonce)2842        val ct = unhex(b.ciphertext)2843        val tag = unhex(b.tag)2844        val blob = ByteArray(nonce.size + ct.size + tag.size).also {2845            System.arraycopy(nonce, 0, it, 0, nonce.size)2846            System.arraycopy(ct, 0, it, nonce.size, ct.size)2847            System.arraycopy(tag, 0, it, nonce.size + ct.size, tag.size)2848        }2849        return StoredVault(version = 1, salt = b64(salt), blob = b64(blob))2850    }28512852    /** Re-seal slot A from the current in-memory state under the live key. */2853    private fun persistSlotA(2854        bumpVersion: Boolean,2855        snapshotReason: String? = "local_save",2856        expectedEpoch: Long? = null,2857    ): Boolean {2858        val snapshot = snapshotForPersist(expectedEpoch)2859            ?: throw IllegalStateException("vault_locked_or_stale")2860        return try {2861            // Decoy sessions persist to the decoy slot only — never touch the real slot A.2862            if (snapshot.decoy) {2863                val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")2864                val plaintext = VaultCodec.encode(snapshot.payload)2865                val blob = try {2866                    b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))2867                } finally {2868                    // Keep the last reference alive until the zero, including the2869                    // successful encrypt path (M-05).2870                    VaultCrypto.zero(plaintext)2871                }2872                beforeDurableCommit()2873                return withEpochCommit(snapshot.epoch) {2874                    store.writeDecoySlot(prior.copy(blob = blob))2875                } ?: false2876            }2877            val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")2878            // H-01: captured BEFORE the noise write so a stamp failure can restore2879            // the prior slot B alongside the prior slot A. Slot B is always2880            // overwritten by writeMatchingNoiseSlotB below, so a stamp failure2881            // leaves (new A, new B, old version) on disk — partial commit.2882            val priorB = store.loadSlotB()2883            beforeDurableCommit()2884            if (snapshotReason != null && !takeVaultSnapshot(snapshotReason, snapshot.epoch)) return false2885            val plaintext = VaultCodec.encode(snapshot.payload)2886            val blob = try {2887                b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))2888            } finally {2889                // Do not drop [plaintext] before fill(0): the serialized vault2890                // contains every entry password and is the primary M-05 target.2891                VaultCrypto.zero(plaintext)2892            }2893            val next = prior.copy(blob = blob)2894            // The epoch check and the entire A/B/D/version commit share one brief2895            // stateLock critical section. lock() either wins before this block or2896            // waits until the already-committed write is complete; it can never2897            // clear the session between the check and the durable write.2898            withEpochCommit(snapshot.epoch) {2899                if (!store.writeSlotA(next)) return@withEpochCommit false2900                try {2901                    if (!writeMatchingNoiseSlotB(next)) throw java.io.IOException("noise_slot_b_commit_failed")2902                    // H-04: duress slot stays present (real one untouched, fake one2903                    // re-padded to slot A's current size on every persist).2904                    if (!writeCompanionDuressSlot(next)) throw java.io.IOException("duress_slot_commit_failed")2905                    if (bumpVersion) store.stampLocalMutation()2906                } catch (e: Exception) {2907                    store.writeSlotA(prior)2908                    if (priorB != null) runCatching { store.writeSlotB(priorB) }2909                    throw e2910                }2911                true2912            } ?: false2913        } finally {2914            // Snapshot keys are copies, so lock() may zero the live key while this2915            // operation is still deriving/encrypting; always scrub our copy too.2916            VaultCrypto.zero(snapshot.key)2917        }2918    }29192920    /**2921     * H-01: durably commit a slot-A rotation by writing slot A, its2922     * size-matched noise slot B, and the local-mutation stamp in order. Any2923     * failure rolls the previously-committed steps back so the at-rest pair2924     * matches what was there before the call. Returns true only when every2925     * step succeeded — callers must NOT swap their session key on false.2926     */2927    private fun commitVaultRotation(2928        priorA: StoredVault,2929        priorB: String?,2930        nextA: StoredVault,2931        expectedEpoch: Long,2932    ): Boolean {2933        beforeDurableCommit()2934        return withEpochCommit(expectedEpoch) {2935            if (!store.writeSlotA(nextA)) return@withEpochCommit false2936            // P1-1 (codex): the noise write's boolean AND any thrown exception from2937            // it must trigger rollback; previously a throw from writeMatchingNoiseSlotB2938            // escaped the helper and left slot A committed.2939            try {2940                if (!writeMatchingNoiseSlotB(nextA)) throw java.io.IOException("noise_slot_b_commit_failed")2941                // H-04: a password rotation changes slot A's plaintext size (new2942                // salt → re-encrypted blob), so the duress slot must be re-padded2943                // alongside. writeCompanionDuressSlot leaves a real decoy alone2944                // and re-emits a fake of slot A's size otherwise.2945                if (!writeCompanionDuressSlot(nextA)) throw java.io.IOException("duress_slot_commit_failed")2946                store.stampLocalMutation()2947            } catch (_: Exception) {2948                rollbackRotation(priorA, priorB)2949                return@withEpochCommit false2950            }2951            true2952        } ?: false2953    }29542955    /**2956     * Best-effort undo of the writes [commitVaultRotation] may have committed.2957     * Each step runs independently — a failed rollback must not mask the2958     * original commit failure. Log is a throwing stub off-device.2959     */2960    private fun rollbackRotation(priorA: StoredVault, priorB: String?) {2961        val failures = mutableListOf<String>()2962        runCatching { if (!store.writeSlotA(priorA)) failures += "writeSlotA returned false" }2963            .onFailure { failures += "writeSlotA: $it" }2964        if (priorB != null) {2965            runCatching { if (!store.writeSlotB(priorB)) failures += "writeSlotB returned false" }2966                .onFailure { failures += "writeSlotB: $it" }2967        }2968        if (failures.isNotEmpty()) runCatching { Log.w("PeachVault", "vault rotation rollback incomplete: $failures") }2969    }29702971    /** Persist a local mutation, rolling the in-memory list back on failure. */2972    private fun persistOrRollback(rollback: MutableList<VaultEntry>, expectedEpoch: Long) {2973        try {2974            if (!persistSlotA(bumpVersion = true, expectedEpoch = expectedEpoch)) {2975                mutateIfCurrentEpoch(expectedEpoch) { entryList = rollback }2976                throw IllegalStateException("storage_write_failed")2977            }2978        } catch (e: Exception) {2979            mutateIfCurrentEpoch(expectedEpoch) { entryList = rollback }2980            throw e2981        }2982        // A lock can win in the small interval after the durable commit and2983        // before publication. The epoch check prevents pre-lock entries from2984        // being republished into a newly locked (or newly unlocked) session.2985        mutateIfCurrentEpoch(expectedEpoch) { publish() }2986        runCatching { LockedSyncSpoolHooks.refresh(this) }2987    }2988}