VaultRepository.kt

147.5 KB · raw

1package com.peachpasswords.vault23import kotlinx.coroutines.flow.MutableStateFlow4import kotlinx.coroutines.flow.StateFlow5import kotlinx.coroutines.flow.asStateFlow6import kotlinx.coroutines.sync.Mutex7import kotlinx.coroutines.sync.withLock8import java.security.MessageDigest9import java.security.SecureRandom10import java.text.Normalizer11import kotlinx.serialization.json.Json12import android.os.SystemClock13import android.util.Log14import androidx.annotation.VisibleForTesting15import com.peachpasswords.BuildConfig16import com.peachpasswords.sync.SyncLimits17import com.peachpasswords.sync.LockedSyncSpoolHooks18import kotlinx.serialization.json.JsonElement19import kotlinx.serialization.json.JsonNull20import kotlinx.serialization.json.JsonObject21import kotlinx.serialization.json.JsonPrimitive22import java.util.Base6423import java.util.UUID24import java.util.concurrent.locks.ReentrantLock25import javax.inject.Inject26import javax.inject.Singleton2728/** Lenient parser for the Codex vault-blob wrapper only. */29private val CodexJson = Json { ignoreUnknownKeys = true; isLenient = true }3031private fun b64(bytes: ByteArray): String = Base64.getEncoder().withoutPadding().encodeToString(bytes)32private fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s)3334/** Cap on retained past passwords per entry. Mirrors the browser PASSWORD_HISTORY_MAX. */35private const val PASSWORD_HISTORY_MAX = 5036private const val VAULT_HISTORY_MAX = 53738// How long the transient-background-lock suppression stays valid. If the39// launched system Activity never reports the expected lifecycle stop (picker40// crashed, user backed out into another app, OEM killed the picker process),41// the flag expires and the next genuine background event locks the vault42// rather than consuming a stale suppression.43private const val BACKGROUND_LOCK_SUPPRESSION_TIMEOUT_MS = 30_000L4445sealed interface UnlockResult {46    data object Success : UnlockResult47    data object WrongPassword : UnlockResult48    data class Error(val reason: String) : UnlockResult49}5051sealed interface CreateVaultResult {52    data object Success : CreateVaultResult53    data class Error(val reason: String) : CreateVaultResult54}5556sealed interface AdoptVaultResult {57    data class Success(val vaultId: String) : AdoptVaultResult58    data class Error(val reason: String) : AdoptVaultResult59}6061/**62 * In-memory vault session backed by [VaultStore]. Faithful port of the browser63 * `vault.ts` semantics that matter for correctness:64 *65 *  - Two-slot at rest: slot A is the real (encrypted) vault, slot B a size-matched66 *    noise blob so a fresh install shows two similarly-shaped records.67 *  - Every modifiedAt/deletedAt uses [VaultCrypto.monotonicEntryTimestamp] so a68 *    deletion always wins last-write-wins against an in-flight edit.69 *  - Local writes bump the version counter; sync-applied writes do NOT (so a70 *    sync round never cascades into another outbound sync).71 *  - add/update/delete roll back in-memory state if the disk write fails.72 *  - destroyVault never touches the Pro license (separate store).73 */74@Singleton75class VaultRepository @Inject constructor(76    private val store: VaultStorage,77) {78    private val mutex = Mutex()79    // H-03: lock() and requireUnlocked() cannot take [mutex] from non-suspend80    // callers (ProcessLifecycleOwner, ViewModels, VaultLockTimer). This sync81    // lock guards ONLY the brief read/write of derivedKey/rootKey/entryList so82    // lock() can serialize against an in-flight suspend op without blocking on83    // Argon2id or store I/O. Suspend ops hold [mutex] for their full body and84    // take [stateLock] only around the state-write portions. Acquisition order85    // is always mutex → stateLock.86    private val stateLock = ReentrantLock()87    private val rng = SecureRandom()8889    /**90     * Monotonic session generation.  [lock] advances this before clearing any91     * secret state; work that captured the previous generation is therefore92     * stale even if it is still running its (non-suspending) storage step.93     */94    private var sessionEpoch: Long = 0L9596    private fun nextSessionEpoch(epoch: Long): Long =97        if (epoch == Long.MAX_VALUE) 0L else epoch + 1L9899    /** Test seam for deterministic "lock while waiting to commit" races. */100    @VisibleForTesting101    internal var beforeDurableCommit: () -> Unit = {}102103    /** Test seam after a failed Codex rollback, while the epoch fence is held. */104    @VisibleForTesting105    internal var afterCodexRollback: () -> Unit = {}106107    /**108     * Run [block] with [stateLock] held. Used to fence the small state-write109     * portions of suspend operations against [lock] and [requireUnlocked]110     * racing from another thread.111     */112    private inline fun <T> mutateState(block: () -> T): T {113        stateLock.lock()114        return try { block() } finally { stateLock.unlock() }115    }116117    /** Run a durable commit only while the session generation is still live. */118    private inline fun <T> withEpochCommit(epoch: Long, block: () -> T): T? {119        stateLock.lock()120        return try {121            if (sessionEpoch != epoch) null else block()122        } finally {123            stateLock.unlock()124        }125    }126127    /** Test seam for a caller that must stage work before the epoch fence. */128    @VisibleForTesting129    internal var beforeSessionEpochCommit: () -> Unit = {}130131    /**132     * Test seam for the narrower H-03 race: a suspend mutation has authenticated133     * the session and staged its candidate state, but has not yet entered the134     * epoch-fenced in-memory write. Production callers leave this as a no-op.135     */136    @VisibleForTesting137    internal var beforeSessionStateMutation: () -> Unit = {}138139    /**140     * Run an external session-bound commit while the repository's epoch fence is141     * held. The callback is deliberately non-suspending: [lock] cannot advance142     * the epoch until the whole external batch has reached its linearization143     * point.144     */145    internal fun <T> withSessionEpochCommit(epoch: Long, block: () -> T): T? {146        beforeSessionEpochCommit()147        return withEpochCommit(epoch, block)148    }149150    private fun currentEpoch(): Long = mutateState { sessionEpoch }151152    private inline fun <T> mutateIfCurrentEpoch(epoch: Long, block: () -> T): T? =153        mutateState { if (sessionEpoch == epoch) block() else null }154155    /** Invoke the pre-state-write seam, then linearize only in the same epoch. */156    private inline fun <T> mutateCurrentSession(epoch: Long, block: () -> T): T? {157        beforeSessionStateMutation()158        return mutateIfCurrentEpoch(epoch, block)159    }160161    private data class PersistSnapshot(162        val epoch: Long,163        val key: ByteArray,164        val payload: VaultPayload,165        val decoy: Boolean,166    )167168    /** Copy all session material while fenced; callers own and must zero [key]. */169    private fun snapshotForPersist(expectedEpoch: Long? = null): PersistSnapshot? = mutateState {170        if (expectedEpoch != null && sessionEpoch != expectedEpoch) return@mutateState null171        val liveKey = derivedKey ?: return@mutateState null172        PersistSnapshot(173            epoch = sessionEpoch,174            key = liveKey.copyOf(),175            payload = currentPayloadLocked(),176            decoy = decoyMode,177        )178    }179180    private var derivedKey: ByteArray? = null181    private var rootKey: ByteArray? = null182    private var entryList: MutableList<VaultEntry> = mutableListOf()183    private var authenticatedDuressConfigured: Boolean = false184    private var recoveryWordHash: String? = null185    private var recoveryWordsSet: Boolean = false186    /** True when an authenticated vault payload is available for local reads. */187    private var sessionDataAvailable: Boolean = false188    /** True while a decoy (duress) session is active — persistence targets the decoy slot. */189    private var decoyMode: Boolean = false190191    private val _isUnlocked = MutableStateFlow(false)192    val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()193194    private val _duressConfigured = MutableStateFlow(false)195    /** Authenticated payload state; never loaded from plaintext settings. */196    val duressConfigured: StateFlow<Boolean> = _duressConfigured.asStateFlow()197198199    /**200     * UI-only gate for sync-retained background mode. The vault stays unlocked201     * in memory (sync can proceed) but the UI shows the lock screen until the202     * user authenticates on resume. Cleared by a full [lock] or an explicit203     * [clearUiGate] from the lock screen.204     */205    private val _uiGateLocked = MutableStateFlow(false)206    val uiGateLocked: StateFlow<Boolean> = _uiGateLocked.asStateFlow()207208    private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())209    /** Active (non-deleted) entryList. */210    val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()211212    // Settings live in plain prefs, not inside the sealed vault — they hold no213    // secrets — so they are readable before unlock. Loading them here keeps the214    // lock screen at the user's chosen appearance instead of the defaults, which215    // otherwise snap to the real values the moment they authenticate.216    private val _settings = MutableStateFlow(store.loadSettings())217    val settings: StateFlow<VaultSettings> = _settings.asStateFlow()218219    /** Clear every in-memory session field while [stateLock] is held. */220    private fun clearSessionStateLocked() {221        derivedKey?.let(VaultCrypto::zero)222        rootKey?.let(VaultCrypto::zero)223        derivedKey = null224        rootKey = null225        entryList = mutableListOf()226        authenticatedDuressConfigured = false227        _duressConfigured.value = false228        recoveryWordHash = null229        recoveryWordsSet = false230        sessionDataAvailable = false231        decoyMode = false232        _settings.value = store.loadSettings()233        _entries.value = emptyList()234        _isUnlocked.value = false235    }236237    fun hasVault(): Boolean = store.hasVault()238239    // ---- Codex (printed paper backup) -------------------------------------240241    /**242     * The at-rest slot pair as base64 JSON `{"a": <StoredVault>, "b": <StoredVault>}` — the243     * Codex payload's vaultBlob. "b" is the duress slot (matching the browser's244     * A/B naming where slot B is the duress decoy); the noise slot is local-only245     * and never crosses devices. Restorable on any device that has the master246     * password. Null when no vault exists.247     */248    fun codexVaultBlobBase64(): String? {249        val slotA = store.loadSlotA() ?: return null250        // H-04: duress slot is always present after createVault (real or fake),251        // so the wrapper can rely on it being loadable.252        val slotD = store.loadDecoySlot() ?: return null253        val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)},"b":${VaultCodec.encodeSlot(slotD)}}"""254        return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))255    }256257    /**258     * Replace the local vault from a Codex blob, then unlock with [password].259     * Writes slot A (and a size-matched noise slot B) before unlocking so the260     * restored vault is at rest exactly as a freshly-created one would be.261     */262    /** A slot is stored either as a JSON string (browser) or inline object (Android). */263    private fun JsonElement?.asSlotJson(): String? = when {264        this == null || this is JsonNull -> null265        this is JsonPrimitive && isString -> content266        else -> toString()267    }268269    suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {270        val expectedEpoch = currentEpoch()271        var candidateKey: ByteArray? = null272        var plaintext: ByteArray? = null273        return try {274            val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)275            // Parsed as JSON, not matched with a regex. The wrapper is276            // `{ "a": <slot>, "b": <slot|null> }` and the browser — which277            // generates most real Codexes — writes each slot as a JSON278            // *string*, with "b" present. A regex looking for an object279            // literal under "a" at the very end of the wrapper matches280            // neither of those, so every browser-generated Codex failed here281            // with "invalid_codex_blob" after decoding perfectly.282            val wrapper = CodexJson.parseToJsonElement(wrapperJson) as? JsonObject283                ?: return UnlockResult.Error("invalid_codex_blob")284            val slotJson = wrapper["a"].asSlotJson() ?: return UnlockResult.Error("invalid_codex_blob")285            // A Codex printed from the browser carries a browser-shaped slot,286            // which is the common case — most Codexes are printed there. It is287            // translated to Android's shape (see BrowserSlot) rather than288            // rejected. A translation failure is a wrong password, not a bad289            // blob: the codes decoded fine, the password just didn't open them.290            val slotA = VaultCodec.decodeSlot(slotJson)291                ?: BrowserSlot.parse(slotJson)?.let {292                    BrowserSlot.toAndroidSlot(it, password) ?: return UnlockResult.WrongPassword293                }294                ?: return UnlockResult.Error("invalid_codex_blob")295            // C-01: authenticate the candidate ENTIRELY in memory before touching296            // storage. VaultCodec.decodeSlot is structural — an Android-shaped297            // Codex parses under ANY password — so writing slot A first and298            // unlocking afterwards destroyed the device's existing vault every299            // time the user mistyped the password.300            candidateKey = VaultCrypto.deriveKey(password, unb64(slotA.salt))301            plaintext = decryptSlotABlob(slotA, candidateKey)302            // LV-1: a Codex printed from a vault sealed before NFC normalization303            // opens only under the raw password bytes. unlockLocked used to supply304            // this fallback; authenticating up front here has to keep it, or those305            // Codexes become unrestorable.306            if (plaintext == null && password != Normalizer.normalize(password, Normalizer.Form.NFC)) {307                VaultCrypto.zero(candidateKey)308                candidateKey = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))309                plaintext = decryptSlotABlob(slotA, candidateKey)310            }311            if (plaintext == null) return UnlockResult.WrongPassword312            val payload = try {313                VaultCodec.decode(plaintext)314            } catch (_: Exception) {315                return UnlockResult.Error("invalid_codex_blob")316            }317318            val priorA = store.loadSlotA()319            val priorB = store.loadSlotB()320            val priorD = store.loadDecoySlot()321            // Carry the real duress slot across when the Codex has one — the322            // browser writes "b" as its duress-shaped slot, and dropping it323            // here would silently destroy a configured decoy.324            // H-04: write browser B into the duress slot (not the noise slot),325            // translating browser-shaped slots to Android's StoredVault shape.326            val codexDuressJson = wrapper["b"].asSlotJson()327            val codexDuress: StoredVault? = codexDuressJson?.let {328                VaultCodec.decodeSlot(it)?.let { slot ->329                    if (slot.version != LEGACY_ANDROID_SLOT_VERSION && slot.version != CURRENT_ANDROID_SLOT_VERSION) null else slot330                } ?: BrowserSlot.parse(it)?.let { b ->331                    browserDuressPassthrough(b)332                }333            }334335            beforeDurableCommit()336            val committed = runCatching {337                withEpochCommit(expectedEpoch) {338                    try {339                        // Keep every slot write, including the inverse, under the340                        // same epoch fence. Releasing stateLock after a partial341                        // write and reacquiring it for rollback lets lock() advance342                        // the epoch in between and strand the incoming slot A.343                        if (!store.writeSlotA(slotA)) throw java.io.IOException("slot_a_commit_failed")344                        // Noise slot is always size-matched to slot A — local-only,345                        // never written from a Codex.346                        if (!writeMatchingNoiseSlotB(slotA)) throw IllegalStateException("noise_slot_commit_failed")347                        // H-04: duress slot always present; real one from the Codex or348                        // a fake the size of slot A.349                        val duressOk = if (codexDuress != null) {350                            store.writeDecoySlot(codexDuress)351                        } else {352                            writeFakeDuressSlot(slotA)353                        }354                        if (!duressOk) throw IllegalStateException("duress_slot_commit_failed")355                        store.stampLocalMutation()356                        true357                    } catch (_: Exception) {358                        reportRollbackFailures(rollbackRestoreLocked(priorA, priorB, priorD))359                        // Keep the fence held through the final rollback360                        // observation. A concurrent lock() may queue here, but361                        // cannot invalidate the restored A/B/D triad.362                        afterCodexRollback()363                        false364                    }365                } ?: false366            }.getOrDefault(false)367            if (!committed) {368                return UnlockResult.Error("storage_write_failed")369            }370371            val ownedKey = candidateKey!!372            candidateKey = null // the session owns the key from here on373            adoptSlotA(ownedKey, payload, expectedEpoch)374        } catch (e: Exception) {375            // A raw kotlinx parse error ("Unexpected JSON token at offset N")376            // reaching the user says nothing about WHICH json failed — the377            // wrapper, or the payload decrypted out of it. Codex screens are378            // FLAG_SECURE so this can't be screenshotted either. Debug builds379            // log the structure around the failure; alphanumerics are masked so380            // no ciphertext or vault content lands in a log.381            if (BuildConfig.DEBUG) Log.w("PeachCodex", codexFailureShape(vaultBlobBase64, e))382            UnlockResult.Error(e.message ?: "restore_failed")383        } finally {384            plaintext?.let(VaultCrypto::zero)385            candidateKey?.let(VaultCrypto::zero)386        }387    }388389    /** Slot-A plaintext under [key], or null when the GCM tag fails (wrong password). */390    private fun decryptSlotABlob(slot: StoredVault, key: ByteArray): ByteArray? =391        runCatching { VaultCrypto.decrypt(unb64(slot.blob), key, VaultCrypto.AAD_SLOT_A) }.getOrNull()392393    /**394     * Undo a partially-committed Codex restore while [stateLock] is already held.395     * Every step is attempted independently so one failure cannot strand the396     * others. Callers that need epoch validation must enter through397     * [withEpochCommit] first; this helper deliberately does not reacquire the398     * lock, avoiding a reentrant gap between a failed write and its inverse.399     * With no prior vault the accurate inverse is having none at all, rather400     * than a half-written slot A that [hasVault] would report as a real vault.401     */402    private fun rollbackRestoreLocked(403        priorA: StoredVault?,404        priorB: String?,405        priorD: StoredVault? = null,406    ): List<String> {407        val failures = mutableListOf<String>()408        if (priorA == null) {409            runCatching { store.clearVault() }.onFailure { failures += "clearVault: $it" }410        } else {411            runCatching { if (!store.writeSlotA(priorA)) failures += "writeSlotA returned false" }412                .onFailure { failures += "writeSlotA: $it" }413            if (priorB != null) {414                runCatching { if (!store.writeSlotB(priorB)) failures += "writeSlotB returned false" }415                    .onFailure { failures += "writeSlotB: $it" }416            }417            // H-04: restore the prior duress slot — a half-committed restore that418            // left the duress record on the Codex side and slot A on the prior419            // side would put the at-rest pair in a state that never existed.420            if (priorD != null) {421                runCatching { if (!store.writeDecoySlot(priorD)) failures += "writeDecoySlot returned false" }422                    .onFailure { failures += "writeDecoySlot: $it" }423            } else {424                runCatching { store.clearDecoySlot() }.onFailure { failures += "clearDecoySlot: $it" }425            }426        }427        return failures428    }429430    private fun reportRollbackFailures(failures: List<String>) {431        // Log is a throwing stub off-device, and a failed log must never mask432        // the rollback result the caller is about to report.433        if (failures.isNotEmpty()) runCatching { Log.w("PeachCodex", "codex rollback incomplete: $failures") }434    }435436    /** Debug-only: structure of a failed Codex restore, with content masked. */437    private fun codexFailureShape(vaultBlobBase64: String, e: Exception): String = runCatching {438        val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)439        val offset = Regex("offset (\\d+)").find(e.message.orEmpty())?.groupValues?.get(1)?.toIntOrNull()440        val window = offset?.let {441            val from = (it - 40).coerceAtLeast(0)442            val to = (it + 40).coerceAtMost(wrapperJson.length)443            wrapperJson.substring(from, to).replace(Regex("[A-Za-z0-9+/=_-]"), "x")444        }445        val wrapper = runCatching { CodexJson.parseToJsonElement(wrapperJson) as? JsonObject }.getOrNull()446        val slot = wrapper?.get("a")447        buildString {448            append("codex restore failed: ").append(e::class.simpleName).append(": ").append(e.message)449            append(" | blobBase64=").append(vaultBlobBase64.length)450            append(" wrapperChars=").append(wrapperJson.length)451            append(" wrapperParses=").append(wrapper != null)452            append(" keys=").append(wrapper?.keys)453            append(" slotAKind=").append(454                when {455                    slot == null -> "absent"456                    slot is JsonPrimitive && slot.isString -> "string"457                    slot is JsonObject -> "object:" + slot.keys458                    else -> slot::class.simpleName459                },460            )461            if (window != null) append(" masked@").append(offset).append("=").append(window)462        }463    }.getOrElse { "codex restore failed: ${e.message} (shape unavailable: $it)" }464465    suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {466        val expectedEpoch = currentEpoch()467        var key: ByteArray? = null468        return try {469            val salt = VaultCrypto.generateSalt()470            key = VaultCrypto.deriveKey(password, salt)471            if (mutateIfCurrentEpoch(expectedEpoch) {472                entryList = mutableListOf()473                authenticatedDuressConfigured = false474                _duressConfigured.value = false475                recoveryWordHash = null476                recoveryWordsSet = false477                decoyMode = false478                sessionDataAvailable = false479                rootKey = generateRecoverableRootKey()480            } == null) return CreateVaultResult.Error("stale_create")481            // M-04: the fields above have to be live before sealSlotA, since it482            // seals currentPayload(). That stages a root key the session would483            // otherwise keep after a failed create — [lock] discards the whole484            // staged session on every non-success exit below.485            val slotA = sealSlotA(key!!, salt)486            // P1-3 (codex): every later step must roll the slot pair back if it487            // fails — leaving a half-built vault is worse than refusing to make it.488            beforeDurableCommit()489            val created = withEpochCommit(expectedEpoch) {490                if (!store.writeSlotA(slotA)) return@withEpochCommit false491                try {492                    if (!writeMatchingNoiseSlotB(slotA)) throw java.io.IOException("noise_slot_b_commit_failed")493                    // H-04: duress slot must be present from the start so its494                    // existence on disk is independent of authenticatedDuressConfigured.495                    if (!writeFakeDuressSlot(slotA)) throw java.io.IOException("duress_slot_commit_failed")496                    store.stampLocalMutation()497                    if (!store.writeSettings(_settings.value)) throw java.io.IOException("settings_commit_failed")498                    true499                } catch (_: Exception) {500                    // Half-built vault on disk is worse than no vault — refuse to501                    // create if any step past slot A fails.502                    store.clearVault()503                    false504                }505            } ?: false506            if (!created) {507                lock()508                return CreateVaultResult.Error("storage_write_failed")509            }510            val sessionKey = key ?: return CreateVaultResult.Error("create_key_missing")511            if (mutateIfCurrentEpoch(expectedEpoch) {512                derivedKey = sessionKey513                key = null514                publish()515                _isUnlocked.value = true516                sessionDataAvailable = true517                sessionEpoch = nextSessionEpoch(sessionEpoch)518            } == null) return CreateVaultResult.Error("stale_create")519            CreateVaultResult.Success520        } catch (e: Exception) {521            lock()522            CreateVaultResult.Error(e.message ?: "create_failed")523        } finally {524            key?.let(VaultCrypto::zero)525        }526    }527528    suspend fun createVaultFromRootKey(password: String, rootKeyHex: String): AdoptVaultResult = mutex.withLock {529        val expectedEpoch = currentEpoch()530        if (password.isEmpty()) return AdoptVaultResult.Error("ADOPT_INVALID_PASSWORD")531        if (store.hasVault()) return AdoptVaultResult.Error("ADOPT_VAULT_ALREADY_EXISTS")532        if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {533            return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars")534        }535        var adoptedRootKey: ByteArray? = null536        var nextDerivedKey: ByteArray? = null537        var sessionRootKey: ByteArray? = null538        return try {539            adoptedRootKey = hexToRootKey(rootKeyHex)540            if (adoptedRootKey.size != VaultCrypto.KEY_SIZE) {541                return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes")542            }543            val vaultId = com.peachpasswords.sync.computeVaultId(adoptedRootKey)544            val salt = VaultCrypto.generateSalt()545            nextDerivedKey = VaultCrypto.deriveKey(password, salt)546            sessionRootKey = adoptedRootKey.copyOf()547            val payload = VaultPayload(548                entries = emptyList(),549                duressConfigured = false,550                rootKeyB64 = b64(sessionRootKey),551                recoveryWordHash = null,552                recoveryWordsSet = false,553            )554            val plaintext = VaultCodec.encode(payload)555            val blob = try {556                b64(VaultCrypto.encrypt(plaintext, nextDerivedKey, VaultCrypto.AAD_SLOT_A))557            } finally {558                VaultCrypto.zero(plaintext)559            }560            val slotA = StoredVault(version = 1, salt = b64(salt), blob = blob)561            // P1-3 (codex): same partial-commit guard as createVault — any failure562            // past slot A wipes the half-built vault and refuses adoption.563            beforeDurableCommit()564            val created = withEpochCommit(expectedEpoch) {565                if (!store.writeSlotA(slotA)) return@withEpochCommit false566                try {567                    if (!writeMatchingNoiseSlotB(slotA)) throw java.io.IOException("noise_slot_b_commit_failed")568                    // H-04: duress slot must be present from the start so its569                    // existence on disk is independent of authenticatedDuressConfigured.570                    if (!writeFakeDuressSlot(slotA)) throw java.io.IOException("duress_slot_commit_failed")571                    store.stampLocalMutation()572                    if (!store.writeSettings(_settings.value)) throw java.io.IOException("settings_commit_failed")573                    true574                } catch (_: Exception) {575                    store.clearVault()576                    false577                }578            } ?: false579            if (!created) return AdoptVaultResult.Error("storage_write_failed")580581            val adopted = mutateIfCurrentEpoch(expectedEpoch) {582                val previousDerivedKey = derivedKey583                val previousRootKey = rootKey584                derivedKey = nextDerivedKey585                rootKey = sessionRootKey586                nextDerivedKey = null587                sessionRootKey = null588                entryList = mutableListOf()589                authenticatedDuressConfigured = false590                _duressConfigured.value = false591                recoveryWordHash = null592                recoveryWordsSet = false593                decoyMode = false594                sessionDataAvailable = true595                publish()596                _isUnlocked.value = true597                sessionEpoch = nextSessionEpoch(sessionEpoch)598                previousDerivedKey to previousRootKey599            }600            if (adopted == null) return AdoptVaultResult.Error("stale_adoption")601            val (previousDerivedKey, previousRootKey) = adopted602            previousDerivedKey?.let(VaultCrypto::zero)603            previousRootKey?.let(VaultCrypto::zero)604            // Write the recovery escrow so the forgot-password flow works on605            // this device. The words are deterministic from the root key and606            // were already confirmed on the source device.607            runCatching {608                val words = rootKeyToWords(rootKey!!)609                val escrow = buildRecoveryEscrow(words)610                val rkEscrow = buildRootKeyEscrow(words)611                if (escrow != null || rkEscrow != null) {612                    val prior = store.loadSlotA()613                    if (prior != null) {614                        store.writeSlotA(prior.copy(615                            recoveryEscrow = escrow ?: prior.recoveryEscrow,616                            rootKeyEscrow = rkEscrow ?: prior.rootKeyEscrow,617                        ))618                    }619                    mutateState {620                        recoveryWordHash = recoveryWordsHash(words)621                        recoveryWordsSet = true622                    }623                }624            }625            AdoptVaultResult.Success(vaultId)626        } catch (e: Exception) {627            AdoptVaultResult.Error(e.message ?: "adoption_create_failed")628        } finally {629            adoptedRootKey?.let(VaultCrypto::zero)630            nextDerivedKey?.let(VaultCrypto::zero)631            sessionRootKey?.let(VaultCrypto::zero)632        }633    }634635    suspend fun unlock(password: String): UnlockResult = mutex.withLock {636        val result = unlockLocked(password, currentEpoch())637        if (result is UnlockResult.Success) ensureRecoveryEscrow()638        result639    }640641    /** Unlock body without acquiring the mutex — callers must already hold it. */642    private fun unlockLocked(password: String, expectedEpoch: Long): UnlockResult {643        val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")644        val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))645        val payload = try {646            val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A)647            try {648                VaultCodec.decode(plaintext)649            } finally {650                VaultCrypto.zero(plaintext)651            }652        } catch (_: Exception) {653            VaultCrypto.zero(key)654            // LV-1: a vault sealed before NFC normalization with a non-NFC655            // password derives a different key now. If the supplied password is656            // not already in NFC form, retry with the raw (un-normalized) bytes.657            if (password != Normalizer.normalize(password, Normalizer.Form.NFC)) {658                val legacy = tryLegacyRawUnlock(password, slotA, expectedEpoch)659                if (legacy != null) return legacy660            }661            return UnlockResult.WrongPassword662        }663        return adoptSlotA(key, payload, expectedEpoch)664    }665666    /**667     * LV-1 legacy fallback: unlock a slot-A vault that was sealed under the raw668     * (un-normalized) password bytes. On success the slot is HEALED — re-sealed669     * under the NFC-normalized key — so every future unlock takes the normal670     * path. Returns null when the raw key also fails (genuinely wrong password)671     * OR when any step of the heal commits fails (the original slot A is restored672     * so disk and session stay aligned).673     */674    private fun tryLegacyRawUnlock(password: String, slotA: StoredVault, expectedEpoch: Long): UnlockResult? {675        var rawKey: ByteArray? = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))676        var newKey: ByteArray? = null677        return try {678            val payload = try {679                val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), rawKey!!, VaultCrypto.AAD_SLOT_A)680                try {681                    VaultCodec.decode(plaintext)682                } finally {683                    VaultCrypto.zero(plaintext)684                }685            } catch (_: Exception) {686                return null687            }688            // Heal: re-seal slot A under the NFC key (mirrors changePassword's689            // re-seal). Escrows carry forward unchanged — only the wrapping rotates.690            val newSalt = VaultCrypto.generateSalt()691            newKey = VaultCrypto.deriveKey(password, newSalt)692            val plaintext = VaultCodec.encode(payload)693            val blob = try {694                b64(VaultCrypto.encrypt(plaintext, newKey!!, VaultCrypto.AAD_SLOT_A))695            } finally {696                VaultCrypto.zero(plaintext)697            }698            val next = StoredVault(699                version = slotA.version,700                salt = b64(newSalt),701                blob = blob,702                recoveryEscrow = slotA.recoveryEscrow,703                rootKeyEscrow = slotA.rootKeyEscrow,704            )705            // P1-1/P1-3/P1-2 (codex): any failure of writeSlotA, writeMatchingNoiseSlotB,706            // or stampLocalMutation must restore the prior slot A AND slot B so disk707            // and the eventual session key never disagree on the wrapping.708            val priorB = store.loadSlotB()709            beforeDurableCommit()710            val healed = withEpochCommit(expectedEpoch) {711                if (!store.writeSlotA(next)) {712                    false713                } else try {714                    if (!writeMatchingNoiseSlotB(next)) {715                        runCatching { store.writeSlotA(slotA) }716                        if (priorB != null) runCatching { store.writeSlotB(priorB) }717                        false718                    } else if (!writeCompanionDuressSlot(next)) {719                        runCatching { store.writeSlotA(slotA) }720                        if (priorB != null) runCatching { store.writeSlotB(priorB) }721                        false722                    } else {723                        store.stampLocalMutation()724                        true725                    }726                } catch (_: Exception) {727                    runCatching { store.writeSlotA(slotA) }728                    if (priorB != null) runCatching { store.writeSlotB(priorB) }729                    false730                }731            } ?: false732            if (healed) {733                VaultCrypto.zero(rawKey!!)734                rawKey = null735                val result = adoptSlotA(newKey!!, payload, expectedEpoch) // session key now matches the re-sealed slot736                newKey = null737                result738            } else {739                VaultCrypto.zero(newKey!!)740                newKey = null741                val result = adoptSlotA(rawKey!!, payload, expectedEpoch) // heal failed — keep using the raw key742                rawKey = null743                result744            }745        } finally {746            // Cover codec, encryption, storage, and stale-epoch failures before747            // either candidate key can be transferred into the live session.748            rawKey?.let(VaultCrypto::zero)749            newKey?.let(VaultCrypto::zero)750        }751    }752753    /** Adopt a derived slot-A [key]/[payload] as the live (real-vault) session. */754    private fun adoptSlotA(key: ByteArray, payload: VaultPayload, expectedEpoch: Long): UnlockResult {755        return try {756            // M-04: ensureRootKey and autoPurgeExpiredTrash both persist, so they757            // can throw after the fields above are live. There is no prior session758            // worth restoring — adoption has already replaced it — so a failed759            // adoption discards everything rather than leaving entries and keys760            // resident behind _isUnlocked=false.761            val adopted = mutateIfCurrentEpoch(expectedEpoch) {762                derivedKey = key763                decoyMode = false764                entryList = payload.entries.toMutableList()765                authenticatedDuressConfigured = payload.duressConfigured766                _duressConfigured.value = payload.duressConfigured767                recoveryWordHash = payload.recoveryWordHash768                recoveryWordsSet = payload.recoveryWordsSet769                sessionDataAvailable = true770                _settings.value = store.loadSettings()771                ensureRootKey(payload)772                autoPurgeExpiredTrash()773                consolidatePasskeyEntries()774                publish()775                _isUnlocked.value = true776                // A successful adoption starts a new generation. A sibling777                // SlotAUnlock captured in the prior epoch will fail closed at778                // the next commit instead of replacing this session.779                sessionEpoch = nextSessionEpoch(sessionEpoch)780            }781            if (adopted == null) {782                VaultCrypto.zero(key)783                UnlockResult.Error("stale_unlock")784            } else {785                UnlockResult.Success786            }787        } catch (e: Exception) {788            // Do not call lock() here: a concurrent newer session may already789            // own this repository. Only invalidate the failed epoch's fields.790            mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }791            VaultCrypto.zero(key)792            UnlockResult.Error(e.message ?: "unlock_failed")793        }794    }795796    // ---- Constant-time unlock (MF-5) --------------------------------------797798    /**799     * A slot-A unlock that has been derived but not yet adopted. Holds the live800     * Argon2id key and decoded payload so the caller can derive several candidates801     * concurrently and commit only the winner. The key is owned by this token until802     * [commitSlotAUnlock] adopts it or [discardSlotAUnlock] zeroes it.803     */804    class SlotAUnlock internal constructor(805        key: ByteArray,806        internal val payload: VaultPayload,807        internal val epoch: Long,808    ) {809        private var ownedKey: ByteArray? = key810        private var consumed = false811812        /** Transfer the key exactly once to the adopter. */813        internal fun takeKey(): ByteArray? = synchronized(this) {814            if (consumed) return@synchronized null815            consumed = true816            ownedKey.also { ownedKey = null }817        }818819        /** Discard an uncommitted token without touching a transferred key. */820        internal fun discard() = synchronized(this) {821            if (consumed) return@synchronized822            consumed = true823            ownedKey?.let(VaultCrypto::zero)824            ownedKey = null825        }826    }827828    /**829     * Derive the slot-A key and decrypt its payload WITHOUT mutating session state.830     * Pure computation (no mutex), so it can run concurrently with other candidate831     * derivations before the caller decides which to commit (MF-5). Returns null on832     * no-vault or wrong password (the derived key is zeroed on a tag mismatch).833     */834    fun tryUnlockSlotA(password: String): SlotAUnlock? {835        val epoch = currentEpoch()836        val slotA = store.loadSlotA() ?: return null837        val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))838        return try {839            val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A)840            val payload = try {841                VaultCodec.decode(plaintext)842            } finally {843                VaultCrypto.zero(plaintext)844            }845            SlotAUnlock(key, payload, epoch)846        } catch (_: Exception) {847            VaultCrypto.zero(key)848            null849        }850    }851852    /** Adopt a previously-derived [SlotAUnlock] as the live session. */853    suspend fun commitSlotAUnlock(unlock: SlotAUnlock): UnlockResult = mutex.withLock {854        val key = unlock.takeKey() ?: return@withLock UnlockResult.Error("unlock_token_consumed")855        adoptSlotA(key, unlock.payload, unlock.epoch)856    }857858    /** Zero a derived [SlotAUnlock] that will not be adopted. */859    fun discardSlotAUnlock(unlock: SlotAUnlock) = unlock.discard()860861    // ---- Duress slot B (MF-6) ---------------------------------------------862863    /**864     * A duress-slot (slot B) unlock derived but not yet adopted. Holds the live key865     * and decoded decoy payload so it can be derived concurrently with slot A and866     * only committed if the duress passphrase was the one entered (MF-5/MF-6).867     */868    class DuressUnlock internal constructor(869        key: ByteArray,870        internal val payload: VaultPayload,871        internal val epoch: Long,872    ) {873        private var ownedKey: ByteArray? = key874        private var consumed = false875876        internal fun takeKey(): ByteArray? = synchronized(this) {877            if (consumed) return@synchronized null878            consumed = true879            ownedKey.also { ownedKey = null }880        }881882        internal fun discard() = synchronized(this) {883            if (consumed) return@synchronized884            consumed = true885            ownedKey?.let(VaultCrypto::zero)886            ownedKey = null887        }888    }889890    /**891     * Try to decrypt the duress slot (slot B) with [password] WITHOUT mutating the892     * session. Success means the entered password is the duress passphrase that keys893     * slot B — indistinguishable from the real slot A at the lock screen. Pure894     * computation (no mutex), safe to run concurrently with [tryUnlockSlotA].895     * Returns null when no duress slot exists or the password is not the duress one.896     */897    fun tryUnlockDuress(password: String): DuressUnlock? {898        val epoch = currentEpoch()899        val slot = store.loadDecoySlot() ?: return null900        if (slot.version != LEGACY_ANDROID_SLOT_VERSION && slot.version != CURRENT_ANDROID_SLOT_VERSION) return null901        var key: ByteArray? = VaultCrypto.deriveKey(password, unb64(slot.salt))902        return try {903            val plaintext = try {904                if (slot.version == CURRENT_ANDROID_SLOT_VERSION) {905                    VaultCrypto.decrypt(unb64(slot.blob), key!!, VaultCrypto.AAD_SLOT_B)906                } else {907                    runCatching {908                        VaultCrypto.decrypt(unb64(slot.blob), key!!, VaultCrypto.AAD_SLOT_A)909                    }.getOrElse {910                        VaultCrypto.decrypt(unb64(slot.blob), key!!, VaultCrypto.AAD_SLOT_B)911                    }912                }913            } catch (_: Exception) {914                VaultCrypto.zero(key!!)915                key = null916                return null917            }918            val payload = try {919                VaultCodec.decode(plaintext)920            } finally {921                VaultCrypto.zero(plaintext)922            }923            if (slot.version == LEGACY_ANDROID_SLOT_VERSION) {924                val migratedKey = migrateLegacyDuressSlot(slot, password, payload, key!!, epoch)925                    ?: run {926                        VaultCrypto.zero(key!!)927                        key = null928                        return null929                    }930                if (migratedKey !== key) {931                    VaultCrypto.zero(key!!)932                    key = migratedKey933                }934            }935            DuressUnlock(key!!, payload, epoch).also { key = null }936        } catch (_: Exception) {937            key?.let(VaultCrypto::zero)938            null939        }940    }941942    /**943     * Re-seal an authenticated legacy decoy under the current Slot-B AAD.944     * A failed write or verification restores the exact legacy record, while945     * already-authenticated unlock remains usable for this session.946     */947    private fun migrateLegacyDuressSlot(948        legacy: StoredVault,949        password: String,950        payload: VaultPayload,951        legacyKey: ByteArray,952        epoch: Long,953    ): ByteArray? {954        var salt: ByteArray? = null955        var migratedKey: ByteArray? = null956        var plaintext: ByteArray? = null957        var restoredLegacy = false958        var migrated = false959        try {960            salt = VaultCrypto.generateSalt()961            migratedKey = VaultCrypto.deriveKey(password, salt)962            plaintext = VaultCodec.encode(payload)963            val next = StoredVault(964                version = CURRENT_ANDROID_SLOT_VERSION,965                salt = b64(salt),966                blob = b64(VaultCrypto.encrypt(plaintext, migratedKey, VaultCrypto.AAD_SLOT_B)),967            )968            var priorA: StoredVault? = null969            var priorB: String? = null970            withSessionEpochCommit(epoch) {971                priorA = store.loadSlotA()972                priorB = store.loadSlotB()973                if (store.loadDecoySlot() != legacy) return@withSessionEpochCommit false974                if (!store.writeDecoySlot(next)) {975                    restoredLegacy = store.loadDecoySlot() == legacy976                    return@withSessionEpochCommit restoredLegacy977                }978                val reopened = store.loadDecoySlot()979                val verified = reopened?.version == CURRENT_ANDROID_SLOT_VERSION && runCatching {980                    val reopenedPlaintext = VaultCrypto.decrypt(unb64(reopened.blob), migratedKey!!, VaultCrypto.AAD_SLOT_B)981                    try { VaultCodec.decode(reopenedPlaintext) == payload } finally { VaultCrypto.zero(reopenedPlaintext) }982                }.getOrDefault(false)983                if (verified) {984                    migrated = true985                    return@withSessionEpochCommit true986                }987                val restored = priorA != null && store.restoreVaultTriad(priorA!!, priorB, legacy)988                restoredLegacy = restored && store.loadSlotA() == priorA && store.loadSlotB() == priorB && store.loadDecoySlot() == legacy989                restoredLegacy990            }991            if (migrated) {992                VaultCrypto.zero(legacyKey)993                return migratedKey.also { migratedKey = null }994            }995            if (restoredLegacy) return legacyKey996        } catch (_: Exception) {997            // A failed migration must not claim a legacy key unless the exact998            // legacy record was durably restored and observed.999        }1000        if (!restoredLegacy) runCatching { store.loadDecoySlot() == legacy }1001        migratedKey?.let(VaultCrypto::zero)1002        return if (restoredLegacy) legacyKey else null1003    }10041005    /** Adopt a derived [DuressUnlock] as a live decoy session (edits persist to slot B only). */1006    suspend fun commitDuressUnlock(unlock: DuressUnlock): UnlockResult = mutex.withLock {1007        val key = unlock.takeKey() ?: return@withLock UnlockResult.Error("unlock_token_consumed")1008        if (currentEpoch() != unlock.epoch) {1009            VaultCrypto.zero(key)1010            return@withLock UnlockResult.Error("stale_unlock")1011        }1012        return try {1013            val adopted = mutateIfCurrentEpoch(unlock.epoch) {1014                derivedKey = key1015                decoyMode = true1016                entryList = unlock.payload.entries.toMutableList()1017                authenticatedDuressConfigured = false1018                _duressConfigured.value = false1019                recoveryWordHash = unlock.payload.recoveryWordHash1020                recoveryWordsSet = unlock.payload.recoveryWordsSet1021                sessionDataAvailable = true1022                rootKey = if (unlock.payload.rootKeyB64.isNotBlank()) unb64(unlock.payload.rootKeyB64)1023                          else VaultCrypto.generateRootKey()1024                _settings.value = store.loadSettings()1025                publish()1026                _isUnlocked.value = true1027                sessionEpoch = nextSessionEpoch(sessionEpoch)1028            }1029            if (adopted == null) {1030                VaultCrypto.zero(key)1031                UnlockResult.Error("stale_unlock")1032            } else {1033                UnlockResult.Success1034            }1035        } catch (e: Exception) {1036            // A payload/root/settings failure can occur after the candidate key1037            // has been assigned to derivedKey. Tear down only this epoch so a1038            // newer session is not disturbed, and scrub the token reference on1039            // every error path.1040            mutateIfCurrentEpoch(unlock.epoch) { clearSessionStateLocked() }1041            VaultCrypto.zero(key)1042            UnlockResult.Error(e.message ?: "decoy_unlock_failed")1043        }1044    }10451046    /** Zero a derived [DuressUnlock] that will not be adopted. */1047    fun discardDuressUnlock(unlock: DuressUnlock) = unlock.discard()10481049    /**1050     * Configure the duress vault (MF-6): seal a fresh, empty decoy payload under an1051     * Argon2id key derived from [duressPassphrase] (fresh salt) into slot B. The1052     * passphrase is never stored — only its ability to decrypt slot B proves it.1053     * Requires the real vault to be unlocked and not itself a decoy session.1054     */1055    suspend fun setDuressPassphrase(duressPassphrase: String): Boolean = mutex.withLock {1056        // H-03: read derivedKey/decoyMode atomically with any concurrent lock().1057        val expectedEpoch = mutateState {1058            if (derivedKey != null && !decoyMode) sessionEpoch else null1059        } ?: return false1060        // Reject a duress passphrase that also opens the real vault: it would make the1061        // lock screen ambiguous (both slots would decrypt for the same input).1062        tryUnlockSlotA(duressPassphrase)?.let { discardSlotAUnlock(it); return false }1063        var key: ByteArray? = null1064        var basePlaintext: ByteArray? = null1065        return try {1066            val salt = VaultCrypto.generateSalt()1067            key = VaultCrypto.deriveKey(duressPassphrase, salt)1068            // An empty decoy vault with its own fresh sync root key — nothing real leaks.1069            val decoyRoot = VaultCrypto.generateRootKey()1070            val decoyRootB64 = try { b64(decoyRoot) } finally { VaultCrypto.zero(decoyRoot) }1071            val decoyPayload = VaultPayload(entries = emptyList(), rootKeyB64 = decoyRootB64)1072            basePlaintext = VaultCodec.encode(decoyPayload)1073            // H-04: pad the duress plaintext to slot A's ciphertext length so the1074            // duress blob matches slot A's blob on disk. VaultCodec.decode strips1075            // trailing NULs, so the extra padding survives encrypt but never1076            // reaches the JSON parser.1077            // This decoy plaintext length is frozen from here on: re-sealing it1078            // on later growth would need the duress passphrase, which is never1079            // retained. VaultStore compensates by re-padding the two slot1080            // RECORDS to the longer of the two on every write, so the frozen1081            // blob no longer shows up as a length difference at rest.1082            val slotA = store.loadSlotA()1083            val targetSize = slotA?.let(::matchingCiphertextLength) ?: 01084            val plaintext = if (targetSize > basePlaintext!!.size) basePlaintext!!.copyOf(targetSize) else basePlaintext!!1085            val blob = try {1086                b64(VaultCrypto.encrypt(plaintext, key!!, VaultCrypto.AAD_SLOT_B))1087            } finally {1088                VaultCrypto.zero(plaintext)1089                // Padding creates a second array; scrub the original encoded1090                // payload too rather than dropping its last reference untouched.1091                if (plaintext !== basePlaintext) basePlaintext?.let(VaultCrypto::zero)1092                basePlaintext = null1093                key?.let(VaultCrypto::zero)1094                key = null1095            }1096            beforeDurableCommit()1097            val ok = withEpochCommit(expectedEpoch) {1098                store.writeDecoySlot(StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(salt), blob = blob))1099            } ?: false1100            if (!ok) return false1101            val marked = mutateIfCurrentEpoch(expectedEpoch) {1102                authenticatedDuressConfigured = true1103                _duressConfigured.value = true1104                true1105            } ?: false1106            if (!marked) return false1107            if (!runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }.getOrDefault(false)) {1108                mutateIfCurrentEpoch(expectedEpoch) {1109                    authenticatedDuressConfigured = false1110                    _duressConfigured.value = false1111                }1112                runCatching { writeFakeDuressSlot(store.loadSlotA()!!) }1113                return false1114            }1115            true1116        } catch (_: Exception) {1117            false1118        } finally {1119            // Cover failures before the encrypt block is entered (for example a1120            // codec/copy exception) as well as any early return after key derivation.1121            key?.let(VaultCrypto::zero)1122            basePlaintext?.let(VaultCrypto::zero)1123        }1124    }112511261127    /**1128     * Export the decoy slot as browser-shaped JSON for adoption snapshots.1129     *1130     * Returns the sealed slot as `{version, salt, nonce, ciphertext, tag}` all1131     * lowercase hex — identical to the browser's `duress_slot` wire format — so1132     * any receiver (browser or Android) can install it via the existing1133     * passthrough. Returns null when duress is not configured, no decoy exists,1134     * or any conversion failure occurs. Never decrypts.1135     */1136    suspend fun exportDuressSlotForAdoption(): String? = mutex.withLock {1137        if (!authenticatedDuressConfigured) return null1138        val slot = store.loadDecoySlot() ?: return null1139        return runCatching { androidDuressSlotToBrowserJson(slot) }.getOrNull()1140    }11411142    /**1143     * Convert an Android [StoredVault] decoy slot to browser-shaped JSON.1144     *1145     * Mirrors the inverse of [installAdoptedDuressSlot]: base64 salt/blob are1146     * split into lowercase hex fields matching [BrowserSlotA]. Intermediate1147     * byte arrays are zeroed in finally.1148     */1149    private fun androidDuressSlotToBrowserJson(slot: StoredVault): String {1150        // Build the wire JSON directly with JsonObject so `version: 1` is ALWAYS1151        // serialized — kotlinx-serialization's encodeDefaults = false would1152        // otherwise omit BrowserSlotA.version (its Kotlin default), and the1153        // browser's hasValidVaultSchema strictly requires `r.version === 1`,1154        // silently dropping the duress slot on Android→browser adoptions.1155        var salt: ByteArray? = null1156        var blob: ByteArray? = null1157        var nonce: ByteArray? = null1158        var ctAndTag: ByteArray? = null1159        var ct: ByteArray? = null1160        var tag: ByteArray? = null1161        try {1162            salt = unb64(slot.salt)1163            blob = unb64(slot.blob)1164            nonce = blob.copyOfRange(0, VaultCrypto.NONCE_SIZE)1165            ctAndTag = blob.copyOfRange(VaultCrypto.NONCE_SIZE, blob.size)1166            ct = ctAndTag.copyOfRange(0, ctAndTag.size - 16)1167            tag = ctAndTag.copyOfRange(ctAndTag.size - 16, ctAndTag.size)1168            val obj = JsonObject(mapOf(1169                "version" to JsonPrimitive(1),1170                "salt" to JsonPrimitive(salt.joinToString("") { "%02x".format(it) }),1171                "nonce" to JsonPrimitive(nonce.joinToString("") { "%02x".format(it) }),1172                "ciphertext" to JsonPrimitive(ct.joinToString("") { "%02x".format(it) }),1173                "tag" to JsonPrimitive(tag.joinToString("") { "%02x".format(it) }),1174            ))1175            return obj.toString()1176        } finally {1177            salt?.let(VaultCrypto::zero)1178            blob?.let(VaultCrypto::zero)1179            nonce?.let(VaultCrypto::zero)1180            ctAndTag?.let(VaultCrypto::zero)1181            ct?.let(VaultCrypto::zero)1182            tag?.let(VaultCrypto::zero)1183        }1184    }11851186    /**1187     * Install a browser-shaped duress slot received through adoption.1188     */1189    suspend fun installAdoptedDuressSlot(json: String): Boolean = mutex.withLock {1190        val b = BrowserSlot.parse(json) ?: return false1191        if (b.version != 1) return false1192        val expectedEpoch = currentEpoch()1193        var salt: ByteArray? = null1194        var nonce: ByteArray? = null1195        var ct: ByteArray? = null1196        var tag: ByteArray? = null1197        var blob: ByteArray? = null1198        try {1199            salt = unhex(b.salt)1200            nonce = unhex(b.nonce)1201            ct = unhex(b.ciphertext)1202            tag = unhex(b.tag)1203            blob = ByteArray(nonce.size + ct.size + tag.size).also {1204                System.arraycopy(nonce, 0, it, 0, nonce.size)1205                System.arraycopy(ct, 0, it, nonce.size, ct.size)1206                System.arraycopy(tag, 0, it, nonce.size + ct.size, tag.size)1207            }1208            val stored = StoredVault(version = LEGACY_ANDROID_SLOT_VERSION, salt = b64(salt), blob = b64(blob))1209            val priorA = store.loadSlotA() ?: return false1210            val priorB = store.loadSlotB()1211            val priorD = store.loadDecoySlot() ?: return false1212            beforeDurableCommit()1213            val committed = withEpochCommit(expectedEpoch) {1214                if (!store.writeDecoySlot(stored)) return@withEpochCommit false1215                authenticatedDuressConfigured = true1216                _duressConfigured.value = true1217                true1218            } ?: false1219            if (!committed) return false1220            if (runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }.getOrDefault(false)) {1221                true1222            } else {1223                mutateIfCurrentEpoch(expectedEpoch) {1224                    authenticatedDuressConfigured = false1225                    _duressConfigured.value = false1226                }1227                withEpochCommit(expectedEpoch) { store.restoreVaultTriad(priorA, priorB, priorD) }1228                false1229            }1230        } catch (_: Exception) {1231            false1232        } finally {1233            salt?.let(VaultCrypto::zero)1234            nonce?.let(VaultCrypto::zero)1235            ct?.let(VaultCrypto::zero)1236            tag?.let(VaultCrypto::zero)1237            blob?.let(VaultCrypto::zero)1238        }1239    }12401241    /** Tear down the duress vault: drop slot B and the duress flag on the real payload. */1242    suspend fun clearDuress(): Boolean = mutex.withLock {1243        // H-04: presence-indistinguishable — replace the real decoy with a fake1244        // blob of slot A's size rather than removing the duress record. The1245        // record stays on disk at the same length, so an at-rest observer1246        // cannot tell "duress cleared" from "no duress ever configured".1247        val expectedEpoch = currentEpoch()1248        val replaced = withEpochCommit(expectedEpoch) {1249            store.loadSlotA()?.let { slotA -> runCatching { writeFakeDuressSlot(slotA) }.getOrDefault(false) }1250                ?: runCatching { store.clearDecoySlot(); true }.getOrDefault(false)1251        } ?: false1252        if (!replaced) return@withLock false1253        // H-03: stateLock-fence the derivedKey/decoyMode read AND the1254        // authenticatedDuressConfigured write so a concurrent lock() cannot land between them.1255        if (!isSessionEpochCurrent(expectedEpoch)) return false1256        val shouldClear = mutateIfCurrentEpoch(expectedEpoch) { derivedKey != null && !decoyMode } == true1257        if (shouldClear && mutateIfCurrentEpoch(expectedEpoch) {1258            authenticatedDuressConfigured = false1259            _duressConfigured.value = false1260        } != null) {1261            runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }1262        }1263        true1264    }12651266    /** True for the provider-specific exception used for a valid GCM blob/key mismatch. */1267    private fun isGcmAuthenticationFailure(error: Throwable): Boolean {1268        var current: Throwable? = error1269        while (current != null) {1270            if (current is javax.crypto.AEADBadTagException) return true1271            // Some Android providers expose a GCM tag failure as the parent1272            // BadPaddingException rather than the AEAD-specific subtype.  A1273            // short ciphertext is an IllegalBlockSizeException and therefore1274            // remains an internal/malformed-payload Error below.1275            if (current is javax.crypto.BadPaddingException) return true1276            current = current.cause1277        }1278        return false1279    }12801281    /** Unlock with an already-derived AES-256 key (biometric path). */1282    suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {1283        val expectedEpoch = currentEpoch()1284        val slotA = try {1285            store.loadSlotA()1286        } catch (_: Exception) {1287            return@withLock UnlockResult.Error("unlock_key_storage_failed")1288        } ?: return@withLock UnlockResult.Error("no_vault")1289        // Keep the caller-owned key separate from the staged session key. The1290        // biometric caller always zeroes its input in a finally block; adoption1291        // must therefore own a copy and use the same all-or-nothing path as a1292        // password unlock rather than publishing a partially decoded session.1293        var stagedKey: ByteArray? = key.copyOf()1294        return try {1295            val encrypted = try {1296                unb64(slotA.blob)1297            } catch (_: Exception) {1298                return@withLock UnlockResult.Error("invalid_vault_blob")1299            }1300            // A GCM record must include nonce + authentication tag.  Providers1301            // differ on whether a shorter record is reported as BadPadding or1302            // AEADBadTag; reject it before decrypt so malformed storage cannot be1303            // misreported as a user-entered wrong key.1304            if (encrypted.size < VaultCrypto.NONCE_SIZE + (VaultCrypto.TAG_LENGTH_BITS / 8)) {1305                return@withLock UnlockResult.Error("invalid_vault_blob")1306            }1307            val plaintext = try {1308                VaultCrypto.decrypt(encrypted, stagedKey!!, VaultCrypto.AAD_SLOT_A)1309            } catch (e: Exception) {1310                if (isGcmAuthenticationFailure(e)) {1311                    return@withLock UnlockResult.WrongPassword1312                }1313                return@withLock UnlockResult.Error("unlock_key_decrypt_failed")1314            }1315            val payload = try {1316                VaultCodec.decode(plaintext)1317            } catch (_: Exception) {1318                return@withLock UnlockResult.Error("invalid_vault_payload")1319            } finally {1320                VaultCrypto.zero(plaintext)1321            }1322            val candidate = stagedKey ?: return UnlockResult.Error("unlock_key_missing")1323            val result = adoptSlotA(candidate, payload, expectedEpoch)1324            if (result is UnlockResult.Success) { stagedKey = null; ensureRecoveryEscrow() }1325            result1326        } finally {1327            stagedKey?.let(VaultCrypto::zero)1328        }1329    }13301331    fun lock() {1332        // Never snapshot a mutation that has changed entryList but has not yet1333        // crossed its durable epoch fence. Successful writes refresh the spool1334        // before releasing this mutex; an in-flight writer therefore makes this1335        // lock skip the convenience refresh and fail closed to the prior cache.1336        if (mutex.tryLock()) {1337            try {1338                runCatching { LockedSyncSpoolHooks.refresh(this) }1339            } finally {1340                mutex.unlock()1341            }1342        }1343        // H-03: must observe derivedKey/entryList atomically with any in-flight1344        // suspend op (an addEntry mid-encrypt, an unlock adopting the payload,1345        // etc.). mutex cannot be acquired from this non-suspend caller; stateLock1346        // guards just the brief state reset. Advancing the epoch first invalidates1347        // every operation that captured this session before it reaches a later1348        // durable commit or publication.1349        stateLock.lock()1350        try {1351            sessionEpoch = nextSessionEpoch(sessionEpoch)1352            clearSessionStateLocked()1353            _uiGateLocked.value = false1354        } finally {1355            stateLock.unlock()1356        }1357    }13581359    /**1360     * Enter sync-retained background mode: the UI shows the lock screen but the1361     * vault stays fully unlocked in memory so [PeachSyncService] can complete1362     * sync sessions. Called from [PeachApplication.onStop] when background sync1363     * is enabled. A subsequent full [lock] (auto-lock timer, manual lock)1364     * supersedes this and zeroes everything.1365     */1366    fun lockUiGate() {1367        if (_isUnlocked.value) _uiGateLocked.value = true1368    }13691370    /** Dismiss the UI gate after the user authenticates on resume. */1371    fun clearUiGate() {1372        _uiGateLocked.value = false1373    }13741375    @Volatile private var suppressNextBackgroundLockUntil: Long = 0L13761377    // Test seam so the expiry branch is reachable from plain JUnit (SystemClock1378    // is a stub off-device).1379    @VisibleForTesting1380    internal var nowMs: () -> Long = { SystemClock.elapsedRealtime() }13811382    /**1383     * Call immediately before launching a system Activity (a SAF file1384     * picker/save dialog, a share sheet) that briefly takes the whole process1385     * out of the foreground as an expected part of an in-app flow — not a1386     * genuine user backgrounding. ProcessLifecycleOwner.onStop can't tell the1387     * two apart on its own (it fires for both), and without this, exporting or1388     * importing a file silently locked and wiped the vault mid-flow the moment1389     * the picker took over, before its result ever reached the app.1390     *1391     * The suppression auto-expires after [BACKGROUND_LOCK_SUPPRESSION_TIMEOUT_MS]1392     * (M-07); a never-consumed stale flag cannot suppress a later real lock.1393     */1394    fun expectTransientBackground() {1395        suppressNextBackgroundLockUntil = nowMs() + BACKGROUND_LOCK_SUPPRESSION_TIMEOUT_MS1396    }13971398    /**1399     * Consumed once by the next background-lock check; see [expectTransientBackground].1400     * Returns false (and clears the flag) if the suppression has expired or was1401     * never set — a genuine background event must always lock.1402     */1403    fun consumeTransientBackgroundSuppression(): Boolean {1404        val until = suppressNextBackgroundLockUntil1405        val active = until != 0L && nowMs() < until1406        suppressNextBackgroundLockUntil = 0L1407        return active1408    }14091410    // ---- Sync identity ----------------------------------------------------14111412    /**1413     * The vault's stable sync master key (a copy). Caller must zero it. Backs1414     * vault_id, the Noise static key, the Ed25519 manifest key, and per-entry1415     * envelope keys. Null when locked. See [VaultPayload.rootKeyB64].1416     */1417    /**1418     * HOLE 5 — the duress vault never syncs.1419     *1420     * [commitDuressUnlock] gives the decoy session a root key so its own codex1421     * and recovery paths work, which means (unlike the browser, where the decoy1422     * path simply has no root key) the sync surface has to refuse explicitly.1423     * Without this the decoy vault would present a second, different vault_id1424     * to a paired device, and a coerced user opening it would make sync visibly1425     * fail on their other devices — a duress indicator, which is the one thing1426     * a duress vault must never be.1427     */1428    // M-04: the "null when locked" half of the contract was documented but never1429    // enforced — a rootKey outlives _isUnlocked in the recovery half-unlock (see1430    // [unlockWithRecoveryWords], which installs a root key with no password key1431    // yet) and in a create that failed after staging. Sync must fail closed1432    // there, so the authoritative unlocked flag gates it, not just decoyMode.1433    internal data class SyncMasterKeySnapshot(val epoch: Long, val key: ByteArray)14341435    internal fun syncMasterKeySnapshot(): SyncMasterKeySnapshot? = mutateState {1436        if (decoyMode || !_isUnlocked.value) null1437        else rootKey?.copyOf()?.let { SyncMasterKeySnapshot(sessionEpoch, it) }1438    }14391440    internal fun isSessionEpochCurrent(epoch: Long): Boolean =1441        mutateState { sessionEpoch == epoch }14421443    internal fun unlockedSessionEpoch(): Long? = mutateState {1444        if (derivedKey != null && _isUnlocked.value) sessionEpoch else null1445    }14461447    fun syncMasterKey(): ByteArray? = syncMasterKeySnapshot()?.key14481449    /**1450     * The current session's root key, decoy included. For local-only uses that1451     * must behave identically in a decoy session — Codex backup and recovery1452     * words — because a feature that errors under duress is itself a duress1453     * tell. In a decoy session this is the DECOY's root key (see1454     * [commitDuressUnlock]), never the real vault's, so neither surface can1455     * leak the real vault. Anything that leaves the device must use1456     * [syncMasterKey] instead.1457     */1458    fun sessionRootKey(): ByteArray? = mutateState {1459        if (!sessionDataAvailable) null else rootKey?.copyOf()1460    }14611462    /** Stable per-vault id two paired devices must share to sync. Null when1463     *  locked, and never present for the decoy vault (see [syncMasterKey]). */1464    fun syncVaultId(): String? = mutateState {1465        if (decoyMode || !_isUnlocked.value) null1466        else rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }1467    }14681469    /**1470     * Browser parity (MV-8): rotate the sync identity by replacing the stable1471     * root key. Entries remain under the master-password key, while sync1472     * credentials, vault_id, and recovery words all change.1473     */1474    suspend fun rotateSyncIdentity(): Boolean = mutex.withLock {1475        val expectedEpoch = mutateState { if (derivedKey != null && !decoyMode) sessionEpoch else null }1476            ?: return false1477        installRootKey(generateRecoverableRootKey(), expectedEpoch)1478    }14791480    /**1481     * Join the vault behind [rootKeyHex]: adopt that vault's identity while1482     * keeping every local entry.1483     *1484     * Sync identity (vault id, signing keys) derives from the root key, and1485     * `sync-coordinator` refuses a `vault_id_mismatch`, so two independently1486     * created vaults can never reconcile. Taking the other side's root key is1487     * what makes them one vault; from the next sync on, both entry sets merge.1488     *1489     * Entries survive because they are sealed under the password-derived key,1490     * not the root key — the same property [rotateSyncIdentity] relies on.1491     *1492     * CONSEQUENCE, which the caller must have disclosed and had confirmed:1493     * this device's previous recovery words stop working for good, and its new1494     * words are the source vault's words, because words are a deterministic1495     * encoding of the root key.1496     */1497    suspend fun joinVault(rootKeyHex: String): AdoptVaultResult = mutex.withLock {1498        if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {1499            return AdoptVaultResult.Error("JOIN_INVALID_ROOT_KEY: expected 64 lowercase hex chars")1500        }1501        val expectedEpoch = mutateState {1502            when {1503                derivedKey == null -> null1504                decoyMode -> Long.MIN_VALUE1505                else -> sessionEpoch1506            }1507        }1508        if (expectedEpoch == null) return AdoptVaultResult.Error("vault_locked")1509        if (expectedEpoch == Long.MIN_VALUE) return AdoptVaultResult.Error("JOIN_DECOY_MODE")1510        if (!store.hasVault()) return AdoptVaultResult.Error("JOIN_NO_LOCAL_VAULT")15111512        val incoming = hexToRootKey(rootKeyHex)1513        if (incoming.size != VaultCrypto.KEY_SIZE) {1514            VaultCrypto.zero(incoming)1515            return AdoptVaultResult.Error("JOIN_INVALID_ROOT_KEY: expected 32 bytes")1516        }1517        // Refuse before committing rather than leave this device holding a vault1518        // whose recovery words cannot be typed back. generateRecoverableRootKey1519        // screens its own keys for this; a key arriving from a peer has not been.1520        val roundTrips = runCatching { wordsToRootKeyMaterial(rootKeyToWords(incoming)) }.isSuccess1521        if (!roundTrips) {1522            VaultCrypto.zero(incoming)1523            return AdoptVaultResult.Error("JOIN_UNRECOVERABLE_ROOT_KEY")1524        }15251526        val vaultId = com.peachpasswords.sync.computeVaultId(incoming)1527        return if (installRootKey(incoming, expectedEpoch)) {1528            AdoptVaultResult.Success(vaultId)1529        } else {1530            AdoptVaultResult.Error("JOIN_INSTALL_FAILED")1531        }1532    }15331534    /**1535     * The recovery words [rootKeyHex] will produce once joined, or null if it is1536     * not a usable root key. Lets the join flow show the user the words that are1537     * about to replace theirs *before* anything is committed.1538     */1539    fun previewRecoveryWords(rootKeyHex: String): List<String>? {1540        if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) return null1541        val bytes = hexToRootKey(rootKeyHex)1542        return try {1543            val words = rootKeyToWords(bytes)1544            if (runCatching { wordsToRootKeyMaterial(words) }.isSuccess) words else null1545        } catch (_: Exception) {1546            null1547        } finally {1548            VaultCrypto.zero(bytes)1549        }1550    }15511552    /**1553     * Swap the vault's root key, keeping every entry, and re-escrow under the1554     * words the new key encodes. Takes ownership of [nextRootKey]. Caller holds1555     * [mutex].1556     */1557    private suspend fun installRootKey(nextRootKey: ByteArray, expectedEpoch: Long): Boolean {1558        // H-03: snapshot the live fields under stateLock so the success and the1559        // rollback paths both see consistent prior/new state. Writing the new1560        // rootKey/recovery fields is inside its own mutateState at the end.1561        // H-03 (P1-3 codex): the snapshot must COPY the live key/rootKey arrays1562        // — holding live references would let a zero-on-failure operation also1563        // wipe the session's still-live key arrays.1564        data class Snapshot(1565            val key: ByteArray,1566            val priorRootKey: ByteArray,1567            val priorRecoveryHash: String?,1568            val priorRecoverySet: Boolean,1569        )1570        val snap = mutateIfCurrentEpoch(expectedEpoch) {1571            val k = derivedKey ?: return@mutateIfCurrentEpoch null1572            if (decoyMode) return@mutateIfCurrentEpoch null1573            val priorRoot = rootKey ?: return@mutateIfCurrentEpoch null1574            Snapshot(k.copyOf(), priorRoot.copyOf(), recoveryWordHash, recoveryWordsSet)1575        } ?: run {1576            VaultCrypto.zero(nextRootKey)1577            return false1578        }1579        val priorSlot = store.loadSlotA() ?: run {1580            VaultCrypto.zero(snap.key)1581            VaultCrypto.zero(snap.priorRootKey)1582            VaultCrypto.zero(nextRootKey)1583            return false1584        }1585        val nextWords = rootKeyToWords(nextRootKey)15861587        return try {1588            beforeDurableCommit()1589            if (!takeVaultSnapshot("local_save", expectedEpoch)) throw IllegalStateException("snapshot_failed")1590            if (mutateIfCurrentEpoch(expectedEpoch) {1591                rootKey = nextRootKey1592                recoveryWordHash = recoveryWordsHash(nextWords)1593                recoveryWordsSet = false1594            } == null) throw IllegalStateException("stale_root_rotation")15951596            val nextRecoveryEscrow = buildRecoveryEscrow(nextWords)1597                ?: throw IllegalStateException("recovery_escrow_failed")1598            val nextRootKeyEscrow = buildRootKeyEscrow(nextWords)1599                ?: throw IllegalStateException("root_escrow_failed")1600            val plaintext = VaultCodec.encode(currentPayload())1601            val blob = try {1602                b64(VaultCrypto.encrypt(plaintext, snap.key, VaultCrypto.AAD_SLOT_A))1603            } finally {1604                VaultCrypto.zero(plaintext)1605            }1606            val nextSlot = priorSlot.copy(1607                blob = blob,1608                recoveryEscrow = nextRecoveryEscrow,1609                rootKeyEscrow = nextRootKeyEscrow,1610            )1611            val committed = withEpochCommit(expectedEpoch) {1612                if (!store.writeSlotA(nextSlot)) return@withEpochCommit false1613                try {1614                    if (!writeMatchingNoiseSlotB(nextSlot)) throw IllegalStateException("noise_slot_b_commit_failed")1615                    // H-04: a root-key rotation re-seals slot A, so the duress slot1616                    // (real or fake) must be re-padded to the new ciphertext length.1617                    if (!writeCompanionDuressSlot(nextSlot)) throw IllegalStateException("duress_slot_commit_failed")1618                    store.stampLocalMutation()1619                } catch (_: Exception) {1620                    store.writeSlotA(priorSlot)1621                    return@withEpochCommit false1622                }1623                true1624            } ?: false1625            if (!committed) throw IllegalStateException("storage_write_failed")1626            mutateIfCurrentEpoch(expectedEpoch) { publish() }1627            true1628        } catch (_: Exception) {1629            val restored = mutateIfCurrentEpoch(expectedEpoch) {1630                rootKey?.let(VaultCrypto::zero)1631                rootKey = snap.priorRootKey.copyOf()1632                recoveryWordHash = snap.priorRecoveryHash1633                recoveryWordsSet = snap.priorRecoverySet1634            }1635            if (restored != null) {1636                withEpochCommit(expectedEpoch) { store.writeSlotA(priorSlot) }1637            }1638            false1639        } finally {1640            VaultCrypto.zero(snap.key)1641            VaultCrypto.zero(snap.priorRootKey)1642            // On success nextRootKey is owned by rootKey. On every other path1643            // it is not, including a stale epoch after lock(); scrub it while1644            // the local reference is still available.1645            val stillOwnedBySession = mutateState {1646                sessionEpoch == expectedEpoch && rootKey === nextRootKey1647            }1648            if (!stillOwnedBySession) VaultCrypto.zero(nextRootKey)1649        }1650    }16511652    /**1653     * A copy of the live Argon2id-derived vault key, for biometric escrow only1654     * (wrapped under a hardware KeyStore key on biometric enable). Null when1655     * locked. Caller must [VaultCrypto.zero] it after use.1656     */1657    fun currentVaultKey(): ByteArray? = mutateState {1658        if (!isFullyUnlockedLocked()) null else derivedKey?.copyOf()1659    }16601661    suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {1662        val expectedEpoch = currentEpoch()1663        val slotA = store.loadSlotA() ?: return false1664        var oldKey: ByteArray? = null1665        var newKey: ByteArray? = null1666        var plaintext: ByteArray? = null1667        return try {1668            oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))1669            // Keep ownership of the decrypted vault plaintext until decoding has1670            // finished.  Passing decrypt() inline made the byte array unreachable1671            // before the finally block, so a successful or failed password change1672            // could leave the full plaintext resident in the heap.1673            val decrypted = VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A)1674            val payload = try {1675                VaultCodec.decode(decrypted)1676            } finally {1677                VaultCrypto.zero(decrypted)1678            }1679            val newSalt = VaultCrypto.generateSalt()1680            newKey = VaultCrypto.deriveKey(newPassword, newSalt)1681            // Re-seal the existing payload under the new key/salt.1682            plaintext = VaultCodec.encode(payload)1683            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))1684            // The escrow seals the slot-A PLAINTEXT, which a password change does not1685            // alter — only the wrapping changes — so carry it forward; rebuilding the1686            // StoredVault from scratch would silently drop it.1687            // Carry BOTH escrows forward unchanged: each seals plaintext/root-key1688            // content that a password change does not alter — only the slot-A1689            // wrapping rotates. The root-key escrow staying stable across password1690            // changes matches the browser (`vault.ts:363-364`).1691            val next = StoredVault(1692                version = slotA.version,1693                salt = b64(newSalt),1694                blob = blob,1695                recoveryEscrow = slotA.recoveryEscrow,1696                rootKeyEscrow = slotA.rootKeyEscrow,1697            )1698            // H-01: durably commit slot A + size-matched noise + version stamp1699            // before swapping the session key. A partial commit (new A on disk,1700            // old key in memory) would have the next save encrypt under the old1701            // key while matching disk on the new one.1702            val priorB = store.loadSlotB()1703            if (!commitVaultRotation(slotA, priorB, next, expectedEpoch)) return false1704            // H-03 (P1-2 codex): zero the OLD live key and assign the NEW one1705            // inside the same stateLock critical section, so a concurrent lock()1706            // can't observe the in-between (zeroed but not yet reassigned).1707            if (mutateIfCurrentEpoch(expectedEpoch) {1708                oldKey?.let(VaultCrypto::zero); oldKey = null1709                derivedKey?.let(VaultCrypto::zero)1710                derivedKey = newKey; newKey = null1711            } == null) return false1712            true1713        } catch (_: Exception) {1714            false1715        } finally {1716            oldKey?.let(VaultCrypto::zero)1717            newKey?.let(VaultCrypto::zero)1718            plaintext?.let(VaultCrypto::zero)1719        }1720    }17211722    /**1723     * Irreversible wipe. Locks the session and clears every vault key. The Pro1724     * license is in a separate store and is preserved by construction.1725     */1726    suspend fun destroyVault() = mutex.withLock {1727        lock()1728        store.clearVault()1729        store.clearDecoySlot()1730    }17311732    // ---- Entry CRUD -------------------------------------------------------17331734    /**1735     * A Peach entry id is a UUID. Import and restore carry ids from foreign1736     * files (another Peach install, a vendor export, a hand-written backup) and1737     * no reader bounds them, so an id that is not a well-formed Peach id is1738     * replaced here rather than trusted.1739     *1740     * This is the naturalisation seam, and it is deliberately the only place it1741     * happens. Minting costs at most one duplicate if the same vault is later1742     * restored on a device that still holds the old id — visible and fixable.1743     * The sync path must NOT do this: adopting a peer's id verbatim is the only1744     * thing that keeps two devices agreeing on which entry they are discussing,1745     * so reminting there would fork identity on every device, on every round.1746     */1747    private val entryIdShape = Regex("[A-Za-z0-9_-]{1,64}")17481749    private fun String?.normalizedEntryId(): String =1750        if (this != null && entryIdShape.matches(this)) this else UUID.randomUUID().toString()17511752    suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {1753        val epoch = requireUnlocked()1754        val stamp = VaultCrypto.monotonicEntryTimestamp()1755        val now = System.currentTimeMillis()1756        val entry = withDerivedLast4(draft.copy(1757            id = draft.id.normalizedEntryId(),1758            createdAt = if (draft.createdAt > 0) draft.createdAt else now,1759            modifiedAt = stamp,1760            passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1761        ))1762        // H-03: capture rollback AND write entryList under stateLock so a1763        // concurrent lock() cannot zero the session between the read and the write.1764        val rollback = mutateCurrentSession(epoch) {1765            val r = entryList.toMutableList()1766            entryList.add(entry)1767            r1768        } ?: throw IllegalStateException("vault_locked")1769        persistOrRollback(rollback, epoch)1770        entry1771    }17721773    /**1774     * Insert many entries with a single encrypt-and-write at the end.1775     *1776     * Importing a real vault through [addEntry] was quadratic: every entry took1777     * the lock and re-encrypted and rewrote the whole vault, so an 806-entry1778     * restore did 806 full-vault writes and hung the app long enough to ANR.1779     * Rolls back to the pre-import list if the one write fails, matching1780     * [addEntry]'s all-or-nothing behaviour.1781     */1782    suspend fun addEntries(drafts: List<VaultEntry>): Int = mutex.withLock {1783        val epoch = requireUnlocked()1784        if (drafts.isEmpty()) return 01785        val now = System.currentTimeMillis()1786        val ready = drafts.map { draft ->1787            val stamp = VaultCrypto.monotonicEntryTimestamp()1788            withDerivedLast4(1789                draft.copy(1790                    id = draft.id.normalizedEntryId(),1791                    createdAt = if (draft.createdAt > 0) draft.createdAt else now,1792                    modifiedAt = stamp,1793                    passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1794                ),1795            )1796        }1797        // H-03: capture rollback AND append every entry under stateLock.1798        val rollback = mutateCurrentSession(epoch) {1799            val r = entryList.toMutableList()1800            entryList.addAll(ready)1801            r1802        } ?: throw IllegalStateException("vault_locked")1803        persistOrRollback(rollback, epoch)1804        return drafts.size1805    }18061807    /**1808     * M-01: replace the whole active set with [newEntries] in one write.1809     *1810     * Import's REPLACE mode used to soft-delete every current entry one durable1811     * write at a time (swallowing each failure) and then batch-add, so a failed1812     * add left the old entries stranded in Trash with nothing restored. Staging1813     * the entire next list in memory and committing it through1814     * [persistOrRollback] makes the swap all-or-nothing: on any failure the1815     * pre-import list — active entries included — is restored.1816     *1817     * Existing tombstones are preserved so paired devices still see the1818     * deletions they already know about.1819     */1820    suspend fun replaceEntries(newEntries: List<VaultEntry>): Int = mutex.withLock {1821        val epoch = requireUnlocked()1822        val now = System.currentTimeMillis()1823        val ready = newEntries.map { draft ->1824            val stamp = VaultCrypto.monotonicEntryTimestamp()1825            withDerivedLast4(1826                draft.copy(1827                    id = draft.id.normalizedEntryId(),1828                    createdAt = if (draft.createdAt > 0) draft.createdAt else now,1829                    modifiedAt = stamp,1830                    passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1831                ),1832            )1833        }1834        // M-03: an incoming entry that shares an id with an existing live entry1835        // is meant to *replace* it (PEACHSCRIPT REPLACE restore). Tombstoning1836        // the old one and then appending the new one would leave the list with1837        // two entries of the same id — the tombstoned one would be returned by1838        // updateEntry's indexOfFirst and trip entry_not_found. Drop the to-be-1839        // superseded entries from the tombstone set instead.1840        val incomingIds = ready.map { it.id }.toHashSet()1841        val rollback = mutateCurrentSession(epoch) {1842            val r = entryList.toMutableList()1843            val replaced = entryList.map { entry ->1844                if (entry.deletedAt != null) return@map entry1845                if (entry.id in incomingIds) return@map null1846                val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)1847                entry.copy(deletedAt = stamp, modifiedAt = stamp)1848            }.filterNotNull()1849            entryList = (replaced + ready).toMutableList()1850            r1851        } ?: throw IllegalStateException("vault_locked")1852        persistOrRollback(rollback, epoch)1853        return ready.size1854    }18551856    suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {1857        val epoch = requireUnlocked()1858        // H-03: read entryList, compute the patched entry, and write it under a1859        // single stateLock so a concurrent lock() cannot interleave between the1860        // lookup and the assignment (would IndexOutOfBoundsException on a shrunk1861        // list, or clobber the entry onto the wrong id after a relock).1862        val prepared = mutateCurrentSession(epoch) {1863            val idx = entryList.indexOfFirst { it.id == patch.id }1864            if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1865            val current = entryList[idx]1866            val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1867            // Only refresh passwordChangedAt when the password value actually changes.1868            val passwordChanged = patch.password != null && patch.password != current.password1869            // Capture the outgoing password (newest first) so the user can reveal/copy/1870            // restore it later. History is computed authoritatively from `current`, not1871            // the patch — updateEntry is a full-entry replace, so trusting patch's value1872            // would let a stale form clobber the real history. Record the age the old1873            // password carried, skip an empty prior, and skip an immediate exact dupe1874            // (e.g. restore-then-restore). Capped at PASSWORD_HISTORY_MAX.1875            val priorPassword = current.password1876            val shouldCapture = passwordChanged &&1877                !priorPassword.isNullOrEmpty() &&1878                current.passwordHistory?.firstOrNull()?.password != priorPassword1879            val nextHistory = if (shouldCapture) {1880                (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +1881                    (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)1882            } else {1883                current.passwordHistory1884            }1885            val updated = withDerivedLast4(patch.copy(1886                createdAt = current.createdAt,1887                modifiedAt = stamp,1888                passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,1889                passwordHistory = nextHistory,1890            ))1891            val rollback = entryList.toMutableList()1892            entryList[idx] = updated1893            updated to rollback1894        } ?: throw IllegalStateException("vault_locked")1895        val (updated, rollback) = prepared1896        persistOrRollback(rollback, epoch)1897        updated1898    }18991900    /** Soft-delete: writes a tombstone whose timestamp beats any in-flight edit. */1901    suspend fun deleteEntry(id: String) = mutex.withLock {1902        val epoch = requireUnlocked()1903        // H-03: lookup + tombstone write under stateLock so lock() cannot shrink1904        // the list out from under the indexOfFirst.1905        val rollback = mutateCurrentSession(epoch) {1906            val idx = entryList.indexOfFirst { it.id == id }1907            if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1908            val current = entryList[idx]1909            val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1910            val prior = entryList.toMutableList()1911            entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)1912            prior1913        } ?: throw IllegalStateException("vault_locked")1914        persistOrRollback(rollback, epoch)1915    }19161917    suspend fun restoreEntry(id: String) = mutex.withLock {1918        val epoch = requireUnlocked()1919        val rollback = mutateCurrentSession(epoch) {1920            val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }1921            if (idx == -1) throw IllegalStateException("deleted entry not found")1922            val current = entryList[idx]1923            val prior = entryList.toMutableList()1924            entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))1925            prior1926        } ?: throw IllegalStateException("vault_locked")1927        persistOrRollback(rollback, epoch)1928    }19291930    /** Permanent delete — no tombstone, no recovery. */1931    suspend fun purgeEntry(id: String) = mutex.withLock {1932        val epoch = requireUnlocked()1933        val rollback = mutateCurrentSession(epoch) {1934            val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }1935            if (idx == -1) throw IllegalStateException("deleted entry not found")1936            val prior = entryList.toMutableList()1937            entryList.removeAt(idx)1938            prior1939        } ?: throw IllegalStateException("vault_locked")1940        persistOrRollback(rollback, epoch)1941    }19421943    /** Permanently empty the trash — hard-deletes every soft-deleted entry. */1944    suspend fun purgeDeletedEntries(): Int = mutex.withLock {1945        val epoch = requireUnlocked()1946        // H-03: read+remove under stateLock so lock() can't reorder the remove.1947        data class R(val rollback: MutableList<VaultEntry>, val removed: Int)1948        val r = mutateCurrentSession(epoch) {1949            val rollback = entryList.toMutableList()1950            val before = entryList.size1951            entryList.removeAll { it.deletedAt != null }1952            R(rollback, before - entryList.size)1953        } ?: throw IllegalStateException("vault_locked")1954        if (r.removed > 0) persistOrRollback(r.rollback, epoch)1955        r.removed1956    }19571958    /** Browser parity: number of active entries that dedupe would move to trash. */1959    suspend fun countDuplicateEntries(): Int = mutex.withLock {1960        val epoch = requireUnlocked()1961        // countDuplicateEntriesLocked reads entryList; H-03 fences the read so1962        // lock() can't race the read with state writes.1963        mutateCurrentSession(epoch) { countDuplicateEntriesLocked() }1964            ?: throw IllegalStateException("vault_locked")1965    }19661967    /**1968     * Browser parity: soft-delete duplicate entries, keeping the most recently1969     * modified member of each group. Refuse in decoy mode so the duress vault is1970     * not reshaped into a forensically distinct state.1971     */1972    suspend fun deduplicateEntries(): Int = mutex.withLock {1973        val epoch = requireUnlocked()1974        data class R(val rollback: MutableList<VaultEntry>, val removed: Int)1975        val ready = mutateCurrentSession(epoch) {1976            if (decoyMode) throw IllegalStateException("deduplicate disabled in decoy mode")1977            val active = entryList.filter { it.deletedAt == null }1978            val keepIds = mutableSetOf<String>()1979            active.groupBy { it.duplicateKey() }.values.forEach { group ->1980                keepIds += group.maxBy { it.modifiedAt.takeIf { ts -> ts > 0 } ?: it.createdAt }.id1981            }1982            val rollback = entryList.toMutableList()1983            var removed = 01984            entryList = entryList.map { entry ->1985                if (entry.deletedAt == null && entry.id !in keepIds) {1986                    removed++1987                    val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)1988                    entry.copy(deletedAt = stamp, modifiedAt = stamp)1989                } else {1990                    entry1991                }1992            }.toMutableList()1993            R(rollback, removed)1994        } ?: throw IllegalStateException("vault_locked")1995        if (ready.removed > 0) persistOrRollback(ready.rollback, epoch)1996        ready.removed1997    }19981999    fun getEntries(): List<VaultEntry> = mutateState {2000        if (!sessionDataAvailable) emptyList() else entryList.filter { it.deletedAt == null }2001    }2002    fun getEntry(id: String): VaultEntry? = mutateState {2003        if (!sessionDataAvailable) null else entryList.firstOrNull { it.id == id && it.deletedAt == null }2004    }2005    fun getDeletedEntries(): List<VaultEntry> = mutateState {2006        if (!sessionDataAvailable) emptyList()2007        else entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }2008    }20092010    /** Active entries, optionally narrowed to those carrying [tagFilter]. */2011    fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {2012        return mutateState {2013            if (!sessionDataAvailable) return@mutateState emptyList()2014            val active = entryList.filter { it.deletedAt == null }2015            if (tagFilter == null) return@mutateState active2016            val needle = tagFilter.trim().lowercase()2017            active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }2018        }2019    }20202021    /** Sorted, de-duplicated tags across all active entries. */2022    fun getDistinctTags(): List<String> = mutateState {2023        if (!sessionDataAvailable) return@mutateState emptyList()2024        entryList.asSequence()2025            .filter { it.deletedAt == null }2026            .flatMap { it.tags?.asSequence() ?: emptySequence() }2027            .map { it.trim().lowercase() }2028            .filter { it.isNotEmpty() }2029            .distinct()2030            .sorted()2031            .toList()2032    }20332034    /**2035     * Distinct non-blank values for an identity field across active entries,2036     * most-frequently-used first. Supports "username" and "email"; unknown field2037     * names return an empty list. Values keep original casing (deduped2038     * case-insensitively) so a suggestion matches what the user typed.2039     */2040    fun getDistinctFieldValues(field: String): List<String> {2041        val select: (VaultEntry) -> String? = when (field) {2042            "username" -> { e -> e.username }2043            "email" -> { e -> e.email }2044            else -> return emptyList()2045        }2046        return mutateState {2047            if (!sessionDataAvailable) return@mutateState emptyList()2048            entryList.asSequence()2049                .filter { it.deletedAt == null }2050                .mapNotNull { select(it)?.trim() }2051                .filter { it.isNotEmpty() }2052                .groupingBy { it.lowercase() }2053                .aggregate { _, acc: Pair<String, Int>?, value, _ ->2054                    Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)2055                }2056                .values2057                .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })2058                .map { it.first }2059        }2060    }20612062    fun getTombstones(): List<Tombstone> = mutateState {2063        if (!sessionDataAvailable) emptyList()2064        else entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }2065    }2066    fun getVaultVersion(): Long = store.version()2067    fun getVaultHistory(): List<VaultSnapshot> = store.loadVaultHistory().snapshots20682069    suspend fun restoreVaultSnapshot(snapshotId: String): Boolean = mutex.withLock {2070        val expectedEpoch = currentEpoch()2071        val snapshot = store.loadVaultHistory().snapshots.firstOrNull { it.id == snapshotId } ?: return false2072        val restoredA = VaultCodec.decodeSlot(snapshot.vault_a) ?: return false2073        // H-04: snapshots now carry the duress slot too — restore preserves2074        // the at-rest triad (A/B/D), not just the A/B pair.2075        val restoredD: StoredVault? = snapshot.vault_d?.let(VaultCodec::decodeSlot)2076        val priorA = store.loadSlotA()2077        val priorB = store.loadSlotB()2078        val priorD = store.loadDecoySlot()2079        // H-02: capture pre-restore state as the recovery snapshot BEFORE any2080        // slot write — the old code took this snapshot, then stranded it on2081        // every failure, polluting history with a "restore" entry that never2082        // restored anything. The history below is rolled back together with2083        // the slots if the commit fails.2084        val priorHistory = store.loadVaultHistory()2085        // P1-4 (codex): the recovery snapshot must land before we commit the2086        // slot pair, otherwise a failed restore cannot be rolled back to the2087        // pre-restore history. If the history write itself fails, refuse to2088        // proceed — the alternative is a successful restore with no undo path.2089        beforeDurableCommit()2090        if (!takeVaultSnapshot("restore", expectedEpoch)) {2091            return false2092        }2093        // H-04: legacy snapshots without vault_d, or vault_d that fails to2094        // decode, fall back to a fake duress of slot A's size — presence-2095        // indistinguishable from any other freshly-restored vault.2096        val nextD: StoredVault = restoredD ?: run {2097            val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(restoredA) + 162098            val fakeBlob = ByteArray(target).also(rng::nextBytes)2099            val fakeSalt = VaultCrypto.generateSalt()2100            StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob))2101        }2102        if (!commitRestoreAtomic(restoredA, snapshot.vault_b, nextD, priorA, priorB, priorD, expectedEpoch)) {2103            withEpochCommit(expectedEpoch) { store.writeVaultHistory(priorHistory) }2104            return false2105        }2106        lock()2107        true2108    }21092110    /**2111     * H-02: atomic slot-A + slot-B + version stamp for a snapshot restore.2112     * Mirrors [commitVaultRotation] but writes the snapshot's EXACT slot B2113     * (a restore preserves the duress-shaped blob from history), not a fresh2114     * noise record. Any failure rolls back so the at-rest pair never holds a2115     * restored slot A against a pre-restore slot B. Caller is responsible for2116     * restoring the pre-snapshot history on a false return.2117     *2118     * H-04: duress slot is now part of the atomic triad — restored last so2119     * a duress-write failure rolls the A/B pair back too.2120     */2121    private fun commitRestoreAtomic(2122        nextA: StoredVault,2123        nextB: String,2124        nextD: StoredVault,2125        priorA: StoredVault?,2126        priorB: String?,2127        priorD: StoredVault?,2128        expectedEpoch: Long,2129    ): Boolean {2130        return withEpochCommit(expectedEpoch) {2131            if (!store.writeSlotA(nextA)) return@withEpochCommit false2132            // P1-2 (codex): writeSlotB's boolean AND any thrown exception from it2133            // must trigger rollback; previously a throw escaped without restoring2134            // the prior slot A and history.2135            try {2136                if (!store.writeSlotB(nextB)) throw java.io.IOException("slot_b_commit_failed")2137                // H-04: duress slot is part of the restore triad. Failures here2138                // roll A+B back so the at-rest state stays consistent.2139                if (!store.writeDecoySlot(nextD)) throw java.io.IOException("duress_slot_commit_failed")2140                store.stampLocalMutation()2141            } catch (_: Exception) {2142                reportRollbackFailures(rollbackRestoreLocked(priorA, priorB, priorD))2143                return@withEpochCommit false2144            }2145            true2146        } ?: false2147    }21482149    // ---- Sync apply (does NOT advance the version) ------------------------21502151    /**2152     * Apply remote entryList + tombstones with per-entry last-write-wins. Persists2153     * WITHOUT bumping the version counter, so a sync round cannot cascade into2154     * another outbound sync. Returns the number of locally-applied changes.2155     */2156    suspend fun applyMergedRemoteEntries(2157        remoteEntries: List<VaultEntry>,2158        remoteTombstones: List<Tombstone>,2159        expectedEpoch: Long? = null,2160    ): Int = mutex.withLock {2161        val epoch = expectedEpoch ?: requireUnlocked()2162        if (expectedEpoch != null && mutateIfCurrentEpoch(epoch) { true } != true) return@withLock 02163        // HV-1: clamp every peer-supplied timestamp to now + MAX_CLOCK_SKEW_MS2164        // BEFORE any comparison against a local one. Without this a peer can2165        // send a far-future modifiedAt and permanently pin its version of an2166        // entry against every honest local edit. The browser clamps in the2167        // matching place (vault.ts applyMergedRemoteEntries).2168        val mergeNow = System.currentTimeMillis()2169        val clamped = remoteEntries.mapNotNull { entry ->2170            // MN-3: drop peer entries that decode cleanly but are semantically2171            // hollow (blank title, credential-less login, husk passkey) and2172            // re-cap passwordHistory before anything merges into the vault.2173            SyncEntrySanitizer.sanitize(entry, PASSWORD_HISTORY_MAX)?.copy(2174                modifiedAt = SyncLimits.clampSyncTimestamp(entry.modifiedAt, mergeNow),2175                deletedAt = entry.deletedAt?.let {2176                    SyncLimits.clampSyncTimestamp(it, mergeNow)2177                },2178            )2179        }2180        val tombMap = remoteTombstones.associate {2181            it.id to SyncLimits.clampSyncTimestamp(it.deletedAt, mergeNow)2182        }2183        // H-03: build the new entryList under stateLock so a concurrent lock()2184        // cannot zero derivedKey/entryList between the byId read and the merge.2185        val applied = mutateCurrentSession(epoch) {2186            var n = 02187            val byId = entryList.associateBy { it.id }.toMutableMap()21882189            for (remote in clamped) {2190                val tomb = tombMap[remote.id]2191                if (tomb != null && tomb >= remote.modifiedAt) continue2192                val local = byId[remote.id]2193                if (local == null) {2194                    entryList.add(remote); byId[remote.id] = remote; n++2195                } else if (remote.modifiedAt > local.modifiedAt) {2196                    val i = entryList.indexOfFirst { it.id == local.id }2197                    if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; n++ }2198                }2199            }22002201            for ((id, deletedAt) in tombMap) {2202                val local = byId[id] ?: continue2203                if (local.deletedAt != null && local.deletedAt >= deletedAt) continue2204                if (deletedAt < local.modifiedAt) continue2205                val i = entryList.indexOfFirst { it.id == id }2206                if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); n++ }2207            }2208            n2209        } ?: return@withLock 022102211        if (applied > 0) {2212            persistSlotA(bumpVersion = false, snapshotReason = "sync_received", expectedEpoch = epoch)2213            mutateIfCurrentEpoch(epoch) { publish() }2214            runCatching { LockedSyncSpoolHooks.refresh(this) }2215        }2216        applied2217    }22182219    suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {2220        // Require a fully live session before exposing a settings mutation.  The2221        // epoch is captured with the read so a lock/new-session boundary cannot2222        // let stale work publish into the replacement session.2223        val epoch = requireUnlocked()2224        val prior = mutateCurrentSession(epoch) {2225            val old = _settings.value2226            _settings.value = settings2227            old2228        } ?: throw IllegalStateException("vault_locked")22292230        val committed = try {2231            beforeDurableCommit()2232            // The durable write is inside the same epoch fence as the in-memory2233            // publication.  If lock() won first, this returns null and no stale2234            // settings reach storage or the public StateFlow.2235            withSessionEpochCommit(epoch) { store.writeSettings(settings) } == true2236        } catch (_: Exception) {2237            false2238        }2239        if (!committed) {2240            // A live-session storage failure rolls back the public value.  A2241            // stale epoch is already reset by lock()/the new session and must2242            // not be allowed to overwrite that safe state.2243            mutateIfCurrentEpoch(epoch) { _settings.value = prior }2244            throw IllegalStateException("settings_write_failed")2245        }2246    }22472248    // ---- Recovery words (vault metadata) ----------------------------------22492250    /** True once the user has confirmed their recovery words for this vault. */2251    fun isRecoveryWordsSet(): Boolean = mutateState { recoveryWordsSet }22522253    /**2254     * Record the BLAKE3 hash of the confirmed recovery words and mark them set.2255     * Persisted without bumping the version — recovery metadata is local-only and2256     * is not an entry mutation paired devices should sync against.2257     */2258    suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {2259        val epoch = requireUnlocked()2260        // H-03: hash + escrow-related state fields set under stateLock so a2261        // concurrent lock() cannot zero them in the middle of buildRecoveryEscrow.2262        // M-04: the flags have to be live before the escrows are built — both seal2263        // currentPayload() — so capture the prior pair and put it back if the write2264        // never lands. Otherwise the session reports words set against a slot A2265        // that still holds no escrow, and the recovery screen never offers a retry.2266        val prior = mutateCurrentSession(epoch) {2267            val priorPair = recoveryWordHash to recoveryWordsSet2268            recoveryWordHash = recoveryWordsHash(words)2269            recoveryWordsSet = true2270            priorPair2271        } ?: return@withLock false2272        // Seal TWO escrows (MF-1): the browser-byte-compatible root-key escrow2273        // (cross-platform recovery of the sync root key) and Android's whole-payload2274        // escrow (offline forgot-password restore of entries). Both derive their key2275        // from the same `wordsToRootKeyMaterial` IKM but use distinct AADs.2276        val persisted = runCatching {2277            persistSlotAWithEscrows(2278                buildRecoveryEscrow(words),2279                buildRootKeyEscrow(words),2280                expectedEpoch = epoch,2281            )2282        }.getOrDefault(false)2283        if (!persisted) {2284            mutateIfCurrentEpoch(epoch) {2285                recoveryWordHash = prior.first2286                recoveryWordsSet = prior.second2287            }2288        }2289        persisted2290    }22912292    /** Verify entered words against the stored recovery hash. */2293    fun verifyRecoveryWords(words: List<String>): Boolean {2294        return mutateState {2295            val stored = recoveryWordHash ?: return@mutateState false2296            MessageDigest.isEqual(2297                stored.toByteArray(Charsets.UTF_8),2298                recoveryWordsHash(words).toByteArray(Charsets.UTF_8),2299            )2300        }2301    }23022303    // ---- Recovery escrow (forgot-password) --------------------------------23042305    /** True at rest if this vault has any recovery escrow the recovery flow can use. */2306    fun hasRecoveryEscrow(): Boolean =2307        store.loadSlotA()?.let { it.recoveryEscrow != null || it.rootKeyEscrow != null } ?: false23082309    /**2310     * One-time self-heal: if this vault has a root key but no recovery escrow2311     * on disk (adopted vaults created before the escrow fix), build and persist2312     * it now. Called on every successful unlock; no-ops once the escrow exists.2313     */2314    private fun ensureRecoveryEscrow() {2315        if (hasRecoveryEscrow()) return2316        val rk = mutateState { rootKey?.copyOf() } ?: return2317        runCatching {2318            val words = rootKeyToWords(rk)2319            val escrow = buildRecoveryEscrow(words)2320            val rkEscrow = buildRootKeyEscrow(words)2321            if (escrow != null || rkEscrow != null) {2322                val prior = store.loadSlotA() ?: return@runCatching2323                store.writeSlotA(prior.copy(2324                    recoveryEscrow = escrow ?: prior.recoveryEscrow,2325                    rootKeyEscrow = rkEscrow ?: prior.rootKeyEscrow,2326                ))2327                mutateState {2328                    recoveryWordHash = recoveryWordsHash(words)2329                    recoveryWordsSet = true2330                }2331            }2332        }.also { VaultCrypto.zero(rk) }2333    }23342335    /**2336     * Attempt to unlock the vault using the 12 BIP39 recovery [words] instead of2337     * the master password. On success the slot-A plaintext sealed in the escrow is2338     * adopted as the live session (entries, rootKey, settings), but no Argon2id2339     * password key exists yet — call [resetPasswordWithRecoveryWords] next to set a2340     * new password and finish unlocking. Returns false when there is no escrow, the2341     * words fail the BIP39 checksum, or the words are wrong (GCM tag mismatch).2342     *2343     * Unlike the brief's `unlockWithRecoveryWords(): ByteArray?`, there is no2344     * detached vault key to return here — slot A is wrapped under the rotating2345     * Argon2id key — so this opens the escrowed payload directly.2346     */2347    suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {2348        val expectedEpoch = currentEpoch()2349        val slotA = store.loadSlotA() ?: return false2350        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false23512352        // Prefer Android's whole-payload escrow: a full offline restore of entries,2353        // root key, and settings. Present for Android-created vaults.2354        val fullEscrow = slotA.recoveryEscrow2355        if (fullEscrow != null) {2356            val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull()2357            if (material != null) {2358                var keyBytes: ByteArray? = null2359                var plaintext: ByteArray? = null2360                var candidateRoot: ByteArray? = null2361                var stateCommitStarted = false2362                try {2363                    keyBytes = deriveRecoveryKey(material, unb64(fullEscrow.salt)).encoded2364                    plaintext = VaultCrypto.decrypt(unb64(fullEscrow.blob), keyBytes!!, VaultCrypto.AAD_RECOVERY)2365                    val payload = VaultCodec.decode(plaintext)2366                    // Stage every fallible operation before touching live session2367                    // fields.  In particular, a settings/provider/decode failure2368                    // cannot leave entries, flags, or a root key resident while the2369                    // public session remains locked.2370                    val candidateSettings = store.loadSettings()2371                    candidateRoot = if (payload.rootKeyB64.isNotBlank()) {2372                        val decodedRoot = unb64(payload.rootKeyB64)2373                        if (decodedRoot.size != VaultCrypto.KEY_SIZE) {2374                            // Do not let a malformed authenticated payload abandon2375                            // this decoded root-key candidate before the outer2376                            // finally block owns it.2377                            VaultCrypto.zero(decodedRoot)2378                            throw IllegalArgumentException("invalid recovery root key")2379                        }2380                        decodedRoot2381                    } else {2382                        generateRecoverableRootKey()2383                    }2384                    stateCommitStarted = true2385                    val adopted = mutateIfCurrentEpoch(expectedEpoch) {2386                        clearSessionStateLocked()2387                        entryList = payload.entries.toMutableList()2388                        authenticatedDuressConfigured = payload.duressConfigured2389                        _duressConfigured.value = payload.duressConfigured2390                        recoveryWordHash = payload.recoveryWordHash2391                        recoveryWordsSet = payload.recoveryWordsSet2392                        rootKey = candidateRoot2393                        candidateRoot = null2394                        _settings.value = candidateSettings2395                        publish()2396                        // This is the authenticated recovery half-unlock boundary:2397                        // only set it after every candidate field is installed.2398                        sessionDataAvailable = true2399                        _isUnlocked.value = false2400                        true2401                    }2402                    if (adopted == true) return@withLock true2403                } catch (_: Exception) {2404                    // Wrong words, malformed payloads, provider failures, and2405                    // settings failures all fall through to the browser-compatible2406                    // root-key escrow.  If the state commit had started, invalidate2407                    // that epoch so no partial candidate survives.2408                    if (stateCommitStarted) {2409                        mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }2410                    }2411                } finally {2412                    plaintext?.let(VaultCrypto::zero)2413                    VaultCrypto.zero(material)2414                    keyBytes?.let(VaultCrypto::zero)2415                    candidateRoot?.let(VaultCrypto::zero)2416                }2417            }2418        }24192420        // Browser-format vault (only the root-key escrow): recover the 32-byte root2421        // key (sync identity) and reset the password; entries return via sync. This2422        // is exactly the browser's recovery semantics (`messages.ts:312-347`).2423        val rootEscrow = slotA.rootKeyEscrow2424        if (rootEscrow != null) {2425            var candidateRoot: ByteArray? = null2426            var stateCommitStarted = false2427            try {2428                candidateRoot = unsealRootKeyEscrow(words, rootEscrow) ?: return false2429                require(candidateRoot!!.size == VaultCrypto.KEY_SIZE) { "invalid recovery root key" }2430                val candidateSettings = store.loadSettings()2431                stateCommitStarted = true2432                val adopted = mutateIfCurrentEpoch(expectedEpoch) {2433                    clearSessionStateLocked()2434                    entryList = mutableListOf()2435                    authenticatedDuressConfigured = false2436                    _duressConfigured.value = false2437                    recoveryWordHash = recoveryWordsHash(words)2438                    recoveryWordsSet = true2439                    rootKey = candidateRoot2440                    candidateRoot = null2441                    _settings.value = candidateSettings2442                    publish()2443                    sessionDataAvailable = true2444                    _isUnlocked.value = false2445                    true2446                }2447                if (adopted == true) return@withLock true2448            } catch (_: Exception) {2449                if (stateCommitStarted) {2450                    mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }2451                }2452            } finally {2453                candidateRoot?.let(VaultCrypto::zero)2454            }2455        }2456        return false2457    }24582459    /**2460     * After [unlockWithRecoveryWords] succeeds, set a brand-new master password:2461     * re-seal slot A under a fresh Argon2id key, rotate the escrow under the same2462     * words, mark the session fully unlocked, and publish. Returns false if called2463     * without a prior successful recovery unlock (no in-memory root key).2464     *2465     * Folds the brief's `resetPasswordWithRecoveryKey(vaultKey, …)` + `unlock(…)`2466     * into one step, since there is no detached vault key here.2467     */2468    suspend fun resetPasswordWithRecoveryWords(2469        words: List<String>,2470        newPassword: String,2471    ): Boolean = mutex.withLock {2472        val expectedEpoch = currentEpoch()2473        // H-03: read rootKey + entryList under stateLock before computing the new2474        // plaintext, then re-publish + swap the derived key under stateLock so a2475        // concurrent lock() cannot straddle the two fences.2476        if (mutateIfCurrentEpoch(expectedEpoch) { rootKey != null } != true) return false2477        val priorA = store.loadSlotA() ?: return false2478        var newKey: ByteArray? = null2479        var plaintext: ByteArray? = null2480        return try {2481            val newSalt = VaultCrypto.generateSalt()2482            newKey = VaultCrypto.deriveKey(newPassword, newSalt)2483            plaintext = VaultCodec.encode(currentPayload())2484            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))2485            // Rebuild both escrows against the recovered session so their salts rotate2486            // with the password reset; fall back to the prior escrows if rebuild fails2487            // (e.g. a checksum-invalid phrase). The same 12 words keep working.2488            val valid = words.size == 12 && findInvalidWords(words).isEmpty()2489            val freshRecovery = if (valid) buildRecoveryEscrow(words) ?: priorA.recoveryEscrow else priorA.recoveryEscrow2490            val freshRootKey = if (valid) buildRootKeyEscrow(words) ?: priorA.rootKeyEscrow else priorA.rootKeyEscrow2491            val next = StoredVault(2492                version = priorA.version,2493                salt = b64(newSalt),2494                blob = blob,2495                recoveryEscrow = freshRecovery,2496                rootKeyEscrow = freshRootKey,2497            )2498            // H-01: see changePassword — both rotations share the same2499            // commit-or-keep-old-key contract so a partial write can't strand2500            // the session on a key that no longer matches disk.2501            val priorB = store.loadSlotB()2502            if (!commitVaultRotation(priorA, priorB, next, expectedEpoch)) return false2503            // H-03 (P1-2 codex): zero the old live key and install the new one2504            // inside the same stateLock critical section so a concurrent lock()2505            // can't observe the in-between.2506            if (mutateIfCurrentEpoch(expectedEpoch) {2507                derivedKey?.let(VaultCrypto::zero)2508                derivedKey = newKey; newKey = null2509                publish()2510                _isUnlocked.value = true2511            } == null) return false2512            true2513        } catch (_: Exception) {2514            false2515        } finally {2516            newKey?.let(VaultCrypto::zero)2517            plaintext?.let(VaultCrypto::zero)2518        }2519    }25202521    /**2522     * Seal the current slot-A plaintext under a key derived from the 12 BIP392523     * recovery [words] (Android offline-restore escrow). IKM is the browser's2524     * `wordsToRootKeyMaterial` (MF-1), AAD is the string [VaultCrypto.AAD_RECOVERY].2525     * Returns null for a checksum-invalid phrase.2526     */2527    private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {2528        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null2529        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2530        var keyBytes: ByteArray? = null2531        var plaintext: ByteArray? = null2532        return try {2533            val salt = VaultCrypto.generateSalt()2534            val recoveryKey = deriveRecoveryKey(material, salt)2535            keyBytes = recoveryKey.encoded2536            plaintext = VaultCodec.encode(currentPayload())2537            val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)2538            RecoveryEscrow(salt = b64(salt), blob = b64(sealed))2539        } finally {2540            VaultCrypto.zero(material)2541            keyBytes?.let(VaultCrypto::zero)2542            plaintext?.let(VaultCrypto::zero)2543        }2544    }25452546    /**2547     * Seal ONLY the 32-byte root key under a key the recovery [words] derive,2548     * byte-for-byte the browser algorithm (MF-1): plaintext = lowercase ASCII hex2549     * of the root key, IKM = `wordsToRootKeyMaterial`, HKDF salt random-16,2550     * info `peach-recovery-v1`, AES-256-GCM AAD = 0x01. The same 12 words unwrap2551     * the same root key on the browser. Returns null with no in-memory root key or2552     * a checksum-invalid phrase.2553     */2554    private fun buildRootKeyEscrow(words: List<String>): RootKeyEscrow? {2555        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null2556        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2557        val rk = mutateState { rootKey?.copyOf() } ?: run {2558            VaultCrypto.zero(material)2559            return null2560        }2561        var keyBytes: ByteArray? = null2562        var plaintext: ByteArray? = null2563        return try {2564            val salt = VaultCrypto.generateSalt()2565            val recoveryKey = deriveRecoveryKey(material, salt)2566            keyBytes = recoveryKey.encoded2567            plaintext = rootKeyToHex(rk).toByteArray(Charsets.US_ASCII)2568            // combined = nonce(12) || ciphertext || tag(16)2569            val combined = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)2570            val nonce = combined.copyOfRange(0, VaultCrypto.NONCE_SIZE)2571            val ctTag = combined.copyOfRange(VaultCrypto.NONCE_SIZE, combined.size)2572            val tag = ctTag.copyOfRange(ctTag.size - 16, ctTag.size)2573            val ct = ctTag.copyOfRange(0, ctTag.size - 16)2574            RootKeyEscrow(salt = b64(salt), wrappedRootKey = b64(ct), nonce = b64(nonce), tag = b64(tag))2575        } finally {2576            VaultCrypto.zero(rk)2577            VaultCrypto.zero(material)2578            keyBytes?.let(VaultCrypto::zero)2579            plaintext?.let(VaultCrypto::zero)2580        }2581    }25822583    /** Unwrap the 32-byte root key from a browser-compatible [escrow]; null on wrong words. */2584    private fun unsealRootKeyEscrow(words: List<String>, escrow: RootKeyEscrow): ByteArray? {2585        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2586        var keyBytes: ByteArray? = null2587        var pt: ByteArray? = null2588        return try {2589            val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))2590            keyBytes = recoveryKey.encoded2591            val combined = unb64(escrow.nonce) + unb64(escrow.wrappedRootKey) + unb64(escrow.tag)2592            pt = VaultCrypto.decrypt(combined, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)2593            hexToRootKey(String(pt, Charsets.US_ASCII))2594        } catch (_: Exception) {2595            null2596        } finally {2597            // M-05: pt is the lowercase hex of the 32-byte root key — i.e. the2598            // IKM-equivalent of the vault identity. material+keyBytes were2599            // already zeroed; pt was leaking.2600            VaultCrypto.zero(material)2601            keyBytes?.let(VaultCrypto::zero)2602            pt?.let(VaultCrypto::zero)2603        }2604    }26052606    /**2607     * Re-seal slot A from the current in-memory state under the live key, carrying2608     * both [recoveryEscrow] and [rootKeyEscrow] onto the written record. Never runs2609     * in decoy mode (recovery is never offered for the decoy) and persists without2610     * a version bump, like the recovery-words metadata write it replaces.2611     */2612    private fun persistSlotAWithEscrows(2613        recoveryEscrow: RecoveryEscrow?,2614        rootKeyEscrow: RootKeyEscrow?,2615        expectedEpoch: Long? = null,2616    ): Boolean {2617        val snapshot = snapshotForPersist(expectedEpoch)2618            ?: throw IllegalStateException("vault_locked_or_stale")2619        if (snapshot.decoy) {2620            VaultCrypto.zero(snapshot.key)2621            return false2622        }2623        try {2624            val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")2625            val plaintext = VaultCodec.encode(snapshot.payload)2626            val blob = try {2627                b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))2628            } finally {2629                // The escrow path used to drop this reference before zeroing it;2630                // keep it live through the fill on both success and failure.2631                VaultCrypto.zero(plaintext)2632            }2633            val next = prior.copy(2634                blob = blob,2635                recoveryEscrow = recoveryEscrow ?: prior.recoveryEscrow,2636                rootKeyEscrow = rootKeyEscrow ?: prior.rootKeyEscrow,2637            )2638            beforeDurableCommit()2639            return withEpochCommit(snapshot.epoch) {2640                if (!store.writeSlotA(next)) return@withEpochCommit false2641                try {2642                    if (!writeMatchingNoiseSlotB(next)) throw java.io.IOException("noise_slot_b_commit_failed")2643                    // H-04: escrow rebuild changes slot A's plaintext size, so re-pad2644                    // the duress slot too. A real decoy is left alone; a fake is2645                    // re-sized to slot A's new ciphertext length.2646                    if (!writeCompanionDuressSlot(next)) throw java.io.IOException("duress_slot_commit_failed")2647                } catch (e: Exception) {2648                    store.writeSlotA(prior)2649                    throw e2650                }2651                true2652            } ?: false2653        } finally {2654            VaultCrypto.zero(snapshot.key)2655        }2656    }26572658    // ---- Internals --------------------------------------------------------26592660    private fun requireUnlocked(): Long {2661        // H-03: read derivedKey atomically with [lock]'s reset; without it,2662        // [lock] from a background lifecycle event can run between this read2663        // and the caller's first state touch.2664        stateLock.lock()2665        try {2666            if (derivedKey == null) throw IllegalStateException("vault_locked")2667            return sessionEpoch2668        } finally {2669            stateLock.unlock()2670        }2671    }26722673    /** A locked or half-adopted session must not expose secret-bearing fields. */2674    private fun isFullyUnlockedLocked(): Boolean = _isUnlocked.value && derivedKey != null26752676    private fun countDuplicateEntriesLocked(): Int {2677        val seen = mutableMapOf<String, VaultEntry>()2678        var duplicates = 02679        for (entry in entryList.filter { it.deletedAt == null }) {2680            val key = entry.duplicateKey()2681            val existing = seen[key]2682            if (existing == null) {2683                seen[key] = entry2684            } else {2685                duplicates++2686                val entryStamp = entry.modifiedAt.takeIf { it > 0 } ?: entry.createdAt2687                val existingStamp = existing.modifiedAt.takeIf { it > 0 } ?: existing.createdAt2688                if (entryStamp > existingStamp) seen[key] = entry2689            }2690        }2691        return duplicates2692    }26932694    private fun VaultEntry.duplicateKey(): String {2695        if (type == "note") return "note|${title.lowercase()}"2696        val passkeyData = passkey2697        if (passkeyData != null) {2698            return "passkey|${passkeyData.rpId.lowercase()}|${passkeyData.userName.lowercase()}"2699        }2700        return "login|${title.lowercase()}|${url.orEmpty().lowercase()}|${username.orEmpty().lowercase()}"2701    }27022703    /**2704     * Capture the current slot pair (and metadata) into the history list.2705     * Returns true when the history write landed, false when it didn't — callers2706     * that depend on the snapshot existing (notably [restoreVaultSnapshot])2707     * must check the result and roll back if it does not.2708     */2709    private fun takeVaultSnapshot(reason: String, expectedEpoch: Long? = null): Boolean {2710        val epoch = expectedEpoch ?: currentEpoch()2711        if (mutateIfCurrentEpoch(epoch) { true } != true) return false2712        val slotA = store.loadSlotA() ?: return false2713        val vaultA = VaultCodec.encodeSlot(slotA)2714        val vaultB = store.loadSlotB() ?: slotA.blob2715        // H-04: capture the duress slot so a restore preserves the at-rest2716        // triad, not just the A/B pair. The duress slot is always present2717        // (real or fake), so loadDecoySlot() returning null is a logic error2718        // — fall through to a fake duress in that case rather than silently2719        // losing the record from the snapshot.2720        val vaultD = store.loadDecoySlot()?.let(VaultCodec::encodeSlot) ?: run {2721            val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 162722            val fakeBlob = ByteArray(target).also(rng::nextBytes)2723            val fakeSalt = VaultCrypto.generateSalt()2724            VaultCodec.encodeSlot(StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob)))2725        }2726        val history = store.loadVaultHistory()2727        val latest = history.snapshots.firstOrNull()2728        if (latest?.vault_a == vaultA && latest.vault_b == vaultB && latest.vault_d == vaultD) return true2729        val entryCount = mutateIfCurrentEpoch(epoch) {2730            if (derivedKey != null && !decoyMode) {2731                bucketEntryCount(entryList.count { it.deletedAt == null })2732            } else {2733                null2734            }2735        } ?: return false2736        return try {2737            val snapshot = VaultSnapshot(2738                id = UUID.randomUUID().toString(),2739                savedAt = System.currentTimeMillis(),2740                reason = reason,2741                vault_a = vaultA,2742                vault_b = vaultB,2743                vault_d = vaultD,2744                entryCount = entryCount,2745            )2746            // P1-4 (codex): return the history-write boolean to callers so a2747            // false return no longer leaves the snapshot out of history while2748            // callers (notably restoreVaultSnapshot) proceed as if it succeeded.2749            withEpochCommit(epoch) {2750                store.writeVaultHistory(2751                    history.copy(snapshots = (listOf(snapshot) + history.snapshots).take(VAULT_HISTORY_MAX)),2752                )2753            } ?: false2754        } catch (_: Exception) {2755            false2756        }2757    }27582759    private fun bucketEntryCount(n: Int): Int = when {2760        n <= 0 -> 02761        n <= 10 -> 102762        n <= 25 -> 252763        n <= 50 -> 502764        n <= 100 -> 1002765        n <= 250 -> 2502766        n <= 500 -> 5002767        else -> ((n + 499) / 500) * 5002768    }27692770    /**2771     * Keep [VaultEntry.last4] in sync with the card number for card entries (MF-3),2772     * so it is stored explicitly and survives the sync wire format rather than being2773     * re-derived at render time. Non-card entries pass through unchanged.2774     *2775     * M-03: never overwrite a stored last4 with null. A card kept only as last42776     * (e.g. after a PeachScript import that had no PAN) must keep that value;2777     * re-deriving from an absent cardNumber would silently zero the field.2778     */2779    private fun withDerivedLast4(entry: VaultEntry): VaultEntry {2780        if (!entry.isCard()) return entry2781        val digits = entry.cardNumber?.filter { it.isDigit() } ?: ""2782        val derived = if (digits.length >= 4) digits.takeLast(4) else null2783        return entry.copy(last4 = derived ?: entry.last4)2784    }27852786    /**2787     * On unlock, hard-delete trashed entries older than the retention window.2788     * A null or non-positive [VaultSettings.trashRetentionDays] means "never"2789     * (the app's "Never" option), so nothing is purged. Persists without a2790     * version bump and without touching the publish state (caller publishes).2791     */2792    private fun autoPurgeExpiredTrash() {2793        val days = _settings.value.trashRetentionDays ?: return2794        if (days <= 0) return2795        val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L2796        val before = entryList.size2797        entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }2798        if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }2799    }28002801    /**2802     * Browser parity (P1): merge orphaned passkey-only entries into matching2803     * login entries that share the same registrable domain. A passkey-only2804     * entry has passkey fields (rpId + credentialId) but no password. Runs on2805     * unlock so consolidation is idempotent and cheap.2806     */2807    private fun consolidatePasskeyEntries() {2808        val passkeyOnly = entryList.filter { entry ->2809            entry.deletedAt == null &&2810                entry.isLogin() &&2811                entry.password.isNullOrBlank() &&2812                !entry.rpId.isNullOrBlank() &&2813                !entry.credentialId.isNullOrBlank()2814        }2815        if (passkeyOnly.isEmpty()) return2816        var changed = false2817        val now = System.currentTimeMillis()2818        for (pkEntry in passkeyOnly) {2819            val rpId = pkEntry.rpId ?: continue2820            val target = entryList.firstOrNull { candidate ->2821                candidate.deletedAt == null &&2822                    candidate.id != pkEntry.id &&2823                    candidate.isLogin() &&2824                    candidate.passkey == null &&2825                    candidate.credentialId.isNullOrBlank() &&2826                    !candidate.password.isNullOrBlank() &&2827                    listOfNotNull(candidate.url, *candidate.additionalUrls.orEmpty().toTypedArray())2828                        .any { com.peachpasswords.shared.extractDomain(it) == rpId }2829            } ?: continue2830            val idx = entryList.indexOfFirst { it.id == target.id }2831            if (idx < 0) continue2832            entryList[idx] = target.copy(2833                rpId = pkEntry.rpId,2834                rpName = pkEntry.rpName ?: target.rpName,2835                credentialId = pkEntry.credentialId,2836                publicKeyCose = pkEntry.publicKeyCose,2837                privateKeyJwk = pkEntry.privateKeyJwk,2838                userHandle = pkEntry.userHandle,2839                userName = pkEntry.userName,2840                userDisplayName = pkEntry.userDisplayName,2841                algorithm = pkEntry.algorithm,2842                signCount = pkEntry.signCount,2843                lastUsedAt = pkEntry.lastUsedAt,2844                modifiedAt = now,2845            )2846            // Soft-delete the orphan so it lands in trash (recoverable).2847            val pkIdx = entryList.indexOfFirst { it.id == pkEntry.id }2848            if (pkIdx >= 0) entryList[pkIdx] = pkEntry.copy(deletedAt = now)2849            changed = true2850        }2851        if (changed) runCatching { persistSlotA(bumpVersion = false) }2852    }28532854    /** The slot-A plaintext envelope for the current in-memory session. */2855    private fun currentPayload(): VaultPayload = mutateState { currentPayloadLocked() }28562857    private fun currentPayloadLocked(): VaultPayload =2858        VaultPayload(2859            entries = entryList.toList(),2860            duressConfigured = authenticatedDuressConfigured,2861            rootKeyB64 = rootKey?.let(::b64) ?: "",2862            recoveryWordHash = recoveryWordHash,2863            recoveryWordsSet = recoveryWordsSet,2864        )28652866    /**2867     * Adopt the payload's root key, lazily minting one for legacy payloads.2868     * A freshly-minted key is persisted WITHOUT bumping the version — adopting2869     * a root key is not a mutation paired devices should sync against.2870     */2871    private fun ensureRootKey(payload: VaultPayload) {2872        if (payload.rootKeyB64.isNotBlank()) {2873            rootKey = unb64(payload.rootKeyB64)2874            return2875        }2876        rootKey = generateRecoverableRootKey()2877        runCatching { persistSlotA(bumpVersion = false) }2878    }28792880    private fun publish() {2881        _entries.value = entryList.filter { it.deletedAt == null }2882    }28832884    private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {2885        var plaintext = VaultCodec.encode(currentPayload())2886        return try {2887            val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))2888            StoredVault(version = LEGACY_ANDROID_SLOT_VERSION, salt = b64(salt), blob = blob)2889        } finally {2890            // M-05: full vault plaintext is allocated here once per createVault.2891            // Zeroing in finally keeps the transient copy off the heap after the2892            // caller either succeeds or rolls back via lock().2893            VaultCrypto.zero(plaintext)2894        }2895    }28962897    private fun writeMatchingNoiseSlotB(slotA: StoredVault): Boolean {2898        // Size the noise so its base64 length matches slot A's blob (MN-1): with the2899        // plaintext now bucket-padded, an at-rest observer sees two equal-length slots2900        // and cannot pick the real one by size. b64(N bytes) ≈ N*4/3 chars.2901        val approxBytes = (slotA.blob.length * 3 / 4).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)2902        val noise = ByteArray(approxBytes).also(rng::nextBytes)2903        return store.writeSlotB(b64(noise))2904    }29052906    /** H-04: the ciphertext length slot A is using right now, so the duress2907     *  slot's blob can match it on disk. AES-GCM is a stream cipher — plaintext2908     *  length equals ciphertext length, so this also matches slot A's plaintext. */2909    private fun matchingCiphertextLength(slotA: StoredVault): Int =2910        (unb64(slotA.blob).size - VaultCrypto.NONCE_SIZE - 16).coerceAtLeast(0)29112912    /** H-04: a decoy-shaped StoredVault with a random blob of [matchingCiphertextLength]2913     *  bytes. Replaces a real decoy when the user clears duress, and is the2914     *  initial duress slot when no decoy is configured — so the record's2915     *  PRESENCE on disk is independent of authenticatedDuressConfigured, and its SIZE2916     *  matches slot A's blob length. */2917    private fun writeFakeDuressSlot(slotA: StoredVault): Boolean {2918        val blobSize = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 162919        val fakeBlob = ByteArray(blobSize).also(rng::nextBytes)2920        val fakeSalt = VaultCrypto.generateSalt()2921        return store.writeDecoySlot(StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob)))2922    }29232924    /** H-04: keep the duress record present on every persist. A real decoy is2925     *  left alone (it was padded at setDuressPassphrase time, and we don't have2926     *  the duress key here to re-seal it) — VaultStore re-pads both slot2927     *  records to the longer of the two on every write, which is what keeps the2928     *  pair the same length after slot A crosses a padding bucket2929     *  (PAI-2026-004). No real decoy → a fresh fake of slot A's size. */2930    private fun writeCompanionDuressSlot(slotA: StoredVault): Boolean {2931        val isConfigured = mutateState { authenticatedDuressConfigured }2932        return if (isConfigured) true else writeFakeDuressSlot(slotA)2933    }29342935    /**2936     * H-04: convert a browser-shaped duress slot to Android StoredVault2937     * without decrypting. The browser seals slot "b" under the duress2938     * passphrase; decrypting with the main password silently drops it.2939     * Concatenates nonce‖ciphertext‖tag into Android's blob and re-encodes2940     * the salt from hex to base64.2941     */2942    private fun browserDuressPassthrough(b: BrowserSlotA): StoredVault {2943        val salt = unhex(b.salt)2944        val nonce = unhex(b.nonce)2945        val ct = unhex(b.ciphertext)2946        val tag = unhex(b.tag)2947        val blob = ByteArray(nonce.size + ct.size + tag.size).also {2948            System.arraycopy(nonce, 0, it, 0, nonce.size)2949            System.arraycopy(ct, 0, it, nonce.size, ct.size)2950            System.arraycopy(tag, 0, it, nonce.size + ct.size, tag.size)2951        }2952        return StoredVault(version = LEGACY_ANDROID_SLOT_VERSION, salt = b64(salt), blob = b64(blob))2953    }2954    /** Re-seal slot A from the current in-memory state under the live key. */2955    private fun persistSlotA(2956        bumpVersion: Boolean,2957        snapshotReason: String? = "local_save",2958        expectedEpoch: Long? = null,2959    ): Boolean {2960        val snapshot = snapshotForPersist(expectedEpoch)2961            ?: throw IllegalStateException("vault_locked_or_stale")2962        return try {2963            // Decoy sessions persist to the decoy slot only — never touch the real slot A.2964            if (snapshot.decoy) {2965                val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")2966                val plaintext = VaultCodec.encode(snapshot.payload)2967                val blob = try {2968                    b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_B))2969                } finally {2970                    // Keep the last reference alive until the zero, including the2971                    // successful encrypt path (M-05).2972                    VaultCrypto.zero(plaintext)2973                }2974                beforeDurableCommit()2975                return withEpochCommit(snapshot.epoch) {2976                    store.writeDecoySlot(prior.copy(version = CURRENT_ANDROID_SLOT_VERSION, blob = blob))2977                } ?: false2978            }2979            val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")2980            // H-01: captured BEFORE the noise write so a stamp failure can restore2981            // the prior slot B alongside the prior slot A. Slot B is always2982            // overwritten by writeMatchingNoiseSlotB below, so a stamp failure2983            // leaves (new A, new B, old version) on disk — partial commit.2984            val priorB = store.loadSlotB()2985            beforeDurableCommit()2986            if (snapshotReason != null && !takeVaultSnapshot(snapshotReason, snapshot.epoch)) return false2987            val plaintext = VaultCodec.encode(snapshot.payload)2988            val blob = try {2989                b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))2990            } finally {2991                // Do not drop [plaintext] before fill(0): the serialized vault2992                // contains every entry password and is the primary M-05 target.2993                VaultCrypto.zero(plaintext)2994            }2995            val next = prior.copy(blob = blob)2996            // The epoch check and the entire A/B/D/version commit share one brief2997            // stateLock critical section. lock() either wins before this block or2998            // waits until the already-committed write is complete; it can never2999            // clear the session between the check and the durable write.3000            withEpochCommit(snapshot.epoch) {3001                if (!store.writeSlotA(next)) return@withEpochCommit false3002                try {3003                    if (!writeMatchingNoiseSlotB(next)) throw java.io.IOException("noise_slot_b_commit_failed")3004                    // H-04: duress slot stays present (real one untouched, fake one3005                    // re-padded to slot A's current size on every persist).3006                    if (!writeCompanionDuressSlot(next)) throw java.io.IOException("duress_slot_commit_failed")3007                    if (bumpVersion) store.stampLocalMutation()3008                } catch (e: Exception) {3009                    store.writeSlotA(prior)3010                    if (priorB != null) runCatching { store.writeSlotB(priorB) }3011                    throw e3012                }3013                true3014            } ?: false3015        } finally {3016            // Snapshot keys are copies, so lock() may zero the live key while this3017            // operation is still deriving/encrypting; always scrub our copy too.3018            VaultCrypto.zero(snapshot.key)3019        }3020    }30213022    /**3023     * H-01: durably commit a slot-A rotation by writing slot A, its3024     * size-matched noise slot B, and the local-mutation stamp in order. Any3025     * failure rolls the previously-committed steps back so the at-rest pair3026     * matches what was there before the call. Returns true only when every3027     * step succeeded — callers must NOT swap their session key on false.3028     */3029    private fun commitVaultRotation(3030        priorA: StoredVault,3031        priorB: String?,3032        nextA: StoredVault,3033        expectedEpoch: Long,3034    ): Boolean {3035        beforeDurableCommit()3036        return withEpochCommit(expectedEpoch) {3037            if (!store.writeSlotA(nextA)) return@withEpochCommit false3038            // P1-1 (codex): the noise write's boolean AND any thrown exception from3039            // it must trigger rollback; previously a throw from writeMatchingNoiseSlotB3040            // escaped the helper and left slot A committed.3041            try {3042                if (!writeMatchingNoiseSlotB(nextA)) throw java.io.IOException("noise_slot_b_commit_failed")3043                // H-04: a password rotation changes slot A's plaintext size (new3044                // salt → re-encrypted blob), so the duress slot must be re-padded3045                // alongside. writeCompanionDuressSlot leaves a real decoy alone3046                // and re-emits a fake of slot A's size otherwise.3047                if (!writeCompanionDuressSlot(nextA)) throw java.io.IOException("duress_slot_commit_failed")3048                store.stampLocalMutation()3049            } catch (_: Exception) {3050                rollbackRotation(priorA, priorB)3051                return@withEpochCommit false3052            }3053            true3054        } ?: false3055    }30563057    /**3058     * Best-effort undo of the writes [commitVaultRotation] may have committed.3059     * Each step runs independently — a failed rollback must not mask the3060     * original commit failure. Log is a throwing stub off-device.3061     */3062    private fun rollbackRotation(priorA: StoredVault, priorB: String?) {3063        val failures = mutableListOf<String>()3064        runCatching { if (!store.writeSlotA(priorA)) failures += "writeSlotA returned false" }3065            .onFailure { failures += "writeSlotA: $it" }3066        if (priorB != null) {3067            runCatching { if (!store.writeSlotB(priorB)) failures += "writeSlotB returned false" }3068                .onFailure { failures += "writeSlotB: $it" }3069        }3070        if (failures.isNotEmpty()) runCatching { Log.w("PeachVault", "vault rotation rollback incomplete: $failures") }3071    }30723073    /** Persist a local mutation, rolling the in-memory list back on failure. */3074    private fun persistOrRollback(rollback: MutableList<VaultEntry>, expectedEpoch: Long) {3075        try {3076            if (!persistSlotA(bumpVersion = true, expectedEpoch = expectedEpoch)) {3077                mutateIfCurrentEpoch(expectedEpoch) { entryList = rollback }3078                throw IllegalStateException("storage_write_failed")3079            }3080        } catch (e: Exception) {3081            mutateIfCurrentEpoch(expectedEpoch) { entryList = rollback }3082            throw e3083        }3084        // A lock can win in the small interval after the durable commit and3085        // before publication. The epoch check prevents pre-lock entries from3086        // being republished into a newly locked (or newly unlocked) session.3087        mutateIfCurrentEpoch(expectedEpoch) { publish() }3088        runCatching { LockedSyncSpoolHooks.refresh(this) }3089    }3090}