VaultRepository.kt

149.4 KB · raw

1package com.peachpasswords.vault23import kotlinx.coroutines.flow.MutableStateFlow4import kotlinx.coroutines.flow.StateFlow5import kotlinx.coroutines.flow.asStateFlow6import kotlinx.coroutines.sync.Mutex7import kotlinx.coroutines.sync.withLock8import java.security.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 * Slot-A key rotation signal.63 *64 * Every site that re-seals slot A under a different Argon2id key must fire this:65 * the PIN and biometric escrows each wrap a copy of the OLD key, and a stale copy66 * passes the hardware verifier and then fails the slot AEAD — so the user is told67 * the credential was accepted and then that the vault key is wrong. Registered68 * once in [com.peachpasswords.PeachApplication] (PB-26-126).69 */70internal object VaultKeyRotationHooks {71    @Volatile var onRotated: () -> Unit = {}72}7374/**75 * In-memory vault session backed by [VaultStore]. Faithful port of the browser76 * `vault.ts` semantics that matter for correctness:77 *78 *  - Two-slot at rest: slot A is the real (encrypted) vault, slot B a size-matched79 *    noise blob so a fresh install shows two similarly-shaped records.80 *  - Every modifiedAt/deletedAt uses [VaultCrypto.monotonicEntryTimestamp] so a81 *    deletion always wins last-write-wins against an in-flight edit.82 *  - Local writes bump the version counter; sync-applied writes do NOT (so a83 *    sync round never cascades into another outbound sync).84 *  - add/update/delete roll back in-memory state if the disk write fails.85 *  - destroyVault never touches the Pro license (separate store).86 */87@Singleton88class VaultRepository @Inject constructor(89    private val store: VaultStorage,90) {91    private val slotRollback = VaultSlotRollback(store)92    private val mutex = Mutex()93    // H-03: lock() and requireUnlocked() cannot take [mutex] from non-suspend94    // callers (ProcessLifecycleOwner, ViewModels, VaultLockTimer). This sync95    // lock guards ONLY the brief read/write of derivedKey/rootKey/entryList so96    // lock() can serialize against an in-flight suspend op without blocking on97    // Argon2id or store I/O. Suspend ops hold [mutex] for their full body and98    // take [stateLock] only around the state-write portions. Acquisition order99    // is always mutex → stateLock.100    private val stateLock = ReentrantLock()101    private val rng = SecureRandom()102103    /**104     * Monotonic session generation.  [lock] advances this before clearing any105     * secret state; work that captured the previous generation is therefore106     * stale even if it is still running its (non-suspending) storage step.107     */108    private var sessionEpoch: Long = 0L109110    private fun nextSessionEpoch(epoch: Long): Long =111        if (epoch == Long.MAX_VALUE) 0L else epoch + 1L112113    /** Test seam for deterministic "lock while waiting to commit" races. */114    @VisibleForTesting115    internal var beforeDurableCommit: () -> Unit = {}116117    /** Test seam after a failed Codex rollback, while the epoch fence is held. */118    @VisibleForTesting119    internal var afterCodexRollback: () -> Unit = {}120121    /**122     * Run [block] with [stateLock] held. Used to fence the small state-write123     * portions of suspend operations against [lock] and [requireUnlocked]124     * racing from another thread.125     */126    private inline fun <T> mutateState(block: () -> T): T {127        stateLock.lock()128        return try { block() } finally { stateLock.unlock() }129    }130131    /** Run a durable commit only while the session generation is still live. */132    private inline fun <T> withEpochCommit(epoch: Long, block: () -> T): T? {133        stateLock.lock()134        return try {135            if (sessionEpoch != epoch) null else block()136        } finally {137            stateLock.unlock()138        }139    }140141    /** Test seam for a caller that must stage work before the epoch fence. */142    @VisibleForTesting143    internal var beforeSessionEpochCommit: () -> Unit = {}144145    /**146     * Test seam for the narrower H-03 race: a suspend mutation has authenticated147     * the session and staged its candidate state, but has not yet entered the148     * epoch-fenced in-memory write. Production callers leave this as a no-op.149     */150    @VisibleForTesting151    internal var beforeSessionStateMutation: () -> Unit = {}152153    /**154     * Run an external session-bound commit while the repository's epoch fence is155     * held. The callback is deliberately non-suspending: [lock] cannot advance156     * the epoch until the whole external batch has reached its linearization157     * point.158     */159    internal fun <T> withSessionEpochCommit(epoch: Long, block: () -> T): T? {160        beforeSessionEpochCommit()161        return withEpochCommit(epoch, block)162    }163164    private fun currentEpoch(): Long = mutateState { sessionEpoch }165166    private inline fun <T> mutateIfCurrentEpoch(epoch: Long, block: () -> T): T? =167        mutateState { if (sessionEpoch == epoch) block() else null }168169    /** Invoke the pre-state-write seam, then linearize only in the same epoch. */170    private inline fun <T> mutateCurrentSession(epoch: Long, block: () -> T): T? {171        beforeSessionStateMutation()172        return mutateIfCurrentEpoch(epoch, block)173    }174175    private data class PersistSnapshot(176        val epoch: Long,177        val key: ByteArray,178        val payload: VaultPayload,179        val decoy: Boolean,180    )181182    /** Copy all session material while fenced; callers own and must zero [key]. */183    private fun snapshotForPersist(expectedEpoch: Long? = null): PersistSnapshot? = mutateState {184        if (expectedEpoch != null && sessionEpoch != expectedEpoch) return@mutateState null185        val liveKey = derivedKey ?: return@mutateState null186        PersistSnapshot(187            epoch = sessionEpoch,188            key = liveKey.copyOf(),189            payload = currentPayloadLocked(),190            decoy = decoyMode,191        )192    }193194    private var derivedKey: ByteArray? = null195    private var rootKey: ByteArray? = null196    private var entryList: MutableList<VaultEntry> = mutableListOf()197    private var authenticatedDuressConfigured: Boolean = false198    private var recoveryWordHash: String? = null199    private var recoveryWordsSet: Boolean = false200    /** True when an authenticated vault payload is available for local reads. */201    private var sessionDataAvailable: Boolean = false202    /** True while a decoy (duress) session is active — persistence targets the decoy slot. */203    private var decoyMode: Boolean = false204205    private val _isUnlocked = MutableStateFlow(false)206    val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()207208    private val _duressConfigured = MutableStateFlow(false)209    /** Authenticated payload state; never loaded from plaintext settings. */210    val duressConfigured: StateFlow<Boolean> = _duressConfigured.asStateFlow()211212213    /**214     * UI-only gate for sync-retained background mode. The vault stays unlocked215     * in memory (sync can proceed) but the UI shows the lock screen until the216     * user authenticates on resume. Cleared by a full [lock] or an explicit217     * [clearUiGate] from the lock screen.218     */219    private val _uiGateLocked = MutableStateFlow(false)220    val uiGateLocked: StateFlow<Boolean> = _uiGateLocked.asStateFlow()221222    private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())223    /** Active (non-deleted) entryList. */224    val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()225226    // Settings live in plain prefs, not inside the sealed vault — they hold no227    // secrets — so they are readable before unlock. Loading them here keeps the228    // lock screen at the user's chosen appearance instead of the defaults, which229    // otherwise snap to the real values the moment they authenticate.230    private val _settings = MutableStateFlow(store.loadSettings())231    val settings: StateFlow<VaultSettings> = _settings.asStateFlow()232233    /** Clear every in-memory session field while [stateLock] is held. */234    private fun clearSessionStateLocked() {235        derivedKey?.let(VaultCrypto::zero)236        rootKey?.let(VaultCrypto::zero)237        derivedKey = null238        rootKey = null239        entryList = mutableListOf()240        authenticatedDuressConfigured = false241        _duressConfigured.value = false242        recoveryWordHash = null243        recoveryWordsSet = false244        sessionDataAvailable = false245        decoyMode = false246        _settings.value = store.loadSettings()247        _entries.value = emptyList()248        _isUnlocked.value = false249    }250251    fun hasVault(): Boolean = store.hasVault()252253    // ---- Codex (printed paper backup) -------------------------------------254255    /**256     * The at-rest slot pair as base64 JSON `{"a": <StoredVault>, "b": <StoredVault>}` — the257     * Codex payload's vaultBlob. "b" is the duress slot (matching the browser's258     * A/B naming where slot B is the duress decoy); the noise slot is local-only259     * and never crosses devices. Restorable on any device that has the master260     * password. Null when no vault exists.261     */262    fun codexVaultBlobBase64(): String? {263        val slotA = store.loadSlotA() ?: return null264        // H-04: duress slot is always present after createVault (real or fake),265        // so the wrapper can rely on it being loadable.266        val slotD = store.loadDecoySlot() ?: return null267        val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)},"b":${VaultCodec.encodeSlot(slotD)}}"""268        return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))269    }270271    /**272     * Replace the local vault from a Codex blob, then unlock with [password].273     * Writes slot A (and a size-matched noise slot B) before unlocking so the274     * restored vault is at rest exactly as a freshly-created one would be.275     */276    /** A slot is stored either as a JSON string (browser) or inline object (Android). */277    private fun JsonElement?.asSlotJson(): String? = when {278        this == null || this is JsonNull -> null279        this is JsonPrimitive && isString -> content280        else -> toString()281    }282283    suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {284        val expectedEpoch = currentEpoch()285        var candidateKey: ByteArray? = null286        var plaintext: ByteArray? = null287        return try {288            val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)289            // Parsed as JSON, not matched with a regex. The wrapper is290            // `{ "a": <slot>, "b": <slot|null> }` and the browser — which291            // generates most real Codexes — writes each slot as a JSON292            // *string*, with "b" present. A regex looking for an object293            // literal under "a" at the very end of the wrapper matches294            // neither of those, so every browser-generated Codex failed here295            // with "invalid_codex_blob" after decoding perfectly.296            val wrapper = CodexJson.parseToJsonElement(wrapperJson) as? JsonObject297                ?: return UnlockResult.Error("invalid_codex_blob")298            val slotJson = wrapper["a"].asSlotJson() ?: return UnlockResult.Error("invalid_codex_blob")299            // A Codex printed from the browser carries a browser-shaped slot,300            // which is the common case — most Codexes are printed there. It is301            // translated to Android's shape (see BrowserSlot) rather than302            // rejected. A translation failure is a wrong password, not a bad303            // blob: the codes decoded fine, the password just didn't open them.304            val slotA = VaultCodec.decodeSlot(slotJson)305                ?: BrowserSlot.parse(slotJson)?.let {306                    BrowserSlot.toAndroidSlot(it, password) ?: return UnlockResult.WrongPassword307                }308                ?: return UnlockResult.Error("invalid_codex_blob")309            // C-01: authenticate the candidate ENTIRELY in memory before touching310            // storage. VaultCodec.decodeSlot is structural — an Android-shaped311            // Codex parses under ANY password — so writing slot A first and312            // unlocking afterwards destroyed the device's existing vault every313            // time the user mistyped the password.314            candidateKey = VaultCrypto.deriveKey(password, unb64(slotA.salt))315            plaintext = decryptSlotABlob(slotA, candidateKey)316            // LV-1: a Codex printed from a vault sealed before NFC normalization317            // opens only under the raw password bytes. unlockLocked used to supply318            // this fallback; authenticating up front here has to keep it, or those319            // Codexes become unrestorable.320            if (plaintext == null && password != Normalizer.normalize(password, Normalizer.Form.NFC)) {321                VaultCrypto.zero(candidateKey)322                candidateKey = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))323                plaintext = decryptSlotABlob(slotA, candidateKey)324            }325            if (plaintext == null) return UnlockResult.WrongPassword326            val payload = try {327                VaultCodec.decode(plaintext)328            } catch (_: Exception) {329                return UnlockResult.Error("invalid_codex_blob")330            }331332            val priorA = store.loadSlotA()333            val priorB = store.loadSlotB()334            val priorD = store.loadDecoySlot()335            // Carry the real duress slot across when the Codex has one — the336            // browser writes "b" as its duress-shaped slot, and dropping it337            // here would silently destroy a configured decoy.338            // H-04: write browser B into the duress slot (not the noise slot),339            // translating browser-shaped slots to Android's StoredVault shape.340            val codexDuressJson = wrapper["b"].asSlotJson()341            val codexDuress: StoredVault? = codexDuressJson?.let {342                VaultCodec.decodeSlot(it)?.let { slot ->343                    if (slot.version != LEGACY_ANDROID_SLOT_VERSION && slot.version != CURRENT_ANDROID_SLOT_VERSION) null else slot344                } ?: BrowserSlot.parse(it)?.let { b ->345                    browserDuressPassthrough(b)346                }347            }348349            beforeDurableCommit()350            val committed = runCatching {351                withEpochCommit(expectedEpoch) {352                    try {353                        // Keep every slot write, including the inverse, under the354                        // same epoch fence. Releasing stateLock after a partial355                        // write and reacquiring it for rollback lets lock() advance356                        // the epoch in between and strand the incoming slot A.357                        if (!store.writeSlotA(slotA)) throw java.io.IOException("slot_a_commit_failed")358                        // Noise slot is always size-matched to slot A — local-only,359                        // never written from a Codex.360                        if (!writeMatchingNoiseSlotB(slotA)) throw IllegalStateException("noise_slot_commit_failed")361                        // H-04: duress slot always present; real one from the Codex or362                        // a fake the size of slot A.363                        val duressOk = if (codexDuress != null) {364                            store.writeDecoySlot(codexDuress)365                        } else {366                            writeFakeDuressSlot(slotA)367                        }368                        if (!duressOk) throw IllegalStateException("duress_slot_commit_failed")369                        store.stampLocalMutation()370                        true371                    } catch (_: Exception) {372                        reportRollbackFailures(slotRollback.restoreTriad(priorA, priorB, priorD))373                        // Keep the fence held through the final rollback374                        // observation. A concurrent lock() may queue here, but375                        // cannot invalidate the restored A/B/D triad.376                        afterCodexRollback()377                        false378                    }379                } ?: false380            }.getOrDefault(false)381            if (!committed) {382                return UnlockResult.Error("storage_write_failed")383            }384385            val ownedKey = candidateKey!!386            candidateKey = null // the session owns the key from here on387            VaultKeyRotationHooks.onRotated()388            adoptSlotA(ownedKey, payload, expectedEpoch)389        } catch (e: Exception) {390            // A raw kotlinx parse error ("Unexpected JSON token at offset N")391            // reaching the user says nothing about WHICH json failed — the392            // wrapper, or the payload decrypted out of it. Codex screens are393            // FLAG_SECURE so this can't be screenshotted either. Debug builds394            // log the structure around the failure; alphanumerics are masked so395            // no ciphertext or vault content lands in a log.396            if (BuildConfig.DEBUG) Log.w("PeachCodex", codexFailureShape(vaultBlobBase64, e))397            UnlockResult.Error(e.message ?: "restore_failed")398        } finally {399            plaintext?.let(VaultCrypto::zero)400            candidateKey?.let(VaultCrypto::zero)401        }402    }403404    /** Slot-A plaintext under [key], or null when the GCM tag fails (wrong password). */405    private fun decryptSlotABlob(slot: StoredVault, key: ByteArray): ByteArray? =406        runCatching { VaultCrypto.decrypt(unb64(slot.blob), key, VaultCrypto.AAD_SLOT_A) }.getOrNull()407408    private fun reportRollbackFailures(failures: List<String>) {409        // Log is a throwing stub off-device, and a failed log must never mask410        // the rollback result the caller is about to report.411        if (failures.isNotEmpty()) runCatching { Log.w("PeachCodex", "codex rollback incomplete: $failures") }412    }413414    /** Debug-only: structure of a failed Codex restore, with content masked. */415    private fun codexFailureShape(vaultBlobBase64: String, e: Exception): String = runCatching {416        val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)417        val offset = Regex("offset (\\d+)").find(e.message.orEmpty())?.groupValues?.get(1)?.toIntOrNull()418        val window = offset?.let {419            val from = (it - 40).coerceAtLeast(0)420            val to = (it + 40).coerceAtMost(wrapperJson.length)421            wrapperJson.substring(from, to).replace(Regex("[A-Za-z0-9+/=_-]"), "x")422        }423        val wrapper = runCatching { CodexJson.parseToJsonElement(wrapperJson) as? JsonObject }.getOrNull()424        val slot = wrapper?.get("a")425        buildString {426            append("codex restore failed: ").append(e::class.simpleName).append(": ").append(e.message)427            append(" | blobBase64=").append(vaultBlobBase64.length)428            append(" wrapperChars=").append(wrapperJson.length)429            append(" wrapperParses=").append(wrapper != null)430            append(" keys=").append(wrapper?.keys)431            append(" slotAKind=").append(432                when {433                    slot == null -> "absent"434                    slot is JsonPrimitive && slot.isString -> "string"435                    slot is JsonObject -> "object:" + slot.keys436                    else -> slot::class.simpleName437                },438            )439            if (window != null) append(" masked@").append(offset).append("=").append(window)440        }441    }.getOrElse { "codex restore failed: ${e.message} (shape unavailable: $it)" }442443    suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {444        val expectedEpoch = currentEpoch()445        var key: ByteArray? = null446        return try {447            val salt = VaultCrypto.generateSalt()448            key = VaultCrypto.deriveKey(password, salt)449            if (mutateIfCurrentEpoch(expectedEpoch) {450                entryList = mutableListOf()451                authenticatedDuressConfigured = false452                _duressConfigured.value = false453                recoveryWordHash = null454                recoveryWordsSet = false455                decoyMode = false456                sessionDataAvailable = false457                rootKey = generateRecoverableRootKey()458            } == null) return CreateVaultResult.Error("stale_create")459            // M-04: the fields above have to be live before sealSlotA, since it460            // seals currentPayload(). That stages a root key the session would461            // otherwise keep after a failed create — [lock] discards the whole462            // staged session on every non-success exit below.463            val slotA = sealSlotA(key!!, salt)464            // P1-3 (codex): every later step must roll the slot pair back if it465            // fails — leaving a half-built vault is worse than refusing to make it.466            beforeDurableCommit()467            val created = withEpochCommit(expectedEpoch) {468                if (!store.writeSlotA(slotA)) return@withEpochCommit false469                try {470                    if (!writeMatchingNoiseSlotB(slotA)) throw java.io.IOException("noise_slot_b_commit_failed")471                    // H-04: duress slot must be present from the start so its472                    // existence on disk is independent of authenticatedDuressConfigured.473                    if (!writeFakeDuressSlot(slotA)) throw java.io.IOException("duress_slot_commit_failed")474                    store.stampLocalMutation()475                    if (!store.writeSettings(_settings.value)) throw java.io.IOException("settings_commit_failed")476                    true477                } catch (_: Exception) {478                    // Half-built vault on disk is worse than no vault — refuse to479                    // create if any step past slot A fails.480                    store.clearVault()481                    false482                }483            } ?: false484            if (!created) {485                lock()486                return CreateVaultResult.Error("storage_write_failed")487            }488            val sessionKey = key ?: return CreateVaultResult.Error("create_key_missing")489            if (mutateIfCurrentEpoch(expectedEpoch) {490                derivedKey = sessionKey491                key = null492                publish()493                _isUnlocked.value = true494                sessionDataAvailable = true495                sessionEpoch = nextSessionEpoch(sessionEpoch)496            } == null) return CreateVaultResult.Error("stale_create")497            CreateVaultResult.Success498        } catch (e: Exception) {499            lock()500            CreateVaultResult.Error(e.message ?: "create_failed")501        } finally {502            key?.let(VaultCrypto::zero)503        }504    }505506    suspend fun createVaultFromRootKey(password: String, rootKeyHex: String): AdoptVaultResult = mutex.withLock {507        val expectedEpoch = currentEpoch()508        if (password.isEmpty()) return AdoptVaultResult.Error("ADOPT_INVALID_PASSWORD")509        if (store.hasVault()) return AdoptVaultResult.Error("ADOPT_VAULT_ALREADY_EXISTS")510        if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {511            return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars")512        }513        var adoptedRootKey: ByteArray? = null514        var nextDerivedKey: ByteArray? = null515        var sessionRootKey: ByteArray? = null516        return try {517            adoptedRootKey = hexToRootKey(rootKeyHex)518            if (adoptedRootKey.size != VaultCrypto.KEY_SIZE) {519                return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes")520            }521            val vaultId = com.peachpasswords.sync.computeVaultId(adoptedRootKey)522            val salt = VaultCrypto.generateSalt()523            nextDerivedKey = VaultCrypto.deriveKey(password, salt)524            sessionRootKey = adoptedRootKey.copyOf()525            val payload = VaultPayload(526                entries = emptyList(),527                duressConfigured = false,528                rootKeyB64 = b64(sessionRootKey),529                recoveryWordHash = null,530                recoveryWordsSet = false,531            )532            val plaintext = VaultCodec.encode(payload)533            val blob = try {534                b64(VaultCrypto.encrypt(plaintext, nextDerivedKey, VaultCrypto.AAD_SLOT_A))535            } finally {536                VaultCrypto.zero(plaintext)537            }538            val slotA = StoredVault(version = 1, salt = b64(salt), blob = blob)539            // P1-3 (codex): same partial-commit guard as createVault — any failure540            // past slot A wipes the half-built vault and refuses adoption.541            beforeDurableCommit()542            val created = withEpochCommit(expectedEpoch) {543                if (!store.writeSlotA(slotA)) return@withEpochCommit false544                try {545                    if (!writeMatchingNoiseSlotB(slotA)) throw java.io.IOException("noise_slot_b_commit_failed")546                    // H-04: duress slot must be present from the start so its547                    // existence on disk is independent of authenticatedDuressConfigured.548                    if (!writeFakeDuressSlot(slotA)) throw java.io.IOException("duress_slot_commit_failed")549                    store.stampLocalMutation()550                    if (!store.writeSettings(_settings.value)) throw java.io.IOException("settings_commit_failed")551                    true552                } catch (_: Exception) {553                    store.clearVault()554                    false555                }556            } ?: false557            if (!created) return AdoptVaultResult.Error("storage_write_failed")558559            val adopted = mutateIfCurrentEpoch(expectedEpoch) {560                val previousDerivedKey = derivedKey561                val previousRootKey = rootKey562                derivedKey = nextDerivedKey563                rootKey = sessionRootKey564                nextDerivedKey = null565                sessionRootKey = null566                entryList = mutableListOf()567                authenticatedDuressConfigured = false568                _duressConfigured.value = false569                recoveryWordHash = null570                recoveryWordsSet = false571                decoyMode = false572                sessionDataAvailable = true573                publish()574                _isUnlocked.value = true575                sessionEpoch = nextSessionEpoch(sessionEpoch)576                previousDerivedKey to previousRootKey577            }578            if (adopted == null) return AdoptVaultResult.Error("stale_adoption")579            val (previousDerivedKey, previousRootKey) = adopted580            previousDerivedKey?.let(VaultCrypto::zero)581            previousRootKey?.let(VaultCrypto::zero)582            // Write the recovery escrow so the forgot-password flow works on583            // this device. The words are deterministic from the root key and584            // were already confirmed on the source device.585            runCatching {586                val words = rootKeyToWords(rootKey!!)587                val escrow = buildRecoveryEscrow(words)588                val rkEscrow = buildRootKeyEscrow(words)589                if (escrow != null || rkEscrow != null) {590                    val prior = store.loadSlotA()591                    if (prior != null) {592                        store.writeSlotA(prior.copy(593                            recoveryEscrow = escrow ?: prior.recoveryEscrow,594                            rootKeyEscrow = rkEscrow ?: prior.rootKeyEscrow,595                        ))596                    }597                    mutateState {598                        recoveryWordHash = recoveryWordsHash(words)599                        recoveryWordsSet = true600                    }601                }602            }603            AdoptVaultResult.Success(vaultId)604        } catch (e: Exception) {605            AdoptVaultResult.Error(e.message ?: "adoption_create_failed")606        } finally {607            adoptedRootKey?.let(VaultCrypto::zero)608            nextDerivedKey?.let(VaultCrypto::zero)609            sessionRootKey?.let(VaultCrypto::zero)610        }611    }612613    suspend fun unlock(password: String): UnlockResult = mutex.withLock {614        val result = unlockLocked(password, currentEpoch())615        if (result is UnlockResult.Success) ensureRecoveryEscrow()616        result617    }618619    /** Unlock body without acquiring the mutex — callers must already hold it. */620    private fun unlockLocked(password: String, expectedEpoch: Long): UnlockResult {621        val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")622        val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))623        val payload = try {624            val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A)625            try {626                VaultCodec.decode(plaintext)627            } finally {628                VaultCrypto.zero(plaintext)629            }630        } catch (_: Exception) {631            VaultCrypto.zero(key)632            // LV-1: a vault sealed before NFC normalization with a non-NFC633            // password derives a different key now. If the supplied password is634            // not already in NFC form, retry with the raw (un-normalized) bytes.635            if (password != Normalizer.normalize(password, Normalizer.Form.NFC)) {636                val legacy = tryLegacyRawUnlock(password, slotA, expectedEpoch)637                if (legacy != null) return legacy638            }639            return UnlockResult.WrongPassword640        }641        return adoptSlotA(key, payload, expectedEpoch)642    }643644    /**645     * LV-1 legacy fallback: unlock a slot-A vault that was sealed under the raw646     * (un-normalized) password bytes. On success the slot is HEALED — re-sealed647     * under the NFC-normalized key — so every future unlock takes the normal648     * path. Returns null when the raw key also fails (genuinely wrong password)649     * OR when any step of the heal commits fails (the original slot A is restored650     * so disk and session stay aligned).651     */652    private fun tryLegacyRawUnlock(password: String, slotA: StoredVault, expectedEpoch: Long): UnlockResult? {653        var rawKey: ByteArray? = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))654        var newKey: ByteArray? = null655        return try {656            val payload = try {657                val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), rawKey!!, VaultCrypto.AAD_SLOT_A)658                try {659                    VaultCodec.decode(plaintext)660                } finally {661                    VaultCrypto.zero(plaintext)662                }663            } catch (_: Exception) {664                return null665            }666            // Heal: re-seal slot A under the NFC key (mirrors changePassword's667            // re-seal). Escrows carry forward unchanged — only the wrapping rotates.668            val newSalt = VaultCrypto.generateSalt()669            newKey = VaultCrypto.deriveKey(password, newSalt)670            val plaintext = VaultCodec.encode(payload)671            val blob = try {672                b64(VaultCrypto.encrypt(plaintext, newKey!!, VaultCrypto.AAD_SLOT_A))673            } finally {674                VaultCrypto.zero(plaintext)675            }676            val next = StoredVault(677                version = slotA.version,678                salt = b64(newSalt),679                blob = blob,680                recoveryEscrow = slotA.recoveryEscrow,681                rootKeyEscrow = slotA.rootKeyEscrow,682            )683            // P1-1/P1-3/P1-2 (codex): any failure of writeSlotA, writeMatchingNoiseSlotB,684            // or stampLocalMutation must restore the prior slot A AND slot B so disk685            // and the eventual session key never disagree on the wrapping.686            val priorB = store.loadSlotB()687            beforeDurableCommit()688            val healed = withEpochCommit(expectedEpoch) {689                if (!store.writeSlotA(next)) {690                    false691                } else try {692                    if (!writeMatchingNoiseSlotB(next)) {693                        runCatching { store.writeSlotA(slotA) }694                        if (priorB != null) runCatching { store.writeSlotB(priorB) }695                        false696                    } else if (!writeCompanionDuressSlot(next)) {697                        runCatching { store.writeSlotA(slotA) }698                        if (priorB != null) runCatching { store.writeSlotB(priorB) }699                        false700                    } else {701                        store.stampLocalMutation()702                        true703                    }704                } catch (_: Exception) {705                    runCatching { store.writeSlotA(slotA) }706                    if (priorB != null) runCatching { store.writeSlotB(priorB) }707                    false708                }709            } ?: false710            if (healed) {711                VaultCrypto.zero(rawKey!!)712                rawKey = null713                val result = adoptSlotA(newKey!!, payload, expectedEpoch) // session key now matches the re-sealed slot714                newKey = null715                result716            } else {717                VaultCrypto.zero(newKey!!)718                newKey = null719                val result = adoptSlotA(rawKey!!, payload, expectedEpoch) // heal failed — keep using the raw key720                rawKey = null721                result722            }723        } finally {724            // Cover codec, encryption, storage, and stale-epoch failures before725            // either candidate key can be transferred into the live session.726            rawKey?.let(VaultCrypto::zero)727            newKey?.let(VaultCrypto::zero)728        }729    }730731    /** Adopt a derived slot-A [key]/[payload] as the live (real-vault) session. */732    private fun adoptSlotA(key: ByteArray, payload: VaultPayload, expectedEpoch: Long): UnlockResult {733        return try {734            // M-04: ensureRootKey and autoPurgeExpiredTrash both persist, so they735            // can throw after the fields above are live. There is no prior session736            // worth restoring — adoption has already replaced it — so a failed737            // adoption discards everything rather than leaving entries and keys738            // resident behind _isUnlocked=false.739            val adopted = mutateIfCurrentEpoch(expectedEpoch) {740                derivedKey = key741                decoyMode = false742                entryList = payload.entries.toMutableList()743                authenticatedDuressConfigured = payload.duressConfigured744                _duressConfigured.value = payload.duressConfigured745                recoveryWordHash = payload.recoveryWordHash746                recoveryWordsSet = payload.recoveryWordsSet747                sessionDataAvailable = true748                _settings.value = store.loadSettings()749                ensureRootKey(payload)750                autoPurgeExpiredTrash()751                consolidatePasskeyEntries()752                publish()753                _isUnlocked.value = true754                // A successful adoption starts a new generation. A sibling755                // SlotAUnlock captured in the prior epoch will fail closed at756                // the next commit instead of replacing this session.757                sessionEpoch = nextSessionEpoch(sessionEpoch)758            }759            if (adopted == null) {760                VaultCrypto.zero(key)761                UnlockResult.Error("stale_unlock")762            } else {763                UnlockResult.Success764            }765        } catch (e: Exception) {766            // Do not call lock() here: a concurrent newer session may already767            // own this repository. Only invalidate the failed epoch's fields.768            mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }769            VaultCrypto.zero(key)770            UnlockResult.Error(e.message ?: "unlock_failed")771        }772    }773774    // ---- Constant-time unlock (MF-5) --------------------------------------775776    /**777     * A slot-A unlock that has been derived but not yet adopted. Holds the live778     * Argon2id key and decoded payload so the caller can derive several candidates779     * concurrently and commit only the winner. The key is owned by this token until780     * [commitSlotAUnlock] adopts it or [discardSlotAUnlock] zeroes it.781     */782    class SlotAUnlock internal constructor(783        key: ByteArray,784        internal val payload: VaultPayload,785        internal val epoch: Long,786    ) {787        private var ownedKey: ByteArray? = key788        private var consumed = false789790        /** Transfer the key exactly once to the adopter. */791        internal fun takeKey(): ByteArray? = synchronized(this) {792            if (consumed) return@synchronized null793            consumed = true794            ownedKey.also { ownedKey = null }795        }796797        /** Discard an uncommitted token without touching a transferred key. */798        internal fun discard() = synchronized(this) {799            if (consumed) return@synchronized800            consumed = true801            ownedKey?.let(VaultCrypto::zero)802            ownedKey = null803        }804    }805806    /**807     * Derive the slot-A key and decrypt its payload WITHOUT mutating session state.808     * Pure computation (no mutex), so it can run concurrently with other candidate809     * derivations before the caller decides which to commit (MF-5). Returns null on810     * no-vault or wrong password (the derived key is zeroed on a tag mismatch).811     */812    fun tryUnlockSlotA(password: String): SlotAUnlock? {813        val epoch = currentEpoch()814        val slotA = store.loadSlotA() ?: return null815        val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))816        try {817            val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A)818            val payload = try {819                VaultCodec.decode(plaintext)820            } finally {821                VaultCrypto.zero(plaintext)822            }823            return SlotAUnlock(key, payload, epoch)824        } catch (_: Exception) {825            VaultCrypto.zero(key)826        }827828        if (password == Normalizer.normalize(password, Normalizer.Form.NFC)) return null829        return tryLegacyRawCandidate(password, slotA, epoch)830    }831832    /** Legacy raw-password fallback; successful candidates heal slot A to NFC. */833    private fun tryLegacyRawCandidate(password: String, slotA: StoredVault, epoch: Long): SlotAUnlock? {834        var rawKey: ByteArray? = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))835        var newKey: ByteArray? = null836        return try {837            val plaintext = try {838                VaultCrypto.decrypt(unb64(slotA.blob), rawKey!!, VaultCrypto.AAD_SLOT_A)839            } catch (_: Exception) {840                return null841            }842            val payload = try {843                VaultCodec.decode(plaintext)844            } finally {845                VaultCrypto.zero(plaintext)846            }847            val newSalt = VaultCrypto.generateSalt()848            newKey = VaultCrypto.deriveKey(password, newSalt)849            val encoded = VaultCodec.encode(payload)850            val blob = try {851                b64(VaultCrypto.encrypt(encoded, newKey!!, VaultCrypto.AAD_SLOT_A))852            } finally {853                VaultCrypto.zero(encoded)854            }855            val next = slotA.copy(salt = b64(newSalt), blob = blob)856            val priorB = store.loadSlotB()857            beforeDurableCommit()858            val healed = withEpochCommit(epoch) {859                if (!store.writeSlotA(next)) false else try {860                    if (!writeMatchingNoiseSlotB(next) || !writeCompanionDuressSlot(next)) {861                        runCatching { store.writeSlotA(slotA) }862                        if (priorB != null) runCatching { store.writeSlotB(priorB) }863                        false864                    } else {865                        store.stampLocalMutation()866                        true867                    }868                } catch (_: Exception) {869                    runCatching { store.writeSlotA(slotA) }870                    if (priorB != null) runCatching { store.writeSlotB(priorB) }871                    false872                }873            } ?: false874            if (healed) {875                VaultCrypto.zero(rawKey!!)876                rawKey = null877                SlotAUnlock(newKey!!, payload, epoch).also { newKey = null }878            } else {879                VaultCrypto.zero(newKey!!)880                newKey = null881                SlotAUnlock(rawKey!!, payload, epoch).also { rawKey = null }882            }883        } finally {884            rawKey?.let(VaultCrypto::zero)885            newKey?.let(VaultCrypto::zero)886        }887    }888889    /** Adopt a previously-derived [SlotAUnlock] as the live session. */890    suspend fun commitSlotAUnlock(unlock: SlotAUnlock): UnlockResult = mutex.withLock {891        val key = unlock.takeKey() ?: return@withLock UnlockResult.Error("unlock_token_consumed")892        adoptSlotA(key, unlock.payload, unlock.epoch)893    }894895    /** Zero a derived [SlotAUnlock] that will not be adopted. */896    fun discardSlotAUnlock(unlock: SlotAUnlock) = unlock.discard()897898    // ---- Duress slot B (MF-6) ---------------------------------------------899900    /**901     * A duress-slot (slot B) unlock derived but not yet adopted. Holds the live key902     * and decoded decoy payload so it can be derived concurrently with slot A and903     * only committed if the duress passphrase was the one entered (MF-5/MF-6).904     */905    class DuressUnlock internal constructor(906        key: ByteArray,907        internal val payload: VaultPayload,908        internal val epoch: Long,909    ) {910        private var ownedKey: ByteArray? = key911        private var consumed = false912913        internal fun takeKey(): ByteArray? = synchronized(this) {914            if (consumed) return@synchronized null915            consumed = true916            ownedKey.also { ownedKey = null }917        }918919        internal fun discard() = synchronized(this) {920            if (consumed) return@synchronized921            consumed = true922            ownedKey?.let(VaultCrypto::zero)923            ownedKey = null924        }925    }926927    /**928     * Try to decrypt the duress slot (slot B) with [password] WITHOUT mutating the929     * session. Success means the entered password is the duress passphrase that keys930     * slot B — indistinguishable from the real slot A at the lock screen. Pure931     * computation (no mutex), safe to run concurrently with [tryUnlockSlotA].932     * Returns null when no duress slot exists or the password is not the duress one.933     */934    fun tryUnlockDuress(password: String): DuressUnlock? {935        val epoch = currentEpoch()936        val slot = store.loadDecoySlot() ?: return null937        if (slot.version != LEGACY_ANDROID_SLOT_VERSION && slot.version != CURRENT_ANDROID_SLOT_VERSION) return null938        var key: ByteArray? = VaultCrypto.deriveKey(password, unb64(slot.salt))939        return try {940            val plaintext = try {941                if (slot.version == CURRENT_ANDROID_SLOT_VERSION) {942                    VaultCrypto.decrypt(unb64(slot.blob), key!!, VaultCrypto.AAD_SLOT_B)943                } else {944                    runCatching {945                        VaultCrypto.decrypt(unb64(slot.blob), key!!, VaultCrypto.AAD_SLOT_A)946                    }.getOrElse {947                        VaultCrypto.decrypt(unb64(slot.blob), key!!, VaultCrypto.AAD_SLOT_B)948                    }949                }950            } catch (_: Exception) {951                VaultCrypto.zero(key!!)952                key = null953                return null954            }955            val payload = try {956                VaultCodec.decode(plaintext)957            } finally {958                VaultCrypto.zero(plaintext)959            }960            if (slot.version == LEGACY_ANDROID_SLOT_VERSION) {961                val migratedKey = migrateLegacyDuressSlot(slot, password, payload, key!!, epoch)962                    ?: run {963                        VaultCrypto.zero(key!!)964                        key = null965                        return null966                    }967                if (migratedKey !== key) {968                    VaultCrypto.zero(key!!)969                    key = migratedKey970                }971            }972            DuressUnlock(key!!, payload, epoch).also { key = null }973        } catch (_: Exception) {974            key?.let(VaultCrypto::zero)975            null976        }977    }978979    /**980     * Re-seal an authenticated legacy decoy under the current Slot-B AAD.981     * A failed write or verification restores the exact legacy record, while982     * already-authenticated unlock remains usable for this session.983     */984    private fun migrateLegacyDuressSlot(985        legacy: StoredVault,986        password: String,987        payload: VaultPayload,988        legacyKey: ByteArray,989        epoch: Long,990    ): ByteArray? {991        var salt: ByteArray? = null992        var migratedKey: ByteArray? = null993        var plaintext: ByteArray? = null994        var restoredLegacy = false995        var migrated = false996        try {997            salt = VaultCrypto.generateSalt()998            migratedKey = VaultCrypto.deriveKey(password, salt)999            plaintext = VaultCodec.encode(payload)1000            val next = StoredVault(1001                version = CURRENT_ANDROID_SLOT_VERSION,1002                salt = b64(salt),1003                blob = b64(VaultCrypto.encrypt(plaintext, migratedKey, VaultCrypto.AAD_SLOT_B)),1004            )1005            var priorA: StoredVault? = null1006            var priorB: String? = null1007            withSessionEpochCommit(epoch) {1008                priorA = store.loadSlotA()1009                priorB = store.loadSlotB()1010                if (store.loadDecoySlot() != legacy) return@withSessionEpochCommit false1011                if (!store.writeDecoySlot(next)) {1012                    restoredLegacy = store.loadDecoySlot() == legacy1013                    return@withSessionEpochCommit restoredLegacy1014                }1015                val reopened = store.loadDecoySlot()1016                val verified = reopened?.version == CURRENT_ANDROID_SLOT_VERSION && runCatching {1017                    val reopenedPlaintext = VaultCrypto.decrypt(unb64(reopened.blob), migratedKey!!, VaultCrypto.AAD_SLOT_B)1018                    try { VaultCodec.decode(reopenedPlaintext) == payload } finally { VaultCrypto.zero(reopenedPlaintext) }1019                }.getOrDefault(false)1020                if (verified) {1021                    migrated = true1022                    return@withSessionEpochCommit true1023                }1024                val restored = priorA != null && store.restoreVaultTriad(priorA!!, priorB, legacy)1025                restoredLegacy = restored && store.loadSlotA() == priorA && store.loadSlotB() == priorB && store.loadDecoySlot() == legacy1026                restoredLegacy1027            }1028            if (migrated) {1029                VaultCrypto.zero(legacyKey)1030                return migratedKey.also { migratedKey = null }1031            }1032            if (restoredLegacy) return legacyKey1033        } catch (_: Exception) {1034            // A failed migration must not claim a legacy key unless the exact1035            // legacy record was durably restored and observed.1036        }1037        if (!restoredLegacy) runCatching { store.loadDecoySlot() == legacy }1038        migratedKey?.let(VaultCrypto::zero)1039        return if (restoredLegacy) legacyKey else null1040    }10411042    /** Adopt a derived [DuressUnlock] as a live decoy session (edits persist to slot B only). */1043    suspend fun commitDuressUnlock(unlock: DuressUnlock): UnlockResult = mutex.withLock {1044        val key = unlock.takeKey() ?: return@withLock UnlockResult.Error("unlock_token_consumed")1045        if (currentEpoch() != unlock.epoch) {1046            VaultCrypto.zero(key)1047            return@withLock UnlockResult.Error("stale_unlock")1048        }1049        return try {1050            val adopted = mutateIfCurrentEpoch(unlock.epoch) {1051                derivedKey = key1052                decoyMode = true1053                entryList = unlock.payload.entries.toMutableList()1054                authenticatedDuressConfigured = false1055                _duressConfigured.value = false1056                recoveryWordHash = unlock.payload.recoveryWordHash1057                recoveryWordsSet = unlock.payload.recoveryWordsSet1058                sessionDataAvailable = true1059                rootKey = if (unlock.payload.rootKeyB64.isNotBlank()) unb64(unlock.payload.rootKeyB64)1060                          else VaultCrypto.generateRootKey()1061                // The decoy session gets its own defaults, never the real vault's1062                // record. Settings are shared, plaintext state loaded at every1063                // session start, so reading it here both told the coercer the real1064                // configuration and let updateSettings below persist changes into1065                // the record the real vault loads next (PB-26-120).1066                _settings.value = VaultSettings()1067                publish()1068                _isUnlocked.value = true1069                sessionEpoch = nextSessionEpoch(sessionEpoch)1070            }1071            if (adopted == null) {1072                VaultCrypto.zero(key)1073                UnlockResult.Error("stale_unlock")1074            } else {1075                UnlockResult.Success1076            }1077        } catch (e: Exception) {1078            // A payload/root/settings failure can occur after the candidate key1079            // has been assigned to derivedKey. Tear down only this epoch so a1080            // newer session is not disturbed, and scrub the token reference on1081            // every error path.1082            mutateIfCurrentEpoch(unlock.epoch) { clearSessionStateLocked() }1083            VaultCrypto.zero(key)1084            UnlockResult.Error(e.message ?: "decoy_unlock_failed")1085        }1086    }10871088    /** Zero a derived [DuressUnlock] that will not be adopted. */1089    fun discardDuressUnlock(unlock: DuressUnlock) = unlock.discard()10901091    /**1092     * Configure the duress vault (MF-6): seal a fresh, empty decoy payload under an1093     * Argon2id key derived from [duressPassphrase] (fresh salt) into slot B. The1094     * passphrase is never stored — only its ability to decrypt slot B proves it.1095     * Requires the real vault to be unlocked and not itself a decoy session.1096     */1097    suspend fun setDuressPassphrase(duressPassphrase: String): Boolean = mutex.withLock {1098        // H-03: read derivedKey/decoyMode atomically with any concurrent lock().1099        val expectedEpoch = mutateState {1100            if (derivedKey != null && !decoyMode) sessionEpoch else null1101        } ?: return false1102        // Reject a duress passphrase that also opens the real vault: it would make the1103        // lock screen ambiguous (both slots would decrypt for the same input).1104        tryUnlockSlotA(duressPassphrase)?.let { discardSlotAUnlock(it); return false }1105        var key: ByteArray? = null1106        var basePlaintext: ByteArray? = null1107        return try {1108            val salt = VaultCrypto.generateSalt()1109            key = VaultCrypto.deriveKey(duressPassphrase, salt)1110            // An empty decoy vault with its own fresh sync root key — nothing real leaks.1111            val decoyRoot = VaultCrypto.generateRootKey()1112            val decoyRootB64 = try { b64(decoyRoot) } finally { VaultCrypto.zero(decoyRoot) }1113            val decoyPayload = VaultPayload(entries = emptyList(), rootKeyB64 = decoyRootB64)1114            basePlaintext = VaultCodec.encode(decoyPayload)1115            // H-04: pad the duress plaintext to slot A's ciphertext length so the1116            // duress blob matches slot A's blob on disk. VaultCodec.decode strips1117            // trailing NULs, so the extra padding survives encrypt but never1118            // reaches the JSON parser.1119            // This decoy plaintext length is frozen from here on: re-sealing it1120            // on later growth would need the duress passphrase, which is never1121            // retained. VaultStore compensates by re-padding the two slot1122            // RECORDS to the longer of the two on every write, so the frozen1123            // blob no longer shows up as a length difference at rest.1124            val slotA = store.loadSlotA()1125            val targetSize = slotA?.let(::matchingCiphertextLength) ?: 01126            val plaintext = if (targetSize > basePlaintext!!.size) basePlaintext!!.copyOf(targetSize) else basePlaintext!!1127            val blob = try {1128                b64(VaultCrypto.encrypt(plaintext, key!!, VaultCrypto.AAD_SLOT_B))1129            } finally {1130                VaultCrypto.zero(plaintext)1131                // Padding creates a second array; scrub the original encoded1132                // payload too rather than dropping its last reference untouched.1133                if (plaintext !== basePlaintext) basePlaintext?.let(VaultCrypto::zero)1134                basePlaintext = null1135                key?.let(VaultCrypto::zero)1136                key = null1137            }1138            beforeDurableCommit()1139            val ok = withEpochCommit(expectedEpoch) {1140                store.writeDecoySlot(StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(salt), blob = blob))1141            } ?: false1142            if (!ok) return false1143            val marked = mutateIfCurrentEpoch(expectedEpoch) {1144                authenticatedDuressConfigured = true1145                _duressConfigured.value = true1146                true1147            } ?: false1148            if (!marked) return false1149            if (!runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }.getOrDefault(false)) {1150                mutateIfCurrentEpoch(expectedEpoch) {1151                    authenticatedDuressConfigured = false1152                    _duressConfigured.value = false1153                }1154                runCatching { writeFakeDuressSlot(store.loadSlotA()!!) }1155                return false1156            }1157            true1158        } catch (_: Exception) {1159            false1160        } finally {1161            // Cover failures before the encrypt block is entered (for example a1162            // codec/copy exception) as well as any early return after key derivation.1163            key?.let(VaultCrypto::zero)1164            basePlaintext?.let(VaultCrypto::zero)1165        }1166    }116711681169    /**1170     * Export the decoy slot as browser-shaped JSON for adoption snapshots.1171     *1172     * Returns the sealed slot as `{version, salt, nonce, ciphertext, tag}` all1173     * lowercase hex — identical to the browser's `duress_slot` wire format — so1174     * any receiver (browser or Android) can install it via the existing1175     * passthrough. Returns null when duress is not configured, no decoy exists,1176     * or any conversion failure occurs. Never decrypts.1177     */1178    suspend fun exportDuressSlotForAdoption(): String? = mutex.withLock {1179        if (!authenticatedDuressConfigured) return null1180        val slot = store.loadDecoySlot() ?: return null1181        return runCatching { androidDuressSlotToBrowserJson(slot) }.getOrNull()1182    }11831184    /**1185     * Convert an Android [StoredVault] decoy slot to browser-shaped JSON.1186     *1187     * Mirrors the inverse of [installAdoptedDuressSlot]: base64 salt/blob are1188     * split into lowercase hex fields matching [BrowserSlotA]. Intermediate1189     * byte arrays are zeroed in finally.1190     */1191    private fun androidDuressSlotToBrowserJson(slot: StoredVault): String {1192        // Build the wire JSON directly with JsonObject so `version: 1` is ALWAYS1193        // serialized — kotlinx-serialization's encodeDefaults = false would1194        // otherwise omit BrowserSlotA.version (its Kotlin default), and the1195        // browser's hasValidVaultSchema strictly requires `r.version === 1`,1196        // silently dropping the duress slot on Android→browser adoptions.1197        var salt: ByteArray? = null1198        var blob: ByteArray? = null1199        var nonce: ByteArray? = null1200        var ctAndTag: ByteArray? = null1201        var ct: ByteArray? = null1202        var tag: ByteArray? = null1203        try {1204            salt = unb64(slot.salt)1205            blob = unb64(slot.blob)1206            nonce = blob.copyOfRange(0, VaultCrypto.NONCE_SIZE)1207            ctAndTag = blob.copyOfRange(VaultCrypto.NONCE_SIZE, blob.size)1208            ct = ctAndTag.copyOfRange(0, ctAndTag.size - 16)1209            tag = ctAndTag.copyOfRange(ctAndTag.size - 16, ctAndTag.size)1210            val obj = JsonObject(mapOf(1211                "version" to JsonPrimitive(1),1212                "salt" to JsonPrimitive(salt.joinToString("") { "%02x".format(it) }),1213                "nonce" to JsonPrimitive(nonce.joinToString("") { "%02x".format(it) }),1214                "ciphertext" to JsonPrimitive(ct.joinToString("") { "%02x".format(it) }),1215                "tag" to JsonPrimitive(tag.joinToString("") { "%02x".format(it) }),1216            ))1217            return obj.toString()1218        } finally {1219            salt?.let(VaultCrypto::zero)1220            blob?.let(VaultCrypto::zero)1221            nonce?.let(VaultCrypto::zero)1222            ctAndTag?.let(VaultCrypto::zero)1223            ct?.let(VaultCrypto::zero)1224            tag?.let(VaultCrypto::zero)1225        }1226    }12271228    /**1229     * Install a browser-shaped duress slot received through adoption.1230     */1231    suspend fun installAdoptedDuressSlot(json: String): Boolean = mutex.withLock {1232        val b = BrowserSlot.parse(json) ?: return false1233        if (b.version != 1) return false1234        val expectedEpoch = currentEpoch()1235        var salt: ByteArray? = null1236        var nonce: ByteArray? = null1237        var ct: ByteArray? = null1238        var tag: ByteArray? = null1239        var blob: ByteArray? = null1240        try {1241            salt = unhex(b.salt)1242            nonce = unhex(b.nonce)1243            ct = unhex(b.ciphertext)1244            tag = unhex(b.tag)1245            blob = ByteArray(nonce.size + ct.size + tag.size).also {1246                System.arraycopy(nonce, 0, it, 0, nonce.size)1247                System.arraycopy(ct, 0, it, nonce.size, ct.size)1248                System.arraycopy(tag, 0, it, nonce.size + ct.size, tag.size)1249            }1250            val stored = StoredVault(version = LEGACY_ANDROID_SLOT_VERSION, salt = b64(salt), blob = b64(blob))1251            val priorA = store.loadSlotA() ?: return false1252            val priorB = store.loadSlotB()1253            val priorD = store.loadDecoySlot() ?: return false1254            beforeDurableCommit()1255            val committed = withEpochCommit(expectedEpoch) {1256                if (!store.writeDecoySlot(stored)) return@withEpochCommit false1257                authenticatedDuressConfigured = true1258                _duressConfigured.value = true1259                true1260            } ?: false1261            if (!committed) return false1262            if (runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }.getOrDefault(false)) {1263                true1264            } else {1265                mutateIfCurrentEpoch(expectedEpoch) {1266                    authenticatedDuressConfigured = false1267                    _duressConfigured.value = false1268                }1269                withEpochCommit(expectedEpoch) { store.restoreVaultTriad(priorA, priorB, priorD) }1270                false1271            }1272        } catch (_: Exception) {1273            false1274        } finally {1275            salt?.let(VaultCrypto::zero)1276            nonce?.let(VaultCrypto::zero)1277            ct?.let(VaultCrypto::zero)1278            tag?.let(VaultCrypto::zero)1279            blob?.let(VaultCrypto::zero)1280        }1281    }12821283    /** Tear down the duress vault: drop slot B and the duress flag on the real payload. */1284    suspend fun clearDuress(): Boolean = mutex.withLock {1285        // H-04: presence-indistinguishable — replace the real decoy with a fake1286        // blob of slot A's size rather than removing the duress record. The1287        // record stays on disk at the same length, so an at-rest observer1288        // cannot tell "duress cleared" from "no duress ever configured".1289        val expectedEpoch = currentEpoch()1290        val replaced = withEpochCommit(expectedEpoch) {1291            store.loadSlotA()?.let { slotA -> runCatching { writeFakeDuressSlot(slotA) }.getOrDefault(false) }1292                ?: runCatching { store.clearDecoySlot(); true }.getOrDefault(false)1293        } ?: false1294        if (!replaced) return@withLock false1295        // H-03: stateLock-fence the derivedKey/decoyMode read AND the1296        // authenticatedDuressConfigured write so a concurrent lock() cannot land between them.1297        if (!isSessionEpochCurrent(expectedEpoch)) return false1298        val shouldClear = mutateIfCurrentEpoch(expectedEpoch) { derivedKey != null && !decoyMode } == true1299        if (shouldClear && mutateIfCurrentEpoch(expectedEpoch) {1300            authenticatedDuressConfigured = false1301            _duressConfigured.value = false1302        } != null) {1303            runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }1304        }1305        true1306    }13071308    /** True for the provider-specific exception used for a valid GCM blob/key mismatch. */1309    private fun isGcmAuthenticationFailure(error: Throwable): Boolean {1310        var current: Throwable? = error1311        while (current != null) {1312            if (current is javax.crypto.AEADBadTagException) return true1313            // Some Android providers expose a GCM tag failure as the parent1314            // BadPaddingException rather than the AEAD-specific subtype.  A1315            // short ciphertext is an IllegalBlockSizeException and therefore1316            // remains an internal/malformed-payload Error below.1317            if (current is javax.crypto.BadPaddingException) return true1318            current = current.cause1319        }1320        return false1321    }13221323    /** Unlock with an already-derived AES-256 key (biometric path). */1324    suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {1325        val expectedEpoch = currentEpoch()1326        val slotA = try {1327            store.loadSlotA()1328        } catch (_: Exception) {1329            return@withLock UnlockResult.Error("unlock_key_storage_failed")1330        } ?: return@withLock UnlockResult.Error("no_vault")1331        // Keep the caller-owned key separate from the staged session key. The1332        // biometric caller always zeroes its input in a finally block; adoption1333        // must therefore own a copy and use the same all-or-nothing path as a1334        // password unlock rather than publishing a partially decoded session.1335        var stagedKey: ByteArray? = key.copyOf()1336        return try {1337            val encrypted = try {1338                unb64(slotA.blob)1339            } catch (_: Exception) {1340                return@withLock UnlockResult.Error("invalid_vault_blob")1341            }1342            // A GCM record must include nonce + authentication tag.  Providers1343            // differ on whether a shorter record is reported as BadPadding or1344            // AEADBadTag; reject it before decrypt so malformed storage cannot be1345            // misreported as a user-entered wrong key.1346            if (encrypted.size < VaultCrypto.NONCE_SIZE + (VaultCrypto.TAG_LENGTH_BITS / 8)) {1347                return@withLock UnlockResult.Error("invalid_vault_blob")1348            }1349            val plaintext = try {1350                VaultCrypto.decrypt(encrypted, stagedKey!!, VaultCrypto.AAD_SLOT_A)1351            } catch (e: Exception) {1352                if (isGcmAuthenticationFailure(e)) {1353                    return@withLock UnlockResult.WrongPassword1354                }1355                return@withLock UnlockResult.Error("unlock_key_decrypt_failed")1356            }1357            val payload = try {1358                VaultCodec.decode(plaintext)1359            } catch (_: Exception) {1360                return@withLock UnlockResult.Error("invalid_vault_payload")1361            } finally {1362                VaultCrypto.zero(plaintext)1363            }1364            val candidate = stagedKey ?: return UnlockResult.Error("unlock_key_missing")1365            val result = adoptSlotA(candidate, payload, expectedEpoch)1366            if (result is UnlockResult.Success) { stagedKey = null; ensureRecoveryEscrow() }1367            result1368        } finally {1369            stagedKey?.let(VaultCrypto::zero)1370        }1371    }13721373    fun lock() {1374        // Never snapshot a mutation that has changed entryList but has not yet1375        // crossed its durable epoch fence. Successful writes refresh the spool1376        // before releasing this mutex; an in-flight writer therefore makes this1377        // lock skip the convenience refresh and fail closed to the prior cache.1378        if (mutex.tryLock()) {1379            try {1380                runCatching { LockedSyncSpoolHooks.refresh(this) }1381            } finally {1382                mutex.unlock()1383            }1384        }1385        // H-03: must observe derivedKey/entryList atomically with any in-flight1386        // suspend op (an addEntry mid-encrypt, an unlock adopting the payload,1387        // etc.). mutex cannot be acquired from this non-suspend caller; stateLock1388        // guards just the brief state reset. Advancing the epoch first invalidates1389        // every operation that captured this session before it reaches a later1390        // durable commit or publication.1391        stateLock.lock()1392        try {1393            sessionEpoch = nextSessionEpoch(sessionEpoch)1394            clearSessionStateLocked()1395            _uiGateLocked.value = false1396        } finally {1397            stateLock.unlock()1398        }1399    }14001401    /**1402     * Enter sync-retained background mode: the UI shows the lock screen but the1403     * vault stays fully unlocked in memory so [PeachSyncService] can complete1404     * sync sessions. Called from [PeachApplication.onStop] when background sync1405     * is enabled. A subsequent full [lock] (auto-lock timer, manual lock)1406     * supersedes this and zeroes everything.1407     */1408    fun lockUiGate() {1409        if (_isUnlocked.value) _uiGateLocked.value = true1410    }14111412    /** Dismiss the UI gate after the user authenticates on resume. */1413    fun clearUiGate() {1414        _uiGateLocked.value = false1415    }14161417    @Volatile private var suppressNextBackgroundLockUntil: Long = 0L14181419    // Test seam so the expiry branch is reachable from plain JUnit (SystemClock1420    // is a stub off-device).1421    @VisibleForTesting1422    internal var nowMs: () -> Long = { SystemClock.elapsedRealtime() }14231424    /**1425     * Call immediately before launching a system Activity (a SAF file1426     * picker/save dialog, a share sheet) that briefly takes the whole process1427     * out of the foreground as an expected part of an in-app flow — not a1428     * genuine user backgrounding. ProcessLifecycleOwner.onStop can't tell the1429     * two apart on its own (it fires for both), and without this, exporting or1430     * importing a file silently locked and wiped the vault mid-flow the moment1431     * the picker took over, before its result ever reached the app.1432     *1433     * The suppression auto-expires after [BACKGROUND_LOCK_SUPPRESSION_TIMEOUT_MS]1434     * (M-07); a never-consumed stale flag cannot suppress a later real lock.1435     */1436    fun expectTransientBackground() {1437        suppressNextBackgroundLockUntil = nowMs() + BACKGROUND_LOCK_SUPPRESSION_TIMEOUT_MS1438    }14391440    /**1441     * Consumed once by the next background-lock check; see [expectTransientBackground].1442     * Returns false (and clears the flag) if the suppression has expired or was1443     * never set — a genuine background event must always lock.1444     */1445    fun consumeTransientBackgroundSuppression(): Boolean {1446        val until = suppressNextBackgroundLockUntil1447        val active = until != 0L && nowMs() < until1448        suppressNextBackgroundLockUntil = 0L1449        return active1450    }14511452    // ---- Sync identity ----------------------------------------------------14531454    /**1455     * The vault's stable sync master key (a copy). Caller must zero it. Backs1456     * vault_id, the Noise static key, the Ed25519 manifest key, and per-entry1457     * envelope keys. Null when locked. See [VaultPayload.rootKeyB64].1458     */1459    /**1460     * HOLE 5 — the duress vault never syncs.1461     *1462     * [commitDuressUnlock] gives the decoy session a root key so its own codex1463     * and recovery paths work, which means (unlike the browser, where the decoy1464     * path simply has no root key) the sync surface has to refuse explicitly.1465     * Without this the decoy vault would present a second, different vault_id1466     * to a paired device, and a coerced user opening it would make sync visibly1467     * fail on their other devices — a duress indicator, which is the one thing1468     * a duress vault must never be.1469     */1470    // M-04: the "null when locked" half of the contract was documented but never1471    // enforced — a rootKey outlives _isUnlocked in the recovery half-unlock (see1472    // [unlockWithRecoveryWords], which installs a root key with no password key1473    // yet) and in a create that failed after staging. Sync must fail closed1474    // there, so the authoritative unlocked flag gates it, not just decoyMode.1475    internal data class SyncMasterKeySnapshot(val epoch: Long, val key: ByteArray)14761477    internal fun syncMasterKeySnapshot(): SyncMasterKeySnapshot? = mutateState {1478        if (decoyMode || !_isUnlocked.value) null1479        else rootKey?.copyOf()?.let { SyncMasterKeySnapshot(sessionEpoch, it) }1480    }14811482    internal fun isSessionEpochCurrent(epoch: Long): Boolean =1483        mutateState { sessionEpoch == epoch }14841485    internal fun unlockedSessionEpoch(): Long? = mutateState {1486        if (derivedKey != null && _isUnlocked.value) sessionEpoch else null1487    }14881489    fun syncMasterKey(): ByteArray? = syncMasterKeySnapshot()?.key14901491    /**1492     * The current session's root key, decoy included. For local-only uses that1493     * must behave identically in a decoy session — Codex backup and recovery1494     * words — because a feature that errors under duress is itself a duress1495     * tell. In a decoy session this is the DECOY's root key (see1496     * [commitDuressUnlock]), never the real vault's, so neither surface can1497     * leak the real vault. Anything that leaves the device must use1498     * [syncMasterKey] instead.1499     */1500    fun sessionRootKey(): ByteArray? = mutateState {1501        if (!sessionDataAvailable) null else rootKey?.copyOf()1502    }15031504    /** Stable per-vault id two paired devices must share to sync. Null when1505     *  locked, and never present for the decoy vault (see [syncMasterKey]). */1506    fun syncVaultId(): String? = mutateState {1507        if (decoyMode || !_isUnlocked.value) null1508        else rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }1509    }15101511    /**1512     * Browser parity (MV-8): rotate the sync identity by replacing the stable1513     * root key. Entries remain under the master-password key, while sync1514     * credentials, vault_id, and recovery words all change.1515     */1516    suspend fun rotateSyncIdentity(): Boolean = mutex.withLock {1517        val expectedEpoch = mutateState { if (derivedKey != null && !decoyMode) sessionEpoch else null }1518            ?: return false1519        installRootKey(generateRecoverableRootKey(), expectedEpoch)1520    }15211522    /**1523     * Join the vault behind [rootKeyHex]: adopt that vault's identity while1524     * keeping every local entry.1525     *1526     * Sync identity (vault id, signing keys) derives from the root key, and1527     * `sync-coordinator` refuses a `vault_id_mismatch`, so two independently1528     * created vaults can never reconcile. Taking the other side's root key is1529     * what makes them one vault; from the next sync on, both entry sets merge.1530     *1531     * Entries survive because they are sealed under the password-derived key,1532     * not the root key — the same property [rotateSyncIdentity] relies on.1533     *1534     * CONSEQUENCE, which the caller must have disclosed and had confirmed:1535     * this device's previous recovery words stop working for good, and its new1536     * words are the source vault's words, because words are a deterministic1537     * encoding of the root key.1538     */1539    suspend fun joinVault(rootKeyHex: String): AdoptVaultResult = mutex.withLock {1540        if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {1541            return AdoptVaultResult.Error("JOIN_INVALID_ROOT_KEY: expected 64 lowercase hex chars")1542        }1543        val expectedEpoch = mutateState {1544            when {1545                derivedKey == null -> null1546                decoyMode -> Long.MIN_VALUE1547                else -> sessionEpoch1548            }1549        }1550        if (expectedEpoch == null) return AdoptVaultResult.Error("vault_locked")1551        if (expectedEpoch == Long.MIN_VALUE) return AdoptVaultResult.Error("JOIN_DECOY_MODE")1552        if (!store.hasVault()) return AdoptVaultResult.Error("JOIN_NO_LOCAL_VAULT")15531554        val incoming = hexToRootKey(rootKeyHex)1555        if (incoming.size != VaultCrypto.KEY_SIZE) {1556            VaultCrypto.zero(incoming)1557            return AdoptVaultResult.Error("JOIN_INVALID_ROOT_KEY: expected 32 bytes")1558        }1559        // Refuse before committing rather than leave this device holding a vault1560        // whose recovery words cannot be typed back. generateRecoverableRootKey1561        // screens its own keys for this; a key arriving from a peer has not been.1562        val roundTrips = runCatching { wordsToRootKeyMaterial(rootKeyToWords(incoming)) }.isSuccess1563        if (!roundTrips) {1564            VaultCrypto.zero(incoming)1565            return AdoptVaultResult.Error("JOIN_UNRECOVERABLE_ROOT_KEY")1566        }15671568        val vaultId = com.peachpasswords.sync.computeVaultId(incoming)1569        return if (installRootKey(incoming, expectedEpoch)) {1570            AdoptVaultResult.Success(vaultId)1571        } else {1572            AdoptVaultResult.Error("JOIN_INSTALL_FAILED")1573        }1574    }15751576    /**1577     * The recovery words [rootKeyHex] will produce once joined, or null if it is1578     * not a usable root key. Lets the join flow show the user the words that are1579     * about to replace theirs *before* anything is committed.1580     */1581    fun previewRecoveryWords(rootKeyHex: String): List<String>? {1582        if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) return null1583        val bytes = hexToRootKey(rootKeyHex)1584        return try {1585            val words = rootKeyToWords(bytes)1586            if (runCatching { wordsToRootKeyMaterial(words) }.isSuccess) words else null1587        } catch (_: Exception) {1588            null1589        } finally {1590            VaultCrypto.zero(bytes)1591        }1592    }15931594    /**1595     * Swap the vault's root key, keeping every entry, and re-escrow under the1596     * words the new key encodes. Takes ownership of [nextRootKey]. Caller holds1597     * [mutex].1598     */1599    private suspend fun installRootKey(nextRootKey: ByteArray, expectedEpoch: Long): Boolean {1600        // H-03: snapshot the live fields under stateLock so the success and the1601        // rollback paths both see consistent prior/new state. Writing the new1602        // rootKey/recovery fields is inside its own mutateState at the end.1603        // H-03 (P1-3 codex): the snapshot must COPY the live key/rootKey arrays1604        // — holding live references would let a zero-on-failure operation also1605        // wipe the session's still-live key arrays.1606        data class Snapshot(1607            val key: ByteArray,1608            val priorRootKey: ByteArray,1609            val priorRecoveryHash: String?,1610            val priorRecoverySet: Boolean,1611        )1612        val snap = mutateIfCurrentEpoch(expectedEpoch) {1613            val k = derivedKey ?: return@mutateIfCurrentEpoch null1614            if (decoyMode) return@mutateIfCurrentEpoch null1615            val priorRoot = rootKey ?: return@mutateIfCurrentEpoch null1616            Snapshot(k.copyOf(), priorRoot.copyOf(), recoveryWordHash, recoveryWordsSet)1617        } ?: run {1618            VaultCrypto.zero(nextRootKey)1619            return false1620        }1621        val priorSlot = store.loadSlotA() ?: run {1622            VaultCrypto.zero(snap.key)1623            VaultCrypto.zero(snap.priorRootKey)1624            VaultCrypto.zero(nextRootKey)1625            return false1626        }1627        val nextWords = rootKeyToWords(nextRootKey)16281629        return try {1630            beforeDurableCommit()1631            if (!takeVaultSnapshot("local_save", expectedEpoch)) throw IllegalStateException("snapshot_failed")1632            if (mutateIfCurrentEpoch(expectedEpoch) {1633                rootKey = nextRootKey1634                recoveryWordHash = recoveryWordsHash(nextWords)1635                recoveryWordsSet = false1636            } == null) throw IllegalStateException("stale_root_rotation")16371638            val nextRecoveryEscrow = buildRecoveryEscrow(nextWords)1639                ?: throw IllegalStateException("recovery_escrow_failed")1640            val nextRootKeyEscrow = buildRootKeyEscrow(nextWords)1641                ?: throw IllegalStateException("root_escrow_failed")1642            val plaintext = VaultCodec.encode(currentPayload())1643            val blob = try {1644                b64(VaultCrypto.encrypt(plaintext, snap.key, VaultCrypto.AAD_SLOT_A))1645            } finally {1646                VaultCrypto.zero(plaintext)1647            }1648            val nextSlot = priorSlot.copy(1649                blob = blob,1650                recoveryEscrow = nextRecoveryEscrow,1651                rootKeyEscrow = nextRootKeyEscrow,1652            )1653            val committed = withEpochCommit(expectedEpoch) {1654                if (!store.writeSlotA(nextSlot)) return@withEpochCommit false1655                try {1656                    if (!writeMatchingNoiseSlotB(nextSlot)) throw IllegalStateException("noise_slot_b_commit_failed")1657                    // H-04: a root-key rotation re-seals slot A, so the duress slot1658                    // (real or fake) must be re-padded to the new ciphertext length.1659                    if (!writeCompanionDuressSlot(nextSlot)) throw IllegalStateException("duress_slot_commit_failed")1660                    store.stampLocalMutation()1661                } catch (_: Exception) {1662                    store.writeSlotA(priorSlot)1663                    return@withEpochCommit false1664                }1665                true1666            } ?: false1667            if (!committed) throw IllegalStateException("storage_write_failed")1668            mutateIfCurrentEpoch(expectedEpoch) { publish() }1669            true1670        } catch (_: Exception) {1671            val restored = mutateIfCurrentEpoch(expectedEpoch) {1672                rootKey?.let(VaultCrypto::zero)1673                rootKey = snap.priorRootKey.copyOf()1674                recoveryWordHash = snap.priorRecoveryHash1675                recoveryWordsSet = snap.priorRecoverySet1676            }1677            if (restored != null) {1678                withEpochCommit(expectedEpoch) { store.writeSlotA(priorSlot) }1679            }1680            false1681        } finally {1682            VaultCrypto.zero(snap.key)1683            VaultCrypto.zero(snap.priorRootKey)1684            // On success nextRootKey is owned by rootKey. On every other path1685            // it is not, including a stale epoch after lock(); scrub it while1686            // the local reference is still available.1687            val stillOwnedBySession = mutateState {1688                sessionEpoch == expectedEpoch && rootKey === nextRootKey1689            }1690            if (!stillOwnedBySession) VaultCrypto.zero(nextRootKey)1691        }1692    }16931694    /**1695     * A copy of the live Argon2id-derived vault key, for biometric escrow only1696     * (wrapped under a hardware KeyStore key on biometric enable). Null when1697     * locked. Caller must [VaultCrypto.zero] it after use.1698     */1699    fun currentVaultKey(): ByteArray? = mutateState {1700        if (!isFullyUnlockedLocked()) null else derivedKey?.copyOf()1701    }17021703    suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {1704        val expectedEpoch = currentEpoch()1705        val slotA = store.loadSlotA() ?: return false1706        var oldKey: ByteArray? = null1707        var newKey: ByteArray? = null1708        var plaintext: ByteArray? = null1709        return try {1710            oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))1711            // Keep ownership of the decrypted vault plaintext until decoding has1712            // finished.  Passing decrypt() inline made the byte array unreachable1713            // before the finally block, so a successful or failed password change1714            // could leave the full plaintext resident in the heap.1715            val decrypted = VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A)1716            val payload = try {1717                VaultCodec.decode(decrypted)1718            } finally {1719                VaultCrypto.zero(decrypted)1720            }1721            val newSalt = VaultCrypto.generateSalt()1722            newKey = VaultCrypto.deriveKey(newPassword, newSalt)1723            // Re-seal the existing payload under the new key/salt.1724            plaintext = VaultCodec.encode(payload)1725            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))1726            // The escrow seals the slot-A PLAINTEXT, which a password change does not1727            // alter — only the wrapping changes — so carry it forward; rebuilding the1728            // StoredVault from scratch would silently drop it.1729            // Carry BOTH escrows forward unchanged: each seals plaintext/root-key1730            // content that a password change does not alter — only the slot-A1731            // wrapping rotates. The root-key escrow staying stable across password1732            // changes matches the browser (`vault.ts:363-364`).1733            val next = StoredVault(1734                version = slotA.version,1735                salt = b64(newSalt),1736                blob = blob,1737                recoveryEscrow = slotA.recoveryEscrow,1738                rootKeyEscrow = slotA.rootKeyEscrow,1739            )1740            // H-01: durably commit slot A + size-matched noise + version stamp1741            // before swapping the session key. A partial commit (new A on disk,1742            // old key in memory) would have the next save encrypt under the old1743            // key while matching disk on the new one.1744            val priorB = store.loadSlotB()1745            if (!commitVaultRotation(slotA, priorB, next, expectedEpoch)) return false1746            // H-03 (P1-2 codex): zero the OLD live key and assign the NEW one1747            // inside the same stateLock critical section, so a concurrent lock()1748            // can't observe the in-between (zeroed but not yet reassigned).1749            if (mutateIfCurrentEpoch(expectedEpoch) {1750                oldKey?.let(VaultCrypto::zero); oldKey = null1751                derivedKey?.let(VaultCrypto::zero)1752                derivedKey = newKey; newKey = null1753            } == null) return false1754            VaultKeyRotationHooks.onRotated()1755            true1756        } catch (_: Exception) {1757            false1758        } finally {1759            oldKey?.let(VaultCrypto::zero)1760            newKey?.let(VaultCrypto::zero)1761            plaintext?.let(VaultCrypto::zero)1762        }1763    }17641765    /**1766     * Irreversible wipe. Locks the session and clears every vault key. The Pro1767     * license is in a separate store and is preserved by construction.1768     */1769    suspend fun destroyVault(): Boolean = mutex.withLock {1770        lock()1771        val cleared = store.clearVault()1772        store.clearDecoySlot()1773        cleared1774    }17751776    // ---- Entry CRUD -------------------------------------------------------17771778    /**1779     * A Peach entry id is a UUID. Import and restore carry ids from foreign1780     * files (another Peach install, a vendor export, a hand-written backup) and1781     * no reader bounds them, so an id that is not a well-formed Peach id is1782     * replaced here rather than trusted.1783     *1784     * This is the naturalisation seam, and it is deliberately the only place it1785     * happens. Minting costs at most one duplicate if the same vault is later1786     * restored on a device that still holds the old id — visible and fixable.1787     * The sync path must NOT do this: adopting a peer's id verbatim is the only1788     * thing that keeps two devices agreeing on which entry they are discussing,1789     * so reminting there would fork identity on every device, on every round.1790     */1791    private val entryIdShape = Regex("[A-Za-z0-9_-]{1,64}")17921793    private fun String?.normalizedEntryId(): String =1794        if (this != null && entryIdShape.matches(this)) this else UUID.randomUUID().toString()17951796    suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {1797        val epoch = requireUnlocked()1798        val stamp = VaultCrypto.monotonicEntryTimestamp()1799        val now = System.currentTimeMillis()1800        val entry = withDerivedLast4(draft.copy(1801            id = draft.id.normalizedEntryId(),1802            createdAt = if (draft.createdAt > 0) draft.createdAt else now,1803            modifiedAt = stamp,1804            passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1805        ))1806        // H-03: capture rollback AND write entryList under stateLock so a1807        // concurrent lock() cannot zero the session between the read and the write.1808        val rollback = mutateCurrentSession(epoch) {1809            val r = entryList.toMutableList()1810            entryList.add(entry)1811            r1812        } ?: throw IllegalStateException("vault_locked")1813        persistOrRollback(rollback, epoch)1814        entry1815    }18161817    /**1818     * Insert many entries with a single encrypt-and-write at the end.1819     *1820     * Importing a real vault through [addEntry] was quadratic: every entry took1821     * the lock and re-encrypted and rewrote the whole vault, so an 806-entry1822     * restore did 806 full-vault writes and hung the app long enough to ANR.1823     * Rolls back to the pre-import list if the one write fails, matching1824     * [addEntry]'s all-or-nothing behaviour.1825     */1826    suspend fun addEntries(drafts: List<VaultEntry>): Int = mutex.withLock {1827        val epoch = requireUnlocked()1828        if (drafts.isEmpty()) return 01829        val now = System.currentTimeMillis()1830        val ready = drafts.map { draft ->1831            val stamp = VaultCrypto.monotonicEntryTimestamp()1832            withDerivedLast4(1833                draft.copy(1834                    id = draft.id.normalizedEntryId(),1835                    createdAt = if (draft.createdAt > 0) draft.createdAt else now,1836                    modifiedAt = stamp,1837                    passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1838                ),1839            )1840        }1841        // H-03: capture rollback AND append every entry under stateLock.1842        val rollback = mutateCurrentSession(epoch) {1843            val r = entryList.toMutableList()1844            entryList.addAll(ready)1845            r1846        } ?: throw IllegalStateException("vault_locked")1847        persistOrRollback(rollback, epoch)1848        return drafts.size1849    }18501851    /**1852     * M-01: replace the whole active set with [newEntries] in one write.1853     *1854     * Import's REPLACE mode used to soft-delete every current entry one durable1855     * write at a time (swallowing each failure) and then batch-add, so a failed1856     * add left the old entries stranded in Trash with nothing restored. Staging1857     * the entire next list in memory and committing it through1858     * [persistOrRollback] makes the swap all-or-nothing: on any failure the1859     * pre-import list — active entries included — is restored.1860     *1861     * Existing tombstones are preserved so paired devices still see the1862     * deletions they already know about.1863     */1864    suspend fun replaceEntries(newEntries: List<VaultEntry>): Int = mutex.withLock {1865        val epoch = requireUnlocked()1866        val now = System.currentTimeMillis()1867        val ready = newEntries.map { draft ->1868            val stamp = VaultCrypto.monotonicEntryTimestamp()1869            withDerivedLast4(1870                draft.copy(1871                    id = draft.id.normalizedEntryId(),1872                    createdAt = if (draft.createdAt > 0) draft.createdAt else now,1873                    modifiedAt = stamp,1874                    passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1875                ),1876            )1877        }1878        // M-03: an incoming entry that shares an id with an existing live entry1879        // is meant to *replace* it (PEACHSCRIPT REPLACE restore). Tombstoning1880        // the old one and then appending the new one would leave the list with1881        // two entries of the same id — the tombstoned one would be returned by1882        // updateEntry's indexOfFirst and trip entry_not_found. Drop the to-be-1883        // superseded entries from the tombstone set instead.1884        val incomingIds = ready.map { it.id }.toHashSet()1885        val rollback = mutateCurrentSession(epoch) {1886            val r = entryList.toMutableList()1887            val replaced = entryList.map { entry ->1888                if (entry.deletedAt != null) return@map entry1889                if (entry.id in incomingIds) return@map null1890                val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)1891                entry.copy(deletedAt = stamp, modifiedAt = stamp)1892            }.filterNotNull()1893            entryList = (replaced + ready).toMutableList()1894            r1895        } ?: throw IllegalStateException("vault_locked")1896        persistOrRollback(rollback, epoch)1897        return ready.size1898    }18991900    suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {1901        val epoch = requireUnlocked()1902        // H-03: read entryList, compute the patched entry, and write it under a1903        // single stateLock so a concurrent lock() cannot interleave between the1904        // lookup and the assignment (would IndexOutOfBoundsException on a shrunk1905        // list, or clobber the entry onto the wrong id after a relock).1906        val prepared = mutateCurrentSession(epoch) {1907            val idx = entryList.indexOfFirst { it.id == patch.id }1908            if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1909            val current = entryList[idx]1910            val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1911            // Only refresh passwordChangedAt when the password value actually changes.1912            val passwordChanged = patch.password != null && patch.password != current.password1913            // Capture the outgoing password (newest first) so the user can reveal/copy/1914            // restore it later. History is computed authoritatively from `current`, not1915            // the patch — updateEntry is a full-entry replace, so trusting patch's value1916            // would let a stale form clobber the real history. Record the age the old1917            // password carried, skip an empty prior, and skip an immediate exact dupe1918            // (e.g. restore-then-restore). Capped at PASSWORD_HISTORY_MAX.1919            val priorPassword = current.password1920            val shouldCapture = passwordChanged &&1921                !priorPassword.isNullOrEmpty() &&1922                current.passwordHistory?.firstOrNull()?.password != priorPassword1923            val nextHistory = if (shouldCapture) {1924                (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +1925                    (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)1926            } else {1927                current.passwordHistory1928            }1929            val updated = withDerivedLast4(patch.copy(1930                createdAt = current.createdAt,1931                modifiedAt = stamp,1932                passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,1933                passwordHistory = nextHistory,1934            ))1935            val rollback = entryList.toMutableList()1936            entryList[idx] = updated1937            updated to rollback1938        } ?: throw IllegalStateException("vault_locked")1939        val (updated, rollback) = prepared1940        persistOrRollback(rollback, epoch)1941        updated1942    }19431944    /** Soft-delete: writes a tombstone whose timestamp beats any in-flight edit. */1945    suspend fun deleteEntry(id: String) = mutex.withLock {1946        val epoch = requireUnlocked()1947        // H-03: lookup + tombstone write under stateLock so lock() cannot shrink1948        // the list out from under the indexOfFirst.1949        val rollback = mutateCurrentSession(epoch) {1950            val idx = entryList.indexOfFirst { it.id == id }1951            if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1952            val current = entryList[idx]1953            val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1954            val prior = entryList.toMutableList()1955            entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)1956            prior1957        } ?: throw IllegalStateException("vault_locked")1958        persistOrRollback(rollback, epoch)1959    }19601961    suspend fun restoreEntry(id: String) = mutex.withLock {1962        val epoch = requireUnlocked()1963        val rollback = mutateCurrentSession(epoch) {1964            val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }1965            if (idx == -1) throw IllegalStateException("deleted entry not found")1966            val current = entryList[idx]1967            val prior = entryList.toMutableList()1968            entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))1969            prior1970        } ?: throw IllegalStateException("vault_locked")1971        persistOrRollback(rollback, epoch)1972    }19731974    /** Permanent delete — no tombstone, no recovery. */1975    suspend fun purgeEntry(id: String) = mutex.withLock {1976        val epoch = requireUnlocked()1977        val rollback = mutateCurrentSession(epoch) {1978            val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }1979            if (idx == -1) throw IllegalStateException("deleted entry not found")1980            val prior = entryList.toMutableList()1981            entryList.removeAt(idx)1982            prior1983        } ?: throw IllegalStateException("vault_locked")1984        persistOrRollback(rollback, epoch)1985    }19861987    /** Permanently empty the trash — hard-deletes every soft-deleted entry. */1988    suspend fun purgeDeletedEntries(): Int = mutex.withLock {1989        val epoch = requireUnlocked()1990        // H-03: read+remove under stateLock so lock() can't reorder the remove.1991        data class R(val rollback: MutableList<VaultEntry>, val removed: Int)1992        val r = mutateCurrentSession(epoch) {1993            val rollback = entryList.toMutableList()1994            val before = entryList.size1995            entryList.removeAll { it.deletedAt != null }1996            R(rollback, before - entryList.size)1997        } ?: throw IllegalStateException("vault_locked")1998        if (r.removed > 0) persistOrRollback(r.rollback, epoch)1999        r.removed2000    }20012002    /** Browser parity: number of active entries that dedupe would move to trash. */2003    suspend fun countDuplicateEntries(): Int = mutex.withLock {2004        val epoch = requireUnlocked()2005        // countDuplicateEntriesLocked reads entryList; H-03 fences the read so2006        // lock() can't race the read with state writes.2007        mutateCurrentSession(epoch) { countDuplicateEntriesLocked() }2008            ?: throw IllegalStateException("vault_locked")2009    }20102011    /**2012     * Browser parity: soft-delete duplicate entries, keeping the most recently2013     * modified member of each group. Refuse in decoy mode so the duress vault is2014     * not reshaped into a forensically distinct state.2015     */2016    suspend fun deduplicateEntries(): Int = mutex.withLock {2017        val epoch = requireUnlocked()2018        data class R(val rollback: MutableList<VaultEntry>, val removed: Int)2019        val ready = mutateCurrentSession(epoch) {2020            if (decoyMode) throw IllegalStateException("deduplicate disabled in decoy mode")2021            val active = entryList.filter { it.deletedAt == null }2022            val keepIds = mutableSetOf<String>()2023            active.groupBy { it.duplicateKey() }.values.forEach { group ->2024                keepIds += group.maxBy { it.modifiedAt.takeIf { ts -> ts > 0 } ?: it.createdAt }.id2025            }2026            val rollback = entryList.toMutableList()2027            var removed = 02028            entryList = entryList.map { entry ->2029                if (entry.deletedAt == null && entry.id !in keepIds) {2030                    removed++2031                    val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)2032                    entry.copy(deletedAt = stamp, modifiedAt = stamp)2033                } else {2034                    entry2035                }2036            }.toMutableList()2037            R(rollback, removed)2038        } ?: throw IllegalStateException("vault_locked")2039        if (ready.removed > 0) persistOrRollback(ready.rollback, epoch)2040        ready.removed2041    }20422043    fun getEntries(): List<VaultEntry> = mutateState {2044        if (!sessionDataAvailable) emptyList() else entryList.filter { it.deletedAt == null }2045    }2046    fun getEntry(id: String): VaultEntry? = mutateState {2047        if (!sessionDataAvailable) null else entryList.firstOrNull { it.id == id && it.deletedAt == null }2048    }2049    fun getDeletedEntries(): List<VaultEntry> = mutateState {2050        if (!sessionDataAvailable) emptyList()2051        else entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }2052    }20532054    /** Active entries, optionally narrowed to those carrying [tagFilter]. */2055    fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {2056        return mutateState {2057            if (!sessionDataAvailable) return@mutateState emptyList()2058            val active = entryList.filter { it.deletedAt == null }2059            if (tagFilter == null) return@mutateState active2060            val needle = tagFilter.trim().lowercase()2061            active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }2062        }2063    }20642065    /** Sorted, de-duplicated tags across all active entries. */2066    fun getDistinctTags(): List<String> = mutateState {2067        if (!sessionDataAvailable) return@mutateState emptyList()2068        entryList.asSequence()2069            .filter { it.deletedAt == null }2070            .flatMap { it.tags?.asSequence() ?: emptySequence() }2071            .map { it.trim().lowercase() }2072            .filter { it.isNotEmpty() }2073            .distinct()2074            .sorted()2075            .toList()2076    }20772078    /**2079     * Distinct non-blank values for an identity field across active entries,2080     * most-frequently-used first. Supports "username" and "email"; unknown field2081     * names return an empty list. Values keep original casing (deduped2082     * case-insensitively) so a suggestion matches what the user typed.2083     */2084    fun getDistinctFieldValues(field: String): List<String> {2085        val select: (VaultEntry) -> String? = when (field) {2086            "username" -> { e -> e.username }2087            "email" -> { e -> e.email }2088            else -> return emptyList()2089        }2090        return mutateState {2091            if (!sessionDataAvailable) return@mutateState emptyList()2092            entryList.asSequence()2093                .filter { it.deletedAt == null }2094                .mapNotNull { select(it)?.trim() }2095                .filter { it.isNotEmpty() }2096                .groupingBy { it.lowercase() }2097                .aggregate { _, acc: Pair<String, Int>?, value, _ ->2098                    Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)2099                }2100                .values2101                .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })2102                .map { it.first }2103        }2104    }21052106    fun getTombstones(): List<Tombstone> = mutateState {2107        if (!sessionDataAvailable) emptyList()2108        else entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }2109    }2110    fun getVaultVersion(): Long = store.version()2111    fun getVaultHistory(): List<VaultSnapshot> = store.loadVaultHistory().snapshots21122113    suspend fun restoreVaultSnapshot(snapshotId: String): Boolean = mutex.withLock {2114        val expectedEpoch = currentEpoch()2115        val snapshot = store.loadVaultHistory().snapshots.firstOrNull { it.id == snapshotId } ?: return false2116        val restoredA = VaultCodec.decodeSlot(snapshot.vault_a) ?: return false2117        // H-04: snapshots now carry the duress slot too — restore preserves2118        // the at-rest triad (A/B/D), not just the A/B pair.2119        val restoredD: StoredVault? = snapshot.vault_d?.let(VaultCodec::decodeSlot)2120        val priorA = store.loadSlotA()2121        val priorB = store.loadSlotB()2122        val priorD = store.loadDecoySlot()2123        // H-02: capture pre-restore state as the recovery snapshot BEFORE any2124        // slot write — the old code took this snapshot, then stranded it on2125        // every failure, polluting history with a "restore" entry that never2126        // restored anything. The history below is rolled back together with2127        // the slots if the commit fails.2128        val priorHistory = store.loadVaultHistory()2129        // P1-4 (codex): the recovery snapshot must land before we commit the2130        // slot pair, otherwise a failed restore cannot be rolled back to the2131        // pre-restore history. If the history write itself fails, refuse to2132        // proceed — the alternative is a successful restore with no undo path.2133        beforeDurableCommit()2134        if (!takeVaultSnapshot("restore", expectedEpoch)) {2135            return false2136        }2137        // H-04: legacy snapshots without vault_d, or vault_d that fails to2138        // decode, fall back to a fake duress of slot A's size — presence-2139        // indistinguishable from any other freshly-restored vault.2140        val nextD: StoredVault = restoredD ?: run {2141            val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(restoredA) + 162142            val fakeBlob = ByteArray(target).also(rng::nextBytes)2143            val fakeSalt = VaultCrypto.generateSalt()2144            StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob))2145        }2146        if (!commitRestoreAtomic(restoredA, snapshot.vault_b, nextD, priorA, priorB, priorD, expectedEpoch)) {2147            withEpochCommit(expectedEpoch) { store.writeVaultHistory(priorHistory) }2148            return false2149        }2150        lock()2151        true2152    }21532154    /**2155     * H-02: atomic slot-A + slot-B + version stamp for a snapshot restore.2156     * Mirrors [commitVaultRotation] but writes the snapshot's EXACT slot B2157     * (a restore preserves the duress-shaped blob from history), not a fresh2158     * noise record. Any failure rolls back so the at-rest pair never holds a2159     * restored slot A against a pre-restore slot B. Caller is responsible for2160     * restoring the pre-snapshot history on a false return.2161     *2162     * H-04: duress slot is now part of the atomic triad — restored last so2163     * a duress-write failure rolls the A/B pair back too.2164     */2165    private fun commitRestoreAtomic(2166        nextA: StoredVault,2167        nextB: String,2168        nextD: StoredVault,2169        priorA: StoredVault?,2170        priorB: String?,2171        priorD: StoredVault?,2172        expectedEpoch: Long,2173    ): Boolean {2174        return withEpochCommit(expectedEpoch) {2175            if (!store.writeSlotA(nextA)) return@withEpochCommit false2176            // P1-2 (codex): writeSlotB's boolean AND any thrown exception from it2177            // must trigger rollback; previously a throw escaped without restoring2178            // the prior slot A and history.2179            try {2180                if (!store.writeSlotB(nextB)) throw java.io.IOException("slot_b_commit_failed")2181                // H-04: duress slot is part of the restore triad. Failures here2182                // roll A+B back so the at-rest state stays consistent.2183                if (!store.writeDecoySlot(nextD)) throw java.io.IOException("duress_slot_commit_failed")2184                store.stampLocalMutation()2185            } catch (_: Exception) {2186                reportRollbackFailures(slotRollback.restoreTriad(priorA, priorB, priorD))2187                return@withEpochCommit false2188            }2189            true2190        } ?: false2191    }21922193    // ---- Sync apply (does NOT advance the version) ------------------------21942195    /**2196     * Apply remote entryList + tombstones with per-entry last-write-wins. Persists2197     * WITHOUT bumping the version counter, so a sync round cannot cascade into2198     * another outbound sync. Returns the number of locally-applied changes.2199     */2200    suspend fun applyMergedRemoteEntries(2201        remoteEntries: List<VaultEntry>,2202        remoteTombstones: List<Tombstone>,2203        expectedEpoch: Long? = null,2204    ): Int = mutex.withLock {2205        val epoch = expectedEpoch ?: requireUnlocked()2206        if (expectedEpoch != null && mutateIfCurrentEpoch(epoch) { true } != true) return@withLock 02207        // HV-1: clamp every peer-supplied timestamp to now + MAX_CLOCK_SKEW_MS2208        // BEFORE any comparison against a local one. Without this a peer can2209        // send a far-future modifiedAt and permanently pin its version of an2210        // entry against every honest local edit. The browser clamps in the2211        // matching place (vault.ts applyMergedRemoteEntries).2212        val mergeNow = System.currentTimeMillis()2213        val clamped = remoteEntries.mapNotNull { entry ->2214            // MN-3: drop peer entries that decode cleanly but are semantically2215            // hollow (blank title, credential-less login, husk passkey) and2216            // re-cap passwordHistory before anything merges into the vault.2217            SyncEntrySanitizer.sanitize(entry, PASSWORD_HISTORY_MAX)?.copy(2218                modifiedAt = SyncLimits.clampSyncTimestamp(entry.modifiedAt, mergeNow),2219                deletedAt = entry.deletedAt?.let {2220                    SyncLimits.clampSyncTimestamp(it, mergeNow)2221                },2222            )2223        }2224        val tombMap = remoteTombstones.associate {2225            it.id to SyncLimits.clampSyncTimestamp(it.deletedAt, mergeNow)2226        }2227        // H-03: build the new entryList under stateLock so a concurrent lock()2228        // cannot zero derivedKey/entryList between the byId read and the merge.2229        val applied = mutateCurrentSession(epoch) {2230            var n = 02231            val byId = entryList.associateBy { it.id }.toMutableMap()22322233            for (remote in clamped) {2234                val tomb = tombMap[remote.id]2235                if (tomb != null && tomb >= remote.modifiedAt) continue2236                val local = byId[remote.id]2237                if (local == null) {2238                    entryList.add(remote); byId[remote.id] = remote; n++2239                } else if (remote.modifiedAt > local.modifiedAt) {2240                    val i = entryList.indexOfFirst { it.id == local.id }2241                    if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; n++ }2242                }2243            }22442245            for ((id, deletedAt) in tombMap) {2246                val local = byId[id] ?: continue2247                if (local.deletedAt != null && local.deletedAt >= deletedAt) continue2248                if (deletedAt < local.modifiedAt) continue2249                val i = entryList.indexOfFirst { it.id == id }2250                if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); n++ }2251            }2252            n2253        } ?: return@withLock 022542255        if (applied > 0) {2256            persistSlotA(bumpVersion = false, snapshotReason = "sync_received", expectedEpoch = epoch)2257            mutateIfCurrentEpoch(epoch) { publish() }2258            runCatching { LockedSyncSpoolHooks.refresh(this) }2259        }2260        applied2261    }22622263    suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {2264        // A decoy session edits an in-memory copy only — discarded at lock.2265        // The real vault's settings record is not the duress session's to2266        // change, and letting it through weakened capture protection on a plain2267        // in-app surface (PB-26-120).2268        if (mutateState { decoyMode }) {2269            val decoyEpoch = requireUnlocked()2270            mutateCurrentSession(decoyEpoch) { _settings.value = settings }2271                ?: throw IllegalStateException("vault_locked")2272            return@withLock2273        }2274        // Require a fully live session before exposing a settings mutation.  The2275        // epoch is captured with the read so a lock/new-session boundary cannot2276        // let stale work publish into the replacement session.2277        val epoch = requireUnlocked()2278        val prior = mutateCurrentSession(epoch) {2279            val old = _settings.value2280            _settings.value = settings2281            old2282        } ?: throw IllegalStateException("vault_locked")22832284        val committed = try {2285            beforeDurableCommit()2286            // The durable write is inside the same epoch fence as the in-memory2287            // publication.  If lock() won first, this returns null and no stale2288            // settings reach storage or the public StateFlow.2289            withSessionEpochCommit(epoch) { store.writeSettings(settings) } == true2290        } catch (_: Exception) {2291            false2292        }2293        if (!committed) {2294            // A live-session storage failure rolls back the public value.  A2295            // stale epoch is already reset by lock()/the new session and must2296            // not be allowed to overwrite that safe state.2297            mutateIfCurrentEpoch(epoch) { _settings.value = prior }2298            throw IllegalStateException("settings_write_failed")2299        }2300    }23012302    // ---- Recovery words (vault metadata) ----------------------------------23032304    /** True once the user has confirmed their recovery words for this vault. */2305    fun isRecoveryWordsSet(): Boolean = mutateState { recoveryWordsSet }23062307    /**2308     * Record the BLAKE3 hash of the confirmed recovery words and mark them set.2309     * Persisted without bumping the version — recovery metadata is local-only and2310     * is not an entry mutation paired devices should sync against.2311     */2312    suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {2313        val epoch = requireUnlocked()2314        // H-03: hash + escrow-related state fields set under stateLock so a2315        // concurrent lock() cannot zero them in the middle of buildRecoveryEscrow.2316        // M-04: the flags have to be live before the escrows are built — both seal2317        // currentPayload() — so capture the prior pair and put it back if the write2318        // never lands. Otherwise the session reports words set against a slot A2319        // that still holds no escrow, and the recovery screen never offers a retry.2320        val prior = mutateCurrentSession(epoch) {2321            val priorPair = recoveryWordHash to recoveryWordsSet2322            recoveryWordHash = recoveryWordsHash(words)2323            recoveryWordsSet = true2324            priorPair2325        } ?: return@withLock false2326        // Seal TWO escrows (MF-1): the browser-byte-compatible root-key escrow2327        // (cross-platform recovery of the sync root key) and Android's whole-payload2328        // escrow (offline forgot-password restore of entries). Both derive their key2329        // from the same `wordsToRootKeyMaterial` IKM but use distinct AADs.2330        val persisted = runCatching {2331            persistSlotAWithEscrows(2332                buildRecoveryEscrow(words),2333                buildRootKeyEscrow(words),2334                expectedEpoch = epoch,2335            )2336        }.getOrDefault(false)2337        if (!persisted) {2338            mutateIfCurrentEpoch(epoch) {2339                recoveryWordHash = prior.first2340                recoveryWordsSet = prior.second2341            }2342        }2343        persisted2344    }23452346    /** Verify entered words against the stored recovery hash. */2347    fun verifyRecoveryWords(words: List<String>): Boolean {2348        return mutateState {2349            val stored = recoveryWordHash ?: return@mutateState false2350            MessageDigest.isEqual(2351                stored.toByteArray(Charsets.UTF_8),2352                recoveryWordsHash(words).toByteArray(Charsets.UTF_8),2353            )2354        }2355    }23562357    // ---- Recovery escrow (forgot-password) --------------------------------23582359    /** True at rest if this vault has any recovery escrow the recovery flow can use. */2360    fun hasRecoveryEscrow(): Boolean =2361        store.loadSlotA()?.let { it.recoveryEscrow != null || it.rootKeyEscrow != null } ?: false23622363    /**2364     * One-time self-heal: if this vault has a root key but no recovery escrow2365     * on disk (adopted vaults created before the escrow fix), build and persist2366     * it now. Called on every successful unlock; no-ops once the escrow exists.2367     */2368    private fun ensureRecoveryEscrow() {2369        if (hasRecoveryEscrow()) return2370        val rk = mutateState { rootKey?.copyOf() } ?: return2371        runCatching {2372            val words = rootKeyToWords(rk)2373            val escrow = buildRecoveryEscrow(words)2374            val rkEscrow = buildRootKeyEscrow(words)2375            if (escrow != null || rkEscrow != null) {2376                val prior = store.loadSlotA() ?: return@runCatching2377                store.writeSlotA(prior.copy(2378                    recoveryEscrow = escrow ?: prior.recoveryEscrow,2379                    rootKeyEscrow = rkEscrow ?: prior.rootKeyEscrow,2380                ))2381                mutateState {2382                    recoveryWordHash = recoveryWordsHash(words)2383                    recoveryWordsSet = true2384                }2385            }2386        }.also { VaultCrypto.zero(rk) }2387    }23882389    /**2390     * Attempt to unlock the vault using the 12 BIP39 recovery [words] instead of2391     * the master password. On success the slot-A plaintext sealed in the escrow is2392     * adopted as the live session (entries, rootKey, settings), but no Argon2id2393     * password key exists yet — call [resetPasswordWithRecoveryWords] next to set a2394     * new password and finish unlocking. Returns false when there is no escrow, the2395     * words fail the BIP39 checksum, or the words are wrong (GCM tag mismatch).2396     *2397     * Unlike the brief's `unlockWithRecoveryWords(): ByteArray?`, there is no2398     * detached vault key to return here — slot A is wrapped under the rotating2399     * Argon2id key — so this opens the escrowed payload directly.2400     */2401    suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {2402        val expectedEpoch = currentEpoch()2403        val slotA = store.loadSlotA() ?: return false2404        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false24052406        // Prefer Android's whole-payload escrow: a full offline restore of entries,2407        // root key, and settings. Present for Android-created vaults.2408        val fullEscrow = slotA.recoveryEscrow2409        if (fullEscrow != null) {2410            val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull()2411            if (material != null) {2412                var keyBytes: ByteArray? = null2413                var plaintext: ByteArray? = null2414                var candidateRoot: ByteArray? = null2415                var stateCommitStarted = false2416                try {2417                    keyBytes = deriveRecoveryKey(material, unb64(fullEscrow.salt)).encoded2418                    plaintext = VaultCrypto.decrypt(unb64(fullEscrow.blob), keyBytes!!, VaultCrypto.AAD_RECOVERY)2419                    val payload = VaultCodec.decode(plaintext)2420                    // Stage every fallible operation before touching live session2421                    // fields.  In particular, a settings/provider/decode failure2422                    // cannot leave entries, flags, or a root key resident while the2423                    // public session remains locked.2424                    val candidateSettings = store.loadSettings()2425                    candidateRoot = if (payload.rootKeyB64.isNotBlank()) {2426                        val decodedRoot = unb64(payload.rootKeyB64)2427                        if (decodedRoot.size != VaultCrypto.KEY_SIZE) {2428                            // Do not let a malformed authenticated payload abandon2429                            // this decoded root-key candidate before the outer2430                            // finally block owns it.2431                            VaultCrypto.zero(decodedRoot)2432                            throw IllegalArgumentException("invalid recovery root key")2433                        }2434                        decodedRoot2435                    } else {2436                        generateRecoverableRootKey()2437                    }2438                    stateCommitStarted = true2439                    val adopted = mutateIfCurrentEpoch(expectedEpoch) {2440                        clearSessionStateLocked()2441                        entryList = payload.entries.toMutableList()2442                        authenticatedDuressConfigured = payload.duressConfigured2443                        _duressConfigured.value = payload.duressConfigured2444                        recoveryWordHash = payload.recoveryWordHash2445                        recoveryWordsSet = payload.recoveryWordsSet2446                        rootKey = candidateRoot2447                        candidateRoot = null2448                        _settings.value = candidateSettings2449                        publish()2450                        // This is the authenticated recovery half-unlock boundary:2451                        // only set it after every candidate field is installed.2452                        sessionDataAvailable = true2453                        _isUnlocked.value = false2454                        true2455                    }2456                    if (adopted == true) return@withLock true2457                } catch (_: Exception) {2458                    // Wrong words, malformed payloads, provider failures, and2459                    // settings failures all fall through to the browser-compatible2460                    // root-key escrow.  If the state commit had started, invalidate2461                    // that epoch so no partial candidate survives.2462                    if (stateCommitStarted) {2463                        mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }2464                    }2465                } finally {2466                    plaintext?.let(VaultCrypto::zero)2467                    VaultCrypto.zero(material)2468                    keyBytes?.let(VaultCrypto::zero)2469                    candidateRoot?.let(VaultCrypto::zero)2470                }2471            }2472        }24732474        // Browser-format vault (only the root-key escrow): recover the 32-byte root2475        // key (sync identity) and reset the password; entries return via sync. This2476        // is exactly the browser's recovery semantics (`messages.ts:312-347`).2477        val rootEscrow = slotA.rootKeyEscrow2478        if (rootEscrow != null) {2479            var candidateRoot: ByteArray? = null2480            var stateCommitStarted = false2481            try {2482                candidateRoot = unsealRootKeyEscrow(words, rootEscrow) ?: return false2483                require(candidateRoot!!.size == VaultCrypto.KEY_SIZE) { "invalid recovery root key" }2484                val candidateSettings = store.loadSettings()2485                stateCommitStarted = true2486                val adopted = mutateIfCurrentEpoch(expectedEpoch) {2487                    clearSessionStateLocked()2488                    entryList = mutableListOf()2489                    authenticatedDuressConfigured = false2490                    _duressConfigured.value = false2491                    recoveryWordHash = recoveryWordsHash(words)2492                    recoveryWordsSet = true2493                    rootKey = candidateRoot2494                    candidateRoot = null2495                    _settings.value = candidateSettings2496                    publish()2497                    sessionDataAvailable = true2498                    _isUnlocked.value = false2499                    true2500                }2501                if (adopted == true) return@withLock true2502            } catch (_: Exception) {2503                if (stateCommitStarted) {2504                    mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }2505                }2506            } finally {2507                candidateRoot?.let(VaultCrypto::zero)2508            }2509        }2510        return false2511    }25122513    /**2514     * After [unlockWithRecoveryWords] succeeds, set a brand-new master password:2515     * re-seal slot A under a fresh Argon2id key, rotate the escrow under the same2516     * words, mark the session fully unlocked, and publish. Returns false if called2517     * without a prior successful recovery unlock (no in-memory root key).2518     *2519     * Folds the brief's `resetPasswordWithRecoveryKey(vaultKey, …)` + `unlock(…)`2520     * into one step, since there is no detached vault key here.2521     */2522    suspend fun resetPasswordWithRecoveryWords(2523        words: List<String>,2524        newPassword: String,2525    ): Boolean = mutex.withLock {2526        val expectedEpoch = currentEpoch()2527        // H-03: read rootKey + entryList under stateLock before computing the new2528        // plaintext, then re-publish + swap the derived key under stateLock so a2529        // concurrent lock() cannot straddle the two fences.2530        if (mutateIfCurrentEpoch(expectedEpoch) { rootKey != null } != true) return false2531        val priorA = store.loadSlotA() ?: return false2532        var newKey: ByteArray? = null2533        var plaintext: ByteArray? = null2534        return try {2535            val newSalt = VaultCrypto.generateSalt()2536            newKey = VaultCrypto.deriveKey(newPassword, newSalt)2537            plaintext = VaultCodec.encode(currentPayload())2538            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))2539            // Rebuild both escrows against the recovered session so their salts rotate2540            // with the password reset; fall back to the prior escrows if rebuild fails2541            // (e.g. a checksum-invalid phrase). The same 12 words keep working.2542            val valid = words.size == 12 && findInvalidWords(words).isEmpty()2543            val freshRecovery = if (valid) buildRecoveryEscrow(words) ?: priorA.recoveryEscrow else priorA.recoveryEscrow2544            val freshRootKey = if (valid) buildRootKeyEscrow(words) ?: priorA.rootKeyEscrow else priorA.rootKeyEscrow2545            val next = StoredVault(2546                version = priorA.version,2547                salt = b64(newSalt),2548                blob = blob,2549                recoveryEscrow = freshRecovery,2550                rootKeyEscrow = freshRootKey,2551            )2552            // H-01: see changePassword — both rotations share the same2553            // commit-or-keep-old-key contract so a partial write can't strand2554            // the session on a key that no longer matches disk.2555            val priorB = store.loadSlotB()2556            if (!commitVaultRotation(priorA, priorB, next, expectedEpoch)) return false2557            // H-03 (P1-2 codex): zero the old live key and install the new one2558            // inside the same stateLock critical section so a concurrent lock()2559            // can't observe the in-between.2560            if (mutateIfCurrentEpoch(expectedEpoch) {2561                derivedKey?.let(VaultCrypto::zero)2562                derivedKey = newKey; newKey = null2563                publish()2564                _isUnlocked.value = true2565            } == null) return false2566            VaultKeyRotationHooks.onRotated()2567            true2568        } catch (_: Exception) {2569            false2570        } finally {2571            newKey?.let(VaultCrypto::zero)2572            plaintext?.let(VaultCrypto::zero)2573        }2574    }25752576    /**2577     * Seal the current slot-A plaintext under a key derived from the 12 BIP392578     * recovery [words] (Android offline-restore escrow). IKM is the browser's2579     * `wordsToRootKeyMaterial` (MF-1), AAD is the string [VaultCrypto.AAD_RECOVERY].2580     * Returns null for a checksum-invalid phrase.2581     */2582    private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {2583        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null2584        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2585        var keyBytes: ByteArray? = null2586        var plaintext: ByteArray? = null2587        return try {2588            val salt = VaultCrypto.generateSalt()2589            val recoveryKey = deriveRecoveryKey(material, salt)2590            keyBytes = recoveryKey.encoded2591            plaintext = VaultCodec.encode(currentPayload())2592            val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)2593            RecoveryEscrow(salt = b64(salt), blob = b64(sealed))2594        } finally {2595            VaultCrypto.zero(material)2596            keyBytes?.let(VaultCrypto::zero)2597            plaintext?.let(VaultCrypto::zero)2598        }2599    }26002601    /**2602     * Seal ONLY the 32-byte root key under a key the recovery [words] derive,2603     * byte-for-byte the browser algorithm (MF-1): plaintext = lowercase ASCII hex2604     * of the root key, IKM = `wordsToRootKeyMaterial`, HKDF salt random-16,2605     * info `peach-recovery-v1`, AES-256-GCM AAD = 0x01. The same 12 words unwrap2606     * the same root key on the browser. Returns null with no in-memory root key or2607     * a checksum-invalid phrase.2608     */2609    private fun buildRootKeyEscrow(words: List<String>): RootKeyEscrow? {2610        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null2611        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2612        val rk = mutateState { rootKey?.copyOf() } ?: run {2613            VaultCrypto.zero(material)2614            return null2615        }2616        var keyBytes: ByteArray? = null2617        var plaintext: ByteArray? = null2618        return try {2619            val salt = VaultCrypto.generateSalt()2620            val recoveryKey = deriveRecoveryKey(material, salt)2621            keyBytes = recoveryKey.encoded2622            plaintext = rootKeyToHex(rk).toByteArray(Charsets.US_ASCII)2623            // combined = nonce(12) || ciphertext || tag(16)2624            val combined = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)2625            val nonce = combined.copyOfRange(0, VaultCrypto.NONCE_SIZE)2626            val ctTag = combined.copyOfRange(VaultCrypto.NONCE_SIZE, combined.size)2627            val tag = ctTag.copyOfRange(ctTag.size - 16, ctTag.size)2628            val ct = ctTag.copyOfRange(0, ctTag.size - 16)2629            RootKeyEscrow(salt = b64(salt), wrappedRootKey = b64(ct), nonce = b64(nonce), tag = b64(tag))2630        } finally {2631            VaultCrypto.zero(rk)2632            VaultCrypto.zero(material)2633            keyBytes?.let(VaultCrypto::zero)2634            plaintext?.let(VaultCrypto::zero)2635        }2636    }26372638    /** Unwrap the 32-byte root key from a browser-compatible [escrow]; null on wrong words. */2639    private fun unsealRootKeyEscrow(words: List<String>, escrow: RootKeyEscrow): ByteArray? {2640        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2641        var keyBytes: ByteArray? = null2642        var pt: ByteArray? = null2643        return try {2644            val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))2645            keyBytes = recoveryKey.encoded2646            val combined = unb64(escrow.nonce) + unb64(escrow.wrappedRootKey) + unb64(escrow.tag)2647            pt = VaultCrypto.decrypt(combined, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)2648            hexToRootKey(String(pt, Charsets.US_ASCII))2649        } catch (_: Exception) {2650            null2651        } finally {2652            // M-05: pt is the lowercase hex of the 32-byte root key — i.e. the2653            // IKM-equivalent of the vault identity. material+keyBytes were2654            // already zeroed; pt was leaking.2655            VaultCrypto.zero(material)2656            keyBytes?.let(VaultCrypto::zero)2657            pt?.let(VaultCrypto::zero)2658        }2659    }26602661    /**2662     * Re-seal slot A from the current in-memory state under the live key, carrying2663     * both [recoveryEscrow] and [rootKeyEscrow] onto the written record. Never runs2664     * in decoy mode (recovery is never offered for the decoy) and persists without2665     * a version bump, like the recovery-words metadata write it replaces.2666     */2667    private fun persistSlotAWithEscrows(2668        recoveryEscrow: RecoveryEscrow?,2669        rootKeyEscrow: RootKeyEscrow?,2670        expectedEpoch: Long? = null,2671    ): Boolean {2672        val snapshot = snapshotForPersist(expectedEpoch)2673            ?: throw IllegalStateException("vault_locked_or_stale")2674        if (snapshot.decoy) {2675            VaultCrypto.zero(snapshot.key)2676            return false2677        }2678        try {2679            val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")2680            val plaintext = VaultCodec.encode(snapshot.payload)2681            val blob = try {2682                b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))2683            } finally {2684                // The escrow path used to drop this reference before zeroing it;2685                // keep it live through the fill on both success and failure.2686                VaultCrypto.zero(plaintext)2687            }2688            val next = prior.copy(2689                blob = blob,2690                recoveryEscrow = recoveryEscrow ?: prior.recoveryEscrow,2691                rootKeyEscrow = rootKeyEscrow ?: prior.rootKeyEscrow,2692            )2693            beforeDurableCommit()2694            return withEpochCommit(snapshot.epoch) {2695                if (!store.writeSlotA(next)) return@withEpochCommit false2696                try {2697                    if (!writeMatchingNoiseSlotB(next)) throw java.io.IOException("noise_slot_b_commit_failed")2698                    // H-04: escrow rebuild changes slot A's plaintext size, so re-pad2699                    // the duress slot too. A real decoy is left alone; a fake is2700                    // re-sized to slot A's new ciphertext length.2701                    if (!writeCompanionDuressSlot(next)) throw java.io.IOException("duress_slot_commit_failed")2702                } catch (e: Exception) {2703                    store.writeSlotA(prior)2704                    throw e2705                }2706                true2707            } ?: false2708        } finally {2709            VaultCrypto.zero(snapshot.key)2710        }2711    }27122713    // ---- Internals --------------------------------------------------------27142715    private fun requireUnlocked(): Long {2716        // H-03: read derivedKey atomically with [lock]'s reset; without it,2717        // [lock] from a background lifecycle event can run between this read2718        // and the caller's first state touch.2719        stateLock.lock()2720        try {2721            if (derivedKey == null) throw IllegalStateException("vault_locked")2722            return sessionEpoch2723        } finally {2724            stateLock.unlock()2725        }2726    }27272728    /** A locked or half-adopted session must not expose secret-bearing fields. */2729    private fun isFullyUnlockedLocked(): Boolean = _isUnlocked.value && derivedKey != null27302731    private fun countDuplicateEntriesLocked(): Int {2732        val seen = mutableMapOf<String, VaultEntry>()2733        var duplicates = 02734        for (entry in entryList.filter { it.deletedAt == null }) {2735            val key = entry.duplicateKey()2736            val existing = seen[key]2737            if (existing == null) {2738                seen[key] = entry2739            } else {2740                duplicates++2741                val entryStamp = entry.modifiedAt.takeIf { it > 0 } ?: entry.createdAt2742                val existingStamp = existing.modifiedAt.takeIf { it > 0 } ?: existing.createdAt2743                if (entryStamp > existingStamp) seen[key] = entry2744            }2745        }2746        return duplicates2747    }27482749    private fun VaultEntry.duplicateKey(): String {2750        if (type == "note") return "note|${title.lowercase()}"2751        val passkeyData = passkey2752        if (passkeyData != null) {2753            return "passkey|${passkeyData.rpId.lowercase()}|${passkeyData.userName.lowercase()}"2754        }2755        return "login|${title.lowercase()}|${url.orEmpty().lowercase()}|${username.orEmpty().lowercase()}"2756    }27572758    /**2759     * Capture the current slot pair (and metadata) into the history list.2760     * Returns true when the history write landed, false when it didn't — callers2761     * that depend on the snapshot existing (notably [restoreVaultSnapshot])2762     * must check the result and roll back if it does not.2763     */2764    private fun takeVaultSnapshot(reason: String, expectedEpoch: Long? = null): Boolean {2765        val epoch = expectedEpoch ?: currentEpoch()2766        if (mutateIfCurrentEpoch(epoch) { true } != true) return false2767        val slotA = store.loadSlotA() ?: return false2768        val vaultA = VaultCodec.encodeSlot(slotA)2769        val vaultB = store.loadSlotB() ?: slotA.blob2770        // H-04: capture the duress slot so a restore preserves the at-rest2771        // triad, not just the A/B pair. The duress slot is always present2772        // (real or fake), so loadDecoySlot() returning null is a logic error2773        // — fall through to a fake duress in that case rather than silently2774        // losing the record from the snapshot.2775        val vaultD = store.loadDecoySlot()?.let(VaultCodec::encodeSlot) ?: run {2776            val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 162777            val fakeBlob = ByteArray(target).also(rng::nextBytes)2778            val fakeSalt = VaultCrypto.generateSalt()2779            VaultCodec.encodeSlot(StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob)))2780        }2781        val history = store.loadVaultHistory()2782        val latest = history.snapshots.firstOrNull()2783        if (latest?.vault_a == vaultA && latest.vault_b == vaultB && latest.vault_d == vaultD) return true2784        val entryCount = mutateIfCurrentEpoch(epoch) {2785            if (derivedKey != null && !decoyMode) {2786                bucketEntryCount(entryList.count { it.deletedAt == null })2787            } else {2788                null2789            }2790        } ?: return false2791        return try {2792            val snapshot = VaultSnapshot(2793                id = UUID.randomUUID().toString(),2794                savedAt = System.currentTimeMillis(),2795                reason = reason,2796                vault_a = vaultA,2797                vault_b = vaultB,2798                vault_d = vaultD,2799                entryCount = entryCount,2800            )2801            // P1-4 (codex): return the history-write boolean to callers so a2802            // false return no longer leaves the snapshot out of history while2803            // callers (notably restoreVaultSnapshot) proceed as if it succeeded.2804            withEpochCommit(epoch) {2805                store.writeVaultHistory(2806                    history.copy(snapshots = (listOf(snapshot) + history.snapshots).take(VAULT_HISTORY_MAX)),2807                )2808            } ?: false2809        } catch (_: Exception) {2810            false2811        }2812    }28132814    private fun bucketEntryCount(n: Int): Int = when {2815        n <= 0 -> 02816        n <= 10 -> 102817        n <= 25 -> 252818        n <= 50 -> 502819        n <= 100 -> 1002820        n <= 250 -> 2502821        n <= 500 -> 5002822        else -> ((n + 499) / 500) * 5002823    }28242825    /**2826     * Keep [VaultEntry.last4] in sync with the card number for card entries (MF-3),2827     * so it is stored explicitly and survives the sync wire format rather than being2828     * re-derived at render time. Non-card entries pass through unchanged.2829     *2830     * M-03: never overwrite a stored last4 with null. A card kept only as last42831     * (e.g. after a PeachScript import that had no PAN) must keep that value;2832     * re-deriving from an absent cardNumber would silently zero the field.2833     */2834    private fun withDerivedLast4(entry: VaultEntry): VaultEntry {2835        if (!entry.isCard()) return entry2836        val digits = entry.cardNumber?.filter { it.isDigit() } ?: ""2837        val derived = if (digits.length >= 4) digits.takeLast(4) else null2838        return entry.copy(last4 = derived ?: entry.last4)2839    }28402841    /**2842     * On unlock, hard-delete trashed entries older than the retention window.2843     * A null or non-positive [VaultSettings.trashRetentionDays] means "never"2844     * (the app's "Never" option), so nothing is purged. Persists without a2845     * version bump and without touching the publish state (caller publishes).2846     */2847    private fun autoPurgeExpiredTrash() {2848        val days = _settings.value.trashRetentionDays ?: return2849        if (days <= 0) return2850        val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L2851        val before = entryList.size2852        entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }2853        if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }2854    }28552856    /**2857     * Browser parity (P1): merge orphaned passkey-only entries into matching2858     * login entries that share the same registrable domain. A passkey-only2859     * entry has passkey fields (rpId + credentialId) but no password. Runs on2860     * unlock so consolidation is idempotent and cheap.2861     */2862    private fun consolidatePasskeyEntries() {2863        val passkeyOnly = entryList.filter { entry ->2864            entry.deletedAt == null &&2865                entry.isLogin() &&2866                entry.password.isNullOrBlank() &&2867                !entry.rpId.isNullOrBlank() &&2868                !entry.credentialId.isNullOrBlank()2869        }2870        if (passkeyOnly.isEmpty()) return2871        var changed = false2872        val now = System.currentTimeMillis()2873        for (pkEntry in passkeyOnly) {2874            val rpId = pkEntry.rpId ?: continue2875            val target = entryList.firstOrNull { candidate ->2876                candidate.deletedAt == null &&2877                    candidate.id != pkEntry.id &&2878                    candidate.isLogin() &&2879                    candidate.passkey == null &&2880                    candidate.credentialId.isNullOrBlank() &&2881                    !candidate.password.isNullOrBlank() &&2882                    listOfNotNull(candidate.url, *candidate.additionalUrls.orEmpty().toTypedArray())2883                        .any { com.peachpasswords.shared.extractDomain(it) == rpId }2884            } ?: continue2885            val idx = entryList.indexOfFirst { it.id == target.id }2886            if (idx < 0) continue2887            entryList[idx] = target.copy(2888                rpId = pkEntry.rpId,2889                rpName = pkEntry.rpName ?: target.rpName,2890                credentialId = pkEntry.credentialId,2891                publicKeyCose = pkEntry.publicKeyCose,2892                privateKeyJwk = pkEntry.privateKeyJwk,2893                userHandle = pkEntry.userHandle,2894                userName = pkEntry.userName,2895                userDisplayName = pkEntry.userDisplayName,2896                algorithm = pkEntry.algorithm,2897                signCount = pkEntry.signCount,2898                lastUsedAt = pkEntry.lastUsedAt,2899                modifiedAt = now,2900            )2901            // Soft-delete the orphan so it lands in trash (recoverable).2902            val pkIdx = entryList.indexOfFirst { it.id == pkEntry.id }2903            if (pkIdx >= 0) entryList[pkIdx] = pkEntry.copy(deletedAt = now)2904            changed = true2905        }2906        if (changed) runCatching { persistSlotA(bumpVersion = false) }2907    }29082909    /** The slot-A plaintext envelope for the current in-memory session. */2910    private fun currentPayload(): VaultPayload = mutateState { currentPayloadLocked() }29112912    private fun currentPayloadLocked(): VaultPayload =2913        VaultPayload(2914            entries = entryList.toList(),2915            duressConfigured = authenticatedDuressConfigured,2916            rootKeyB64 = rootKey?.let(::b64) ?: "",2917            recoveryWordHash = recoveryWordHash,2918            recoveryWordsSet = recoveryWordsSet,2919        )29202921    /**2922     * Adopt the payload's root key, lazily minting one for legacy payloads.2923     * A freshly-minted key is persisted WITHOUT bumping the version — adopting2924     * a root key is not a mutation paired devices should sync against.2925     */2926    private fun ensureRootKey(payload: VaultPayload) {2927        if (payload.rootKeyB64.isNotBlank()) {2928            rootKey = unb64(payload.rootKeyB64)2929            return2930        }2931        rootKey = generateRecoverableRootKey()2932        runCatching { persistSlotA(bumpVersion = false) }2933    }29342935    private fun publish() {2936        _entries.value = entryList.filter { it.deletedAt == null }2937    }29382939    private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {2940        var plaintext = VaultCodec.encode(currentPayload())2941        return try {2942            val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))2943            StoredVault(version = LEGACY_ANDROID_SLOT_VERSION, salt = b64(salt), blob = blob)2944        } finally {2945            // M-05: full vault plaintext is allocated here once per createVault.2946            // Zeroing in finally keeps the transient copy off the heap after the2947            // caller either succeeds or rolls back via lock().2948            VaultCrypto.zero(plaintext)2949        }2950    }29512952    private fun writeMatchingNoiseSlotB(slotA: StoredVault): Boolean {2953        // Size the noise so its base64 length matches slot A's blob (MN-1): with the2954        // plaintext now bucket-padded, an at-rest observer sees two equal-length slots2955        // and cannot pick the real one by size. b64(N bytes) ≈ N*4/3 chars.2956        val approxBytes = (slotA.blob.length * 3 / 4).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)2957        val noise = ByteArray(approxBytes).also(rng::nextBytes)2958        return store.writeSlotB(b64(noise))2959    }29602961    /** H-04: the ciphertext length slot A is using right now, so the duress2962     *  slot's blob can match it on disk. AES-GCM is a stream cipher — plaintext2963     *  length equals ciphertext length, so this also matches slot A's plaintext. */2964    private fun matchingCiphertextLength(slotA: StoredVault): Int =2965        (unb64(slotA.blob).size - VaultCrypto.NONCE_SIZE - 16).coerceAtLeast(0)29662967    /** H-04: a decoy-shaped StoredVault with a random blob of [matchingCiphertextLength]2968     *  bytes. Replaces a real decoy when the user clears duress, and is the2969     *  initial duress slot when no decoy is configured — so the record's2970     *  PRESENCE on disk is independent of authenticatedDuressConfigured, and its SIZE2971     *  matches slot A's blob length. */2972    private fun writeFakeDuressSlot(slotA: StoredVault): Boolean {2973        val blobSize = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 162974        val fakeBlob = ByteArray(blobSize).also(rng::nextBytes)2975        val fakeSalt = VaultCrypto.generateSalt()2976        return store.writeDecoySlot(StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob)))2977    }29782979    /** H-04: keep the duress record present on every persist. A real decoy is2980     *  left alone (it was padded at setDuressPassphrase time, and we don't have2981     *  the duress key here to re-seal it) — VaultStore re-pads both slot2982     *  records to the longer of the two on every write, which is what keeps the2983     *  pair the same length after slot A crosses a padding bucket2984     *  (PAI-2026-004). No real decoy → a fresh fake of slot A's size. */2985    private fun writeCompanionDuressSlot(slotA: StoredVault): Boolean {2986        val isConfigured = mutateState { authenticatedDuressConfigured }2987        return if (isConfigured) true else writeFakeDuressSlot(slotA)2988    }29892990    /**2991     * H-04: convert a browser-shaped duress slot to Android StoredVault2992     * without decrypting. The browser seals slot "b" under the duress2993     * passphrase; decrypting with the main password silently drops it.2994     * Concatenates nonce‖ciphertext‖tag into Android's blob and re-encodes2995     * the salt from hex to base64.2996     */2997    private fun browserDuressPassthrough(b: BrowserSlotA): StoredVault {2998        val salt = unhex(b.salt)2999        val nonce = unhex(b.nonce)3000        val ct = unhex(b.ciphertext)3001        val tag = unhex(b.tag)3002        val blob = ByteArray(nonce.size + ct.size + tag.size).also {3003            System.arraycopy(nonce, 0, it, 0, nonce.size)3004            System.arraycopy(ct, 0, it, nonce.size, ct.size)3005            System.arraycopy(tag, 0, it, nonce.size + ct.size, tag.size)3006        }3007        return StoredVault(version = LEGACY_ANDROID_SLOT_VERSION, salt = b64(salt), blob = b64(blob))3008    }3009    /** Re-seal slot A from the current in-memory state under the live key. */3010    private fun persistSlotA(3011        bumpVersion: Boolean,3012        snapshotReason: String? = "local_save",3013        expectedEpoch: Long? = null,3014    ): Boolean {3015        val snapshot = snapshotForPersist(expectedEpoch)3016            ?: throw IllegalStateException("vault_locked_or_stale")3017        return try {3018            // Decoy sessions persist to the decoy slot only — never touch the real slot A.3019            if (snapshot.decoy) {3020                val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")3021                val plaintext = VaultCodec.encode(snapshot.payload)3022                val blob = try {3023                    b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_B))3024                } finally {3025                    // Keep the last reference alive until the zero, including the3026                    // successful encrypt path (M-05).3027                    VaultCrypto.zero(plaintext)3028                }3029                beforeDurableCommit()3030                return withEpochCommit(snapshot.epoch) {3031                    store.writeDecoySlot(prior.copy(version = CURRENT_ANDROID_SLOT_VERSION, blob = blob))3032                } ?: false3033            }3034            val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")3035            // H-01: captured BEFORE the noise write so a stamp failure can restore3036            // the prior slot B alongside the prior slot A. Slot B is always3037            // overwritten by writeMatchingNoiseSlotB below, so a stamp failure3038            // leaves (new A, new B, old version) on disk — partial commit.3039            val priorB = store.loadSlotB()3040            beforeDurableCommit()3041            if (snapshotReason != null && !takeVaultSnapshot(snapshotReason, snapshot.epoch)) return false3042            val plaintext = VaultCodec.encode(snapshot.payload)3043            val blob = try {3044                b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))3045            } finally {3046                // Do not drop [plaintext] before fill(0): the serialized vault3047                // contains every entry password and is the primary M-05 target.3048                VaultCrypto.zero(plaintext)3049            }3050            val next = prior.copy(blob = blob)3051            // The epoch check and the entire A/B/D/version commit share one brief3052            // stateLock critical section. lock() either wins before this block or3053            // waits until the already-committed write is complete; it can never3054            // clear the session between the check and the durable write.3055            withEpochCommit(snapshot.epoch) {3056                if (!store.writeSlotA(next)) return@withEpochCommit false3057                try {3058                    if (!writeMatchingNoiseSlotB(next)) throw java.io.IOException("noise_slot_b_commit_failed")3059                    // H-04: duress slot stays present (real one untouched, fake one3060                    // re-padded to slot A's current size on every persist).3061                    if (!writeCompanionDuressSlot(next)) throw java.io.IOException("duress_slot_commit_failed")3062                    if (bumpVersion) store.stampLocalMutation()3063                } catch (e: Exception) {3064                    store.writeSlotA(prior)3065                    if (priorB != null) runCatching { store.writeSlotB(priorB) }3066                    throw e3067                }3068                true3069            } ?: false3070        } finally {3071            // Snapshot keys are copies, so lock() may zero the live key while this3072            // operation is still deriving/encrypting; always scrub our copy too.3073            VaultCrypto.zero(snapshot.key)3074        }3075    }30763077    /**3078     * H-01: durably commit a slot-A rotation by writing slot A, its3079     * size-matched noise slot B, and the local-mutation stamp in order. Any3080     * failure rolls the previously-committed steps back so the at-rest pair3081     * matches what was there before the call. Returns true only when every3082     * step succeeded — callers must NOT swap their session key on false.3083     */3084    private fun commitVaultRotation(3085        priorA: StoredVault,3086        priorB: String?,3087        nextA: StoredVault,3088        expectedEpoch: Long,3089    ): Boolean {3090        beforeDurableCommit()3091        return withEpochCommit(expectedEpoch) {3092            if (!store.writeSlotA(nextA)) return@withEpochCommit false3093            // P1-1 (codex): the noise write's boolean AND any thrown exception from3094            // it must trigger rollback; previously a throw from writeMatchingNoiseSlotB3095            // escaped the helper and left slot A committed.3096            try {3097                if (!writeMatchingNoiseSlotB(nextA)) throw java.io.IOException("noise_slot_b_commit_failed")3098                // H-04: a password rotation changes slot A's plaintext size (new3099                // salt → re-encrypted blob), so the duress slot must be re-padded3100                // alongside. writeCompanionDuressSlot leaves a real decoy alone3101                // and re-emits a fake of slot A's size otherwise.3102                if (!writeCompanionDuressSlot(nextA)) throw java.io.IOException("duress_slot_commit_failed")3103                store.stampLocalMutation()3104            } catch (_: Exception) {3105                reportRotationRollback(slotRollback.restorePair(priorA, priorB))3106                return@withEpochCommit false3107            }3108            true3109        } ?: false3110    }31113112    /**3113     * Best-effort undo of the writes [commitVaultRotation] may have committed.3114     * Each step runs independently — a failed rollback must not mask the3115     * original commit failure. Log is a throwing stub off-device.3116     */3117    private fun reportRotationRollback(failures: List<String>) {3118        if (failures.isNotEmpty()) runCatching { Log.w("PeachVault", "vault rotation rollback incomplete: $failures") }3119    }31203121    /** Persist a local mutation, rolling the in-memory list back on failure. */3122    private fun persistOrRollback(rollback: MutableList<VaultEntry>, expectedEpoch: Long) {3123        try {3124            if (!persistSlotA(bumpVersion = true, expectedEpoch = expectedEpoch)) {3125                mutateIfCurrentEpoch(expectedEpoch) { entryList = rollback }3126                throw IllegalStateException("storage_write_failed")3127            }3128        } catch (e: Exception) {3129            mutateIfCurrentEpoch(expectedEpoch) { entryList = rollback }3130            throw e3131        }3132        // A lock can win in the small interval after the durable commit and3133        // before publication. The epoch check prevents pre-lock entries from3134        // being republished into a newly locked (or newly unlocked) session.3135        mutateIfCurrentEpoch(expectedEpoch) { publish() }3136        runCatching { LockedSyncSpoolHooks.refresh(this) }3137    }3138}