VaultRepository.kt

141.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 duressConfigured: 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()193194195    /**196     * UI-only gate for sync-retained background mode. The vault stays unlocked197     * in memory (sync can proceed) but the UI shows the lock screen until the198     * user authenticates on resume. Cleared by a full [lock] or an explicit199     * [clearUiGate] from the lock screen.200     */201    private val _uiGateLocked = MutableStateFlow(false)202    val uiGateLocked: StateFlow<Boolean> = _uiGateLocked.asStateFlow()203204    private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())205    /** Active (non-deleted) entryList. */206    val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()207208    // Settings live in plain prefs, not inside the sealed vault — they hold no209    // secrets — so they are readable before unlock. Loading them here keeps the210    // lock screen at the user's chosen appearance instead of the defaults, which211    // otherwise snap to the real values the moment they authenticate.212    private val _settings = MutableStateFlow(store.loadSettings())213    val settings: StateFlow<VaultSettings> = _settings.asStateFlow()214215    /** Clear every in-memory session field while [stateLock] is held. */216    private fun clearSessionStateLocked() {217        derivedKey?.let(VaultCrypto::zero)218        rootKey?.let(VaultCrypto::zero)219        derivedKey = null220        rootKey = null221        entryList = mutableListOf()222        duressConfigured = false223        recoveryWordHash = null224        recoveryWordsSet = false225        sessionDataAvailable = false226        decoyMode = false227        _settings.value = store.loadSettings()228        _entries.value = emptyList()229        _isUnlocked.value = false230    }231232    fun hasVault(): Boolean = store.hasVault()233234    // ---- Codex (printed paper backup) -------------------------------------235236    /**237     * The at-rest slot pair as base64 JSON `{"a": <StoredVault>, "b": <StoredVault>}` — the238     * Codex payload's vaultBlob. "b" is the duress slot (matching the browser's239     * A/B naming where slot B is the duress decoy); the noise slot is local-only240     * and never crosses devices. Restorable on any device that has the master241     * password. Null when no vault exists.242     */243    fun codexVaultBlobBase64(): String? {244        val slotA = store.loadSlotA() ?: return null245        // H-04: duress slot is always present after createVault (real or fake),246        // so the wrapper can rely on it being loadable.247        val slotD = store.loadDecoySlot() ?: return null248        val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)},"b":${VaultCodec.encodeSlot(slotD)}}"""249        return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))250    }251252    /**253     * Replace the local vault from a Codex blob, then unlock with [password].254     * Writes slot A (and a size-matched noise slot B) before unlocking so the255     * restored vault is at rest exactly as a freshly-created one would be.256     */257    /** A slot is stored either as a JSON string (browser) or inline object (Android). */258    private fun JsonElement?.asSlotJson(): String? = when {259        this == null || this is JsonNull -> null260        this is JsonPrimitive && isString -> content261        else -> toString()262    }263264    suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {265        val expectedEpoch = currentEpoch()266        var candidateKey: ByteArray? = null267        var plaintext: ByteArray? = null268        return try {269            val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)270            // Parsed as JSON, not matched with a regex. The wrapper is271            // `{ "a": <slot>, "b": <slot|null> }` and the browser — which272            // generates most real Codexes — writes each slot as a JSON273            // *string*, with "b" present. A regex looking for an object274            // literal under "a" at the very end of the wrapper matches275            // neither of those, so every browser-generated Codex failed here276            // with "invalid_codex_blob" after decoding perfectly.277            val wrapper = CodexJson.parseToJsonElement(wrapperJson) as? JsonObject278                ?: return UnlockResult.Error("invalid_codex_blob")279            val slotJson = wrapper["a"].asSlotJson() ?: return UnlockResult.Error("invalid_codex_blob")280            // A Codex printed from the browser carries a browser-shaped slot,281            // which is the common case — most Codexes are printed there. It is282            // translated to Android's shape (see BrowserSlot) rather than283            // rejected. A translation failure is a wrong password, not a bad284            // blob: the codes decoded fine, the password just didn't open them.285            val slotA = VaultCodec.decodeSlot(slotJson)286                ?: BrowserSlot.parse(slotJson)?.let {287                    BrowserSlot.toAndroidSlot(it, password) ?: return UnlockResult.WrongPassword288                }289                ?: return UnlockResult.Error("invalid_codex_blob")290            // C-01: authenticate the candidate ENTIRELY in memory before touching291            // storage. VaultCodec.decodeSlot is structural — an Android-shaped292            // Codex parses under ANY password — so writing slot A first and293            // unlocking afterwards destroyed the device's existing vault every294            // time the user mistyped the password.295            candidateKey = VaultCrypto.deriveKey(password, unb64(slotA.salt))296            plaintext = decryptSlotABlob(slotA, candidateKey)297            // LV-1: a Codex printed from a vault sealed before NFC normalization298            // opens only under the raw password bytes. unlockLocked used to supply299            // this fallback; authenticating up front here has to keep it, or those300            // Codexes become unrestorable.301            if (plaintext == null && password != Normalizer.normalize(password, Normalizer.Form.NFC)) {302                VaultCrypto.zero(candidateKey)303                candidateKey = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))304                plaintext = decryptSlotABlob(slotA, candidateKey)305            }306            if (plaintext == null) return UnlockResult.WrongPassword307            val payload = try {308                VaultCodec.decode(plaintext)309            } catch (_: Exception) {310                return UnlockResult.Error("invalid_codex_blob")311            }312313            val priorA = store.loadSlotA()314            val priorB = store.loadSlotB()315            val priorD = store.loadDecoySlot()316            // Carry the real duress slot across when the Codex has one — the317            // browser writes "b" as its duress-shaped slot, and dropping it318            // here would silently destroy a configured decoy.319            // H-04: write browser B into the duress slot (not the noise slot),320            // translating browser-shaped slots to Android's StoredVault shape.321            val codexDuressJson = wrapper["b"].asSlotJson()322            val codexDuress: StoredVault? = codexDuressJson?.let {323                VaultCodec.decodeSlot(it) ?: BrowserSlot.parse(it)?.let { b ->324                    // H-04: pass-through — the browser duress slot is sealed325                    // under the duress passphrase, not the main password. Trying326                    // to decrypt with the slot-A password fails the GCM tag and327                    // silently drops a real decoy. Re-encode the browser hex328                    // fields as Android base64 salt/blob so tryUnlockDuress can329                    // still open it with the duress passphrase.330                    browserDuressPassthrough(b)331                }332            }333334            beforeDurableCommit()335            val committed = runCatching {336                withEpochCommit(expectedEpoch) {337                    try {338                        // Keep every slot write, including the inverse, under the339                        // same epoch fence. Releasing stateLock after a partial340                        // write and reacquiring it for rollback lets lock() advance341                        // the epoch in between and strand the incoming slot A.342                        if (!store.writeSlotA(slotA)) throw java.io.IOException("slot_a_commit_failed")343                        // Noise slot is always size-matched to slot A — local-only,344                        // never written from a Codex.345                        if (!writeMatchingNoiseSlotB(slotA)) throw IllegalStateException("noise_slot_commit_failed")346                        // H-04: duress slot always present; real one from the Codex or347                        // a fake the size of slot A.348                        val duressOk = if (codexDuress != null) {349                            store.writeDecoySlot(codexDuress)350                        } else {351                            writeFakeDuressSlot(slotA)352                        }353                        if (!duressOk) throw IllegalStateException("duress_slot_commit_failed")354                        store.stampLocalMutation()355                        true356                    } catch (_: Exception) {357                        reportRollbackFailures(rollbackRestoreLocked(priorA, priorB, priorD))358                        // Keep the fence held through the final rollback359                        // observation. A concurrent lock() may queue here, but360                        // cannot invalidate the restored A/B/D triad.361                        afterCodexRollback()362                        false363                    }364                } ?: false365            }.getOrDefault(false)366            if (!committed) {367                return UnlockResult.Error("storage_write_failed")368            }369370            val ownedKey = candidateKey!!371            candidateKey = null // the session owns the key from here on372            adoptSlotA(ownedKey, payload, expectedEpoch)373        } catch (e: Exception) {374            // A raw kotlinx parse error ("Unexpected JSON token at offset N")375            // reaching the user says nothing about WHICH json failed — the376            // wrapper, or the payload decrypted out of it. Codex screens are377            // FLAG_SECURE so this can't be screenshotted either. Debug builds378            // log the structure around the failure; alphanumerics are masked so379            // no ciphertext or vault content lands in a log.380            if (BuildConfig.DEBUG) Log.w("PeachCodex", codexFailureShape(vaultBlobBase64, e))381            UnlockResult.Error(e.message ?: "restore_failed")382        } finally {383            plaintext?.let(VaultCrypto::zero)384            candidateKey?.let(VaultCrypto::zero)385        }386    }387388    /** Slot-A plaintext under [key], or null when the GCM tag fails (wrong password). */389    private fun decryptSlotABlob(slot: StoredVault, key: ByteArray): ByteArray? =390        runCatching { VaultCrypto.decrypt(unb64(slot.blob), key, VaultCrypto.AAD_SLOT_A) }.getOrNull()391392    /**393     * Undo a partially-committed Codex restore while [stateLock] is already held.394     * Every step is attempted independently so one failure cannot strand the395     * others. Callers that need epoch validation must enter through396     * [withEpochCommit] first; this helper deliberately does not reacquire the397     * lock, avoiding a reentrant gap between a failed write and its inverse.398     * With no prior vault the accurate inverse is having none at all, rather399     * than a half-written slot A that [hasVault] would report as a real vault.400     */401    private fun rollbackRestoreLocked(402        priorA: StoredVault?,403        priorB: String?,404        priorD: StoredVault? = null,405    ): List<String> {406        val failures = mutableListOf<String>()407        if (priorA == null) {408            runCatching { store.clearVault() }.onFailure { failures += "clearVault: $it" }409        } else {410            runCatching { if (!store.writeSlotA(priorA)) failures += "writeSlotA returned false" }411                .onFailure { failures += "writeSlotA: $it" }412            if (priorB != null) {413                runCatching { if (!store.writeSlotB(priorB)) failures += "writeSlotB returned false" }414                    .onFailure { failures += "writeSlotB: $it" }415            }416            // H-04: restore the prior duress slot — a half-committed restore that417            // left the duress record on the Codex side and slot A on the prior418            // side would put the at-rest pair in a state that never existed.419            if (priorD != null) {420                runCatching { if (!store.writeDecoySlot(priorD)) failures += "writeDecoySlot returned false" }421                    .onFailure { failures += "writeDecoySlot: $it" }422            } else {423                runCatching { store.clearDecoySlot() }.onFailure { failures += "clearDecoySlot: $it" }424            }425        }426        return failures427    }428429    private fun reportRollbackFailures(failures: List<String>) {430        // Log is a throwing stub off-device, and a failed log must never mask431        // the rollback result the caller is about to report.432        if (failures.isNotEmpty()) runCatching { Log.w("PeachCodex", "codex rollback incomplete: $failures") }433    }434435    /** Debug-only: structure of a failed Codex restore, with content masked. */436    private fun codexFailureShape(vaultBlobBase64: String, e: Exception): String = runCatching {437        val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)438        val offset = Regex("offset (\\d+)").find(e.message.orEmpty())?.groupValues?.get(1)?.toIntOrNull()439        val window = offset?.let {440            val from = (it - 40).coerceAtLeast(0)441            val to = (it + 40).coerceAtMost(wrapperJson.length)442            wrapperJson.substring(from, to).replace(Regex("[A-Za-z0-9+/=_-]"), "x")443        }444        val wrapper = runCatching { CodexJson.parseToJsonElement(wrapperJson) as? JsonObject }.getOrNull()445        val slot = wrapper?.get("a")446        buildString {447            append("codex restore failed: ").append(e::class.simpleName).append(": ").append(e.message)448            append(" | blobBase64=").append(vaultBlobBase64.length)449            append(" wrapperChars=").append(wrapperJson.length)450            append(" wrapperParses=").append(wrapper != null)451            append(" keys=").append(wrapper?.keys)452            append(" slotAKind=").append(453                when {454                    slot == null -> "absent"455                    slot is JsonPrimitive && slot.isString -> "string"456                    slot is JsonObject -> "object:" + slot.keys457                    else -> slot::class.simpleName458                },459            )460            if (window != null) append(" masked@").append(offset).append("=").append(window)461        }462    }.getOrElse { "codex restore failed: ${e.message} (shape unavailable: $it)" }463464    suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {465        val expectedEpoch = currentEpoch()466        var key: ByteArray? = null467        return try {468            val salt = VaultCrypto.generateSalt()469            key = VaultCrypto.deriveKey(password, salt)470            if (mutateIfCurrentEpoch(expectedEpoch) {471                entryList = mutableListOf()472                duressConfigured = false473                recoveryWordHash = null474                recoveryWordsSet = false475                decoyMode = false476                sessionDataAvailable = false477                rootKey = generateRecoverableRootKey()478            } == null) return CreateVaultResult.Error("stale_create")479            // M-04: the fields above have to be live before sealSlotA, since it480            // seals currentPayload(). That stages a root key the session would481            // otherwise keep after a failed create — [lock] discards the whole482            // staged session on every non-success exit below.483            val slotA = sealSlotA(key!!, salt)484            // P1-3 (codex): every later step must roll the slot pair back if it485            // fails — leaving a half-built vault is worse than refusing to make it.486            beforeDurableCommit()487            val created = withEpochCommit(expectedEpoch) {488                if (!store.writeSlotA(slotA)) return@withEpochCommit false489                try {490                    if (!writeMatchingNoiseSlotB(slotA)) throw java.io.IOException("noise_slot_b_commit_failed")491                    // H-04: duress slot must be present from the start so its492                    // existence on disk is independent of duressConfigured.493                    if (!writeFakeDuressSlot(slotA)) throw java.io.IOException("duress_slot_commit_failed")494                    store.stampLocalMutation()495                    if (!store.writeSettings(_settings.value)) throw java.io.IOException("settings_commit_failed")496                    true497                } catch (_: Exception) {498                    // Half-built vault on disk is worse than no vault — refuse to499                    // create if any step past slot A fails.500                    store.clearVault()501                    false502                }503            } ?: false504            if (!created) {505                lock()506                return CreateVaultResult.Error("storage_write_failed")507            }508            val sessionKey = key ?: return CreateVaultResult.Error("create_key_missing")509            if (mutateIfCurrentEpoch(expectedEpoch) {510                derivedKey = sessionKey511                key = null512                publish()513                _isUnlocked.value = true514                sessionDataAvailable = true515                sessionEpoch = nextSessionEpoch(sessionEpoch)516            } == null) return CreateVaultResult.Error("stale_create")517            CreateVaultResult.Success518        } catch (e: Exception) {519            lock()520            CreateVaultResult.Error(e.message ?: "create_failed")521        } finally {522            key?.let(VaultCrypto::zero)523        }524    }525526    suspend fun createVaultFromRootKey(password: String, rootKeyHex: String): AdoptVaultResult = mutex.withLock {527        val expectedEpoch = currentEpoch()528        if (password.isEmpty()) return AdoptVaultResult.Error("ADOPT_INVALID_PASSWORD")529        if (store.hasVault()) return AdoptVaultResult.Error("ADOPT_VAULT_ALREADY_EXISTS")530        if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {531            return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars")532        }533        var adoptedRootKey: ByteArray? = null534        var nextDerivedKey: ByteArray? = null535        var sessionRootKey: ByteArray? = null536        return try {537            adoptedRootKey = hexToRootKey(rootKeyHex)538            if (adoptedRootKey.size != VaultCrypto.KEY_SIZE) {539                return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes")540            }541            val vaultId = com.peachpasswords.sync.computeVaultId(adoptedRootKey)542            val salt = VaultCrypto.generateSalt()543            nextDerivedKey = VaultCrypto.deriveKey(password, salt)544            sessionRootKey = adoptedRootKey.copyOf()545            val payload = VaultPayload(546                entries = emptyList(),547                duressConfigured = false,548                rootKeyB64 = b64(sessionRootKey),549                recoveryWordHash = null,550                recoveryWordsSet = false,551            )552            val plaintext = VaultCodec.encode(payload)553            val blob = try {554                b64(VaultCrypto.encrypt(plaintext, nextDerivedKey, VaultCrypto.AAD_SLOT_A))555            } finally {556                VaultCrypto.zero(plaintext)557            }558            val slotA = StoredVault(version = 1, salt = b64(salt), blob = blob)559            // P1-3 (codex): same partial-commit guard as createVault — any failure560            // past slot A wipes the half-built vault and refuses adoption.561            beforeDurableCommit()562            val created = withEpochCommit(expectedEpoch) {563                if (!store.writeSlotA(slotA)) return@withEpochCommit false564                try {565                    if (!writeMatchingNoiseSlotB(slotA)) throw java.io.IOException("noise_slot_b_commit_failed")566                    // H-04: duress slot must be present from the start so its567                    // existence on disk is independent of duressConfigured.568                    if (!writeFakeDuressSlot(slotA)) throw java.io.IOException("duress_slot_commit_failed")569                    store.stampLocalMutation()570                    if (!store.writeSettings(_settings.value)) throw java.io.IOException("settings_commit_failed")571                    true572                } catch (_: Exception) {573                    store.clearVault()574                    false575                }576            } ?: false577            if (!created) return AdoptVaultResult.Error("storage_write_failed")578579            val adopted = mutateIfCurrentEpoch(expectedEpoch) {580                val previousDerivedKey = derivedKey581                val previousRootKey = rootKey582                derivedKey = nextDerivedKey583                rootKey = sessionRootKey584                nextDerivedKey = null585                sessionRootKey = null586                entryList = mutableListOf()587                duressConfigured = false588                recoveryWordHash = null589                recoveryWordsSet = false590                decoyMode = false591                sessionDataAvailable = true592                publish()593                _isUnlocked.value = true594                sessionEpoch = nextSessionEpoch(sessionEpoch)595                previousDerivedKey to previousRootKey596            }597            if (adopted == null) return AdoptVaultResult.Error("stale_adoption")598            val (previousDerivedKey, previousRootKey) = adopted599            previousDerivedKey?.let(VaultCrypto::zero)600            previousRootKey?.let(VaultCrypto::zero)601            // Write the recovery escrow so the forgot-password flow works on602            // this device. The words are deterministic from the root key and603            // were already confirmed on the source device.604            runCatching {605                val words = rootKeyToWords(rootKey!!)606                val escrow = buildRecoveryEscrow(words)607                val rkEscrow = buildRootKeyEscrow(words)608                if (escrow != null || rkEscrow != null) {609                    val prior = store.loadSlotA()610                    if (prior != null) {611                        store.writeSlotA(prior.copy(612                            recoveryEscrow = escrow ?: prior.recoveryEscrow,613                            rootKeyEscrow = rkEscrow ?: prior.rootKeyEscrow,614                        ))615                    }616                    mutateState {617                        recoveryWordHash = recoveryWordsHash(words)618                        recoveryWordsSet = true619                    }620                }621            }622            AdoptVaultResult.Success(vaultId)623        } catch (e: Exception) {624            AdoptVaultResult.Error(e.message ?: "adoption_create_failed")625        } finally {626            adoptedRootKey?.let(VaultCrypto::zero)627            nextDerivedKey?.let(VaultCrypto::zero)628            sessionRootKey?.let(VaultCrypto::zero)629        }630    }631632    suspend fun unlock(password: String): UnlockResult = mutex.withLock {633        val result = unlockLocked(password, currentEpoch())634        if (result is UnlockResult.Success) ensureRecoveryEscrow()635        result636    }637638    /** Unlock body without acquiring the mutex — callers must already hold it. */639    private fun unlockLocked(password: String, expectedEpoch: Long): UnlockResult {640        val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")641        val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))642        val payload = try {643            val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A)644            try {645                VaultCodec.decode(plaintext)646            } finally {647                VaultCrypto.zero(plaintext)648            }649        } catch (_: Exception) {650            VaultCrypto.zero(key)651            // LV-1: a vault sealed before NFC normalization with a non-NFC652            // password derives a different key now. If the supplied password is653            // not already in NFC form, retry with the raw (un-normalized) bytes.654            if (password != Normalizer.normalize(password, Normalizer.Form.NFC)) {655                val legacy = tryLegacyRawUnlock(password, slotA, expectedEpoch)656                if (legacy != null) return legacy657            }658            return UnlockResult.WrongPassword659        }660        return adoptSlotA(key, payload, expectedEpoch)661    }662663    /**664     * LV-1 legacy fallback: unlock a slot-A vault that was sealed under the raw665     * (un-normalized) password bytes. On success the slot is HEALED — re-sealed666     * under the NFC-normalized key — so every future unlock takes the normal667     * path. Returns null when the raw key also fails (genuinely wrong password)668     * OR when any step of the heal commits fails (the original slot A is restored669     * so disk and session stay aligned).670     */671    private fun tryLegacyRawUnlock(password: String, slotA: StoredVault, expectedEpoch: Long): UnlockResult? {672        var rawKey: ByteArray? = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))673        var newKey: ByteArray? = null674        return try {675            val payload = try {676                val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), rawKey!!, VaultCrypto.AAD_SLOT_A)677                try {678                    VaultCodec.decode(plaintext)679                } finally {680                    VaultCrypto.zero(plaintext)681                }682            } catch (_: Exception) {683                return null684            }685            // Heal: re-seal slot A under the NFC key (mirrors changePassword's686            // re-seal). Escrows carry forward unchanged — only the wrapping rotates.687            val newSalt = VaultCrypto.generateSalt()688            newKey = VaultCrypto.deriveKey(password, newSalt)689            val plaintext = VaultCodec.encode(payload)690            val blob = try {691                b64(VaultCrypto.encrypt(plaintext, newKey!!, VaultCrypto.AAD_SLOT_A))692            } finally {693                VaultCrypto.zero(plaintext)694            }695            val next = StoredVault(696                version = slotA.version,697                salt = b64(newSalt),698                blob = blob,699                recoveryEscrow = slotA.recoveryEscrow,700                rootKeyEscrow = slotA.rootKeyEscrow,701            )702            // P1-1/P1-3/P1-2 (codex): any failure of writeSlotA, writeMatchingNoiseSlotB,703            // or stampLocalMutation must restore the prior slot A AND slot B so disk704            // and the eventual session key never disagree on the wrapping.705            val priorB = store.loadSlotB()706            beforeDurableCommit()707            val healed = withEpochCommit(expectedEpoch) {708                if (!store.writeSlotA(next)) {709                    false710                } else try {711                    if (!writeMatchingNoiseSlotB(next)) {712                        runCatching { store.writeSlotA(slotA) }713                        if (priorB != null) runCatching { store.writeSlotB(priorB) }714                        false715                    } else if (!writeCompanionDuressSlot(next)) {716                        runCatching { store.writeSlotA(slotA) }717                        if (priorB != null) runCatching { store.writeSlotB(priorB) }718                        false719                    } else {720                        store.stampLocalMutation()721                        true722                    }723                } catch (_: Exception) {724                    runCatching { store.writeSlotA(slotA) }725                    if (priorB != null) runCatching { store.writeSlotB(priorB) }726                    false727                }728            } ?: false729            if (healed) {730                VaultCrypto.zero(rawKey!!)731                rawKey = null732                val result = adoptSlotA(newKey!!, payload, expectedEpoch) // session key now matches the re-sealed slot733                newKey = null734                result735            } else {736                VaultCrypto.zero(newKey!!)737                newKey = null738                val result = adoptSlotA(rawKey!!, payload, expectedEpoch) // heal failed — keep using the raw key739                rawKey = null740                result741            }742        } finally {743            // Cover codec, encryption, storage, and stale-epoch failures before744            // either candidate key can be transferred into the live session.745            rawKey?.let(VaultCrypto::zero)746            newKey?.let(VaultCrypto::zero)747        }748    }749750    /** Adopt a derived slot-A [key]/[payload] as the live (real-vault) session. */751    private fun adoptSlotA(key: ByteArray, payload: VaultPayload, expectedEpoch: Long): UnlockResult {752        return try {753            // M-04: ensureRootKey and autoPurgeExpiredTrash both persist, so they754            // can throw after the fields above are live. There is no prior session755            // worth restoring — adoption has already replaced it — so a failed756            // adoption discards everything rather than leaving entries and keys757            // resident behind _isUnlocked=false.758            val adopted = mutateIfCurrentEpoch(expectedEpoch) {759                derivedKey = key760                decoyMode = false761                entryList = payload.entries.toMutableList()762                duressConfigured = payload.duressConfigured763                recoveryWordHash = payload.recoveryWordHash764                recoveryWordsSet = payload.recoveryWordsSet765                sessionDataAvailable = true766                _settings.value = store.loadSettings()767                ensureRootKey(payload)768                autoPurgeExpiredTrash()769                consolidatePasskeyEntries()770                publish()771                _isUnlocked.value = true772                // A successful adoption starts a new generation. A sibling773                // SlotAUnlock captured in the prior epoch will fail closed at774                // the next commit instead of replacing this session.775                sessionEpoch = nextSessionEpoch(sessionEpoch)776            }777            if (adopted == null) {778                VaultCrypto.zero(key)779                UnlockResult.Error("stale_unlock")780            } else {781                UnlockResult.Success782            }783        } catch (e: Exception) {784            // Do not call lock() here: a concurrent newer session may already785            // own this repository. Only invalidate the failed epoch's fields.786            mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }787            VaultCrypto.zero(key)788            UnlockResult.Error(e.message ?: "unlock_failed")789        }790    }791792    // ---- Constant-time unlock (MF-5) --------------------------------------793794    /**795     * A slot-A unlock that has been derived but not yet adopted. Holds the live796     * Argon2id key and decoded payload so the caller can derive several candidates797     * concurrently and commit only the winner. The key is owned by this token until798     * [commitSlotAUnlock] adopts it or [discardSlotAUnlock] zeroes it.799     */800    class SlotAUnlock internal constructor(801        key: ByteArray,802        internal val payload: VaultPayload,803        internal val epoch: Long,804    ) {805        private var ownedKey: ByteArray? = key806        private var consumed = false807808        /** Transfer the key exactly once to the adopter. */809        internal fun takeKey(): ByteArray? = synchronized(this) {810            if (consumed) return@synchronized null811            consumed = true812            ownedKey.also { ownedKey = null }813        }814815        /** Discard an uncommitted token without touching a transferred key. */816        internal fun discard() = synchronized(this) {817            if (consumed) return@synchronized818            consumed = true819            ownedKey?.let(VaultCrypto::zero)820            ownedKey = null821        }822    }823824    /**825     * Derive the slot-A key and decrypt its payload WITHOUT mutating session state.826     * Pure computation (no mutex), so it can run concurrently with other candidate827     * derivations before the caller decides which to commit (MF-5). Returns null on828     * no-vault or wrong password (the derived key is zeroed on a tag mismatch).829     */830    fun tryUnlockSlotA(password: String): SlotAUnlock? {831        val epoch = currentEpoch()832        val slotA = store.loadSlotA() ?: return null833        val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))834        return try {835            val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A)836            val payload = try {837                VaultCodec.decode(plaintext)838            } finally {839                VaultCrypto.zero(plaintext)840            }841            SlotAUnlock(key, payload, epoch)842        } catch (_: Exception) {843            VaultCrypto.zero(key)844            null845        }846    }847848    /** Adopt a previously-derived [SlotAUnlock] as the live session. */849    suspend fun commitSlotAUnlock(unlock: SlotAUnlock): UnlockResult = mutex.withLock {850        val key = unlock.takeKey() ?: return@withLock UnlockResult.Error("unlock_token_consumed")851        adoptSlotA(key, unlock.payload, unlock.epoch)852    }853854    /** Zero a derived [SlotAUnlock] that will not be adopted. */855    fun discardSlotAUnlock(unlock: SlotAUnlock) = unlock.discard()856857    // ---- Duress slot B (MF-6) ---------------------------------------------858859    /**860     * A duress-slot (slot B) unlock derived but not yet adopted. Holds the live key861     * and decoded decoy payload so it can be derived concurrently with slot A and862     * only committed if the duress passphrase was the one entered (MF-5/MF-6).863     */864    class DuressUnlock internal constructor(865        key: ByteArray,866        internal val payload: VaultPayload,867        internal val epoch: Long,868    ) {869        private var ownedKey: ByteArray? = key870        private var consumed = false871872        internal fun takeKey(): ByteArray? = synchronized(this) {873            if (consumed) return@synchronized null874            consumed = true875            ownedKey.also { ownedKey = null }876        }877878        internal fun discard() = synchronized(this) {879            if (consumed) return@synchronized880            consumed = true881            ownedKey?.let(VaultCrypto::zero)882            ownedKey = null883        }884    }885886    /**887     * Try to decrypt the duress slot (slot B) with [password] WITHOUT mutating the888     * session. Success means the entered password is the duress passphrase that keys889     * slot B — indistinguishable from the real slot A at the lock screen. Pure890     * computation (no mutex), safe to run concurrently with [tryUnlockSlotA].891     * Returns null when no duress slot exists or the password is not the duress one.892     */893    fun tryUnlockDuress(password: String): DuressUnlock? {894        val epoch = currentEpoch()895        val slot = store.loadDecoySlot() ?: return null896        val key = VaultCrypto.deriveKey(password, unb64(slot.salt))897        return try {898            val plaintext = VaultCrypto.decrypt(unb64(slot.blob), key, VaultCrypto.AAD_SLOT_A)899            val payload = try {900                VaultCodec.decode(plaintext)901            } finally {902                VaultCrypto.zero(plaintext)903            }904            DuressUnlock(key, payload, epoch)905        } catch (_: Exception) {906            VaultCrypto.zero(key)907            null908        }909    }910911    /** Adopt a derived [DuressUnlock] as a live decoy session (edits persist to slot B only). */912    suspend fun commitDuressUnlock(unlock: DuressUnlock): UnlockResult = mutex.withLock {913        val key = unlock.takeKey() ?: return@withLock UnlockResult.Error("unlock_token_consumed")914        if (currentEpoch() != unlock.epoch) {915            VaultCrypto.zero(key)916            return@withLock UnlockResult.Error("stale_unlock")917        }918        return try {919            val adopted = mutateIfCurrentEpoch(unlock.epoch) {920                derivedKey = key921                decoyMode = true922                entryList = unlock.payload.entries.toMutableList()923                duressConfigured = false924                recoveryWordHash = unlock.payload.recoveryWordHash925                recoveryWordsSet = unlock.payload.recoveryWordsSet926                sessionDataAvailable = true927                rootKey = if (unlock.payload.rootKeyB64.isNotBlank()) unb64(unlock.payload.rootKeyB64)928                          else VaultCrypto.generateRootKey()929                _settings.value = store.loadSettings()930                publish()931                _isUnlocked.value = true932                sessionEpoch = nextSessionEpoch(sessionEpoch)933            }934            if (adopted == null) {935                VaultCrypto.zero(key)936                UnlockResult.Error("stale_unlock")937            } else {938                UnlockResult.Success939            }940        } catch (e: Exception) {941            // A payload/root/settings failure can occur after the candidate key942            // has been assigned to derivedKey. Tear down only this epoch so a943            // newer session is not disturbed, and scrub the token reference on944            // every error path.945            mutateIfCurrentEpoch(unlock.epoch) { clearSessionStateLocked() }946            VaultCrypto.zero(key)947            UnlockResult.Error(e.message ?: "decoy_unlock_failed")948        }949    }950951    /** Zero a derived [DuressUnlock] that will not be adopted. */952    fun discardDuressUnlock(unlock: DuressUnlock) = unlock.discard()953954    /**955     * Configure the duress vault (MF-6): seal a fresh, empty decoy payload under an956     * Argon2id key derived from [duressPassphrase] (fresh salt) into slot B. The957     * passphrase is never stored — only its ability to decrypt slot B proves it.958     * Requires the real vault to be unlocked and not itself a decoy session.959     */960    suspend fun setDuressPassphrase(duressPassphrase: String): Boolean = mutex.withLock {961        // H-03: read derivedKey/decoyMode atomically with any concurrent lock().962        val expectedEpoch = mutateState {963            if (derivedKey != null && !decoyMode) sessionEpoch else null964        } ?: return false965        // Reject a duress passphrase that also opens the real vault: it would make the966        // lock screen ambiguous (both slots would decrypt for the same input).967        tryUnlockSlotA(duressPassphrase)?.let { discardSlotAUnlock(it); return false }968        var key: ByteArray? = null969        var basePlaintext: ByteArray? = null970        return try {971            val salt = VaultCrypto.generateSalt()972            key = VaultCrypto.deriveKey(duressPassphrase, salt)973            // An empty decoy vault with its own fresh sync root key — nothing real leaks.974            val decoyRoot = VaultCrypto.generateRootKey()975            val decoyRootB64 = try { b64(decoyRoot) } finally { VaultCrypto.zero(decoyRoot) }976            val decoyPayload = VaultPayload(entries = emptyList(), rootKeyB64 = decoyRootB64)977            basePlaintext = VaultCodec.encode(decoyPayload)978            // H-04: pad the duress plaintext to slot A's ciphertext length so the979            // duress blob matches slot A's blob on disk. VaultCodec.decode strips980            // trailing NULs, so the extra padding survives encrypt but never981            // reaches the JSON parser.982            // This decoy plaintext length is frozen from here on: re-sealing it983            // on later growth would need the duress passphrase, which is never984            // retained. VaultStore compensates by re-padding the two slot985            // RECORDS to the longer of the two on every write, so the frozen986            // blob no longer shows up as a length difference at rest.987            val slotA = store.loadSlotA()988            val targetSize = slotA?.let(::matchingCiphertextLength) ?: 0989            val plaintext = if (targetSize > basePlaintext!!.size) basePlaintext!!.copyOf(targetSize) else basePlaintext!!990            val blob = try {991                b64(VaultCrypto.encrypt(plaintext, key!!, VaultCrypto.AAD_SLOT_A))992            } finally {993                VaultCrypto.zero(plaintext)994                // Padding creates a second array; scrub the original encoded995                // payload too rather than dropping its last reference untouched.996                if (plaintext !== basePlaintext) basePlaintext?.let(VaultCrypto::zero)997                basePlaintext = null998                key?.let(VaultCrypto::zero)999                key = null1000            }1001            beforeDurableCommit()1002            val ok = withEpochCommit(expectedEpoch) {1003                store.writeDecoySlot(StoredVault(version = 1, salt = b64(salt), blob = blob))1004            } ?: false1005            if (ok && mutateIfCurrentEpoch(expectedEpoch) { duressConfigured = true } != null) {1006                runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }1007            } else if (ok) {1008                return false1009            }1010            ok1011        } catch (_: Exception) {1012            false1013        } finally {1014            // Cover failures before the encrypt block is entered (for example a1015            // codec/copy exception) as well as any early return after key derivation.1016            key?.let(VaultCrypto::zero)1017            basePlaintext?.let(VaultCrypto::zero)1018        }1019    }102010211022    /**1023     * Export the decoy slot as browser-shaped JSON for adoption snapshots.1024     *1025     * Returns the sealed slot as `{version, salt, nonce, ciphertext, tag}` all1026     * lowercase hex — identical to the browser's `duress_slot` wire format — so1027     * any receiver (browser or Android) can install it via the existing1028     * passthrough. Returns null when duress is not configured, no decoy exists,1029     * or any conversion failure occurs. Never decrypts.1030     */1031    suspend fun exportDuressSlotForAdoption(): String? = mutex.withLock {1032        if (!duressConfigured) return null1033        val slot = store.loadDecoySlot() ?: return null1034        return runCatching { androidDuressSlotToBrowserJson(slot) }.getOrNull()1035    }10361037    /**1038     * Convert an Android [StoredVault] decoy slot to browser-shaped JSON.1039     *1040     * Mirrors the inverse of [installAdoptedDuressSlot]: base64 salt/blob are1041     * split into lowercase hex fields matching [BrowserSlotA]. Intermediate1042     * byte arrays are zeroed in finally.1043     */1044    private fun androidDuressSlotToBrowserJson(slot: StoredVault): String {1045        // Build the wire JSON directly with JsonObject so `version: 1` is ALWAYS1046        // serialized — kotlinx-serialization's encodeDefaults = false would1047        // otherwise omit BrowserSlotA.version (its Kotlin default), and the1048        // browser's hasValidVaultSchema strictly requires `r.version === 1`,1049        // silently dropping the duress slot on Android→browser adoptions.1050        var salt: ByteArray? = null1051        var blob: ByteArray? = null1052        var nonce: ByteArray? = null1053        var ctAndTag: ByteArray? = null1054        var ct: ByteArray? = null1055        var tag: ByteArray? = null1056        try {1057            salt = unb64(slot.salt)1058            blob = unb64(slot.blob)1059            nonce = blob.copyOfRange(0, VaultCrypto.NONCE_SIZE)1060            ctAndTag = blob.copyOfRange(VaultCrypto.NONCE_SIZE, blob.size)1061            ct = ctAndTag.copyOfRange(0, ctAndTag.size - 16)1062            tag = ctAndTag.copyOfRange(ctAndTag.size - 16, ctAndTag.size)1063            val obj = JsonObject(mapOf(1064                "version" to JsonPrimitive(1),1065                "salt" to JsonPrimitive(salt.joinToString("") { "%02x".format(it) }),1066                "nonce" to JsonPrimitive(nonce.joinToString("") { "%02x".format(it) }),1067                "ciphertext" to JsonPrimitive(ct.joinToString("") { "%02x".format(it) }),1068                "tag" to JsonPrimitive(tag.joinToString("") { "%02x".format(it) }),1069            ))1070            return obj.toString()1071        } finally {1072            salt?.let(VaultCrypto::zero)1073            blob?.let(VaultCrypto::zero)1074            nonce?.let(VaultCrypto::zero)1075            ctAndTag?.let(VaultCrypto::zero)1076            ct?.let(VaultCrypto::zero)1077            tag?.let(VaultCrypto::zero)1078        }1079    }10801081    /**1082     * Install a browser-shaped duress slot received through adoption.1083     *1084     * Parses [json] as a [BrowserSlotA], re-encodes it to Android's1085     * [StoredVault] via [browserDuressPassthrough] (no decryption), and1086     * writes the result to the decoy slot. Epoch-fenced like the Codex1087     * restore path so a concurrent lock() cannot strand the write.1088     *1089     * Returns false on invalid input, no live session, or write failure.1090     */1091    suspend fun installAdoptedDuressSlot(json: String): Boolean = mutex.withLock {1092        val b = BrowserSlot.parse(json) ?: return false1093        var stored: StoredVault? = null1094        var salt: ByteArray? = null1095        var nonce: ByteArray? = null1096        var ct: ByteArray? = null1097        var tag: ByteArray? = null1098        var blob: ByteArray? = null1099        try {1100            salt = unhex(b.salt)1101            nonce = unhex(b.nonce)1102            ct = unhex(b.ciphertext)1103            tag = unhex(b.tag)1104            blob = ByteArray(nonce.size + ct.size + tag.size).also {1105                System.arraycopy(nonce, 0, it, 0, nonce.size)1106                System.arraycopy(ct, 0, it, nonce.size, ct.size)1107                System.arraycopy(tag, 0, it, nonce.size + ct.size, tag.size)1108            }1109            stored = StoredVault(version = 1, salt = b64(salt), blob = b64(blob))1110            val expectedEpoch = sessionEpoch1111            beforeDurableCommit()1112            withEpochCommit(expectedEpoch) {1113                store.writeDecoySlot(stored)1114            } ?: false1115        } catch (_: Exception) {1116            false1117        } finally {1118            salt?.let(VaultCrypto::zero)1119            nonce?.let(VaultCrypto::zero)1120            ct?.let(VaultCrypto::zero)1121            tag?.let(VaultCrypto::zero)1122            blob?.let(VaultCrypto::zero)1123        }1124    }11251126    /** Tear down the duress vault: drop slot B and the duress flag on the real payload. */1127    suspend fun clearDuress(): Boolean = mutex.withLock {1128        // H-04: presence-indistinguishable — replace the real decoy with a fake1129        // blob of slot A's size rather than removing the duress record. The1130        // record stays on disk at the same length, so an at-rest observer1131        // cannot tell "duress cleared" from "no duress ever configured".1132        val expectedEpoch = currentEpoch()1133        val replaced = withEpochCommit(expectedEpoch) {1134            store.loadSlotA()?.let { slotA -> runCatching { writeFakeDuressSlot(slotA) }.getOrDefault(false) }1135                ?: runCatching { store.clearDecoySlot(); true }.getOrDefault(false)1136        } ?: false1137        if (!replaced) return@withLock false1138        // H-03: stateLock-fence the derivedKey/decoyMode read AND the1139        // duressConfigured write so a concurrent lock() cannot land between them.1140        if (!isSessionEpochCurrent(expectedEpoch)) return false1141        val shouldClear = mutateIfCurrentEpoch(expectedEpoch) { derivedKey != null && !decoyMode } == true1142        if (shouldClear && mutateIfCurrentEpoch(expectedEpoch) { duressConfigured = false } != null) {1143            runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }1144        }1145        true1146    }11471148    /** True for the provider-specific exception used for a valid GCM blob/key mismatch. */1149    private fun isGcmAuthenticationFailure(error: Throwable): Boolean {1150        var current: Throwable? = error1151        while (current != null) {1152            if (current is javax.crypto.AEADBadTagException) return true1153            // Some Android providers expose a GCM tag failure as the parent1154            // BadPaddingException rather than the AEAD-specific subtype.  A1155            // short ciphertext is an IllegalBlockSizeException and therefore1156            // remains an internal/malformed-payload Error below.1157            if (current is javax.crypto.BadPaddingException) return true1158            current = current.cause1159        }1160        return false1161    }11621163    /** Unlock with an already-derived AES-256 key (biometric path). */1164    suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {1165        val expectedEpoch = currentEpoch()1166        val slotA = try {1167            store.loadSlotA()1168        } catch (_: Exception) {1169            return@withLock UnlockResult.Error("unlock_key_storage_failed")1170        } ?: return@withLock UnlockResult.Error("no_vault")1171        // Keep the caller-owned key separate from the staged session key. The1172        // biometric caller always zeroes its input in a finally block; adoption1173        // must therefore own a copy and use the same all-or-nothing path as a1174        // password unlock rather than publishing a partially decoded session.1175        var stagedKey: ByteArray? = key.copyOf()1176        return try {1177            val encrypted = try {1178                unb64(slotA.blob)1179            } catch (_: Exception) {1180                return@withLock UnlockResult.Error("invalid_vault_blob")1181            }1182            // A GCM record must include nonce + authentication tag.  Providers1183            // differ on whether a shorter record is reported as BadPadding or1184            // AEADBadTag; reject it before decrypt so malformed storage cannot be1185            // misreported as a user-entered wrong key.1186            if (encrypted.size < VaultCrypto.NONCE_SIZE + (VaultCrypto.TAG_LENGTH_BITS / 8)) {1187                return@withLock UnlockResult.Error("invalid_vault_blob")1188            }1189            val plaintext = try {1190                VaultCrypto.decrypt(encrypted, stagedKey!!, VaultCrypto.AAD_SLOT_A)1191            } catch (e: Exception) {1192                if (isGcmAuthenticationFailure(e)) {1193                    return@withLock UnlockResult.WrongPassword1194                }1195                return@withLock UnlockResult.Error("unlock_key_decrypt_failed")1196            }1197            val payload = try {1198                VaultCodec.decode(plaintext)1199            } catch (_: Exception) {1200                return@withLock UnlockResult.Error("invalid_vault_payload")1201            } finally {1202                VaultCrypto.zero(plaintext)1203            }1204            val candidate = stagedKey ?: return UnlockResult.Error("unlock_key_missing")1205            val result = adoptSlotA(candidate, payload, expectedEpoch)1206            if (result is UnlockResult.Success) { stagedKey = null; ensureRecoveryEscrow() }1207            result1208        } finally {1209            stagedKey?.let(VaultCrypto::zero)1210        }1211    }12121213    fun lock() {1214        // Never snapshot a mutation that has changed entryList but has not yet1215        // crossed its durable epoch fence. Successful writes refresh the spool1216        // before releasing this mutex; an in-flight writer therefore makes this1217        // lock skip the convenience refresh and fail closed to the prior cache.1218        if (mutex.tryLock()) {1219            try {1220                runCatching { LockedSyncSpoolHooks.refresh(this) }1221            } finally {1222                mutex.unlock()1223            }1224        }1225        // H-03: must observe derivedKey/entryList atomically with any in-flight1226        // suspend op (an addEntry mid-encrypt, an unlock adopting the payload,1227        // etc.). mutex cannot be acquired from this non-suspend caller; stateLock1228        // guards just the brief state reset. Advancing the epoch first invalidates1229        // every operation that captured this session before it reaches a later1230        // durable commit or publication.1231        stateLock.lock()1232        try {1233            sessionEpoch = nextSessionEpoch(sessionEpoch)1234            clearSessionStateLocked()1235            _uiGateLocked.value = false1236        } finally {1237            stateLock.unlock()1238        }1239    }12401241    /**1242     * Enter sync-retained background mode: the UI shows the lock screen but the1243     * vault stays fully unlocked in memory so [PeachSyncService] can complete1244     * sync sessions. Called from [PeachApplication.onStop] when background sync1245     * is enabled. A subsequent full [lock] (auto-lock timer, manual lock)1246     * supersedes this and zeroes everything.1247     */1248    fun lockUiGate() {1249        if (_isUnlocked.value) _uiGateLocked.value = true1250    }12511252    /** Dismiss the UI gate after the user authenticates on resume. */1253    fun clearUiGate() {1254        _uiGateLocked.value = false1255    }12561257    @Volatile private var suppressNextBackgroundLockUntil: Long = 0L12581259    // Test seam so the expiry branch is reachable from plain JUnit (SystemClock1260    // is a stub off-device).1261    @VisibleForTesting1262    internal var nowMs: () -> Long = { SystemClock.elapsedRealtime() }12631264    /**1265     * Call immediately before launching a system Activity (a SAF file1266     * picker/save dialog, a share sheet) that briefly takes the whole process1267     * out of the foreground as an expected part of an in-app flow — not a1268     * genuine user backgrounding. ProcessLifecycleOwner.onStop can't tell the1269     * two apart on its own (it fires for both), and without this, exporting or1270     * importing a file silently locked and wiped the vault mid-flow the moment1271     * the picker took over, before its result ever reached the app.1272     *1273     * The suppression auto-expires after [BACKGROUND_LOCK_SUPPRESSION_TIMEOUT_MS]1274     * (M-07); a never-consumed stale flag cannot suppress a later real lock.1275     */1276    fun expectTransientBackground() {1277        suppressNextBackgroundLockUntil = nowMs() + BACKGROUND_LOCK_SUPPRESSION_TIMEOUT_MS1278    }12791280    /**1281     * Consumed once by the next background-lock check; see [expectTransientBackground].1282     * Returns false (and clears the flag) if the suppression has expired or was1283     * never set — a genuine background event must always lock.1284     */1285    fun consumeTransientBackgroundSuppression(): Boolean {1286        val until = suppressNextBackgroundLockUntil1287        val active = until != 0L && nowMs() < until1288        suppressNextBackgroundLockUntil = 0L1289        return active1290    }12911292    // ---- Sync identity ----------------------------------------------------12931294    /**1295     * The vault's stable sync master key (a copy). Caller must zero it. Backs1296     * vault_id, the Noise static key, the Ed25519 manifest key, and per-entry1297     * envelope keys. Null when locked. See [VaultPayload.rootKeyB64].1298     */1299    /**1300     * HOLE 5 — the duress vault never syncs.1301     *1302     * [commitDuressUnlock] gives the decoy session a root key so its own codex1303     * and recovery paths work, which means (unlike the browser, where the decoy1304     * path simply has no root key) the sync surface has to refuse explicitly.1305     * Without this the decoy vault would present a second, different vault_id1306     * to a paired device, and a coerced user opening it would make sync visibly1307     * fail on their other devices — a duress indicator, which is the one thing1308     * a duress vault must never be.1309     */1310    // M-04: the "null when locked" half of the contract was documented but never1311    // enforced — a rootKey outlives _isUnlocked in the recovery half-unlock (see1312    // [unlockWithRecoveryWords], which installs a root key with no password key1313    // yet) and in a create that failed after staging. Sync must fail closed1314    // there, so the authoritative unlocked flag gates it, not just decoyMode.1315    internal data class SyncMasterKeySnapshot(val epoch: Long, val key: ByteArray)13161317    internal fun syncMasterKeySnapshot(): SyncMasterKeySnapshot? = mutateState {1318        if (decoyMode || !_isUnlocked.value) null1319        else rootKey?.copyOf()?.let { SyncMasterKeySnapshot(sessionEpoch, it) }1320    }13211322    internal fun isSessionEpochCurrent(epoch: Long): Boolean =1323        mutateState { sessionEpoch == epoch }13241325    internal fun unlockedSessionEpoch(): Long? = mutateState {1326        if (derivedKey != null && _isUnlocked.value) sessionEpoch else null1327    }13281329    fun syncMasterKey(): ByteArray? = syncMasterKeySnapshot()?.key13301331    /**1332     * The current session's root key, decoy included. For local-only uses that1333     * must behave identically in a decoy session — Codex backup and recovery1334     * words — because a feature that errors under duress is itself a duress1335     * tell. In a decoy session this is the DECOY's root key (see1336     * [commitDuressUnlock]), never the real vault's, so neither surface can1337     * leak the real vault. Anything that leaves the device must use1338     * [syncMasterKey] instead.1339     */1340    fun sessionRootKey(): ByteArray? = mutateState {1341        if (!sessionDataAvailable) null else rootKey?.copyOf()1342    }13431344    /** Stable per-vault id two paired devices must share to sync. Null when1345     *  locked, and never present for the decoy vault (see [syncMasterKey]). */1346    fun syncVaultId(): String? = mutateState {1347        if (decoyMode || !_isUnlocked.value) null1348        else rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }1349    }13501351    /**1352     * Browser parity (MV-8): rotate the sync identity by replacing the stable1353     * root key. Entries remain under the master-password key, while sync1354     * credentials, vault_id, and recovery words all change.1355     */1356    suspend fun rotateSyncIdentity(): Boolean = mutex.withLock {1357        val expectedEpoch = mutateState { if (derivedKey != null && !decoyMode) sessionEpoch else null }1358            ?: return false1359        installRootKey(generateRecoverableRootKey(), expectedEpoch)1360    }13611362    /**1363     * Join the vault behind [rootKeyHex]: adopt that vault's identity while1364     * keeping every local entry.1365     *1366     * Sync identity (vault id, signing keys) derives from the root key, and1367     * `sync-coordinator` refuses a `vault_id_mismatch`, so two independently1368     * created vaults can never reconcile. Taking the other side's root key is1369     * what makes them one vault; from the next sync on, both entry sets merge.1370     *1371     * Entries survive because they are sealed under the password-derived key,1372     * not the root key — the same property [rotateSyncIdentity] relies on.1373     *1374     * CONSEQUENCE, which the caller must have disclosed and had confirmed:1375     * this device's previous recovery words stop working for good, and its new1376     * words are the source vault's words, because words are a deterministic1377     * encoding of the root key.1378     */1379    suspend fun joinVault(rootKeyHex: String): AdoptVaultResult = mutex.withLock {1380        if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {1381            return AdoptVaultResult.Error("JOIN_INVALID_ROOT_KEY: expected 64 lowercase hex chars")1382        }1383        val expectedEpoch = mutateState {1384            when {1385                derivedKey == null -> null1386                decoyMode -> Long.MIN_VALUE1387                else -> sessionEpoch1388            }1389        }1390        if (expectedEpoch == null) return AdoptVaultResult.Error("vault_locked")1391        if (expectedEpoch == Long.MIN_VALUE) return AdoptVaultResult.Error("JOIN_DECOY_MODE")1392        if (!store.hasVault()) return AdoptVaultResult.Error("JOIN_NO_LOCAL_VAULT")13931394        val incoming = hexToRootKey(rootKeyHex)1395        if (incoming.size != VaultCrypto.KEY_SIZE) {1396            VaultCrypto.zero(incoming)1397            return AdoptVaultResult.Error("JOIN_INVALID_ROOT_KEY: expected 32 bytes")1398        }1399        // Refuse before committing rather than leave this device holding a vault1400        // whose recovery words cannot be typed back. generateRecoverableRootKey1401        // screens its own keys for this; a key arriving from a peer has not been.1402        val roundTrips = runCatching { wordsToRootKeyMaterial(rootKeyToWords(incoming)) }.isSuccess1403        if (!roundTrips) {1404            VaultCrypto.zero(incoming)1405            return AdoptVaultResult.Error("JOIN_UNRECOVERABLE_ROOT_KEY")1406        }14071408        val vaultId = com.peachpasswords.sync.computeVaultId(incoming)1409        return if (installRootKey(incoming, expectedEpoch)) {1410            AdoptVaultResult.Success(vaultId)1411        } else {1412            AdoptVaultResult.Error("JOIN_INSTALL_FAILED")1413        }1414    }14151416    /**1417     * The recovery words [rootKeyHex] will produce once joined, or null if it is1418     * not a usable root key. Lets the join flow show the user the words that are1419     * about to replace theirs *before* anything is committed.1420     */1421    fun previewRecoveryWords(rootKeyHex: String): List<String>? {1422        if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) return null1423        val bytes = hexToRootKey(rootKeyHex)1424        return try {1425            val words = rootKeyToWords(bytes)1426            if (runCatching { wordsToRootKeyMaterial(words) }.isSuccess) words else null1427        } catch (_: Exception) {1428            null1429        } finally {1430            VaultCrypto.zero(bytes)1431        }1432    }14331434    /**1435     * Swap the vault's root key, keeping every entry, and re-escrow under the1436     * words the new key encodes. Takes ownership of [nextRootKey]. Caller holds1437     * [mutex].1438     */1439    private suspend fun installRootKey(nextRootKey: ByteArray, expectedEpoch: Long): Boolean {1440        // H-03: snapshot the live fields under stateLock so the success and the1441        // rollback paths both see consistent prior/new state. Writing the new1442        // rootKey/recovery fields is inside its own mutateState at the end.1443        // H-03 (P1-3 codex): the snapshot must COPY the live key/rootKey arrays1444        // — holding live references would let a zero-on-failure operation also1445        // wipe the session's still-live key arrays.1446        data class Snapshot(1447            val key: ByteArray,1448            val priorRootKey: ByteArray,1449            val priorRecoveryHash: String?,1450            val priorRecoverySet: Boolean,1451        )1452        val snap = mutateIfCurrentEpoch(expectedEpoch) {1453            val k = derivedKey ?: return@mutateIfCurrentEpoch null1454            if (decoyMode) return@mutateIfCurrentEpoch null1455            val priorRoot = rootKey ?: return@mutateIfCurrentEpoch null1456            Snapshot(k.copyOf(), priorRoot.copyOf(), recoveryWordHash, recoveryWordsSet)1457        } ?: run {1458            VaultCrypto.zero(nextRootKey)1459            return false1460        }1461        val priorSlot = store.loadSlotA() ?: run {1462            VaultCrypto.zero(snap.key)1463            VaultCrypto.zero(snap.priorRootKey)1464            VaultCrypto.zero(nextRootKey)1465            return false1466        }1467        val nextWords = rootKeyToWords(nextRootKey)14681469        return try {1470            beforeDurableCommit()1471            if (!takeVaultSnapshot("local_save", expectedEpoch)) throw IllegalStateException("snapshot_failed")1472            if (mutateIfCurrentEpoch(expectedEpoch) {1473                rootKey = nextRootKey1474                recoveryWordHash = recoveryWordsHash(nextWords)1475                recoveryWordsSet = false1476            } == null) throw IllegalStateException("stale_root_rotation")14771478            val nextRecoveryEscrow = buildRecoveryEscrow(nextWords)1479                ?: throw IllegalStateException("recovery_escrow_failed")1480            val nextRootKeyEscrow = buildRootKeyEscrow(nextWords)1481                ?: throw IllegalStateException("root_escrow_failed")1482            val plaintext = VaultCodec.encode(currentPayload())1483            val blob = try {1484                b64(VaultCrypto.encrypt(plaintext, snap.key, VaultCrypto.AAD_SLOT_A))1485            } finally {1486                VaultCrypto.zero(plaintext)1487            }1488            val nextSlot = priorSlot.copy(1489                blob = blob,1490                recoveryEscrow = nextRecoveryEscrow,1491                rootKeyEscrow = nextRootKeyEscrow,1492            )1493            val committed = withEpochCommit(expectedEpoch) {1494                if (!store.writeSlotA(nextSlot)) return@withEpochCommit false1495                try {1496                    if (!writeMatchingNoiseSlotB(nextSlot)) throw IllegalStateException("noise_slot_b_commit_failed")1497                    // H-04: a root-key rotation re-seals slot A, so the duress slot1498                    // (real or fake) must be re-padded to the new ciphertext length.1499                    if (!writeCompanionDuressSlot(nextSlot)) throw IllegalStateException("duress_slot_commit_failed")1500                    store.stampLocalMutation()1501                } catch (_: Exception) {1502                    store.writeSlotA(priorSlot)1503                    return@withEpochCommit false1504                }1505                true1506            } ?: false1507            if (!committed) throw IllegalStateException("storage_write_failed")1508            mutateIfCurrentEpoch(expectedEpoch) { publish() }1509            true1510        } catch (_: Exception) {1511            val restored = mutateIfCurrentEpoch(expectedEpoch) {1512                rootKey?.let(VaultCrypto::zero)1513                rootKey = snap.priorRootKey.copyOf()1514                recoveryWordHash = snap.priorRecoveryHash1515                recoveryWordsSet = snap.priorRecoverySet1516            }1517            if (restored != null) {1518                withEpochCommit(expectedEpoch) { store.writeSlotA(priorSlot) }1519            }1520            false1521        } finally {1522            VaultCrypto.zero(snap.key)1523            VaultCrypto.zero(snap.priorRootKey)1524            // On success nextRootKey is owned by rootKey. On every other path1525            // it is not, including a stale epoch after lock(); scrub it while1526            // the local reference is still available.1527            val stillOwnedBySession = mutateState {1528                sessionEpoch == expectedEpoch && rootKey === nextRootKey1529            }1530            if (!stillOwnedBySession) VaultCrypto.zero(nextRootKey)1531        }1532    }15331534    /**1535     * A copy of the live Argon2id-derived vault key, for biometric escrow only1536     * (wrapped under a hardware KeyStore key on biometric enable). Null when1537     * locked. Caller must [VaultCrypto.zero] it after use.1538     */1539    fun currentVaultKey(): ByteArray? = mutateState {1540        if (!isFullyUnlockedLocked()) null else derivedKey?.copyOf()1541    }15421543    suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {1544        val expectedEpoch = currentEpoch()1545        val slotA = store.loadSlotA() ?: return false1546        var oldKey: ByteArray? = null1547        var newKey: ByteArray? = null1548        var plaintext: ByteArray? = null1549        return try {1550            oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))1551            // Keep ownership of the decrypted vault plaintext until decoding has1552            // finished.  Passing decrypt() inline made the byte array unreachable1553            // before the finally block, so a successful or failed password change1554            // could leave the full plaintext resident in the heap.1555            val decrypted = VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A)1556            val payload = try {1557                VaultCodec.decode(decrypted)1558            } finally {1559                VaultCrypto.zero(decrypted)1560            }1561            val newSalt = VaultCrypto.generateSalt()1562            newKey = VaultCrypto.deriveKey(newPassword, newSalt)1563            // Re-seal the existing payload under the new key/salt.1564            plaintext = VaultCodec.encode(payload)1565            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))1566            // The escrow seals the slot-A PLAINTEXT, which a password change does not1567            // alter — only the wrapping changes — so carry it forward; rebuilding the1568            // StoredVault from scratch would silently drop it.1569            // Carry BOTH escrows forward unchanged: each seals plaintext/root-key1570            // content that a password change does not alter — only the slot-A1571            // wrapping rotates. The root-key escrow staying stable across password1572            // changes matches the browser (`vault.ts:363-364`).1573            val next = StoredVault(1574                version = slotA.version,1575                salt = b64(newSalt),1576                blob = blob,1577                recoveryEscrow = slotA.recoveryEscrow,1578                rootKeyEscrow = slotA.rootKeyEscrow,1579            )1580            // H-01: durably commit slot A + size-matched noise + version stamp1581            // before swapping the session key. A partial commit (new A on disk,1582            // old key in memory) would have the next save encrypt under the old1583            // key while matching disk on the new one.1584            val priorB = store.loadSlotB()1585            if (!commitVaultRotation(slotA, priorB, next, expectedEpoch)) return false1586            // H-03 (P1-2 codex): zero the OLD live key and assign the NEW one1587            // inside the same stateLock critical section, so a concurrent lock()1588            // can't observe the in-between (zeroed but not yet reassigned).1589            if (mutateIfCurrentEpoch(expectedEpoch) {1590                oldKey?.let(VaultCrypto::zero); oldKey = null1591                derivedKey?.let(VaultCrypto::zero)1592                derivedKey = newKey; newKey = null1593            } == null) return false1594            true1595        } catch (_: Exception) {1596            false1597        } finally {1598            oldKey?.let(VaultCrypto::zero)1599            newKey?.let(VaultCrypto::zero)1600            plaintext?.let(VaultCrypto::zero)1601        }1602    }16031604    /**1605     * Irreversible wipe. Locks the session and clears every vault key. The Pro1606     * license is in a separate store and is preserved by construction.1607     */1608    suspend fun destroyVault() = mutex.withLock {1609        lock()1610        store.clearVault()1611        store.clearDecoySlot()1612    }16131614    // ---- Entry CRUD -------------------------------------------------------16151616    /**1617     * A Peach entry id is a UUID. Import and restore carry ids from foreign1618     * files (another Peach install, a vendor export, a hand-written backup) and1619     * no reader bounds them, so an id that is not a well-formed Peach id is1620     * replaced here rather than trusted.1621     *1622     * This is the naturalisation seam, and it is deliberately the only place it1623     * happens. Minting costs at most one duplicate if the same vault is later1624     * restored on a device that still holds the old id — visible and fixable.1625     * The sync path must NOT do this: adopting a peer's id verbatim is the only1626     * thing that keeps two devices agreeing on which entry they are discussing,1627     * so reminting there would fork identity on every device, on every round.1628     */1629    private val entryIdShape = Regex("[A-Za-z0-9_-]{1,64}")16301631    private fun String?.normalizedEntryId(): String =1632        if (this != null && entryIdShape.matches(this)) this else UUID.randomUUID().toString()16331634    suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {1635        val epoch = requireUnlocked()1636        val stamp = VaultCrypto.monotonicEntryTimestamp()1637        val now = System.currentTimeMillis()1638        val entry = withDerivedLast4(draft.copy(1639            id = draft.id.normalizedEntryId(),1640            createdAt = if (draft.createdAt > 0) draft.createdAt else now,1641            modifiedAt = stamp,1642            passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1643        ))1644        // H-03: capture rollback AND write entryList under stateLock so a1645        // concurrent lock() cannot zero the session between the read and the write.1646        val rollback = mutateCurrentSession(epoch) {1647            val r = entryList.toMutableList()1648            entryList.add(entry)1649            r1650        } ?: throw IllegalStateException("vault_locked")1651        persistOrRollback(rollback, epoch)1652        entry1653    }16541655    /**1656     * Insert many entries with a single encrypt-and-write at the end.1657     *1658     * Importing a real vault through [addEntry] was quadratic: every entry took1659     * the lock and re-encrypted and rewrote the whole vault, so an 806-entry1660     * restore did 806 full-vault writes and hung the app long enough to ANR.1661     * Rolls back to the pre-import list if the one write fails, matching1662     * [addEntry]'s all-or-nothing behaviour.1663     */1664    suspend fun addEntries(drafts: List<VaultEntry>): Int = mutex.withLock {1665        val epoch = requireUnlocked()1666        if (drafts.isEmpty()) return 01667        val now = System.currentTimeMillis()1668        val ready = drafts.map { draft ->1669            val stamp = VaultCrypto.monotonicEntryTimestamp()1670            withDerivedLast4(1671                draft.copy(1672                    id = draft.id.normalizedEntryId(),1673                    createdAt = if (draft.createdAt > 0) draft.createdAt else now,1674                    modifiedAt = stamp,1675                    passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1676                ),1677            )1678        }1679        // H-03: capture rollback AND append every entry under stateLock.1680        val rollback = mutateCurrentSession(epoch) {1681            val r = entryList.toMutableList()1682            entryList.addAll(ready)1683            r1684        } ?: throw IllegalStateException("vault_locked")1685        persistOrRollback(rollback, epoch)1686        return drafts.size1687    }16881689    /**1690     * M-01: replace the whole active set with [newEntries] in one write.1691     *1692     * Import's REPLACE mode used to soft-delete every current entry one durable1693     * write at a time (swallowing each failure) and then batch-add, so a failed1694     * add left the old entries stranded in Trash with nothing restored. Staging1695     * the entire next list in memory and committing it through1696     * [persistOrRollback] makes the swap all-or-nothing: on any failure the1697     * pre-import list — active entries included — is restored.1698     *1699     * Existing tombstones are preserved so paired devices still see the1700     * deletions they already know about.1701     */1702    suspend fun replaceEntries(newEntries: List<VaultEntry>): Int = mutex.withLock {1703        val epoch = requireUnlocked()1704        val now = System.currentTimeMillis()1705        val ready = newEntries.map { draft ->1706            val stamp = VaultCrypto.monotonicEntryTimestamp()1707            withDerivedLast4(1708                draft.copy(1709                    id = draft.id.normalizedEntryId(),1710                    createdAt = if (draft.createdAt > 0) draft.createdAt else now,1711                    modifiedAt = stamp,1712                    passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1713                ),1714            )1715        }1716        // M-03: an incoming entry that shares an id with an existing live entry1717        // is meant to *replace* it (PEACHSCRIPT REPLACE restore). Tombstoning1718        // the old one and then appending the new one would leave the list with1719        // two entries of the same id — the tombstoned one would be returned by1720        // updateEntry's indexOfFirst and trip entry_not_found. Drop the to-be-1721        // superseded entries from the tombstone set instead.1722        val incomingIds = ready.map { it.id }.toHashSet()1723        val rollback = mutateCurrentSession(epoch) {1724            val r = entryList.toMutableList()1725            val replaced = entryList.map { entry ->1726                if (entry.deletedAt != null) return@map entry1727                if (entry.id in incomingIds) return@map null1728                val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)1729                entry.copy(deletedAt = stamp, modifiedAt = stamp)1730            }.filterNotNull()1731            entryList = (replaced + ready).toMutableList()1732            r1733        } ?: throw IllegalStateException("vault_locked")1734        persistOrRollback(rollback, epoch)1735        return ready.size1736    }17371738    suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {1739        val epoch = requireUnlocked()1740        // H-03: read entryList, compute the patched entry, and write it under a1741        // single stateLock so a concurrent lock() cannot interleave between the1742        // lookup and the assignment (would IndexOutOfBoundsException on a shrunk1743        // list, or clobber the entry onto the wrong id after a relock).1744        val prepared = mutateCurrentSession(epoch) {1745            val idx = entryList.indexOfFirst { it.id == patch.id }1746            if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1747            val current = entryList[idx]1748            val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1749            // Only refresh passwordChangedAt when the password value actually changes.1750            val passwordChanged = patch.password != null && patch.password != current.password1751            // Capture the outgoing password (newest first) so the user can reveal/copy/1752            // restore it later. History is computed authoritatively from `current`, not1753            // the patch — updateEntry is a full-entry replace, so trusting patch's value1754            // would let a stale form clobber the real history. Record the age the old1755            // password carried, skip an empty prior, and skip an immediate exact dupe1756            // (e.g. restore-then-restore). Capped at PASSWORD_HISTORY_MAX.1757            val priorPassword = current.password1758            val shouldCapture = passwordChanged &&1759                !priorPassword.isNullOrEmpty() &&1760                current.passwordHistory?.firstOrNull()?.password != priorPassword1761            val nextHistory = if (shouldCapture) {1762                (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +1763                    (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)1764            } else {1765                current.passwordHistory1766            }1767            val updated = withDerivedLast4(patch.copy(1768                createdAt = current.createdAt,1769                modifiedAt = stamp,1770                passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,1771                passwordHistory = nextHistory,1772            ))1773            val rollback = entryList.toMutableList()1774            entryList[idx] = updated1775            updated to rollback1776        } ?: throw IllegalStateException("vault_locked")1777        val (updated, rollback) = prepared1778        persistOrRollback(rollback, epoch)1779        updated1780    }17811782    /** Soft-delete: writes a tombstone whose timestamp beats any in-flight edit. */1783    suspend fun deleteEntry(id: String) = mutex.withLock {1784        val epoch = requireUnlocked()1785        // H-03: lookup + tombstone write under stateLock so lock() cannot shrink1786        // the list out from under the indexOfFirst.1787        val rollback = mutateCurrentSession(epoch) {1788            val idx = entryList.indexOfFirst { it.id == id }1789            if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1790            val current = entryList[idx]1791            val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1792            val prior = entryList.toMutableList()1793            entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)1794            prior1795        } ?: throw IllegalStateException("vault_locked")1796        persistOrRollback(rollback, epoch)1797    }17981799    suspend fun restoreEntry(id: String) = mutex.withLock {1800        val epoch = requireUnlocked()1801        val rollback = mutateCurrentSession(epoch) {1802            val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }1803            if (idx == -1) throw IllegalStateException("deleted entry not found")1804            val current = entryList[idx]1805            val prior = entryList.toMutableList()1806            entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))1807            prior1808        } ?: throw IllegalStateException("vault_locked")1809        persistOrRollback(rollback, epoch)1810    }18111812    /** Permanent delete — no tombstone, no recovery. */1813    suspend fun purgeEntry(id: String) = mutex.withLock {1814        val epoch = requireUnlocked()1815        val rollback = mutateCurrentSession(epoch) {1816            val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }1817            if (idx == -1) throw IllegalStateException("deleted entry not found")1818            val prior = entryList.toMutableList()1819            entryList.removeAt(idx)1820            prior1821        } ?: throw IllegalStateException("vault_locked")1822        persistOrRollback(rollback, epoch)1823    }18241825    /** Permanently empty the trash — hard-deletes every soft-deleted entry. */1826    suspend fun purgeDeletedEntries(): Int = mutex.withLock {1827        val epoch = requireUnlocked()1828        // H-03: read+remove under stateLock so lock() can't reorder the remove.1829        data class R(val rollback: MutableList<VaultEntry>, val removed: Int)1830        val r = mutateCurrentSession(epoch) {1831            val rollback = entryList.toMutableList()1832            val before = entryList.size1833            entryList.removeAll { it.deletedAt != null }1834            R(rollback, before - entryList.size)1835        } ?: throw IllegalStateException("vault_locked")1836        if (r.removed > 0) persistOrRollback(r.rollback, epoch)1837        r.removed1838    }18391840    /** Browser parity: number of active entries that dedupe would move to trash. */1841    suspend fun countDuplicateEntries(): Int = mutex.withLock {1842        val epoch = requireUnlocked()1843        // countDuplicateEntriesLocked reads entryList; H-03 fences the read so1844        // lock() can't race the read with state writes.1845        mutateCurrentSession(epoch) { countDuplicateEntriesLocked() }1846            ?: throw IllegalStateException("vault_locked")1847    }18481849    /**1850     * Browser parity: soft-delete duplicate entries, keeping the most recently1851     * modified member of each group. Refuse in decoy mode so the duress vault is1852     * not reshaped into a forensically distinct state.1853     */1854    suspend fun deduplicateEntries(): Int = mutex.withLock {1855        val epoch = requireUnlocked()1856        data class R(val rollback: MutableList<VaultEntry>, val removed: Int)1857        val ready = mutateCurrentSession(epoch) {1858            if (decoyMode) throw IllegalStateException("deduplicate disabled in decoy mode")1859            val active = entryList.filter { it.deletedAt == null }1860            val keepIds = mutableSetOf<String>()1861            active.groupBy { it.duplicateKey() }.values.forEach { group ->1862                keepIds += group.maxBy { it.modifiedAt.takeIf { ts -> ts > 0 } ?: it.createdAt }.id1863            }1864            val rollback = entryList.toMutableList()1865            var removed = 01866            entryList = entryList.map { entry ->1867                if (entry.deletedAt == null && entry.id !in keepIds) {1868                    removed++1869                    val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)1870                    entry.copy(deletedAt = stamp, modifiedAt = stamp)1871                } else {1872                    entry1873                }1874            }.toMutableList()1875            R(rollback, removed)1876        } ?: throw IllegalStateException("vault_locked")1877        if (ready.removed > 0) persistOrRollback(ready.rollback, epoch)1878        ready.removed1879    }18801881    fun getEntries(): List<VaultEntry> = mutateState {1882        if (!sessionDataAvailable) emptyList() else entryList.filter { it.deletedAt == null }1883    }1884    fun getEntry(id: String): VaultEntry? = mutateState {1885        if (!sessionDataAvailable) null else entryList.firstOrNull { it.id == id && it.deletedAt == null }1886    }1887    fun getDeletedEntries(): List<VaultEntry> = mutateState {1888        if (!sessionDataAvailable) emptyList()1889        else entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }1890    }18911892    /** Active entries, optionally narrowed to those carrying [tagFilter]. */1893    fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {1894        return mutateState {1895            if (!sessionDataAvailable) return@mutateState emptyList()1896            val active = entryList.filter { it.deletedAt == null }1897            if (tagFilter == null) return@mutateState active1898            val needle = tagFilter.trim().lowercase()1899            active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }1900        }1901    }19021903    /** Sorted, de-duplicated tags across all active entries. */1904    fun getDistinctTags(): List<String> = mutateState {1905        if (!sessionDataAvailable) return@mutateState emptyList()1906        entryList.asSequence()1907            .filter { it.deletedAt == null }1908            .flatMap { it.tags?.asSequence() ?: emptySequence() }1909            .map { it.trim().lowercase() }1910            .filter { it.isNotEmpty() }1911            .distinct()1912            .sorted()1913            .toList()1914    }19151916    /**1917     * Distinct non-blank values for an identity field across active entries,1918     * most-frequently-used first. Supports "username" and "email"; unknown field1919     * names return an empty list. Values keep original casing (deduped1920     * case-insensitively) so a suggestion matches what the user typed.1921     */1922    fun getDistinctFieldValues(field: String): List<String> {1923        val select: (VaultEntry) -> String? = when (field) {1924            "username" -> { e -> e.username }1925            "email" -> { e -> e.email }1926            else -> return emptyList()1927        }1928        return mutateState {1929            if (!sessionDataAvailable) return@mutateState emptyList()1930            entryList.asSequence()1931                .filter { it.deletedAt == null }1932                .mapNotNull { select(it)?.trim() }1933                .filter { it.isNotEmpty() }1934                .groupingBy { it.lowercase() }1935                .aggregate { _, acc: Pair<String, Int>?, value, _ ->1936                    Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)1937                }1938                .values1939                .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })1940                .map { it.first }1941        }1942    }19431944    fun getTombstones(): List<Tombstone> = mutateState {1945        if (!sessionDataAvailable) emptyList()1946        else entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }1947    }1948    fun getVaultVersion(): Long = store.version()1949    fun getVaultHistory(): List<VaultSnapshot> = store.loadVaultHistory().snapshots19501951    suspend fun restoreVaultSnapshot(snapshotId: String): Boolean = mutex.withLock {1952        val expectedEpoch = currentEpoch()1953        val snapshot = store.loadVaultHistory().snapshots.firstOrNull { it.id == snapshotId } ?: return false1954        val restoredA = VaultCodec.decodeSlot(snapshot.vault_a) ?: return false1955        // H-04: snapshots now carry the duress slot too — restore preserves1956        // the at-rest triad (A/B/D), not just the A/B pair.1957        val restoredD: StoredVault? = snapshot.vault_d?.let(VaultCodec::decodeSlot)1958        val priorA = store.loadSlotA()1959        val priorB = store.loadSlotB()1960        val priorD = store.loadDecoySlot()1961        // H-02: capture pre-restore state as the recovery snapshot BEFORE any1962        // slot write — the old code took this snapshot, then stranded it on1963        // every failure, polluting history with a "restore" entry that never1964        // restored anything. The history below is rolled back together with1965        // the slots if the commit fails.1966        val priorHistory = store.loadVaultHistory()1967        // P1-4 (codex): the recovery snapshot must land before we commit the1968        // slot pair, otherwise a failed restore cannot be rolled back to the1969        // pre-restore history. If the history write itself fails, refuse to1970        // proceed — the alternative is a successful restore with no undo path.1971        beforeDurableCommit()1972        if (!takeVaultSnapshot("restore", expectedEpoch)) {1973            return false1974        }1975        // H-04: legacy snapshots without vault_d, or vault_d that fails to1976        // decode, fall back to a fake duress of slot A's size — presence-1977        // indistinguishable from any other freshly-restored vault.1978        val nextD: StoredVault = restoredD ?: run {1979            val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(restoredA) + 161980            val fakeBlob = ByteArray(target).also(rng::nextBytes)1981            val fakeSalt = VaultCrypto.generateSalt()1982            StoredVault(version = 1, salt = b64(fakeSalt), blob = b64(fakeBlob))1983        }1984        if (!commitRestoreAtomic(restoredA, snapshot.vault_b, nextD, priorA, priorB, priorD, expectedEpoch)) {1985            withEpochCommit(expectedEpoch) { store.writeVaultHistory(priorHistory) }1986            return false1987        }1988        lock()1989        true1990    }19911992    /**1993     * H-02: atomic slot-A + slot-B + version stamp for a snapshot restore.1994     * Mirrors [commitVaultRotation] but writes the snapshot's EXACT slot B1995     * (a restore preserves the duress-shaped blob from history), not a fresh1996     * noise record. Any failure rolls back so the at-rest pair never holds a1997     * restored slot A against a pre-restore slot B. Caller is responsible for1998     * restoring the pre-snapshot history on a false return.1999     *2000     * H-04: duress slot is now part of the atomic triad — restored last so2001     * a duress-write failure rolls the A/B pair back too.2002     */2003    private fun commitRestoreAtomic(2004        nextA: StoredVault,2005        nextB: String,2006        nextD: StoredVault,2007        priorA: StoredVault?,2008        priorB: String?,2009        priorD: StoredVault?,2010        expectedEpoch: Long,2011    ): Boolean {2012        return withEpochCommit(expectedEpoch) {2013            if (!store.writeSlotA(nextA)) return@withEpochCommit false2014            // P1-2 (codex): writeSlotB's boolean AND any thrown exception from it2015            // must trigger rollback; previously a throw escaped without restoring2016            // the prior slot A and history.2017            try {2018                if (!store.writeSlotB(nextB)) throw java.io.IOException("slot_b_commit_failed")2019                // H-04: duress slot is part of the restore triad. Failures here2020                // roll A+B back so the at-rest state stays consistent.2021                if (!store.writeDecoySlot(nextD)) throw java.io.IOException("duress_slot_commit_failed")2022                store.stampLocalMutation()2023            } catch (_: Exception) {2024                reportRollbackFailures(rollbackRestoreLocked(priorA, priorB, priorD))2025                return@withEpochCommit false2026            }2027            true2028        } ?: false2029    }20302031    // ---- Sync apply (does NOT advance the version) ------------------------20322033    /**2034     * Apply remote entryList + tombstones with per-entry last-write-wins. Persists2035     * WITHOUT bumping the version counter, so a sync round cannot cascade into2036     * another outbound sync. Returns the number of locally-applied changes.2037     */2038    suspend fun applyMergedRemoteEntries(2039        remoteEntries: List<VaultEntry>,2040        remoteTombstones: List<Tombstone>,2041        expectedEpoch: Long? = null,2042    ): Int = mutex.withLock {2043        val epoch = expectedEpoch ?: requireUnlocked()2044        if (expectedEpoch != null && mutateIfCurrentEpoch(epoch) { true } != true) return@withLock 02045        // HV-1: clamp every peer-supplied timestamp to now + MAX_CLOCK_SKEW_MS2046        // BEFORE any comparison against a local one. Without this a peer can2047        // send a far-future modifiedAt and permanently pin its version of an2048        // entry against every honest local edit. The browser clamps in the2049        // matching place (vault.ts applyMergedRemoteEntries).2050        val mergeNow = System.currentTimeMillis()2051        val clamped = remoteEntries.mapNotNull { entry ->2052            // MN-3: drop peer entries that decode cleanly but are semantically2053            // hollow (blank title, credential-less login, husk passkey) and2054            // re-cap passwordHistory before anything merges into the vault.2055            SyncEntrySanitizer.sanitize(entry, PASSWORD_HISTORY_MAX)?.copy(2056                modifiedAt = SyncLimits.clampSyncTimestamp(entry.modifiedAt, mergeNow),2057                deletedAt = entry.deletedAt?.let {2058                    SyncLimits.clampSyncTimestamp(it, mergeNow)2059                },2060            )2061        }2062        val tombMap = remoteTombstones.associate {2063            it.id to SyncLimits.clampSyncTimestamp(it.deletedAt, mergeNow)2064        }2065        // H-03: build the new entryList under stateLock so a concurrent lock()2066        // cannot zero derivedKey/entryList between the byId read and the merge.2067        val applied = mutateCurrentSession(epoch) {2068            var n = 02069            val byId = entryList.associateBy { it.id }.toMutableMap()20702071            for (remote in clamped) {2072                val tomb = tombMap[remote.id]2073                if (tomb != null && tomb >= remote.modifiedAt) continue2074                val local = byId[remote.id]2075                if (local == null) {2076                    entryList.add(remote); byId[remote.id] = remote; n++2077                } else if (remote.modifiedAt > local.modifiedAt) {2078                    val i = entryList.indexOfFirst { it.id == local.id }2079                    if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; n++ }2080                }2081            }20822083            for ((id, deletedAt) in tombMap) {2084                val local = byId[id] ?: continue2085                if (local.deletedAt != null && local.deletedAt >= deletedAt) continue2086                if (deletedAt < local.modifiedAt) continue2087                val i = entryList.indexOfFirst { it.id == id }2088                if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); n++ }2089            }2090            n2091        } ?: return@withLock 020922093        if (applied > 0) {2094            persistSlotA(bumpVersion = false, snapshotReason = "sync_received", expectedEpoch = epoch)2095            mutateIfCurrentEpoch(epoch) { publish() }2096            runCatching { LockedSyncSpoolHooks.refresh(this) }2097        }2098        applied2099    }21002101    suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {2102        // Require a fully live session before exposing a settings mutation.  The2103        // epoch is captured with the read so a lock/new-session boundary cannot2104        // let stale work publish into the replacement session.2105        val epoch = requireUnlocked()2106        val prior = mutateCurrentSession(epoch) {2107            val old = _settings.value2108            _settings.value = settings2109            old2110        } ?: throw IllegalStateException("vault_locked")21112112        val committed = try {2113            beforeDurableCommit()2114            // The durable write is inside the same epoch fence as the in-memory2115            // publication.  If lock() won first, this returns null and no stale2116            // settings reach storage or the public StateFlow.2117            withSessionEpochCommit(epoch) { store.writeSettings(settings) } == true2118        } catch (_: Exception) {2119            false2120        }2121        if (!committed) {2122            // A live-session storage failure rolls back the public value.  A2123            // stale epoch is already reset by lock()/the new session and must2124            // not be allowed to overwrite that safe state.2125            mutateIfCurrentEpoch(epoch) { _settings.value = prior }2126            throw IllegalStateException("settings_write_failed")2127        }2128    }21292130    // ---- Recovery words (vault metadata) ----------------------------------21312132    /** True once the user has confirmed their recovery words for this vault. */2133    fun isRecoveryWordsSet(): Boolean = mutateState { recoveryWordsSet }21342135    /**2136     * Record the BLAKE3 hash of the confirmed recovery words and mark them set.2137     * Persisted without bumping the version — recovery metadata is local-only and2138     * is not an entry mutation paired devices should sync against.2139     */2140    suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {2141        val epoch = requireUnlocked()2142        // H-03: hash + escrow-related state fields set under stateLock so a2143        // concurrent lock() cannot zero them in the middle of buildRecoveryEscrow.2144        // M-04: the flags have to be live before the escrows are built — both seal2145        // currentPayload() — so capture the prior pair and put it back if the write2146        // never lands. Otherwise the session reports words set against a slot A2147        // that still holds no escrow, and the recovery screen never offers a retry.2148        val prior = mutateCurrentSession(epoch) {2149            val priorPair = recoveryWordHash to recoveryWordsSet2150            recoveryWordHash = recoveryWordsHash(words)2151            recoveryWordsSet = true2152            priorPair2153        } ?: return@withLock false2154        // Seal TWO escrows (MF-1): the browser-byte-compatible root-key escrow2155        // (cross-platform recovery of the sync root key) and Android's whole-payload2156        // escrow (offline forgot-password restore of entries). Both derive their key2157        // from the same `wordsToRootKeyMaterial` IKM but use distinct AADs.2158        val persisted = runCatching {2159            persistSlotAWithEscrows(2160                buildRecoveryEscrow(words),2161                buildRootKeyEscrow(words),2162                expectedEpoch = epoch,2163            )2164        }.getOrDefault(false)2165        if (!persisted) {2166            mutateIfCurrentEpoch(epoch) {2167                recoveryWordHash = prior.first2168                recoveryWordsSet = prior.second2169            }2170        }2171        persisted2172    }21732174    /** Verify entered words against the stored recovery hash. */2175    fun verifyRecoveryWords(words: List<String>): Boolean {2176        return mutateState {2177            val stored = recoveryWordHash ?: return@mutateState false2178            MessageDigest.isEqual(2179                stored.toByteArray(Charsets.UTF_8),2180                recoveryWordsHash(words).toByteArray(Charsets.UTF_8),2181            )2182        }2183    }21842185    // ---- Recovery escrow (forgot-password) --------------------------------21862187    /** True at rest if this vault has any recovery escrow the recovery flow can use. */2188    fun hasRecoveryEscrow(): Boolean =2189        store.loadSlotA()?.let { it.recoveryEscrow != null || it.rootKeyEscrow != null } ?: false21902191    /**2192     * One-time self-heal: if this vault has a root key but no recovery escrow2193     * on disk (adopted vaults created before the escrow fix), build and persist2194     * it now. Called on every successful unlock; no-ops once the escrow exists.2195     */2196    private fun ensureRecoveryEscrow() {2197        if (hasRecoveryEscrow()) return2198        val rk = mutateState { rootKey?.copyOf() } ?: return2199        runCatching {2200            val words = rootKeyToWords(rk)2201            val escrow = buildRecoveryEscrow(words)2202            val rkEscrow = buildRootKeyEscrow(words)2203            if (escrow != null || rkEscrow != null) {2204                val prior = store.loadSlotA() ?: return@runCatching2205                store.writeSlotA(prior.copy(2206                    recoveryEscrow = escrow ?: prior.recoveryEscrow,2207                    rootKeyEscrow = rkEscrow ?: prior.rootKeyEscrow,2208                ))2209                mutateState {2210                    recoveryWordHash = recoveryWordsHash(words)2211                    recoveryWordsSet = true2212                }2213            }2214        }.also { VaultCrypto.zero(rk) }2215    }22162217    /**2218     * Attempt to unlock the vault using the 12 BIP39 recovery [words] instead of2219     * the master password. On success the slot-A plaintext sealed in the escrow is2220     * adopted as the live session (entries, rootKey, settings), but no Argon2id2221     * password key exists yet — call [resetPasswordWithRecoveryWords] next to set a2222     * new password and finish unlocking. Returns false when there is no escrow, the2223     * words fail the BIP39 checksum, or the words are wrong (GCM tag mismatch).2224     *2225     * Unlike the brief's `unlockWithRecoveryWords(): ByteArray?`, there is no2226     * detached vault key to return here — slot A is wrapped under the rotating2227     * Argon2id key — so this opens the escrowed payload directly.2228     */2229    suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {2230        val expectedEpoch = currentEpoch()2231        val slotA = store.loadSlotA() ?: return false2232        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false22332234        // Prefer Android's whole-payload escrow: a full offline restore of entries,2235        // root key, and settings. Present for Android-created vaults.2236        val fullEscrow = slotA.recoveryEscrow2237        if (fullEscrow != null) {2238            val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull()2239            if (material != null) {2240                var keyBytes: ByteArray? = null2241                var plaintext: ByteArray? = null2242                var candidateRoot: ByteArray? = null2243                var stateCommitStarted = false2244                try {2245                    keyBytes = deriveRecoveryKey(material, unb64(fullEscrow.salt)).encoded2246                    plaintext = VaultCrypto.decrypt(unb64(fullEscrow.blob), keyBytes!!, VaultCrypto.AAD_RECOVERY)2247                    val payload = VaultCodec.decode(plaintext)2248                    // Stage every fallible operation before touching live session2249                    // fields.  In particular, a settings/provider/decode failure2250                    // cannot leave entries, flags, or a root key resident while the2251                    // public session remains locked.2252                    val candidateSettings = store.loadSettings()2253                    candidateRoot = if (payload.rootKeyB64.isNotBlank()) {2254                        val decodedRoot = unb64(payload.rootKeyB64)2255                        if (decodedRoot.size != VaultCrypto.KEY_SIZE) {2256                            // Do not let a malformed authenticated payload abandon2257                            // this decoded root-key candidate before the outer2258                            // finally block owns it.2259                            VaultCrypto.zero(decodedRoot)2260                            throw IllegalArgumentException("invalid recovery root key")2261                        }2262                        decodedRoot2263                    } else {2264                        generateRecoverableRootKey()2265                    }2266                    stateCommitStarted = true2267                    val adopted = mutateIfCurrentEpoch(expectedEpoch) {2268                        clearSessionStateLocked()2269                        entryList = payload.entries.toMutableList()2270                        duressConfigured = payload.duressConfigured2271                        recoveryWordHash = payload.recoveryWordHash2272                        recoveryWordsSet = payload.recoveryWordsSet2273                        rootKey = candidateRoot2274                        candidateRoot = null2275                        _settings.value = candidateSettings2276                        publish()2277                        // This is the authenticated recovery half-unlock boundary:2278                        // only set it after every candidate field is installed.2279                        sessionDataAvailable = true2280                        _isUnlocked.value = false2281                        true2282                    }2283                    if (adopted == true) return@withLock true2284                } catch (_: Exception) {2285                    // Wrong words, malformed payloads, provider failures, and2286                    // settings failures all fall through to the browser-compatible2287                    // root-key escrow.  If the state commit had started, invalidate2288                    // that epoch so no partial candidate survives.2289                    if (stateCommitStarted) {2290                        mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }2291                    }2292                } finally {2293                    plaintext?.let(VaultCrypto::zero)2294                    VaultCrypto.zero(material)2295                    keyBytes?.let(VaultCrypto::zero)2296                    candidateRoot?.let(VaultCrypto::zero)2297                }2298            }2299        }23002301        // Browser-format vault (only the root-key escrow): recover the 32-byte root2302        // key (sync identity) and reset the password; entries return via sync. This2303        // is exactly the browser's recovery semantics (`messages.ts:312-347`).2304        val rootEscrow = slotA.rootKeyEscrow2305        if (rootEscrow != null) {2306            var candidateRoot: ByteArray? = null2307            var stateCommitStarted = false2308            try {2309                candidateRoot = unsealRootKeyEscrow(words, rootEscrow) ?: return false2310                require(candidateRoot!!.size == VaultCrypto.KEY_SIZE) { "invalid recovery root key" }2311                val candidateSettings = store.loadSettings()2312                stateCommitStarted = true2313                val adopted = mutateIfCurrentEpoch(expectedEpoch) {2314                    clearSessionStateLocked()2315                    entryList = mutableListOf()2316                    duressConfigured = false2317                    recoveryWordHash = recoveryWordsHash(words)2318                    recoveryWordsSet = true2319                    rootKey = candidateRoot2320                    candidateRoot = null2321                    _settings.value = candidateSettings2322                    publish()2323                    sessionDataAvailable = true2324                    _isUnlocked.value = false2325                    true2326                }2327                if (adopted == true) return@withLock true2328            } catch (_: Exception) {2329                if (stateCommitStarted) {2330                    mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }2331                }2332            } finally {2333                candidateRoot?.let(VaultCrypto::zero)2334            }2335        }2336        return false2337    }23382339    /**2340     * After [unlockWithRecoveryWords] succeeds, set a brand-new master password:2341     * re-seal slot A under a fresh Argon2id key, rotate the escrow under the same2342     * words, mark the session fully unlocked, and publish. Returns false if called2343     * without a prior successful recovery unlock (no in-memory root key).2344     *2345     * Folds the brief's `resetPasswordWithRecoveryKey(vaultKey, …)` + `unlock(…)`2346     * into one step, since there is no detached vault key here.2347     */2348    suspend fun resetPasswordWithRecoveryWords(2349        words: List<String>,2350        newPassword: String,2351    ): Boolean = mutex.withLock {2352        val expectedEpoch = currentEpoch()2353        // H-03: read rootKey + entryList under stateLock before computing the new2354        // plaintext, then re-publish + swap the derived key under stateLock so a2355        // concurrent lock() cannot straddle the two fences.2356        if (mutateIfCurrentEpoch(expectedEpoch) { rootKey != null } != true) return false2357        val priorA = store.loadSlotA() ?: return false2358        var newKey: ByteArray? = null2359        var plaintext: ByteArray? = null2360        return try {2361            val newSalt = VaultCrypto.generateSalt()2362            newKey = VaultCrypto.deriveKey(newPassword, newSalt)2363            plaintext = VaultCodec.encode(currentPayload())2364            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))2365            // Rebuild both escrows against the recovered session so their salts rotate2366            // with the password reset; fall back to the prior escrows if rebuild fails2367            // (e.g. a checksum-invalid phrase). The same 12 words keep working.2368            val valid = words.size == 12 && findInvalidWords(words).isEmpty()2369            val freshRecovery = if (valid) buildRecoveryEscrow(words) ?: priorA.recoveryEscrow else priorA.recoveryEscrow2370            val freshRootKey = if (valid) buildRootKeyEscrow(words) ?: priorA.rootKeyEscrow else priorA.rootKeyEscrow2371            val next = StoredVault(2372                version = priorA.version,2373                salt = b64(newSalt),2374                blob = blob,2375                recoveryEscrow = freshRecovery,2376                rootKeyEscrow = freshRootKey,2377            )2378            // H-01: see changePassword — both rotations share the same2379            // commit-or-keep-old-key contract so a partial write can't strand2380            // the session on a key that no longer matches disk.2381            val priorB = store.loadSlotB()2382            if (!commitVaultRotation(priorA, priorB, next, expectedEpoch)) return false2383            // H-03 (P1-2 codex): zero the old live key and install the new one2384            // inside the same stateLock critical section so a concurrent lock()2385            // can't observe the in-between.2386            if (mutateIfCurrentEpoch(expectedEpoch) {2387                derivedKey?.let(VaultCrypto::zero)2388                derivedKey = newKey; newKey = null2389                publish()2390                _isUnlocked.value = true2391            } == null) return false2392            true2393        } catch (_: Exception) {2394            false2395        } finally {2396            newKey?.let(VaultCrypto::zero)2397            plaintext?.let(VaultCrypto::zero)2398        }2399    }24002401    /**2402     * Seal the current slot-A plaintext under a key derived from the 12 BIP392403     * recovery [words] (Android offline-restore escrow). IKM is the browser's2404     * `wordsToRootKeyMaterial` (MF-1), AAD is the string [VaultCrypto.AAD_RECOVERY].2405     * Returns null for a checksum-invalid phrase.2406     */2407    private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {2408        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null2409        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2410        var keyBytes: ByteArray? = null2411        var plaintext: ByteArray? = null2412        return try {2413            val salt = VaultCrypto.generateSalt()2414            val recoveryKey = deriveRecoveryKey(material, salt)2415            keyBytes = recoveryKey.encoded2416            plaintext = VaultCodec.encode(currentPayload())2417            val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)2418            RecoveryEscrow(salt = b64(salt), blob = b64(sealed))2419        } finally {2420            VaultCrypto.zero(material)2421            keyBytes?.let(VaultCrypto::zero)2422            plaintext?.let(VaultCrypto::zero)2423        }2424    }24252426    /**2427     * Seal ONLY the 32-byte root key under a key the recovery [words] derive,2428     * byte-for-byte the browser algorithm (MF-1): plaintext = lowercase ASCII hex2429     * of the root key, IKM = `wordsToRootKeyMaterial`, HKDF salt random-16,2430     * info `peach-recovery-v1`, AES-256-GCM AAD = 0x01. The same 12 words unwrap2431     * the same root key on the browser. Returns null with no in-memory root key or2432     * a checksum-invalid phrase.2433     */2434    private fun buildRootKeyEscrow(words: List<String>): RootKeyEscrow? {2435        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null2436        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2437        val rk = mutateState { rootKey?.copyOf() } ?: run {2438            VaultCrypto.zero(material)2439            return null2440        }2441        var keyBytes: ByteArray? = null2442        var plaintext: ByteArray? = null2443        return try {2444            val salt = VaultCrypto.generateSalt()2445            val recoveryKey = deriveRecoveryKey(material, salt)2446            keyBytes = recoveryKey.encoded2447            plaintext = rootKeyToHex(rk).toByteArray(Charsets.US_ASCII)2448            // combined = nonce(12) || ciphertext || tag(16)2449            val combined = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)2450            val nonce = combined.copyOfRange(0, VaultCrypto.NONCE_SIZE)2451            val ctTag = combined.copyOfRange(VaultCrypto.NONCE_SIZE, combined.size)2452            val tag = ctTag.copyOfRange(ctTag.size - 16, ctTag.size)2453            val ct = ctTag.copyOfRange(0, ctTag.size - 16)2454            RootKeyEscrow(salt = b64(salt), wrappedRootKey = b64(ct), nonce = b64(nonce), tag = b64(tag))2455        } finally {2456            VaultCrypto.zero(rk)2457            VaultCrypto.zero(material)2458            keyBytes?.let(VaultCrypto::zero)2459            plaintext?.let(VaultCrypto::zero)2460        }2461    }24622463    /** Unwrap the 32-byte root key from a browser-compatible [escrow]; null on wrong words. */2464    private fun unsealRootKeyEscrow(words: List<String>, escrow: RootKeyEscrow): ByteArray? {2465        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2466        var keyBytes: ByteArray? = null2467        var pt: ByteArray? = null2468        return try {2469            val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))2470            keyBytes = recoveryKey.encoded2471            val combined = unb64(escrow.nonce) + unb64(escrow.wrappedRootKey) + unb64(escrow.tag)2472            pt = VaultCrypto.decrypt(combined, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)2473            hexToRootKey(String(pt, Charsets.US_ASCII))2474        } catch (_: Exception) {2475            null2476        } finally {2477            // M-05: pt is the lowercase hex of the 32-byte root key — i.e. the2478            // IKM-equivalent of the vault identity. material+keyBytes were2479            // already zeroed; pt was leaking.2480            VaultCrypto.zero(material)2481            keyBytes?.let(VaultCrypto::zero)2482            pt?.let(VaultCrypto::zero)2483        }2484    }24852486    /**2487     * Re-seal slot A from the current in-memory state under the live key, carrying2488     * both [recoveryEscrow] and [rootKeyEscrow] onto the written record. Never runs2489     * in decoy mode (recovery is never offered for the decoy) and persists without2490     * a version bump, like the recovery-words metadata write it replaces.2491     */2492    private fun persistSlotAWithEscrows(2493        recoveryEscrow: RecoveryEscrow?,2494        rootKeyEscrow: RootKeyEscrow?,2495        expectedEpoch: Long? = null,2496    ): Boolean {2497        val snapshot = snapshotForPersist(expectedEpoch)2498            ?: throw IllegalStateException("vault_locked_or_stale")2499        if (snapshot.decoy) {2500            VaultCrypto.zero(snapshot.key)2501            return false2502        }2503        try {2504            val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")2505            val plaintext = VaultCodec.encode(snapshot.payload)2506            val blob = try {2507                b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))2508            } finally {2509                // The escrow path used to drop this reference before zeroing it;2510                // keep it live through the fill on both success and failure.2511                VaultCrypto.zero(plaintext)2512            }2513            val next = prior.copy(2514                blob = blob,2515                recoveryEscrow = recoveryEscrow ?: prior.recoveryEscrow,2516                rootKeyEscrow = rootKeyEscrow ?: prior.rootKeyEscrow,2517            )2518            beforeDurableCommit()2519            return withEpochCommit(snapshot.epoch) {2520                if (!store.writeSlotA(next)) return@withEpochCommit false2521                try {2522                    if (!writeMatchingNoiseSlotB(next)) throw java.io.IOException("noise_slot_b_commit_failed")2523                    // H-04: escrow rebuild changes slot A's plaintext size, so re-pad2524                    // the duress slot too. A real decoy is left alone; a fake is2525                    // re-sized to slot A's new ciphertext length.2526                    if (!writeCompanionDuressSlot(next)) throw java.io.IOException("duress_slot_commit_failed")2527                } catch (e: Exception) {2528                    store.writeSlotA(prior)2529                    throw e2530                }2531                true2532            } ?: false2533        } finally {2534            VaultCrypto.zero(snapshot.key)2535        }2536    }25372538    // ---- Internals --------------------------------------------------------25392540    private fun requireUnlocked(): Long {2541        // H-03: read derivedKey atomically with [lock]'s reset; without it,2542        // [lock] from a background lifecycle event can run between this read2543        // and the caller's first state touch.2544        stateLock.lock()2545        try {2546            if (derivedKey == null) throw IllegalStateException("vault_locked")2547            return sessionEpoch2548        } finally {2549            stateLock.unlock()2550        }2551    }25522553    /** A locked or half-adopted session must not expose secret-bearing fields. */2554    private fun isFullyUnlockedLocked(): Boolean = _isUnlocked.value && derivedKey != null25552556    private fun countDuplicateEntriesLocked(): Int {2557        val seen = mutableMapOf<String, VaultEntry>()2558        var duplicates = 02559        for (entry in entryList.filter { it.deletedAt == null }) {2560            val key = entry.duplicateKey()2561            val existing = seen[key]2562            if (existing == null) {2563                seen[key] = entry2564            } else {2565                duplicates++2566                val entryStamp = entry.modifiedAt.takeIf { it > 0 } ?: entry.createdAt2567                val existingStamp = existing.modifiedAt.takeIf { it > 0 } ?: existing.createdAt2568                if (entryStamp > existingStamp) seen[key] = entry2569            }2570        }2571        return duplicates2572    }25732574    private fun VaultEntry.duplicateKey(): String {2575        if (type == "note") return "note|${title.lowercase()}"2576        val passkeyData = passkey2577        if (passkeyData != null) {2578            return "passkey|${passkeyData.rpId.lowercase()}|${passkeyData.userName.lowercase()}"2579        }2580        return "login|${title.lowercase()}|${url.orEmpty().lowercase()}|${username.orEmpty().lowercase()}"2581    }25822583    /**2584     * Capture the current slot pair (and metadata) into the history list.2585     * Returns true when the history write landed, false when it didn't — callers2586     * that depend on the snapshot existing (notably [restoreVaultSnapshot])2587     * must check the result and roll back if it does not.2588     */2589    private fun takeVaultSnapshot(reason: String, expectedEpoch: Long? = null): Boolean {2590        val epoch = expectedEpoch ?: currentEpoch()2591        if (mutateIfCurrentEpoch(epoch) { true } != true) return false2592        val slotA = store.loadSlotA() ?: return false2593        val vaultA = VaultCodec.encodeSlot(slotA)2594        val vaultB = store.loadSlotB() ?: slotA.blob2595        // H-04: capture the duress slot so a restore preserves the at-rest2596        // triad, not just the A/B pair. The duress slot is always present2597        // (real or fake), so loadDecoySlot() returning null is a logic error2598        // — fall through to a fake duress in that case rather than silently2599        // losing the record from the snapshot.2600        val vaultD = store.loadDecoySlot()?.let(VaultCodec::encodeSlot) ?: run {2601            val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 162602            val fakeBlob = ByteArray(target).also(rng::nextBytes)2603            val fakeSalt = VaultCrypto.generateSalt()2604            VaultCodec.encodeSlot(StoredVault(version = 1, salt = b64(fakeSalt), blob = b64(fakeBlob)))2605        }2606        val history = store.loadVaultHistory()2607        val latest = history.snapshots.firstOrNull()2608        if (latest?.vault_a == vaultA && latest.vault_b == vaultB && latest.vault_d == vaultD) return true2609        val entryCount = mutateIfCurrentEpoch(epoch) {2610            if (derivedKey != null && !decoyMode) {2611                bucketEntryCount(entryList.count { it.deletedAt == null })2612            } else {2613                null2614            }2615        } ?: return false2616        return try {2617            val snapshot = VaultSnapshot(2618                id = UUID.randomUUID().toString(),2619                savedAt = System.currentTimeMillis(),2620                reason = reason,2621                vault_a = vaultA,2622                vault_b = vaultB,2623                vault_d = vaultD,2624                entryCount = entryCount,2625            )2626            // P1-4 (codex): return the history-write boolean to callers so a2627            // false return no longer leaves the snapshot out of history while2628            // callers (notably restoreVaultSnapshot) proceed as if it succeeded.2629            withEpochCommit(epoch) {2630                store.writeVaultHistory(2631                    history.copy(snapshots = (listOf(snapshot) + history.snapshots).take(VAULT_HISTORY_MAX)),2632                )2633            } ?: false2634        } catch (_: Exception) {2635            false2636        }2637    }26382639    private fun bucketEntryCount(n: Int): Int = when {2640        n <= 0 -> 02641        n <= 10 -> 102642        n <= 25 -> 252643        n <= 50 -> 502644        n <= 100 -> 1002645        n <= 250 -> 2502646        n <= 500 -> 5002647        else -> ((n + 499) / 500) * 5002648    }26492650    /**2651     * Keep [VaultEntry.last4] in sync with the card number for card entries (MF-3),2652     * so it is stored explicitly and survives the sync wire format rather than being2653     * re-derived at render time. Non-card entries pass through unchanged.2654     *2655     * M-03: never overwrite a stored last4 with null. A card kept only as last42656     * (e.g. after a PeachScript import that had no PAN) must keep that value;2657     * re-deriving from an absent cardNumber would silently zero the field.2658     */2659    private fun withDerivedLast4(entry: VaultEntry): VaultEntry {2660        if (!entry.isCard()) return entry2661        val digits = entry.cardNumber?.filter { it.isDigit() } ?: ""2662        val derived = if (digits.length >= 4) digits.takeLast(4) else null2663        return entry.copy(last4 = derived ?: entry.last4)2664    }26652666    /**2667     * On unlock, hard-delete trashed entries older than the retention window.2668     * A null or non-positive [VaultSettings.trashRetentionDays] means "never"2669     * (the app's "Never" option), so nothing is purged. Persists without a2670     * version bump and without touching the publish state (caller publishes).2671     */2672    private fun autoPurgeExpiredTrash() {2673        val days = _settings.value.trashRetentionDays ?: return2674        if (days <= 0) return2675        val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L2676        val before = entryList.size2677        entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }2678        if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }2679    }26802681    /**2682     * Browser parity (P1): merge orphaned passkey-only entries into matching2683     * login entries that share the same registrable domain. A passkey-only2684     * entry has passkey fields (rpId + credentialId) but no password. Runs on2685     * unlock so consolidation is idempotent and cheap.2686     */2687    private fun consolidatePasskeyEntries() {2688        val passkeyOnly = entryList.filter { entry ->2689            entry.deletedAt == null &&2690                entry.isLogin() &&2691                entry.password.isNullOrBlank() &&2692                !entry.rpId.isNullOrBlank() &&2693                !entry.credentialId.isNullOrBlank()2694        }2695        if (passkeyOnly.isEmpty()) return2696        var changed = false2697        val now = System.currentTimeMillis()2698        for (pkEntry in passkeyOnly) {2699            val rpId = pkEntry.rpId ?: continue2700            val target = entryList.firstOrNull { candidate ->2701                candidate.deletedAt == null &&2702                    candidate.id != pkEntry.id &&2703                    candidate.isLogin() &&2704                    candidate.passkey == null &&2705                    candidate.credentialId.isNullOrBlank() &&2706                    !candidate.password.isNullOrBlank() &&2707                    listOfNotNull(candidate.url, *candidate.additionalUrls.orEmpty().toTypedArray())2708                        .any { com.peachpasswords.shared.extractDomain(it) == rpId }2709            } ?: continue2710            val idx = entryList.indexOfFirst { it.id == target.id }2711            if (idx < 0) continue2712            entryList[idx] = target.copy(2713                rpId = pkEntry.rpId,2714                rpName = pkEntry.rpName ?: target.rpName,2715                credentialId = pkEntry.credentialId,2716                publicKeyCose = pkEntry.publicKeyCose,2717                privateKeyJwk = pkEntry.privateKeyJwk,2718                userHandle = pkEntry.userHandle,2719                userName = pkEntry.userName,2720                userDisplayName = pkEntry.userDisplayName,2721                algorithm = pkEntry.algorithm,2722                signCount = pkEntry.signCount,2723                lastUsedAt = pkEntry.lastUsedAt,2724                modifiedAt = now,2725            )2726            // Soft-delete the orphan so it lands in trash (recoverable).2727            val pkIdx = entryList.indexOfFirst { it.id == pkEntry.id }2728            if (pkIdx >= 0) entryList[pkIdx] = pkEntry.copy(deletedAt = now)2729            changed = true2730        }2731        if (changed) runCatching { persistSlotA(bumpVersion = false) }2732    }27332734    /** The slot-A plaintext envelope for the current in-memory session. */2735    private fun currentPayload(): VaultPayload = mutateState { currentPayloadLocked() }27362737    private fun currentPayloadLocked(): VaultPayload =2738        VaultPayload(2739            entries = entryList.toList(),2740            duressConfigured = duressConfigured,2741            rootKeyB64 = rootKey?.let(::b64) ?: "",2742            recoveryWordHash = recoveryWordHash,2743            recoveryWordsSet = recoveryWordsSet,2744        )27452746    /**2747     * Adopt the payload's root key, lazily minting one for legacy payloads.2748     * A freshly-minted key is persisted WITHOUT bumping the version — adopting2749     * a root key is not a mutation paired devices should sync against.2750     */2751    private fun ensureRootKey(payload: VaultPayload) {2752        if (payload.rootKeyB64.isNotBlank()) {2753            rootKey = unb64(payload.rootKeyB64)2754            return2755        }2756        rootKey = generateRecoverableRootKey()2757        runCatching { persistSlotA(bumpVersion = false) }2758    }27592760    private fun publish() {2761        _entries.value = entryList.filter { it.deletedAt == null }2762    }27632764    private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {2765        var plaintext = VaultCodec.encode(currentPayload())2766        return try {2767            val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))2768            StoredVault(version = 1, salt = b64(salt), blob = blob)2769        } finally {2770            // M-05: full vault plaintext is allocated here once per createVault.2771            // Zeroing in finally keeps the transient copy off the heap after the2772            // caller either succeeds or rolls back via lock().2773            VaultCrypto.zero(plaintext)2774        }2775    }27762777    private fun writeMatchingNoiseSlotB(slotA: StoredVault): Boolean {2778        // Size the noise so its base64 length matches slot A's blob (MN-1): with the2779        // plaintext now bucket-padded, an at-rest observer sees two equal-length slots2780        // and cannot pick the real one by size. b64(N bytes) ≈ N*4/3 chars.2781        val approxBytes = (slotA.blob.length * 3 / 4).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)2782        val noise = ByteArray(approxBytes).also(rng::nextBytes)2783        return store.writeSlotB(b64(noise))2784    }27852786    /** H-04: the ciphertext length slot A is using right now, so the duress2787     *  slot's blob can match it on disk. AES-GCM is a stream cipher — plaintext2788     *  length equals ciphertext length, so this also matches slot A's plaintext. */2789    private fun matchingCiphertextLength(slotA: StoredVault): Int =2790        (unb64(slotA.blob).size - VaultCrypto.NONCE_SIZE - 16).coerceAtLeast(0)27912792    /** H-04: a decoy-shaped StoredVault with a random blob of [matchingCiphertextLength]2793     *  bytes. Replaces a real decoy when the user clears duress, and is the2794     *  initial duress slot when no decoy is configured — so the record's2795     *  PRESENCE on disk is independent of duressConfigured, and its SIZE2796     *  matches slot A's blob length. */2797    private fun writeFakeDuressSlot(slotA: StoredVault): Boolean {2798        val blobSize = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 162799        val fakeBlob = ByteArray(blobSize).also(rng::nextBytes)2800        val fakeSalt = VaultCrypto.generateSalt()2801        return store.writeDecoySlot(StoredVault(version = 1, salt = b64(fakeSalt), blob = b64(fakeBlob)))2802    }28032804    /** H-04: keep the duress record present on every persist. A real decoy is2805     *  left alone (it was padded at setDuressPassphrase time, and we don't have2806     *  the duress key here to re-seal it) — VaultStore re-pads both slot2807     *  records to the longer of the two on every write, which is what keeps the2808     *  pair the same length after slot A crosses a padding bucket2809     *  (PAI-2026-004). No real decoy → a fresh fake of slot A's size. */2810    private fun writeCompanionDuressSlot(slotA: StoredVault): Boolean {2811        val isConfigured = mutateState { duressConfigured }2812        return if (isConfigured) true else writeFakeDuressSlot(slotA)2813    }28142815    /**2816     * H-04: convert a browser-shaped duress slot to Android StoredVault2817     * without decrypting. The browser seals slot "b" under the duress2818     * passphrase; decrypting with the main password silently drops it.2819     * Concatenates nonce‖ciphertext‖tag into Android's blob and re-encodes2820     * the salt from hex to base64.2821     */2822    private fun browserDuressPassthrough(b: BrowserSlotA): StoredVault {2823        val salt = unhex(b.salt)2824        val nonce = unhex(b.nonce)2825        val ct = unhex(b.ciphertext)2826        val tag = unhex(b.tag)2827        val blob = ByteArray(nonce.size + ct.size + tag.size).also {2828            System.arraycopy(nonce, 0, it, 0, nonce.size)2829            System.arraycopy(ct, 0, it, nonce.size, ct.size)2830            System.arraycopy(tag, 0, it, nonce.size + ct.size, tag.size)2831        }2832        return StoredVault(version = 1, salt = b64(salt), blob = b64(blob))2833    }28342835    /** Re-seal slot A from the current in-memory state under the live key. */2836    private fun persistSlotA(2837        bumpVersion: Boolean,2838        snapshotReason: String? = "local_save",2839        expectedEpoch: Long? = null,2840    ): Boolean {2841        val snapshot = snapshotForPersist(expectedEpoch)2842            ?: throw IllegalStateException("vault_locked_or_stale")2843        return try {2844            // Decoy sessions persist to the decoy slot only — never touch the real slot A.2845            if (snapshot.decoy) {2846                val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")2847                val plaintext = VaultCodec.encode(snapshot.payload)2848                val blob = try {2849                    b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))2850                } finally {2851                    // Keep the last reference alive until the zero, including the2852                    // successful encrypt path (M-05).2853                    VaultCrypto.zero(plaintext)2854                }2855                beforeDurableCommit()2856                return withEpochCommit(snapshot.epoch) {2857                    store.writeDecoySlot(prior.copy(blob = blob))2858                } ?: false2859            }2860            val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")2861            // H-01: captured BEFORE the noise write so a stamp failure can restore2862            // the prior slot B alongside the prior slot A. Slot B is always2863            // overwritten by writeMatchingNoiseSlotB below, so a stamp failure2864            // leaves (new A, new B, old version) on disk — partial commit.2865            val priorB = store.loadSlotB()2866            beforeDurableCommit()2867            if (snapshotReason != null && !takeVaultSnapshot(snapshotReason, snapshot.epoch)) return false2868            val plaintext = VaultCodec.encode(snapshot.payload)2869            val blob = try {2870                b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))2871            } finally {2872                // Do not drop [plaintext] before fill(0): the serialized vault2873                // contains every entry password and is the primary M-05 target.2874                VaultCrypto.zero(plaintext)2875            }2876            val next = prior.copy(blob = blob)2877            // The epoch check and the entire A/B/D/version commit share one brief2878            // stateLock critical section. lock() either wins before this block or2879            // waits until the already-committed write is complete; it can never2880            // clear the session between the check and the durable write.2881            withEpochCommit(snapshot.epoch) {2882                if (!store.writeSlotA(next)) return@withEpochCommit false2883                try {2884                    if (!writeMatchingNoiseSlotB(next)) throw java.io.IOException("noise_slot_b_commit_failed")2885                    // H-04: duress slot stays present (real one untouched, fake one2886                    // re-padded to slot A's current size on every persist).2887                    if (!writeCompanionDuressSlot(next)) throw java.io.IOException("duress_slot_commit_failed")2888                    if (bumpVersion) store.stampLocalMutation()2889                } catch (e: Exception) {2890                    store.writeSlotA(prior)2891                    if (priorB != null) runCatching { store.writeSlotB(priorB) }2892                    throw e2893                }2894                true2895            } ?: false2896        } finally {2897            // Snapshot keys are copies, so lock() may zero the live key while this2898            // operation is still deriving/encrypting; always scrub our copy too.2899            VaultCrypto.zero(snapshot.key)2900        }2901    }29022903    /**2904     * H-01: durably commit a slot-A rotation by writing slot A, its2905     * size-matched noise slot B, and the local-mutation stamp in order. Any2906     * failure rolls the previously-committed steps back so the at-rest pair2907     * matches what was there before the call. Returns true only when every2908     * step succeeded — callers must NOT swap their session key on false.2909     */2910    private fun commitVaultRotation(2911        priorA: StoredVault,2912        priorB: String?,2913        nextA: StoredVault,2914        expectedEpoch: Long,2915    ): Boolean {2916        beforeDurableCommit()2917        return withEpochCommit(expectedEpoch) {2918            if (!store.writeSlotA(nextA)) return@withEpochCommit false2919            // P1-1 (codex): the noise write's boolean AND any thrown exception from2920            // it must trigger rollback; previously a throw from writeMatchingNoiseSlotB2921            // escaped the helper and left slot A committed.2922            try {2923                if (!writeMatchingNoiseSlotB(nextA)) throw java.io.IOException("noise_slot_b_commit_failed")2924                // H-04: a password rotation changes slot A's plaintext size (new2925                // salt → re-encrypted blob), so the duress slot must be re-padded2926                // alongside. writeCompanionDuressSlot leaves a real decoy alone2927                // and re-emits a fake of slot A's size otherwise.2928                if (!writeCompanionDuressSlot(nextA)) throw java.io.IOException("duress_slot_commit_failed")2929                store.stampLocalMutation()2930            } catch (_: Exception) {2931                rollbackRotation(priorA, priorB)2932                return@withEpochCommit false2933            }2934            true2935        } ?: false2936    }29372938    /**2939     * Best-effort undo of the writes [commitVaultRotation] may have committed.2940     * Each step runs independently — a failed rollback must not mask the2941     * original commit failure. Log is a throwing stub off-device.2942     */2943    private fun rollbackRotation(priorA: StoredVault, priorB: String?) {2944        val failures = mutableListOf<String>()2945        runCatching { if (!store.writeSlotA(priorA)) failures += "writeSlotA returned false" }2946            .onFailure { failures += "writeSlotA: $it" }2947        if (priorB != null) {2948            runCatching { if (!store.writeSlotB(priorB)) failures += "writeSlotB returned false" }2949                .onFailure { failures += "writeSlotB: $it" }2950        }2951        if (failures.isNotEmpty()) runCatching { Log.w("PeachVault", "vault rotation rollback incomplete: $failures") }2952    }29532954    /** Persist a local mutation, rolling the in-memory list back on failure. */2955    private fun persistOrRollback(rollback: MutableList<VaultEntry>, expectedEpoch: Long) {2956        try {2957            if (!persistSlotA(bumpVersion = true, expectedEpoch = expectedEpoch)) {2958                mutateIfCurrentEpoch(expectedEpoch) { entryList = rollback }2959                throw IllegalStateException("storage_write_failed")2960            }2961        } catch (e: Exception) {2962            mutateIfCurrentEpoch(expectedEpoch) { entryList = rollback }2963            throw e2964        }2965        // A lock can win in the small interval after the durable commit and2966        // before publication. The epoch check prevents pre-lock entries from2967        // being republished into a newly locked (or newly unlocked) session.2968        mutateIfCurrentEpoch(expectedEpoch) { publish() }2969        runCatching { LockedSyncSpoolHooks.refresh(this) }2970    }2971}