VaultRepository.kt

151.5 KB · raw

1package com.peachpasswords.vault23import kotlinx.coroutines.flow.MutableStateFlow4import kotlinx.coroutines.flow.StateFlow5import kotlinx.coroutines.flow.asStateFlow6import kotlinx.coroutines.sync.Mutex7import kotlinx.coroutines.sync.withLock8import java.security.MessageDigest9import java.security.SecureRandom10import java.text.Normalizer11import kotlinx.serialization.json.Json12import android.os.SystemClock13import android.util.Log14import androidx.annotation.VisibleForTesting15import com.peachpasswords.BuildConfig16import com.peachpasswords.sync.SyncLimits17import com.peachpasswords.sync.LockedSyncSpoolHooks18import kotlinx.serialization.json.JsonElement19import kotlinx.serialization.json.JsonNull20import kotlinx.serialization.json.JsonObject21import kotlinx.serialization.json.JsonPrimitive22import java.util.Base6423import java.util.UUID24import java.util.concurrent.locks.ReentrantLock25import javax.inject.Inject26import javax.inject.Singleton2728/** Lenient parser for the Codex vault-blob wrapper only. */29private val CodexJson = Json { ignoreUnknownKeys = true; isLenient = true }3031private fun b64(bytes: ByteArray): String = Base64.getEncoder().withoutPadding().encodeToString(bytes)32private fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s)3334/** Cap on retained past passwords per entry. Mirrors the browser PASSWORD_HISTORY_MAX. */35private const val PASSWORD_HISTORY_MAX = 5036private const val VAULT_HISTORY_MAX = 53738// How long the transient-background-lock suppression stays valid. If the39// launched system Activity never reports the expected lifecycle stop (picker40// crashed, user backed out into another app, OEM killed the picker process),41// the flag expires and the next genuine background event locks the vault42// rather than consuming a stale suppression.43private const val BACKGROUND_LOCK_SUPPRESSION_TIMEOUT_MS = 30_000L4445sealed interface UnlockResult {46    data object Success : UnlockResult47    data object WrongPassword : UnlockResult48    data class Error(val reason: String) : UnlockResult49}5051sealed interface CreateVaultResult {52    data object Success : CreateVaultResult53    data class Error(val reason: String) : CreateVaultResult54}5556sealed interface AdoptVaultResult {57    data class Success(val vaultId: String) : AdoptVaultResult58    data class Error(val reason: String) : AdoptVaultResult59}6061/**62 * 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 mutex = Mutex()92    // H-03: lock() and requireUnlocked() cannot take [mutex] from non-suspend93    // callers (ProcessLifecycleOwner, ViewModels, VaultLockTimer). This sync94    // lock guards ONLY the brief read/write of derivedKey/rootKey/entryList so95    // lock() can serialize against an in-flight suspend op without blocking on96    // Argon2id or store I/O. Suspend ops hold [mutex] for their full body and97    // take [stateLock] only around the state-write portions. Acquisition order98    // is always mutex → stateLock.99    private val stateLock = ReentrantLock()100    private val rng = SecureRandom()101102    /**103     * Monotonic session generation.  [lock] advances this before clearing any104     * secret state; work that captured the previous generation is therefore105     * stale even if it is still running its (non-suspending) storage step.106     */107    private var sessionEpoch: Long = 0L108109    private fun nextSessionEpoch(epoch: Long): Long =110        if (epoch == Long.MAX_VALUE) 0L else epoch + 1L111112    /** Test seam for deterministic "lock while waiting to commit" races. */113    @VisibleForTesting114    internal var beforeDurableCommit: () -> Unit = {}115116    /** Test seam after a failed Codex rollback, while the epoch fence is held. */117    @VisibleForTesting118    internal var afterCodexRollback: () -> Unit = {}119120    /**121     * Run [block] with [stateLock] held. Used to fence the small state-write122     * portions of suspend operations against [lock] and [requireUnlocked]123     * racing from another thread.124     */125    private inline fun <T> mutateState(block: () -> T): T {126        stateLock.lock()127        return try { block() } finally { stateLock.unlock() }128    }129130    /** Run a durable commit only while the session generation is still live. */131    private inline fun <T> withEpochCommit(epoch: Long, block: () -> T): T? {132        stateLock.lock()133        return try {134            if (sessionEpoch != epoch) null else block()135        } finally {136            stateLock.unlock()137        }138    }139140    /** Test seam for a caller that must stage work before the epoch fence. */141    @VisibleForTesting142    internal var beforeSessionEpochCommit: () -> Unit = {}143144    /**145     * Test seam for the narrower H-03 race: a suspend mutation has authenticated146     * the session and staged its candidate state, but has not yet entered the147     * epoch-fenced in-memory write. Production callers leave this as a no-op.148     */149    @VisibleForTesting150    internal var beforeSessionStateMutation: () -> Unit = {}151152    /**153     * Run an external session-bound commit while the repository's epoch fence is154     * held. The callback is deliberately non-suspending: [lock] cannot advance155     * the epoch until the whole external batch has reached its linearization156     * point.157     */158    internal fun <T> withSessionEpochCommit(epoch: Long, block: () -> T): T? {159        beforeSessionEpochCommit()160        return withEpochCommit(epoch, block)161    }162163    private fun currentEpoch(): Long = mutateState { sessionEpoch }164165    private inline fun <T> mutateIfCurrentEpoch(epoch: Long, block: () -> T): T? =166        mutateState { if (sessionEpoch == epoch) block() else null }167168    /** Invoke the pre-state-write seam, then linearize only in the same epoch. */169    private inline fun <T> mutateCurrentSession(epoch: Long, block: () -> T): T? {170        beforeSessionStateMutation()171        return mutateIfCurrentEpoch(epoch, block)172    }173174    private data class PersistSnapshot(175        val epoch: Long,176        val key: ByteArray,177        val payload: VaultPayload,178        val decoy: Boolean,179    )180181    /** Copy all session material while fenced; callers own and must zero [key]. */182    private fun snapshotForPersist(expectedEpoch: Long? = null): PersistSnapshot? = mutateState {183        if (expectedEpoch != null && sessionEpoch != expectedEpoch) return@mutateState null184        val liveKey = derivedKey ?: return@mutateState null185        PersistSnapshot(186            epoch = sessionEpoch,187            key = liveKey.copyOf(),188            payload = currentPayloadLocked(),189            decoy = decoyMode,190        )191    }192193    private var derivedKey: ByteArray? = null194    private var rootKey: ByteArray? = null195    private var entryList: MutableList<VaultEntry> = mutableListOf()196    private var authenticatedDuressConfigured: Boolean = false197    private var recoveryWordHash: String? = null198    private var recoveryWordsSet: Boolean = false199    /** True when an authenticated vault payload is available for local reads. */200    private var sessionDataAvailable: Boolean = false201    /** True while a decoy (duress) session is active — persistence targets the decoy slot. */202    private var decoyMode: Boolean = false203204    private val _isUnlocked = MutableStateFlow(false)205    val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()206207    private val _duressConfigured = MutableStateFlow(false)208    /** Authenticated payload state; never loaded from plaintext settings. */209    val duressConfigured: StateFlow<Boolean> = _duressConfigured.asStateFlow()210211212    /**213     * UI-only gate for sync-retained background mode. The vault stays unlocked214     * in memory (sync can proceed) but the UI shows the lock screen until the215     * user authenticates on resume. Cleared by a full [lock] or an explicit216     * [clearUiGate] from the lock screen.217     */218    private val _uiGateLocked = MutableStateFlow(false)219    val uiGateLocked: StateFlow<Boolean> = _uiGateLocked.asStateFlow()220221    private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())222    /** Active (non-deleted) entryList. */223    val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()224225    // Settings live in plain prefs, not inside the sealed vault — they hold no226    // secrets — so they are readable before unlock. Loading them here keeps the227    // lock screen at the user's chosen appearance instead of the defaults, which228    // otherwise snap to the real values the moment they authenticate.229    private val _settings = MutableStateFlow(store.loadSettings())230    val settings: StateFlow<VaultSettings> = _settings.asStateFlow()231232    /** Clear every in-memory session field while [stateLock] is held. */233    private fun clearSessionStateLocked() {234        derivedKey?.let(VaultCrypto::zero)235        rootKey?.let(VaultCrypto::zero)236        derivedKey = null237        rootKey = null238        entryList = mutableListOf()239        authenticatedDuressConfigured = false240        _duressConfigured.value = false241        recoveryWordHash = null242        recoveryWordsSet = false243        sessionDataAvailable = false244        decoyMode = false245        _settings.value = store.loadSettings()246        _entries.value = emptyList()247        _isUnlocked.value = false248    }249250    fun hasVault(): Boolean = store.hasVault()251252    // ---- Codex (printed paper backup) -------------------------------------253254    /**255     * The at-rest slot pair as base64 JSON `{"a": <StoredVault>, "b": <StoredVault>}` — the256     * Codex payload's vaultBlob. "b" is the duress slot (matching the browser's257     * A/B naming where slot B is the duress decoy); the noise slot is local-only258     * and never crosses devices. Restorable on any device that has the master259     * password. Null when no vault exists.260     */261    fun codexVaultBlobBase64(): String? {262        val slotA = store.loadSlotA() ?: return null263        // H-04: duress slot is always present after createVault (real or fake),264        // so the wrapper can rely on it being loadable.265        val slotD = store.loadDecoySlot() ?: return null266        val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)},"b":${VaultCodec.encodeSlot(slotD)}}"""267        return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))268    }269270    /**271     * Replace the local vault from a Codex blob, then unlock with [password].272     * Writes slot A (and a size-matched noise slot B) before unlocking so the273     * restored vault is at rest exactly as a freshly-created one would be.274     */275    /** A slot is stored either as a JSON string (browser) or inline object (Android). */276    private fun JsonElement?.asSlotJson(): String? = when {277        this == null || this is JsonNull -> null278        this is JsonPrimitive && isString -> content279        else -> toString()280    }281282    suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {283        val expectedEpoch = currentEpoch()284        var candidateKey: ByteArray? = null285        var plaintext: ByteArray? = null286        return try {287            val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)288            // Parsed as JSON, not matched with a regex. The wrapper is289            // `{ "a": <slot>, "b": <slot|null> }` and the browser — which290            // generates most real Codexes — writes each slot as a JSON291            // *string*, with "b" present. A regex looking for an object292            // literal under "a" at the very end of the wrapper matches293            // neither of those, so every browser-generated Codex failed here294            // with "invalid_codex_blob" after decoding perfectly.295            val wrapper = CodexJson.parseToJsonElement(wrapperJson) as? JsonObject296                ?: return UnlockResult.Error("invalid_codex_blob")297            val slotJson = wrapper["a"].asSlotJson() ?: return UnlockResult.Error("invalid_codex_blob")298            // A Codex printed from the browser carries a browser-shaped slot,299            // which is the common case — most Codexes are printed there. It is300            // translated to Android's shape (see BrowserSlot) rather than301            // rejected. A translation failure is a wrong password, not a bad302            // blob: the codes decoded fine, the password just didn't open them.303            val slotA = VaultCodec.decodeSlot(slotJson)304                ?: BrowserSlot.parse(slotJson)?.let {305                    BrowserSlot.toAndroidSlot(it, password) ?: return UnlockResult.WrongPassword306                }307                ?: return UnlockResult.Error("invalid_codex_blob")308            // C-01: authenticate the candidate ENTIRELY in memory before touching309            // storage. VaultCodec.decodeSlot is structural — an Android-shaped310            // Codex parses under ANY password — so writing slot A first and311            // unlocking afterwards destroyed the device's existing vault every312            // time the user mistyped the password.313            candidateKey = VaultCrypto.deriveKey(password, unb64(slotA.salt))314            plaintext = decryptSlotABlob(slotA, candidateKey)315            // LV-1: a Codex printed from a vault sealed before NFC normalization316            // opens only under the raw password bytes. unlockLocked used to supply317            // this fallback; authenticating up front here has to keep it, or those318            // Codexes become unrestorable.319            if (plaintext == null && password != Normalizer.normalize(password, Normalizer.Form.NFC)) {320                VaultCrypto.zero(candidateKey)321                candidateKey = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))322                plaintext = decryptSlotABlob(slotA, candidateKey)323            }324            if (plaintext == null) return UnlockResult.WrongPassword325            val payload = try {326                VaultCodec.decode(plaintext)327            } catch (_: Exception) {328                return UnlockResult.Error("invalid_codex_blob")329            }330331            val priorA = store.loadSlotA()332            val priorB = store.loadSlotB()333            val priorD = store.loadDecoySlot()334            // Carry the real duress slot across when the Codex has one — the335            // browser writes "b" as its duress-shaped slot, and dropping it336            // here would silently destroy a configured decoy.337            // H-04: write browser B into the duress slot (not the noise slot),338            // translating browser-shaped slots to Android's StoredVault shape.339            val codexDuressJson = wrapper["b"].asSlotJson()340            val codexDuress: StoredVault? = codexDuressJson?.let {341                VaultCodec.decodeSlot(it)?.let { slot ->342                    if (slot.version != LEGACY_ANDROID_SLOT_VERSION && slot.version != CURRENT_ANDROID_SLOT_VERSION) null else slot343                } ?: BrowserSlot.parse(it)?.let { b ->344                    browserDuressPassthrough(b)345                }346            }347348            beforeDurableCommit()349            val committed = runCatching {350                withEpochCommit(expectedEpoch) {351                    try {352                        // Keep every slot write, including the inverse, under the353                        // same epoch fence. Releasing stateLock after a partial354                        // write and reacquiring it for rollback lets lock() advance355                        // the epoch in between and strand the incoming slot A.356                        if (!store.writeSlotA(slotA)) throw java.io.IOException("slot_a_commit_failed")357                        // Noise slot is always size-matched to slot A — local-only,358                        // never written from a Codex.359                        if (!writeMatchingNoiseSlotB(slotA)) throw IllegalStateException("noise_slot_commit_failed")360                        // H-04: duress slot always present; real one from the Codex or361                        // a fake the size of slot A.362                        val duressOk = if (codexDuress != null) {363                            store.writeDecoySlot(codexDuress)364                        } else {365                            writeFakeDuressSlot(slotA)366                        }367                        if (!duressOk) throw IllegalStateException("duress_slot_commit_failed")368                        store.stampLocalMutation()369                        true370                    } catch (_: Exception) {371                        reportRollbackFailures(rollbackRestoreLocked(priorA, priorB, priorD))372                        // Keep the fence held through the final rollback373                        // observation. A concurrent lock() may queue here, but374                        // cannot invalidate the restored A/B/D triad.375                        afterCodexRollback()376                        false377                    }378                } ?: false379            }.getOrDefault(false)380            if (!committed) {381                return UnlockResult.Error("storage_write_failed")382            }383384            val ownedKey = candidateKey!!385            candidateKey = null // the session owns the key from here on386            VaultKeyRotationHooks.onRotated()387            adoptSlotA(ownedKey, payload, expectedEpoch)388        } catch (e: Exception) {389            // A raw kotlinx parse error ("Unexpected JSON token at offset N")390            // reaching the user says nothing about WHICH json failed — the391            // wrapper, or the payload decrypted out of it. Codex screens are392            // FLAG_SECURE so this can't be screenshotted either. Debug builds393            // log the structure around the failure; alphanumerics are masked so394            // no ciphertext or vault content lands in a log.395            if (BuildConfig.DEBUG) Log.w("PeachCodex", codexFailureShape(vaultBlobBase64, e))396            UnlockResult.Error(e.message ?: "restore_failed")397        } finally {398            plaintext?.let(VaultCrypto::zero)399            candidateKey?.let(VaultCrypto::zero)400        }401    }402403    /** Slot-A plaintext under [key], or null when the GCM tag fails (wrong password). */404    private fun decryptSlotABlob(slot: StoredVault, key: ByteArray): ByteArray? =405        runCatching { VaultCrypto.decrypt(unb64(slot.blob), key, VaultCrypto.AAD_SLOT_A) }.getOrNull()406407    /**408     * Undo a partially-committed Codex restore while [stateLock] is already held.409     * Every step is attempted independently so one failure cannot strand the410     * others. Callers that need epoch validation must enter through411     * [withEpochCommit] first; this helper deliberately does not reacquire the412     * lock, avoiding a reentrant gap between a failed write and its inverse.413     * With no prior vault the accurate inverse is having none at all, rather414     * than a half-written slot A that [hasVault] would report as a real vault.415     */416    private fun rollbackRestoreLocked(417        priorA: StoredVault?,418        priorB: String?,419        priorD: StoredVault? = null,420    ): List<String> {421        val failures = mutableListOf<String>()422        if (priorA == null) {423            runCatching { store.clearVault() }.onFailure { failures += "clearVault: $it" }424        } else {425            runCatching { if (!store.writeSlotA(priorA)) failures += "writeSlotA returned false" }426                .onFailure { failures += "writeSlotA: $it" }427            if (priorB != null) {428                runCatching { if (!store.writeSlotB(priorB)) failures += "writeSlotB returned false" }429                    .onFailure { failures += "writeSlotB: $it" }430            }431            // H-04: restore the prior duress slot — a half-committed restore that432            // left the duress record on the Codex side and slot A on the prior433            // side would put the at-rest pair in a state that never existed.434            if (priorD != null) {435                runCatching { if (!store.writeDecoySlot(priorD)) failures += "writeDecoySlot returned false" }436                    .onFailure { failures += "writeDecoySlot: $it" }437            } else {438                runCatching { store.clearDecoySlot() }.onFailure { failures += "clearDecoySlot: $it" }439            }440        }441        return failures442    }443444    private fun reportRollbackFailures(failures: List<String>) {445        // Log is a throwing stub off-device, and a failed log must never mask446        // the rollback result the caller is about to report.447        if (failures.isNotEmpty()) runCatching { Log.w("PeachCodex", "codex rollback incomplete: $failures") }448    }449450    /** Debug-only: structure of a failed Codex restore, with content masked. */451    private fun codexFailureShape(vaultBlobBase64: String, e: Exception): String = runCatching {452        val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)453        val offset = Regex("offset (\\d+)").find(e.message.orEmpty())?.groupValues?.get(1)?.toIntOrNull()454        val window = offset?.let {455            val from = (it - 40).coerceAtLeast(0)456            val to = (it + 40).coerceAtMost(wrapperJson.length)457            wrapperJson.substring(from, to).replace(Regex("[A-Za-z0-9+/=_-]"), "x")458        }459        val wrapper = runCatching { CodexJson.parseToJsonElement(wrapperJson) as? JsonObject }.getOrNull()460        val slot = wrapper?.get("a")461        buildString {462            append("codex restore failed: ").append(e::class.simpleName).append(": ").append(e.message)463            append(" | blobBase64=").append(vaultBlobBase64.length)464            append(" wrapperChars=").append(wrapperJson.length)465            append(" wrapperParses=").append(wrapper != null)466            append(" keys=").append(wrapper?.keys)467            append(" slotAKind=").append(468                when {469                    slot == null -> "absent"470                    slot is JsonPrimitive && slot.isString -> "string"471                    slot is JsonObject -> "object:" + slot.keys472                    else -> slot::class.simpleName473                },474            )475            if (window != null) append(" masked@").append(offset).append("=").append(window)476        }477    }.getOrElse { "codex restore failed: ${e.message} (shape unavailable: $it)" }478479    suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {480        val expectedEpoch = currentEpoch()481        var key: ByteArray? = null482        return try {483            val salt = VaultCrypto.generateSalt()484            key = VaultCrypto.deriveKey(password, salt)485            if (mutateIfCurrentEpoch(expectedEpoch) {486                entryList = mutableListOf()487                authenticatedDuressConfigured = false488                _duressConfigured.value = false489                recoveryWordHash = null490                recoveryWordsSet = false491                decoyMode = false492                sessionDataAvailable = false493                rootKey = generateRecoverableRootKey()494            } == null) return CreateVaultResult.Error("stale_create")495            // M-04: the fields above have to be live before sealSlotA, since it496            // seals currentPayload(). That stages a root key the session would497            // otherwise keep after a failed create — [lock] discards the whole498            // staged session on every non-success exit below.499            val slotA = sealSlotA(key!!, salt)500            // P1-3 (codex): every later step must roll the slot pair back if it501            // fails — leaving a half-built vault is worse than refusing to make it.502            beforeDurableCommit()503            val created = withEpochCommit(expectedEpoch) {504                if (!store.writeSlotA(slotA)) return@withEpochCommit false505                try {506                    if (!writeMatchingNoiseSlotB(slotA)) throw java.io.IOException("noise_slot_b_commit_failed")507                    // H-04: duress slot must be present from the start so its508                    // existence on disk is independent of authenticatedDuressConfigured.509                    if (!writeFakeDuressSlot(slotA)) throw java.io.IOException("duress_slot_commit_failed")510                    store.stampLocalMutation()511                    if (!store.writeSettings(_settings.value)) throw java.io.IOException("settings_commit_failed")512                    true513                } catch (_: Exception) {514                    // Half-built vault on disk is worse than no vault — refuse to515                    // create if any step past slot A fails.516                    store.clearVault()517                    false518                }519            } ?: false520            if (!created) {521                lock()522                return CreateVaultResult.Error("storage_write_failed")523            }524            val sessionKey = key ?: return CreateVaultResult.Error("create_key_missing")525            if (mutateIfCurrentEpoch(expectedEpoch) {526                derivedKey = sessionKey527                key = null528                publish()529                _isUnlocked.value = true530                sessionDataAvailable = true531                sessionEpoch = nextSessionEpoch(sessionEpoch)532            } == null) return CreateVaultResult.Error("stale_create")533            CreateVaultResult.Success534        } catch (e: Exception) {535            lock()536            CreateVaultResult.Error(e.message ?: "create_failed")537        } finally {538            key?.let(VaultCrypto::zero)539        }540    }541542    suspend fun createVaultFromRootKey(password: String, rootKeyHex: String): AdoptVaultResult = mutex.withLock {543        val expectedEpoch = currentEpoch()544        if (password.isEmpty()) return AdoptVaultResult.Error("ADOPT_INVALID_PASSWORD")545        if (store.hasVault()) return AdoptVaultResult.Error("ADOPT_VAULT_ALREADY_EXISTS")546        if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {547            return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars")548        }549        var adoptedRootKey: ByteArray? = null550        var nextDerivedKey: ByteArray? = null551        var sessionRootKey: ByteArray? = null552        return try {553            adoptedRootKey = hexToRootKey(rootKeyHex)554            if (adoptedRootKey.size != VaultCrypto.KEY_SIZE) {555                return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes")556            }557            val vaultId = com.peachpasswords.sync.computeVaultId(adoptedRootKey)558            val salt = VaultCrypto.generateSalt()559            nextDerivedKey = VaultCrypto.deriveKey(password, salt)560            sessionRootKey = adoptedRootKey.copyOf()561            val payload = VaultPayload(562                entries = emptyList(),563                duressConfigured = false,564                rootKeyB64 = b64(sessionRootKey),565                recoveryWordHash = null,566                recoveryWordsSet = false,567            )568            val plaintext = VaultCodec.encode(payload)569            val blob = try {570                b64(VaultCrypto.encrypt(plaintext, nextDerivedKey, VaultCrypto.AAD_SLOT_A))571            } finally {572                VaultCrypto.zero(plaintext)573            }574            val slotA = StoredVault(version = 1, salt = b64(salt), blob = blob)575            // P1-3 (codex): same partial-commit guard as createVault — any failure576            // past slot A wipes the half-built vault and refuses adoption.577            beforeDurableCommit()578            val created = withEpochCommit(expectedEpoch) {579                if (!store.writeSlotA(slotA)) return@withEpochCommit false580                try {581                    if (!writeMatchingNoiseSlotB(slotA)) throw java.io.IOException("noise_slot_b_commit_failed")582                    // H-04: duress slot must be present from the start so its583                    // existence on disk is independent of authenticatedDuressConfigured.584                    if (!writeFakeDuressSlot(slotA)) throw java.io.IOException("duress_slot_commit_failed")585                    store.stampLocalMutation()586                    if (!store.writeSettings(_settings.value)) throw java.io.IOException("settings_commit_failed")587                    true588                } catch (_: Exception) {589                    store.clearVault()590                    false591                }592            } ?: false593            if (!created) return AdoptVaultResult.Error("storage_write_failed")594595            val adopted = mutateIfCurrentEpoch(expectedEpoch) {596                val previousDerivedKey = derivedKey597                val previousRootKey = rootKey598                derivedKey = nextDerivedKey599                rootKey = sessionRootKey600                nextDerivedKey = null601                sessionRootKey = null602                entryList = mutableListOf()603                authenticatedDuressConfigured = false604                _duressConfigured.value = false605                recoveryWordHash = null606                recoveryWordsSet = false607                decoyMode = false608                sessionDataAvailable = true609                publish()610                _isUnlocked.value = true611                sessionEpoch = nextSessionEpoch(sessionEpoch)612                previousDerivedKey to previousRootKey613            }614            if (adopted == null) return AdoptVaultResult.Error("stale_adoption")615            val (previousDerivedKey, previousRootKey) = adopted616            previousDerivedKey?.let(VaultCrypto::zero)617            previousRootKey?.let(VaultCrypto::zero)618            // Write the recovery escrow so the forgot-password flow works on619            // this device. The words are deterministic from the root key and620            // were already confirmed on the source device.621            runCatching {622                val words = rootKeyToWords(rootKey!!)623                val escrow = buildRecoveryEscrow(words)624                val rkEscrow = buildRootKeyEscrow(words)625                if (escrow != null || rkEscrow != null) {626                    val prior = store.loadSlotA()627                    if (prior != null) {628                        store.writeSlotA(prior.copy(629                            recoveryEscrow = escrow ?: prior.recoveryEscrow,630                            rootKeyEscrow = rkEscrow ?: prior.rootKeyEscrow,631                        ))632                    }633                    mutateState {634                        recoveryWordHash = recoveryWordsHash(words)635                        recoveryWordsSet = true636                    }637                }638            }639            AdoptVaultResult.Success(vaultId)640        } catch (e: Exception) {641            AdoptVaultResult.Error(e.message ?: "adoption_create_failed")642        } finally {643            adoptedRootKey?.let(VaultCrypto::zero)644            nextDerivedKey?.let(VaultCrypto::zero)645            sessionRootKey?.let(VaultCrypto::zero)646        }647    }648649    suspend fun unlock(password: String): UnlockResult = mutex.withLock {650        val result = unlockLocked(password, currentEpoch())651        if (result is UnlockResult.Success) ensureRecoveryEscrow()652        result653    }654655    /** Unlock body without acquiring the mutex — callers must already hold it. */656    private fun unlockLocked(password: String, expectedEpoch: Long): UnlockResult {657        val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")658        val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))659        val payload = try {660            val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A)661            try {662                VaultCodec.decode(plaintext)663            } finally {664                VaultCrypto.zero(plaintext)665            }666        } catch (_: Exception) {667            VaultCrypto.zero(key)668            // LV-1: a vault sealed before NFC normalization with a non-NFC669            // password derives a different key now. If the supplied password is670            // not already in NFC form, retry with the raw (un-normalized) bytes.671            if (password != Normalizer.normalize(password, Normalizer.Form.NFC)) {672                val legacy = tryLegacyRawUnlock(password, slotA, expectedEpoch)673                if (legacy != null) return legacy674            }675            return UnlockResult.WrongPassword676        }677        return adoptSlotA(key, payload, expectedEpoch)678    }679680    /**681     * LV-1 legacy fallback: unlock a slot-A vault that was sealed under the raw682     * (un-normalized) password bytes. On success the slot is HEALED — re-sealed683     * under the NFC-normalized key — so every future unlock takes the normal684     * path. Returns null when the raw key also fails (genuinely wrong password)685     * OR when any step of the heal commits fails (the original slot A is restored686     * so disk and session stay aligned).687     */688    private fun tryLegacyRawUnlock(password: String, slotA: StoredVault, expectedEpoch: Long): UnlockResult? {689        var rawKey: ByteArray? = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))690        var newKey: ByteArray? = null691        return try {692            val payload = try {693                val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), rawKey!!, VaultCrypto.AAD_SLOT_A)694                try {695                    VaultCodec.decode(plaintext)696                } finally {697                    VaultCrypto.zero(plaintext)698                }699            } catch (_: Exception) {700                return null701            }702            // Heal: re-seal slot A under the NFC key (mirrors changePassword's703            // re-seal). Escrows carry forward unchanged — only the wrapping rotates.704            val newSalt = VaultCrypto.generateSalt()705            newKey = VaultCrypto.deriveKey(password, newSalt)706            val plaintext = VaultCodec.encode(payload)707            val blob = try {708                b64(VaultCrypto.encrypt(plaintext, newKey!!, VaultCrypto.AAD_SLOT_A))709            } finally {710                VaultCrypto.zero(plaintext)711            }712            val next = StoredVault(713                version = slotA.version,714                salt = b64(newSalt),715                blob = blob,716                recoveryEscrow = slotA.recoveryEscrow,717                rootKeyEscrow = slotA.rootKeyEscrow,718            )719            // P1-1/P1-3/P1-2 (codex): any failure of writeSlotA, writeMatchingNoiseSlotB,720            // or stampLocalMutation must restore the prior slot A AND slot B so disk721            // and the eventual session key never disagree on the wrapping.722            val priorB = store.loadSlotB()723            beforeDurableCommit()724            val healed = withEpochCommit(expectedEpoch) {725                if (!store.writeSlotA(next)) {726                    false727                } else try {728                    if (!writeMatchingNoiseSlotB(next)) {729                        runCatching { store.writeSlotA(slotA) }730                        if (priorB != null) runCatching { store.writeSlotB(priorB) }731                        false732                    } else if (!writeCompanionDuressSlot(next)) {733                        runCatching { store.writeSlotA(slotA) }734                        if (priorB != null) runCatching { store.writeSlotB(priorB) }735                        false736                    } else {737                        store.stampLocalMutation()738                        true739                    }740                } catch (_: Exception) {741                    runCatching { store.writeSlotA(slotA) }742                    if (priorB != null) runCatching { store.writeSlotB(priorB) }743                    false744                }745            } ?: false746            if (healed) {747                VaultCrypto.zero(rawKey!!)748                rawKey = null749                val result = adoptSlotA(newKey!!, payload, expectedEpoch) // session key now matches the re-sealed slot750                newKey = null751                result752            } else {753                VaultCrypto.zero(newKey!!)754                newKey = null755                val result = adoptSlotA(rawKey!!, payload, expectedEpoch) // heal failed — keep using the raw key756                rawKey = null757                result758            }759        } finally {760            // Cover codec, encryption, storage, and stale-epoch failures before761            // either candidate key can be transferred into the live session.762            rawKey?.let(VaultCrypto::zero)763            newKey?.let(VaultCrypto::zero)764        }765    }766767    /** Adopt a derived slot-A [key]/[payload] as the live (real-vault) session. */768    private fun adoptSlotA(key: ByteArray, payload: VaultPayload, expectedEpoch: Long): UnlockResult {769        return try {770            // M-04: ensureRootKey and autoPurgeExpiredTrash both persist, so they771            // can throw after the fields above are live. There is no prior session772            // worth restoring — adoption has already replaced it — so a failed773            // adoption discards everything rather than leaving entries and keys774            // resident behind _isUnlocked=false.775            val adopted = mutateIfCurrentEpoch(expectedEpoch) {776                derivedKey = key777                decoyMode = false778                entryList = payload.entries.toMutableList()779                authenticatedDuressConfigured = payload.duressConfigured780                _duressConfigured.value = payload.duressConfigured781                recoveryWordHash = payload.recoveryWordHash782                recoveryWordsSet = payload.recoveryWordsSet783                sessionDataAvailable = true784                _settings.value = store.loadSettings()785                ensureRootKey(payload)786                autoPurgeExpiredTrash()787                consolidatePasskeyEntries()788                publish()789                _isUnlocked.value = true790                // A successful adoption starts a new generation. A sibling791                // SlotAUnlock captured in the prior epoch will fail closed at792                // the next commit instead of replacing this session.793                sessionEpoch = nextSessionEpoch(sessionEpoch)794            }795            if (adopted == null) {796                VaultCrypto.zero(key)797                UnlockResult.Error("stale_unlock")798            } else {799                UnlockResult.Success800            }801        } catch (e: Exception) {802            // Do not call lock() here: a concurrent newer session may already803            // own this repository. Only invalidate the failed epoch's fields.804            mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }805            VaultCrypto.zero(key)806            UnlockResult.Error(e.message ?: "unlock_failed")807        }808    }809810    // ---- Constant-time unlock (MF-5) --------------------------------------811812    /**813     * A slot-A unlock that has been derived but not yet adopted. Holds the live814     * Argon2id key and decoded payload so the caller can derive several candidates815     * concurrently and commit only the winner. The key is owned by this token until816     * [commitSlotAUnlock] adopts it or [discardSlotAUnlock] zeroes it.817     */818    class SlotAUnlock internal constructor(819        key: ByteArray,820        internal val payload: VaultPayload,821        internal val epoch: Long,822    ) {823        private var ownedKey: ByteArray? = key824        private var consumed = false825826        /** Transfer the key exactly once to the adopter. */827        internal fun takeKey(): ByteArray? = synchronized(this) {828            if (consumed) return@synchronized null829            consumed = true830            ownedKey.also { ownedKey = null }831        }832833        /** Discard an uncommitted token without touching a transferred key. */834        internal fun discard() = synchronized(this) {835            if (consumed) return@synchronized836            consumed = true837            ownedKey?.let(VaultCrypto::zero)838            ownedKey = null839        }840    }841842    /**843     * Derive the slot-A key and decrypt its payload WITHOUT mutating session state.844     * Pure computation (no mutex), so it can run concurrently with other candidate845     * derivations before the caller decides which to commit (MF-5). Returns null on846     * no-vault or wrong password (the derived key is zeroed on a tag mismatch).847     */848    fun tryUnlockSlotA(password: String): SlotAUnlock? {849        val epoch = currentEpoch()850        val slotA = store.loadSlotA() ?: return null851        val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))852        try {853            val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A)854            val payload = try {855                VaultCodec.decode(plaintext)856            } finally {857                VaultCrypto.zero(plaintext)858            }859            return SlotAUnlock(key, payload, epoch)860        } catch (_: Exception) {861            VaultCrypto.zero(key)862        }863864        if (password == Normalizer.normalize(password, Normalizer.Form.NFC)) return null865        return tryLegacyRawCandidate(password, slotA, epoch)866    }867868    /** Legacy raw-password fallback; successful candidates heal slot A to NFC. */869    private fun tryLegacyRawCandidate(password: String, slotA: StoredVault, epoch: Long): SlotAUnlock? {870        var rawKey: ByteArray? = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))871        var newKey: ByteArray? = null872        return try {873            val plaintext = try {874                VaultCrypto.decrypt(unb64(slotA.blob), rawKey!!, VaultCrypto.AAD_SLOT_A)875            } catch (_: Exception) {876                return null877            }878            val payload = try {879                VaultCodec.decode(plaintext)880            } finally {881                VaultCrypto.zero(plaintext)882            }883            val newSalt = VaultCrypto.generateSalt()884            newKey = VaultCrypto.deriveKey(password, newSalt)885            val encoded = VaultCodec.encode(payload)886            val blob = try {887                b64(VaultCrypto.encrypt(encoded, newKey!!, VaultCrypto.AAD_SLOT_A))888            } finally {889                VaultCrypto.zero(encoded)890            }891            val next = slotA.copy(salt = b64(newSalt), blob = blob)892            val priorB = store.loadSlotB()893            beforeDurableCommit()894            val healed = withEpochCommit(epoch) {895                if (!store.writeSlotA(next)) false else try {896                    if (!writeMatchingNoiseSlotB(next) || !writeCompanionDuressSlot(next)) {897                        runCatching { store.writeSlotA(slotA) }898                        if (priorB != null) runCatching { store.writeSlotB(priorB) }899                        false900                    } else {901                        store.stampLocalMutation()902                        true903                    }904                } catch (_: Exception) {905                    runCatching { store.writeSlotA(slotA) }906                    if (priorB != null) runCatching { store.writeSlotB(priorB) }907                    false908                }909            } ?: false910            if (healed) {911                VaultCrypto.zero(rawKey!!)912                rawKey = null913                SlotAUnlock(newKey!!, payload, epoch).also { newKey = null }914            } else {915                VaultCrypto.zero(newKey!!)916                newKey = null917                SlotAUnlock(rawKey!!, payload, epoch).also { rawKey = null }918            }919        } finally {920            rawKey?.let(VaultCrypto::zero)921            newKey?.let(VaultCrypto::zero)922        }923    }924925    /** Adopt a previously-derived [SlotAUnlock] as the live session. */926    suspend fun commitSlotAUnlock(unlock: SlotAUnlock): UnlockResult = mutex.withLock {927        val key = unlock.takeKey() ?: return@withLock UnlockResult.Error("unlock_token_consumed")928        adoptSlotA(key, unlock.payload, unlock.epoch)929    }930931    /** Zero a derived [SlotAUnlock] that will not be adopted. */932    fun discardSlotAUnlock(unlock: SlotAUnlock) = unlock.discard()933934    // ---- Duress slot B (MF-6) ---------------------------------------------935936    /**937     * A duress-slot (slot B) unlock derived but not yet adopted. Holds the live key938     * and decoded decoy payload so it can be derived concurrently with slot A and939     * only committed if the duress passphrase was the one entered (MF-5/MF-6).940     */941    class DuressUnlock internal constructor(942        key: ByteArray,943        internal val payload: VaultPayload,944        internal val epoch: Long,945    ) {946        private var ownedKey: ByteArray? = key947        private var consumed = false948949        internal fun takeKey(): ByteArray? = synchronized(this) {950            if (consumed) return@synchronized null951            consumed = true952            ownedKey.also { ownedKey = null }953        }954955        internal fun discard() = synchronized(this) {956            if (consumed) return@synchronized957            consumed = true958            ownedKey?.let(VaultCrypto::zero)959            ownedKey = null960        }961    }962963    /**964     * Try to decrypt the duress slot (slot B) with [password] WITHOUT mutating the965     * session. Success means the entered password is the duress passphrase that keys966     * slot B — indistinguishable from the real slot A at the lock screen. Pure967     * computation (no mutex), safe to run concurrently with [tryUnlockSlotA].968     * Returns null when no duress slot exists or the password is not the duress one.969     */970    fun tryUnlockDuress(password: String): DuressUnlock? {971        val epoch = currentEpoch()972        val slot = store.loadDecoySlot() ?: return null973        if (slot.version != LEGACY_ANDROID_SLOT_VERSION && slot.version != CURRENT_ANDROID_SLOT_VERSION) return null974        var key: ByteArray? = VaultCrypto.deriveKey(password, unb64(slot.salt))975        return try {976            val plaintext = try {977                if (slot.version == CURRENT_ANDROID_SLOT_VERSION) {978                    VaultCrypto.decrypt(unb64(slot.blob), key!!, VaultCrypto.AAD_SLOT_B)979                } else {980                    runCatching {981                        VaultCrypto.decrypt(unb64(slot.blob), key!!, VaultCrypto.AAD_SLOT_A)982                    }.getOrElse {983                        VaultCrypto.decrypt(unb64(slot.blob), key!!, VaultCrypto.AAD_SLOT_B)984                    }985                }986            } catch (_: Exception) {987                VaultCrypto.zero(key!!)988                key = null989                return null990            }991            val payload = try {992                VaultCodec.decode(plaintext)993            } finally {994                VaultCrypto.zero(plaintext)995            }996            if (slot.version == LEGACY_ANDROID_SLOT_VERSION) {997                val migratedKey = migrateLegacyDuressSlot(slot, password, payload, key!!, epoch)998                    ?: run {999                        VaultCrypto.zero(key!!)1000                        key = null1001                        return null1002                    }1003                if (migratedKey !== key) {1004                    VaultCrypto.zero(key!!)1005                    key = migratedKey1006                }1007            }1008            DuressUnlock(key!!, payload, epoch).also { key = null }1009        } catch (_: Exception) {1010            key?.let(VaultCrypto::zero)1011            null1012        }1013    }10141015    /**1016     * Re-seal an authenticated legacy decoy under the current Slot-B AAD.1017     * A failed write or verification restores the exact legacy record, while1018     * already-authenticated unlock remains usable for this session.1019     */1020    private fun migrateLegacyDuressSlot(1021        legacy: StoredVault,1022        password: String,1023        payload: VaultPayload,1024        legacyKey: ByteArray,1025        epoch: Long,1026    ): ByteArray? {1027        var salt: ByteArray? = null1028        var migratedKey: ByteArray? = null1029        var plaintext: ByteArray? = null1030        var restoredLegacy = false1031        var migrated = false1032        try {1033            salt = VaultCrypto.generateSalt()1034            migratedKey = VaultCrypto.deriveKey(password, salt)1035            plaintext = VaultCodec.encode(payload)1036            val next = StoredVault(1037                version = CURRENT_ANDROID_SLOT_VERSION,1038                salt = b64(salt),1039                blob = b64(VaultCrypto.encrypt(plaintext, migratedKey, VaultCrypto.AAD_SLOT_B)),1040            )1041            var priorA: StoredVault? = null1042            var priorB: String? = null1043            withSessionEpochCommit(epoch) {1044                priorA = store.loadSlotA()1045                priorB = store.loadSlotB()1046                if (store.loadDecoySlot() != legacy) return@withSessionEpochCommit false1047                if (!store.writeDecoySlot(next)) {1048                    restoredLegacy = store.loadDecoySlot() == legacy1049                    return@withSessionEpochCommit restoredLegacy1050                }1051                val reopened = store.loadDecoySlot()1052                val verified = reopened?.version == CURRENT_ANDROID_SLOT_VERSION && runCatching {1053                    val reopenedPlaintext = VaultCrypto.decrypt(unb64(reopened.blob), migratedKey!!, VaultCrypto.AAD_SLOT_B)1054                    try { VaultCodec.decode(reopenedPlaintext) == payload } finally { VaultCrypto.zero(reopenedPlaintext) }1055                }.getOrDefault(false)1056                if (verified) {1057                    migrated = true1058                    return@withSessionEpochCommit true1059                }1060                val restored = priorA != null && store.restoreVaultTriad(priorA!!, priorB, legacy)1061                restoredLegacy = restored && store.loadSlotA() == priorA && store.loadSlotB() == priorB && store.loadDecoySlot() == legacy1062                restoredLegacy1063            }1064            if (migrated) {1065                VaultCrypto.zero(legacyKey)1066                return migratedKey.also { migratedKey = null }1067            }1068            if (restoredLegacy) return legacyKey1069        } catch (_: Exception) {1070            // A failed migration must not claim a legacy key unless the exact1071            // legacy record was durably restored and observed.1072        }1073        if (!restoredLegacy) runCatching { store.loadDecoySlot() == legacy }1074        migratedKey?.let(VaultCrypto::zero)1075        return if (restoredLegacy) legacyKey else null1076    }10771078    /** Adopt a derived [DuressUnlock] as a live decoy session (edits persist to slot B only). */1079    suspend fun commitDuressUnlock(unlock: DuressUnlock): UnlockResult = mutex.withLock {1080        val key = unlock.takeKey() ?: return@withLock UnlockResult.Error("unlock_token_consumed")1081        if (currentEpoch() != unlock.epoch) {1082            VaultCrypto.zero(key)1083            return@withLock UnlockResult.Error("stale_unlock")1084        }1085        return try {1086            val adopted = mutateIfCurrentEpoch(unlock.epoch) {1087                derivedKey = key1088                decoyMode = true1089                entryList = unlock.payload.entries.toMutableList()1090                authenticatedDuressConfigured = false1091                _duressConfigured.value = false1092                recoveryWordHash = unlock.payload.recoveryWordHash1093                recoveryWordsSet = unlock.payload.recoveryWordsSet1094                sessionDataAvailable = true1095                rootKey = if (unlock.payload.rootKeyB64.isNotBlank()) unb64(unlock.payload.rootKeyB64)1096                          else VaultCrypto.generateRootKey()1097                // The decoy session gets its own defaults, never the real vault's1098                // record. Settings are shared, plaintext state loaded at every1099                // session start, so reading it here both told the coercer the real1100                // configuration and let updateSettings below persist changes into1101                // the record the real vault loads next (PB-26-120).1102                _settings.value = VaultSettings()1103                publish()1104                _isUnlocked.value = true1105                sessionEpoch = nextSessionEpoch(sessionEpoch)1106            }1107            if (adopted == null) {1108                VaultCrypto.zero(key)1109                UnlockResult.Error("stale_unlock")1110            } else {1111                UnlockResult.Success1112            }1113        } catch (e: Exception) {1114            // A payload/root/settings failure can occur after the candidate key1115            // has been assigned to derivedKey. Tear down only this epoch so a1116            // newer session is not disturbed, and scrub the token reference on1117            // every error path.1118            mutateIfCurrentEpoch(unlock.epoch) { clearSessionStateLocked() }1119            VaultCrypto.zero(key)1120            UnlockResult.Error(e.message ?: "decoy_unlock_failed")1121        }1122    }11231124    /** Zero a derived [DuressUnlock] that will not be adopted. */1125    fun discardDuressUnlock(unlock: DuressUnlock) = unlock.discard()11261127    /**1128     * Configure the duress vault (MF-6): seal a fresh, empty decoy payload under an1129     * Argon2id key derived from [duressPassphrase] (fresh salt) into slot B. The1130     * passphrase is never stored — only its ability to decrypt slot B proves it.1131     * Requires the real vault to be unlocked and not itself a decoy session.1132     */1133    suspend fun setDuressPassphrase(duressPassphrase: String): Boolean = mutex.withLock {1134        // H-03: read derivedKey/decoyMode atomically with any concurrent lock().1135        val expectedEpoch = mutateState {1136            if (derivedKey != null && !decoyMode) sessionEpoch else null1137        } ?: return false1138        // Reject a duress passphrase that also opens the real vault: it would make the1139        // lock screen ambiguous (both slots would decrypt for the same input).1140        tryUnlockSlotA(duressPassphrase)?.let { discardSlotAUnlock(it); return false }1141        var key: ByteArray? = null1142        var basePlaintext: ByteArray? = null1143        return try {1144            val salt = VaultCrypto.generateSalt()1145            key = VaultCrypto.deriveKey(duressPassphrase, salt)1146            // An empty decoy vault with its own fresh sync root key — nothing real leaks.1147            val decoyRoot = VaultCrypto.generateRootKey()1148            val decoyRootB64 = try { b64(decoyRoot) } finally { VaultCrypto.zero(decoyRoot) }1149            val decoyPayload = VaultPayload(entries = emptyList(), rootKeyB64 = decoyRootB64)1150            basePlaintext = VaultCodec.encode(decoyPayload)1151            // H-04: pad the duress plaintext to slot A's ciphertext length so the1152            // duress blob matches slot A's blob on disk. VaultCodec.decode strips1153            // trailing NULs, so the extra padding survives encrypt but never1154            // reaches the JSON parser.1155            // This decoy plaintext length is frozen from here on: re-sealing it1156            // on later growth would need the duress passphrase, which is never1157            // retained. VaultStore compensates by re-padding the two slot1158            // RECORDS to the longer of the two on every write, so the frozen1159            // blob no longer shows up as a length difference at rest.1160            val slotA = store.loadSlotA()1161            val targetSize = slotA?.let(::matchingCiphertextLength) ?: 01162            val plaintext = if (targetSize > basePlaintext!!.size) basePlaintext!!.copyOf(targetSize) else basePlaintext!!1163            val blob = try {1164                b64(VaultCrypto.encrypt(plaintext, key!!, VaultCrypto.AAD_SLOT_B))1165            } finally {1166                VaultCrypto.zero(plaintext)1167                // Padding creates a second array; scrub the original encoded1168                // payload too rather than dropping its last reference untouched.1169                if (plaintext !== basePlaintext) basePlaintext?.let(VaultCrypto::zero)1170                basePlaintext = null1171                key?.let(VaultCrypto::zero)1172                key = null1173            }1174            beforeDurableCommit()1175            val ok = withEpochCommit(expectedEpoch) {1176                store.writeDecoySlot(StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(salt), blob = blob))1177            } ?: false1178            if (!ok) return false1179            val marked = mutateIfCurrentEpoch(expectedEpoch) {1180                authenticatedDuressConfigured = true1181                _duressConfigured.value = true1182                true1183            } ?: false1184            if (!marked) return false1185            if (!runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }.getOrDefault(false)) {1186                mutateIfCurrentEpoch(expectedEpoch) {1187                    authenticatedDuressConfigured = false1188                    _duressConfigured.value = false1189                }1190                runCatching { writeFakeDuressSlot(store.loadSlotA()!!) }1191                return false1192            }1193            true1194        } catch (_: Exception) {1195            false1196        } finally {1197            // Cover failures before the encrypt block is entered (for example a1198            // codec/copy exception) as well as any early return after key derivation.1199            key?.let(VaultCrypto::zero)1200            basePlaintext?.let(VaultCrypto::zero)1201        }1202    }120312041205    /**1206     * Export the decoy slot as browser-shaped JSON for adoption snapshots.1207     *1208     * Returns the sealed slot as `{version, salt, nonce, ciphertext, tag}` all1209     * lowercase hex — identical to the browser's `duress_slot` wire format — so1210     * any receiver (browser or Android) can install it via the existing1211     * passthrough. Returns null when duress is not configured, no decoy exists,1212     * or any conversion failure occurs. Never decrypts.1213     */1214    suspend fun exportDuressSlotForAdoption(): String? = mutex.withLock {1215        if (!authenticatedDuressConfigured) return null1216        val slot = store.loadDecoySlot() ?: return null1217        return runCatching { androidDuressSlotToBrowserJson(slot) }.getOrNull()1218    }12191220    /**1221     * Convert an Android [StoredVault] decoy slot to browser-shaped JSON.1222     *1223     * Mirrors the inverse of [installAdoptedDuressSlot]: base64 salt/blob are1224     * split into lowercase hex fields matching [BrowserSlotA]. Intermediate1225     * byte arrays are zeroed in finally.1226     */1227    private fun androidDuressSlotToBrowserJson(slot: StoredVault): String {1228        // Build the wire JSON directly with JsonObject so `version: 1` is ALWAYS1229        // serialized — kotlinx-serialization's encodeDefaults = false would1230        // otherwise omit BrowserSlotA.version (its Kotlin default), and the1231        // browser's hasValidVaultSchema strictly requires `r.version === 1`,1232        // silently dropping the duress slot on Android→browser adoptions.1233        var salt: ByteArray? = null1234        var blob: ByteArray? = null1235        var nonce: ByteArray? = null1236        var ctAndTag: ByteArray? = null1237        var ct: ByteArray? = null1238        var tag: ByteArray? = null1239        try {1240            salt = unb64(slot.salt)1241            blob = unb64(slot.blob)1242            nonce = blob.copyOfRange(0, VaultCrypto.NONCE_SIZE)1243            ctAndTag = blob.copyOfRange(VaultCrypto.NONCE_SIZE, blob.size)1244            ct = ctAndTag.copyOfRange(0, ctAndTag.size - 16)1245            tag = ctAndTag.copyOfRange(ctAndTag.size - 16, ctAndTag.size)1246            val obj = JsonObject(mapOf(1247                "version" to JsonPrimitive(1),1248                "salt" to JsonPrimitive(salt.joinToString("") { "%02x".format(it) }),1249                "nonce" to JsonPrimitive(nonce.joinToString("") { "%02x".format(it) }),1250                "ciphertext" to JsonPrimitive(ct.joinToString("") { "%02x".format(it) }),1251                "tag" to JsonPrimitive(tag.joinToString("") { "%02x".format(it) }),1252            ))1253            return obj.toString()1254        } finally {1255            salt?.let(VaultCrypto::zero)1256            blob?.let(VaultCrypto::zero)1257            nonce?.let(VaultCrypto::zero)1258            ctAndTag?.let(VaultCrypto::zero)1259            ct?.let(VaultCrypto::zero)1260            tag?.let(VaultCrypto::zero)1261        }1262    }12631264    /**1265     * Install a browser-shaped duress slot received through adoption.1266     */1267    suspend fun installAdoptedDuressSlot(json: String): Boolean = mutex.withLock {1268        val b = BrowserSlot.parse(json) ?: return false1269        if (b.version != 1) return false1270        val expectedEpoch = currentEpoch()1271        var salt: ByteArray? = null1272        var nonce: ByteArray? = null1273        var ct: ByteArray? = null1274        var tag: ByteArray? = null1275        var blob: ByteArray? = null1276        try {1277            salt = unhex(b.salt)1278            nonce = unhex(b.nonce)1279            ct = unhex(b.ciphertext)1280            tag = unhex(b.tag)1281            blob = ByteArray(nonce.size + ct.size + tag.size).also {1282                System.arraycopy(nonce, 0, it, 0, nonce.size)1283                System.arraycopy(ct, 0, it, nonce.size, ct.size)1284                System.arraycopy(tag, 0, it, nonce.size + ct.size, tag.size)1285            }1286            val stored = StoredVault(version = LEGACY_ANDROID_SLOT_VERSION, salt = b64(salt), blob = b64(blob))1287            val priorA = store.loadSlotA() ?: return false1288            val priorB = store.loadSlotB()1289            val priorD = store.loadDecoySlot() ?: return false1290            beforeDurableCommit()1291            val committed = withEpochCommit(expectedEpoch) {1292                if (!store.writeDecoySlot(stored)) return@withEpochCommit false1293                authenticatedDuressConfigured = true1294                _duressConfigured.value = true1295                true1296            } ?: false1297            if (!committed) return false1298            if (runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }.getOrDefault(false)) {1299                true1300            } else {1301                mutateIfCurrentEpoch(expectedEpoch) {1302                    authenticatedDuressConfigured = false1303                    _duressConfigured.value = false1304                }1305                withEpochCommit(expectedEpoch) { store.restoreVaultTriad(priorA, priorB, priorD) }1306                false1307            }1308        } catch (_: Exception) {1309            false1310        } finally {1311            salt?.let(VaultCrypto::zero)1312            nonce?.let(VaultCrypto::zero)1313            ct?.let(VaultCrypto::zero)1314            tag?.let(VaultCrypto::zero)1315            blob?.let(VaultCrypto::zero)1316        }1317    }13181319    /** Tear down the duress vault: drop slot B and the duress flag on the real payload. */1320    suspend fun clearDuress(): Boolean = mutex.withLock {1321        // H-04: presence-indistinguishable — replace the real decoy with a fake1322        // blob of slot A's size rather than removing the duress record. The1323        // record stays on disk at the same length, so an at-rest observer1324        // cannot tell "duress cleared" from "no duress ever configured".1325        val expectedEpoch = currentEpoch()1326        val replaced = withEpochCommit(expectedEpoch) {1327            store.loadSlotA()?.let { slotA -> runCatching { writeFakeDuressSlot(slotA) }.getOrDefault(false) }1328                ?: runCatching { store.clearDecoySlot(); true }.getOrDefault(false)1329        } ?: false1330        if (!replaced) return@withLock false1331        // H-03: stateLock-fence the derivedKey/decoyMode read AND the1332        // authenticatedDuressConfigured write so a concurrent lock() cannot land between them.1333        if (!isSessionEpochCurrent(expectedEpoch)) return false1334        val shouldClear = mutateIfCurrentEpoch(expectedEpoch) { derivedKey != null && !decoyMode } == true1335        if (shouldClear && mutateIfCurrentEpoch(expectedEpoch) {1336            authenticatedDuressConfigured = false1337            _duressConfigured.value = false1338        } != null) {1339            runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }1340        }1341        true1342    }13431344    /** True for the provider-specific exception used for a valid GCM blob/key mismatch. */1345    private fun isGcmAuthenticationFailure(error: Throwable): Boolean {1346        var current: Throwable? = error1347        while (current != null) {1348            if (current is javax.crypto.AEADBadTagException) return true1349            // Some Android providers expose a GCM tag failure as the parent1350            // BadPaddingException rather than the AEAD-specific subtype.  A1351            // short ciphertext is an IllegalBlockSizeException and therefore1352            // remains an internal/malformed-payload Error below.1353            if (current is javax.crypto.BadPaddingException) return true1354            current = current.cause1355        }1356        return false1357    }13581359    /** Unlock with an already-derived AES-256 key (biometric path). */1360    suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {1361        val expectedEpoch = currentEpoch()1362        val slotA = try {1363            store.loadSlotA()1364        } catch (_: Exception) {1365            return@withLock UnlockResult.Error("unlock_key_storage_failed")1366        } ?: return@withLock UnlockResult.Error("no_vault")1367        // Keep the caller-owned key separate from the staged session key. The1368        // biometric caller always zeroes its input in a finally block; adoption1369        // must therefore own a copy and use the same all-or-nothing path as a1370        // password unlock rather than publishing a partially decoded session.1371        var stagedKey: ByteArray? = key.copyOf()1372        return try {1373            val encrypted = try {1374                unb64(slotA.blob)1375            } catch (_: Exception) {1376                return@withLock UnlockResult.Error("invalid_vault_blob")1377            }1378            // A GCM record must include nonce + authentication tag.  Providers1379            // differ on whether a shorter record is reported as BadPadding or1380            // AEADBadTag; reject it before decrypt so malformed storage cannot be1381            // misreported as a user-entered wrong key.1382            if (encrypted.size < VaultCrypto.NONCE_SIZE + (VaultCrypto.TAG_LENGTH_BITS / 8)) {1383                return@withLock UnlockResult.Error("invalid_vault_blob")1384            }1385            val plaintext = try {1386                VaultCrypto.decrypt(encrypted, stagedKey!!, VaultCrypto.AAD_SLOT_A)1387            } catch (e: Exception) {1388                if (isGcmAuthenticationFailure(e)) {1389                    return@withLock UnlockResult.WrongPassword1390                }1391                return@withLock UnlockResult.Error("unlock_key_decrypt_failed")1392            }1393            val payload = try {1394                VaultCodec.decode(plaintext)1395            } catch (_: Exception) {1396                return@withLock UnlockResult.Error("invalid_vault_payload")1397            } finally {1398                VaultCrypto.zero(plaintext)1399            }1400            val candidate = stagedKey ?: return UnlockResult.Error("unlock_key_missing")1401            val result = adoptSlotA(candidate, payload, expectedEpoch)1402            if (result is UnlockResult.Success) { stagedKey = null; ensureRecoveryEscrow() }1403            result1404        } finally {1405            stagedKey?.let(VaultCrypto::zero)1406        }1407    }14081409    fun lock() {1410        // Never snapshot a mutation that has changed entryList but has not yet1411        // crossed its durable epoch fence. Successful writes refresh the spool1412        // before releasing this mutex; an in-flight writer therefore makes this1413        // lock skip the convenience refresh and fail closed to the prior cache.1414        if (mutex.tryLock()) {1415            try {1416                runCatching { LockedSyncSpoolHooks.refresh(this) }1417            } finally {1418                mutex.unlock()1419            }1420        }1421        // H-03: must observe derivedKey/entryList atomically with any in-flight1422        // suspend op (an addEntry mid-encrypt, an unlock adopting the payload,1423        // etc.). mutex cannot be acquired from this non-suspend caller; stateLock1424        // guards just the brief state reset. Advancing the epoch first invalidates1425        // every operation that captured this session before it reaches a later1426        // durable commit or publication.1427        stateLock.lock()1428        try {1429            sessionEpoch = nextSessionEpoch(sessionEpoch)1430            clearSessionStateLocked()1431            _uiGateLocked.value = false1432        } finally {1433            stateLock.unlock()1434        }1435    }14361437    /**1438     * Enter sync-retained background mode: the UI shows the lock screen but the1439     * vault stays fully unlocked in memory so [PeachSyncService] can complete1440     * sync sessions. Called from [PeachApplication.onStop] when background sync1441     * is enabled. A subsequent full [lock] (auto-lock timer, manual lock)1442     * supersedes this and zeroes everything.1443     */1444    fun lockUiGate() {1445        if (_isUnlocked.value) _uiGateLocked.value = true1446    }14471448    /** Dismiss the UI gate after the user authenticates on resume. */1449    fun clearUiGate() {1450        _uiGateLocked.value = false1451    }14521453    @Volatile private var suppressNextBackgroundLockUntil: Long = 0L14541455    // Test seam so the expiry branch is reachable from plain JUnit (SystemClock1456    // is a stub off-device).1457    @VisibleForTesting1458    internal var nowMs: () -> Long = { SystemClock.elapsedRealtime() }14591460    /**1461     * Call immediately before launching a system Activity (a SAF file1462     * picker/save dialog, a share sheet) that briefly takes the whole process1463     * out of the foreground as an expected part of an in-app flow — not a1464     * genuine user backgrounding. ProcessLifecycleOwner.onStop can't tell the1465     * two apart on its own (it fires for both), and without this, exporting or1466     * importing a file silently locked and wiped the vault mid-flow the moment1467     * the picker took over, before its result ever reached the app.1468     *1469     * The suppression auto-expires after [BACKGROUND_LOCK_SUPPRESSION_TIMEOUT_MS]1470     * (M-07); a never-consumed stale flag cannot suppress a later real lock.1471     */1472    fun expectTransientBackground() {1473        suppressNextBackgroundLockUntil = nowMs() + BACKGROUND_LOCK_SUPPRESSION_TIMEOUT_MS1474    }14751476    /**1477     * Consumed once by the next background-lock check; see [expectTransientBackground].1478     * Returns false (and clears the flag) if the suppression has expired or was1479     * never set — a genuine background event must always lock.1480     */1481    fun consumeTransientBackgroundSuppression(): Boolean {1482        val until = suppressNextBackgroundLockUntil1483        val active = until != 0L && nowMs() < until1484        suppressNextBackgroundLockUntil = 0L1485        return active1486    }14871488    // ---- Sync identity ----------------------------------------------------14891490    /**1491     * The vault's stable sync master key (a copy). Caller must zero it. Backs1492     * vault_id, the Noise static key, the Ed25519 manifest key, and per-entry1493     * envelope keys. Null when locked. See [VaultPayload.rootKeyB64].1494     */1495    /**1496     * HOLE 5 — the duress vault never syncs.1497     *1498     * [commitDuressUnlock] gives the decoy session a root key so its own codex1499     * and recovery paths work, which means (unlike the browser, where the decoy1500     * path simply has no root key) the sync surface has to refuse explicitly.1501     * Without this the decoy vault would present a second, different vault_id1502     * to a paired device, and a coerced user opening it would make sync visibly1503     * fail on their other devices — a duress indicator, which is the one thing1504     * a duress vault must never be.1505     */1506    // M-04: the "null when locked" half of the contract was documented but never1507    // enforced — a rootKey outlives _isUnlocked in the recovery half-unlock (see1508    // [unlockWithRecoveryWords], which installs a root key with no password key1509    // yet) and in a create that failed after staging. Sync must fail closed1510    // there, so the authoritative unlocked flag gates it, not just decoyMode.1511    internal data class SyncMasterKeySnapshot(val epoch: Long, val key: ByteArray)15121513    internal fun syncMasterKeySnapshot(): SyncMasterKeySnapshot? = mutateState {1514        if (decoyMode || !_isUnlocked.value) null1515        else rootKey?.copyOf()?.let { SyncMasterKeySnapshot(sessionEpoch, it) }1516    }15171518    internal fun isSessionEpochCurrent(epoch: Long): Boolean =1519        mutateState { sessionEpoch == epoch }15201521    internal fun unlockedSessionEpoch(): Long? = mutateState {1522        if (derivedKey != null && _isUnlocked.value) sessionEpoch else null1523    }15241525    fun syncMasterKey(): ByteArray? = syncMasterKeySnapshot()?.key15261527    /**1528     * The current session's root key, decoy included. For local-only uses that1529     * must behave identically in a decoy session — Codex backup and recovery1530     * words — because a feature that errors under duress is itself a duress1531     * tell. In a decoy session this is the DECOY's root key (see1532     * [commitDuressUnlock]), never the real vault's, so neither surface can1533     * leak the real vault. Anything that leaves the device must use1534     * [syncMasterKey] instead.1535     */1536    fun sessionRootKey(): ByteArray? = mutateState {1537        if (!sessionDataAvailable) null else rootKey?.copyOf()1538    }15391540    /** Stable per-vault id two paired devices must share to sync. Null when1541     *  locked, and never present for the decoy vault (see [syncMasterKey]). */1542    fun syncVaultId(): String? = mutateState {1543        if (decoyMode || !_isUnlocked.value) null1544        else rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }1545    }15461547    /**1548     * Browser parity (MV-8): rotate the sync identity by replacing the stable1549     * root key. Entries remain under the master-password key, while sync1550     * credentials, vault_id, and recovery words all change.1551     */1552    suspend fun rotateSyncIdentity(): Boolean = mutex.withLock {1553        val expectedEpoch = mutateState { if (derivedKey != null && !decoyMode) sessionEpoch else null }1554            ?: return false1555        installRootKey(generateRecoverableRootKey(), expectedEpoch)1556    }15571558    /**1559     * Join the vault behind [rootKeyHex]: adopt that vault's identity while1560     * keeping every local entry.1561     *1562     * Sync identity (vault id, signing keys) derives from the root key, and1563     * `sync-coordinator` refuses a `vault_id_mismatch`, so two independently1564     * created vaults can never reconcile. Taking the other side's root key is1565     * what makes them one vault; from the next sync on, both entry sets merge.1566     *1567     * Entries survive because they are sealed under the password-derived key,1568     * not the root key — the same property [rotateSyncIdentity] relies on.1569     *1570     * CONSEQUENCE, which the caller must have disclosed and had confirmed:1571     * this device's previous recovery words stop working for good, and its new1572     * words are the source vault's words, because words are a deterministic1573     * encoding of the root key.1574     */1575    suspend fun joinVault(rootKeyHex: String): AdoptVaultResult = mutex.withLock {1576        if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {1577            return AdoptVaultResult.Error("JOIN_INVALID_ROOT_KEY: expected 64 lowercase hex chars")1578        }1579        val expectedEpoch = mutateState {1580            when {1581                derivedKey == null -> null1582                decoyMode -> Long.MIN_VALUE1583                else -> sessionEpoch1584            }1585        }1586        if (expectedEpoch == null) return AdoptVaultResult.Error("vault_locked")1587        if (expectedEpoch == Long.MIN_VALUE) return AdoptVaultResult.Error("JOIN_DECOY_MODE")1588        if (!store.hasVault()) return AdoptVaultResult.Error("JOIN_NO_LOCAL_VAULT")15891590        val incoming = hexToRootKey(rootKeyHex)1591        if (incoming.size != VaultCrypto.KEY_SIZE) {1592            VaultCrypto.zero(incoming)1593            return AdoptVaultResult.Error("JOIN_INVALID_ROOT_KEY: expected 32 bytes")1594        }1595        // Refuse before committing rather than leave this device holding a vault1596        // whose recovery words cannot be typed back. generateRecoverableRootKey1597        // screens its own keys for this; a key arriving from a peer has not been.1598        val roundTrips = runCatching { wordsToRootKeyMaterial(rootKeyToWords(incoming)) }.isSuccess1599        if (!roundTrips) {1600            VaultCrypto.zero(incoming)1601            return AdoptVaultResult.Error("JOIN_UNRECOVERABLE_ROOT_KEY")1602        }16031604        val vaultId = com.peachpasswords.sync.computeVaultId(incoming)1605        return if (installRootKey(incoming, expectedEpoch)) {1606            AdoptVaultResult.Success(vaultId)1607        } else {1608            AdoptVaultResult.Error("JOIN_INSTALL_FAILED")1609        }1610    }16111612    /**1613     * The recovery words [rootKeyHex] will produce once joined, or null if it is1614     * not a usable root key. Lets the join flow show the user the words that are1615     * about to replace theirs *before* anything is committed.1616     */1617    fun previewRecoveryWords(rootKeyHex: String): List<String>? {1618        if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) return null1619        val bytes = hexToRootKey(rootKeyHex)1620        return try {1621            val words = rootKeyToWords(bytes)1622            if (runCatching { wordsToRootKeyMaterial(words) }.isSuccess) words else null1623        } catch (_: Exception) {1624            null1625        } finally {1626            VaultCrypto.zero(bytes)1627        }1628    }16291630    /**1631     * Swap the vault's root key, keeping every entry, and re-escrow under the1632     * words the new key encodes. Takes ownership of [nextRootKey]. Caller holds1633     * [mutex].1634     */1635    private suspend fun installRootKey(nextRootKey: ByteArray, expectedEpoch: Long): Boolean {1636        // H-03: snapshot the live fields under stateLock so the success and the1637        // rollback paths both see consistent prior/new state. Writing the new1638        // rootKey/recovery fields is inside its own mutateState at the end.1639        // H-03 (P1-3 codex): the snapshot must COPY the live key/rootKey arrays1640        // — holding live references would let a zero-on-failure operation also1641        // wipe the session's still-live key arrays.1642        data class Snapshot(1643            val key: ByteArray,1644            val priorRootKey: ByteArray,1645            val priorRecoveryHash: String?,1646            val priorRecoverySet: Boolean,1647        )1648        val snap = mutateIfCurrentEpoch(expectedEpoch) {1649            val k = derivedKey ?: return@mutateIfCurrentEpoch null1650            if (decoyMode) return@mutateIfCurrentEpoch null1651            val priorRoot = rootKey ?: return@mutateIfCurrentEpoch null1652            Snapshot(k.copyOf(), priorRoot.copyOf(), recoveryWordHash, recoveryWordsSet)1653        } ?: run {1654            VaultCrypto.zero(nextRootKey)1655            return false1656        }1657        val priorSlot = store.loadSlotA() ?: run {1658            VaultCrypto.zero(snap.key)1659            VaultCrypto.zero(snap.priorRootKey)1660            VaultCrypto.zero(nextRootKey)1661            return false1662        }1663        val nextWords = rootKeyToWords(nextRootKey)16641665        return try {1666            beforeDurableCommit()1667            if (!takeVaultSnapshot("local_save", expectedEpoch)) throw IllegalStateException("snapshot_failed")1668            if (mutateIfCurrentEpoch(expectedEpoch) {1669                rootKey = nextRootKey1670                recoveryWordHash = recoveryWordsHash(nextWords)1671                recoveryWordsSet = false1672            } == null) throw IllegalStateException("stale_root_rotation")16731674            val nextRecoveryEscrow = buildRecoveryEscrow(nextWords)1675                ?: throw IllegalStateException("recovery_escrow_failed")1676            val nextRootKeyEscrow = buildRootKeyEscrow(nextWords)1677                ?: throw IllegalStateException("root_escrow_failed")1678            val plaintext = VaultCodec.encode(currentPayload())1679            val blob = try {1680                b64(VaultCrypto.encrypt(plaintext, snap.key, VaultCrypto.AAD_SLOT_A))1681            } finally {1682                VaultCrypto.zero(plaintext)1683            }1684            val nextSlot = priorSlot.copy(1685                blob = blob,1686                recoveryEscrow = nextRecoveryEscrow,1687                rootKeyEscrow = nextRootKeyEscrow,1688            )1689            val committed = withEpochCommit(expectedEpoch) {1690                if (!store.writeSlotA(nextSlot)) return@withEpochCommit false1691                try {1692                    if (!writeMatchingNoiseSlotB(nextSlot)) throw IllegalStateException("noise_slot_b_commit_failed")1693                    // H-04: a root-key rotation re-seals slot A, so the duress slot1694                    // (real or fake) must be re-padded to the new ciphertext length.1695                    if (!writeCompanionDuressSlot(nextSlot)) throw IllegalStateException("duress_slot_commit_failed")1696                    store.stampLocalMutation()1697                } catch (_: Exception) {1698                    store.writeSlotA(priorSlot)1699                    return@withEpochCommit false1700                }1701                true1702            } ?: false1703            if (!committed) throw IllegalStateException("storage_write_failed")1704            mutateIfCurrentEpoch(expectedEpoch) { publish() }1705            true1706        } catch (_: Exception) {1707            val restored = mutateIfCurrentEpoch(expectedEpoch) {1708                rootKey?.let(VaultCrypto::zero)1709                rootKey = snap.priorRootKey.copyOf()1710                recoveryWordHash = snap.priorRecoveryHash1711                recoveryWordsSet = snap.priorRecoverySet1712            }1713            if (restored != null) {1714                withEpochCommit(expectedEpoch) { store.writeSlotA(priorSlot) }1715            }1716            false1717        } finally {1718            VaultCrypto.zero(snap.key)1719            VaultCrypto.zero(snap.priorRootKey)1720            // On success nextRootKey is owned by rootKey. On every other path1721            // it is not, including a stale epoch after lock(); scrub it while1722            // the local reference is still available.1723            val stillOwnedBySession = mutateState {1724                sessionEpoch == expectedEpoch && rootKey === nextRootKey1725            }1726            if (!stillOwnedBySession) VaultCrypto.zero(nextRootKey)1727        }1728    }17291730    /**1731     * A copy of the live Argon2id-derived vault key, for biometric escrow only1732     * (wrapped under a hardware KeyStore key on biometric enable). Null when1733     * locked. Caller must [VaultCrypto.zero] it after use.1734     */1735    fun currentVaultKey(): ByteArray? = mutateState {1736        if (!isFullyUnlockedLocked()) null else derivedKey?.copyOf()1737    }17381739    suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {1740        val expectedEpoch = currentEpoch()1741        val slotA = store.loadSlotA() ?: return false1742        var oldKey: ByteArray? = null1743        var newKey: ByteArray? = null1744        var plaintext: ByteArray? = null1745        return try {1746            oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))1747            // Keep ownership of the decrypted vault plaintext until decoding has1748            // finished.  Passing decrypt() inline made the byte array unreachable1749            // before the finally block, so a successful or failed password change1750            // could leave the full plaintext resident in the heap.1751            val decrypted = VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A)1752            val payload = try {1753                VaultCodec.decode(decrypted)1754            } finally {1755                VaultCrypto.zero(decrypted)1756            }1757            val newSalt = VaultCrypto.generateSalt()1758            newKey = VaultCrypto.deriveKey(newPassword, newSalt)1759            // Re-seal the existing payload under the new key/salt.1760            plaintext = VaultCodec.encode(payload)1761            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))1762            // The escrow seals the slot-A PLAINTEXT, which a password change does not1763            // alter — only the wrapping changes — so carry it forward; rebuilding the1764            // StoredVault from scratch would silently drop it.1765            // Carry BOTH escrows forward unchanged: each seals plaintext/root-key1766            // content that a password change does not alter — only the slot-A1767            // wrapping rotates. The root-key escrow staying stable across password1768            // changes matches the browser (`vault.ts:363-364`).1769            val next = StoredVault(1770                version = slotA.version,1771                salt = b64(newSalt),1772                blob = blob,1773                recoveryEscrow = slotA.recoveryEscrow,1774                rootKeyEscrow = slotA.rootKeyEscrow,1775            )1776            // H-01: durably commit slot A + size-matched noise + version stamp1777            // before swapping the session key. A partial commit (new A on disk,1778            // old key in memory) would have the next save encrypt under the old1779            // key while matching disk on the new one.1780            val priorB = store.loadSlotB()1781            if (!commitVaultRotation(slotA, priorB, next, expectedEpoch)) return false1782            // H-03 (P1-2 codex): zero the OLD live key and assign the NEW one1783            // inside the same stateLock critical section, so a concurrent lock()1784            // can't observe the in-between (zeroed but not yet reassigned).1785            if (mutateIfCurrentEpoch(expectedEpoch) {1786                oldKey?.let(VaultCrypto::zero); oldKey = null1787                derivedKey?.let(VaultCrypto::zero)1788                derivedKey = newKey; newKey = null1789            } == null) return false1790            VaultKeyRotationHooks.onRotated()1791            true1792        } catch (_: Exception) {1793            false1794        } finally {1795            oldKey?.let(VaultCrypto::zero)1796            newKey?.let(VaultCrypto::zero)1797            plaintext?.let(VaultCrypto::zero)1798        }1799    }18001801    /**1802     * Irreversible wipe. Locks the session and clears every vault key. The Pro1803     * license is in a separate store and is preserved by construction.1804     */1805    suspend fun destroyVault() = mutex.withLock {1806        lock()1807        store.clearVault()1808        store.clearDecoySlot()1809    }18101811    // ---- Entry CRUD -------------------------------------------------------18121813    /**1814     * A Peach entry id is a UUID. Import and restore carry ids from foreign1815     * files (another Peach install, a vendor export, a hand-written backup) and1816     * no reader bounds them, so an id that is not a well-formed Peach id is1817     * replaced here rather than trusted.1818     *1819     * This is the naturalisation seam, and it is deliberately the only place it1820     * happens. Minting costs at most one duplicate if the same vault is later1821     * restored on a device that still holds the old id — visible and fixable.1822     * The sync path must NOT do this: adopting a peer's id verbatim is the only1823     * thing that keeps two devices agreeing on which entry they are discussing,1824     * so reminting there would fork identity on every device, on every round.1825     */1826    private val entryIdShape = Regex("[A-Za-z0-9_-]{1,64}")18271828    private fun String?.normalizedEntryId(): String =1829        if (this != null && entryIdShape.matches(this)) this else UUID.randomUUID().toString()18301831    suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {1832        val epoch = requireUnlocked()1833        val stamp = VaultCrypto.monotonicEntryTimestamp()1834        val now = System.currentTimeMillis()1835        val entry = withDerivedLast4(draft.copy(1836            id = draft.id.normalizedEntryId(),1837            createdAt = if (draft.createdAt > 0) draft.createdAt else now,1838            modifiedAt = stamp,1839            passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1840        ))1841        // H-03: capture rollback AND write entryList under stateLock so a1842        // concurrent lock() cannot zero the session between the read and the write.1843        val rollback = mutateCurrentSession(epoch) {1844            val r = entryList.toMutableList()1845            entryList.add(entry)1846            r1847        } ?: throw IllegalStateException("vault_locked")1848        persistOrRollback(rollback, epoch)1849        entry1850    }18511852    /**1853     * Insert many entries with a single encrypt-and-write at the end.1854     *1855     * Importing a real vault through [addEntry] was quadratic: every entry took1856     * the lock and re-encrypted and rewrote the whole vault, so an 806-entry1857     * restore did 806 full-vault writes and hung the app long enough to ANR.1858     * Rolls back to the pre-import list if the one write fails, matching1859     * [addEntry]'s all-or-nothing behaviour.1860     */1861    suspend fun addEntries(drafts: List<VaultEntry>): Int = mutex.withLock {1862        val epoch = requireUnlocked()1863        if (drafts.isEmpty()) return 01864        val now = System.currentTimeMillis()1865        val ready = drafts.map { draft ->1866            val stamp = VaultCrypto.monotonicEntryTimestamp()1867            withDerivedLast4(1868                draft.copy(1869                    id = draft.id.normalizedEntryId(),1870                    createdAt = if (draft.createdAt > 0) draft.createdAt else now,1871                    modifiedAt = stamp,1872                    passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1873                ),1874            )1875        }1876        // H-03: capture rollback AND append every entry under stateLock.1877        val rollback = mutateCurrentSession(epoch) {1878            val r = entryList.toMutableList()1879            entryList.addAll(ready)1880            r1881        } ?: throw IllegalStateException("vault_locked")1882        persistOrRollback(rollback, epoch)1883        return drafts.size1884    }18851886    /**1887     * M-01: replace the whole active set with [newEntries] in one write.1888     *1889     * Import's REPLACE mode used to soft-delete every current entry one durable1890     * write at a time (swallowing each failure) and then batch-add, so a failed1891     * add left the old entries stranded in Trash with nothing restored. Staging1892     * the entire next list in memory and committing it through1893     * [persistOrRollback] makes the swap all-or-nothing: on any failure the1894     * pre-import list — active entries included — is restored.1895     *1896     * Existing tombstones are preserved so paired devices still see the1897     * deletions they already know about.1898     */1899    suspend fun replaceEntries(newEntries: List<VaultEntry>): Int = mutex.withLock {1900        val epoch = requireUnlocked()1901        val now = System.currentTimeMillis()1902        val ready = newEntries.map { draft ->1903            val stamp = VaultCrypto.monotonicEntryTimestamp()1904            withDerivedLast4(1905                draft.copy(1906                    id = draft.id.normalizedEntryId(),1907                    createdAt = if (draft.createdAt > 0) draft.createdAt else now,1908                    modifiedAt = stamp,1909                    passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1910                ),1911            )1912        }1913        // M-03: an incoming entry that shares an id with an existing live entry1914        // is meant to *replace* it (PEACHSCRIPT REPLACE restore). Tombstoning1915        // the old one and then appending the new one would leave the list with1916        // two entries of the same id — the tombstoned one would be returned by1917        // updateEntry's indexOfFirst and trip entry_not_found. Drop the to-be-1918        // superseded entries from the tombstone set instead.1919        val incomingIds = ready.map { it.id }.toHashSet()1920        val rollback = mutateCurrentSession(epoch) {1921            val r = entryList.toMutableList()1922            val replaced = entryList.map { entry ->1923                if (entry.deletedAt != null) return@map entry1924                if (entry.id in incomingIds) return@map null1925                val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)1926                entry.copy(deletedAt = stamp, modifiedAt = stamp)1927            }.filterNotNull()1928            entryList = (replaced + ready).toMutableList()1929            r1930        } ?: throw IllegalStateException("vault_locked")1931        persistOrRollback(rollback, epoch)1932        return ready.size1933    }19341935    suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {1936        val epoch = requireUnlocked()1937        // H-03: read entryList, compute the patched entry, and write it under a1938        // single stateLock so a concurrent lock() cannot interleave between the1939        // lookup and the assignment (would IndexOutOfBoundsException on a shrunk1940        // list, or clobber the entry onto the wrong id after a relock).1941        val prepared = mutateCurrentSession(epoch) {1942            val idx = entryList.indexOfFirst { it.id == patch.id }1943            if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1944            val current = entryList[idx]1945            val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1946            // Only refresh passwordChangedAt when the password value actually changes.1947            val passwordChanged = patch.password != null && patch.password != current.password1948            // Capture the outgoing password (newest first) so the user can reveal/copy/1949            // restore it later. History is computed authoritatively from `current`, not1950            // the patch — updateEntry is a full-entry replace, so trusting patch's value1951            // would let a stale form clobber the real history. Record the age the old1952            // password carried, skip an empty prior, and skip an immediate exact dupe1953            // (e.g. restore-then-restore). Capped at PASSWORD_HISTORY_MAX.1954            val priorPassword = current.password1955            val shouldCapture = passwordChanged &&1956                !priorPassword.isNullOrEmpty() &&1957                current.passwordHistory?.firstOrNull()?.password != priorPassword1958            val nextHistory = if (shouldCapture) {1959                (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +1960                    (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)1961            } else {1962                current.passwordHistory1963            }1964            val updated = withDerivedLast4(patch.copy(1965                createdAt = current.createdAt,1966                modifiedAt = stamp,1967                passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,1968                passwordHistory = nextHistory,1969            ))1970            val rollback = entryList.toMutableList()1971            entryList[idx] = updated1972            updated to rollback1973        } ?: throw IllegalStateException("vault_locked")1974        val (updated, rollback) = prepared1975        persistOrRollback(rollback, epoch)1976        updated1977    }19781979    /** Soft-delete: writes a tombstone whose timestamp beats any in-flight edit. */1980    suspend fun deleteEntry(id: String) = mutex.withLock {1981        val epoch = requireUnlocked()1982        // H-03: lookup + tombstone write under stateLock so lock() cannot shrink1983        // the list out from under the indexOfFirst.1984        val rollback = mutateCurrentSession(epoch) {1985            val idx = entryList.indexOfFirst { it.id == id }1986            if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1987            val current = entryList[idx]1988            val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1989            val prior = entryList.toMutableList()1990            entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)1991            prior1992        } ?: throw IllegalStateException("vault_locked")1993        persistOrRollback(rollback, epoch)1994    }19951996    suspend fun restoreEntry(id: String) = mutex.withLock {1997        val epoch = requireUnlocked()1998        val rollback = mutateCurrentSession(epoch) {1999            val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }2000            if (idx == -1) throw IllegalStateException("deleted entry not found")2001            val current = entryList[idx]2002            val prior = entryList.toMutableList()2003            entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))2004            prior2005        } ?: throw IllegalStateException("vault_locked")2006        persistOrRollback(rollback, epoch)2007    }20082009    /** Permanent delete — no tombstone, no recovery. */2010    suspend fun purgeEntry(id: String) = mutex.withLock {2011        val epoch = requireUnlocked()2012        val rollback = mutateCurrentSession(epoch) {2013            val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }2014            if (idx == -1) throw IllegalStateException("deleted entry not found")2015            val prior = entryList.toMutableList()2016            entryList.removeAt(idx)2017            prior2018        } ?: throw IllegalStateException("vault_locked")2019        persistOrRollback(rollback, epoch)2020    }20212022    /** Permanently empty the trash — hard-deletes every soft-deleted entry. */2023    suspend fun purgeDeletedEntries(): Int = mutex.withLock {2024        val epoch = requireUnlocked()2025        // H-03: read+remove under stateLock so lock() can't reorder the remove.2026        data class R(val rollback: MutableList<VaultEntry>, val removed: Int)2027        val r = mutateCurrentSession(epoch) {2028            val rollback = entryList.toMutableList()2029            val before = entryList.size2030            entryList.removeAll { it.deletedAt != null }2031            R(rollback, before - entryList.size)2032        } ?: throw IllegalStateException("vault_locked")2033        if (r.removed > 0) persistOrRollback(r.rollback, epoch)2034        r.removed2035    }20362037    /** Browser parity: number of active entries that dedupe would move to trash. */2038    suspend fun countDuplicateEntries(): Int = mutex.withLock {2039        val epoch = requireUnlocked()2040        // countDuplicateEntriesLocked reads entryList; H-03 fences the read so2041        // lock() can't race the read with state writes.2042        mutateCurrentSession(epoch) { countDuplicateEntriesLocked() }2043            ?: throw IllegalStateException("vault_locked")2044    }20452046    /**2047     * Browser parity: soft-delete duplicate entries, keeping the most recently2048     * modified member of each group. Refuse in decoy mode so the duress vault is2049     * not reshaped into a forensically distinct state.2050     */2051    suspend fun deduplicateEntries(): Int = mutex.withLock {2052        val epoch = requireUnlocked()2053        data class R(val rollback: MutableList<VaultEntry>, val removed: Int)2054        val ready = mutateCurrentSession(epoch) {2055            if (decoyMode) throw IllegalStateException("deduplicate disabled in decoy mode")2056            val active = entryList.filter { it.deletedAt == null }2057            val keepIds = mutableSetOf<String>()2058            active.groupBy { it.duplicateKey() }.values.forEach { group ->2059                keepIds += group.maxBy { it.modifiedAt.takeIf { ts -> ts > 0 } ?: it.createdAt }.id2060            }2061            val rollback = entryList.toMutableList()2062            var removed = 02063            entryList = entryList.map { entry ->2064                if (entry.deletedAt == null && entry.id !in keepIds) {2065                    removed++2066                    val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)2067                    entry.copy(deletedAt = stamp, modifiedAt = stamp)2068                } else {2069                    entry2070                }2071            }.toMutableList()2072            R(rollback, removed)2073        } ?: throw IllegalStateException("vault_locked")2074        if (ready.removed > 0) persistOrRollback(ready.rollback, epoch)2075        ready.removed2076    }20772078    fun getEntries(): List<VaultEntry> = mutateState {2079        if (!sessionDataAvailable) emptyList() else entryList.filter { it.deletedAt == null }2080    }2081    fun getEntry(id: String): VaultEntry? = mutateState {2082        if (!sessionDataAvailable) null else entryList.firstOrNull { it.id == id && it.deletedAt == null }2083    }2084    fun getDeletedEntries(): List<VaultEntry> = mutateState {2085        if (!sessionDataAvailable) emptyList()2086        else entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }2087    }20882089    /** Active entries, optionally narrowed to those carrying [tagFilter]. */2090    fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {2091        return mutateState {2092            if (!sessionDataAvailable) return@mutateState emptyList()2093            val active = entryList.filter { it.deletedAt == null }2094            if (tagFilter == null) return@mutateState active2095            val needle = tagFilter.trim().lowercase()2096            active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }2097        }2098    }20992100    /** Sorted, de-duplicated tags across all active entries. */2101    fun getDistinctTags(): List<String> = mutateState {2102        if (!sessionDataAvailable) return@mutateState emptyList()2103        entryList.asSequence()2104            .filter { it.deletedAt == null }2105            .flatMap { it.tags?.asSequence() ?: emptySequence() }2106            .map { it.trim().lowercase() }2107            .filter { it.isNotEmpty() }2108            .distinct()2109            .sorted()2110            .toList()2111    }21122113    /**2114     * Distinct non-blank values for an identity field across active entries,2115     * most-frequently-used first. Supports "username" and "email"; unknown field2116     * names return an empty list. Values keep original casing (deduped2117     * case-insensitively) so a suggestion matches what the user typed.2118     */2119    fun getDistinctFieldValues(field: String): List<String> {2120        val select: (VaultEntry) -> String? = when (field) {2121            "username" -> { e -> e.username }2122            "email" -> { e -> e.email }2123            else -> return emptyList()2124        }2125        return mutateState {2126            if (!sessionDataAvailable) return@mutateState emptyList()2127            entryList.asSequence()2128                .filter { it.deletedAt == null }2129                .mapNotNull { select(it)?.trim() }2130                .filter { it.isNotEmpty() }2131                .groupingBy { it.lowercase() }2132                .aggregate { _, acc: Pair<String, Int>?, value, _ ->2133                    Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)2134                }2135                .values2136                .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })2137                .map { it.first }2138        }2139    }21402141    fun getTombstones(): List<Tombstone> = mutateState {2142        if (!sessionDataAvailable) emptyList()2143        else entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }2144    }2145    fun getVaultVersion(): Long = store.version()2146    fun getVaultHistory(): List<VaultSnapshot> = store.loadVaultHistory().snapshots21472148    suspend fun restoreVaultSnapshot(snapshotId: String): Boolean = mutex.withLock {2149        val expectedEpoch = currentEpoch()2150        val snapshot = store.loadVaultHistory().snapshots.firstOrNull { it.id == snapshotId } ?: return false2151        val restoredA = VaultCodec.decodeSlot(snapshot.vault_a) ?: return false2152        // H-04: snapshots now carry the duress slot too — restore preserves2153        // the at-rest triad (A/B/D), not just the A/B pair.2154        val restoredD: StoredVault? = snapshot.vault_d?.let(VaultCodec::decodeSlot)2155        val priorA = store.loadSlotA()2156        val priorB = store.loadSlotB()2157        val priorD = store.loadDecoySlot()2158        // H-02: capture pre-restore state as the recovery snapshot BEFORE any2159        // slot write — the old code took this snapshot, then stranded it on2160        // every failure, polluting history with a "restore" entry that never2161        // restored anything. The history below is rolled back together with2162        // the slots if the commit fails.2163        val priorHistory = store.loadVaultHistory()2164        // P1-4 (codex): the recovery snapshot must land before we commit the2165        // slot pair, otherwise a failed restore cannot be rolled back to the2166        // pre-restore history. If the history write itself fails, refuse to2167        // proceed — the alternative is a successful restore with no undo path.2168        beforeDurableCommit()2169        if (!takeVaultSnapshot("restore", expectedEpoch)) {2170            return false2171        }2172        // H-04: legacy snapshots without vault_d, or vault_d that fails to2173        // decode, fall back to a fake duress of slot A's size — presence-2174        // indistinguishable from any other freshly-restored vault.2175        val nextD: StoredVault = restoredD ?: run {2176            val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(restoredA) + 162177            val fakeBlob = ByteArray(target).also(rng::nextBytes)2178            val fakeSalt = VaultCrypto.generateSalt()2179            StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob))2180        }2181        if (!commitRestoreAtomic(restoredA, snapshot.vault_b, nextD, priorA, priorB, priorD, expectedEpoch)) {2182            withEpochCommit(expectedEpoch) { store.writeVaultHistory(priorHistory) }2183            return false2184        }2185        lock()2186        true2187    }21882189    /**2190     * H-02: atomic slot-A + slot-B + version stamp for a snapshot restore.2191     * Mirrors [commitVaultRotation] but writes the snapshot's EXACT slot B2192     * (a restore preserves the duress-shaped blob from history), not a fresh2193     * noise record. Any failure rolls back so the at-rest pair never holds a2194     * restored slot A against a pre-restore slot B. Caller is responsible for2195     * restoring the pre-snapshot history on a false return.2196     *2197     * H-04: duress slot is now part of the atomic triad — restored last so2198     * a duress-write failure rolls the A/B pair back too.2199     */2200    private fun commitRestoreAtomic(2201        nextA: StoredVault,2202        nextB: String,2203        nextD: StoredVault,2204        priorA: StoredVault?,2205        priorB: String?,2206        priorD: StoredVault?,2207        expectedEpoch: Long,2208    ): Boolean {2209        return withEpochCommit(expectedEpoch) {2210            if (!store.writeSlotA(nextA)) return@withEpochCommit false2211            // P1-2 (codex): writeSlotB's boolean AND any thrown exception from it2212            // must trigger rollback; previously a throw escaped without restoring2213            // the prior slot A and history.2214            try {2215                if (!store.writeSlotB(nextB)) throw java.io.IOException("slot_b_commit_failed")2216                // H-04: duress slot is part of the restore triad. Failures here2217                // roll A+B back so the at-rest state stays consistent.2218                if (!store.writeDecoySlot(nextD)) throw java.io.IOException("duress_slot_commit_failed")2219                store.stampLocalMutation()2220            } catch (_: Exception) {2221                reportRollbackFailures(rollbackRestoreLocked(priorA, priorB, priorD))2222                return@withEpochCommit false2223            }2224            true2225        } ?: false2226    }22272228    // ---- Sync apply (does NOT advance the version) ------------------------22292230    /**2231     * Apply remote entryList + tombstones with per-entry last-write-wins. Persists2232     * WITHOUT bumping the version counter, so a sync round cannot cascade into2233     * another outbound sync. Returns the number of locally-applied changes.2234     */2235    suspend fun applyMergedRemoteEntries(2236        remoteEntries: List<VaultEntry>,2237        remoteTombstones: List<Tombstone>,2238        expectedEpoch: Long? = null,2239    ): Int = mutex.withLock {2240        val epoch = expectedEpoch ?: requireUnlocked()2241        if (expectedEpoch != null && mutateIfCurrentEpoch(epoch) { true } != true) return@withLock 02242        // HV-1: clamp every peer-supplied timestamp to now + MAX_CLOCK_SKEW_MS2243        // BEFORE any comparison against a local one. Without this a peer can2244        // send a far-future modifiedAt and permanently pin its version of an2245        // entry against every honest local edit. The browser clamps in the2246        // matching place (vault.ts applyMergedRemoteEntries).2247        val mergeNow = System.currentTimeMillis()2248        val clamped = remoteEntries.mapNotNull { entry ->2249            // MN-3: drop peer entries that decode cleanly but are semantically2250            // hollow (blank title, credential-less login, husk passkey) and2251            // re-cap passwordHistory before anything merges into the vault.2252            SyncEntrySanitizer.sanitize(entry, PASSWORD_HISTORY_MAX)?.copy(2253                modifiedAt = SyncLimits.clampSyncTimestamp(entry.modifiedAt, mergeNow),2254                deletedAt = entry.deletedAt?.let {2255                    SyncLimits.clampSyncTimestamp(it, mergeNow)2256                },2257            )2258        }2259        val tombMap = remoteTombstones.associate {2260            it.id to SyncLimits.clampSyncTimestamp(it.deletedAt, mergeNow)2261        }2262        // H-03: build the new entryList under stateLock so a concurrent lock()2263        // cannot zero derivedKey/entryList between the byId read and the merge.2264        val applied = mutateCurrentSession(epoch) {2265            var n = 02266            val byId = entryList.associateBy { it.id }.toMutableMap()22672268            for (remote in clamped) {2269                val tomb = tombMap[remote.id]2270                if (tomb != null && tomb >= remote.modifiedAt) continue2271                val local = byId[remote.id]2272                if (local == null) {2273                    entryList.add(remote); byId[remote.id] = remote; n++2274                } else if (remote.modifiedAt > local.modifiedAt) {2275                    val i = entryList.indexOfFirst { it.id == local.id }2276                    if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; n++ }2277                }2278            }22792280            for ((id, deletedAt) in tombMap) {2281                val local = byId[id] ?: continue2282                if (local.deletedAt != null && local.deletedAt >= deletedAt) continue2283                if (deletedAt < local.modifiedAt) continue2284                val i = entryList.indexOfFirst { it.id == id }2285                if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); n++ }2286            }2287            n2288        } ?: return@withLock 022892290        if (applied > 0) {2291            persistSlotA(bumpVersion = false, snapshotReason = "sync_received", expectedEpoch = epoch)2292            mutateIfCurrentEpoch(epoch) { publish() }2293            runCatching { LockedSyncSpoolHooks.refresh(this) }2294        }2295        applied2296    }22972298    suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {2299        // A decoy session edits an in-memory copy only — discarded at lock.2300        // The real vault's settings record is not the duress session's to2301        // change, and letting it through weakened capture protection on a plain2302        // in-app surface (PB-26-120).2303        if (mutateState { decoyMode }) {2304            val decoyEpoch = requireUnlocked()2305            mutateCurrentSession(decoyEpoch) { _settings.value = settings }2306                ?: throw IllegalStateException("vault_locked")2307            return@withLock2308        }2309        // Require a fully live session before exposing a settings mutation.  The2310        // epoch is captured with the read so a lock/new-session boundary cannot2311        // let stale work publish into the replacement session.2312        val epoch = requireUnlocked()2313        val prior = mutateCurrentSession(epoch) {2314            val old = _settings.value2315            _settings.value = settings2316            old2317        } ?: throw IllegalStateException("vault_locked")23182319        val committed = try {2320            beforeDurableCommit()2321            // The durable write is inside the same epoch fence as the in-memory2322            // publication.  If lock() won first, this returns null and no stale2323            // settings reach storage or the public StateFlow.2324            withSessionEpochCommit(epoch) { store.writeSettings(settings) } == true2325        } catch (_: Exception) {2326            false2327        }2328        if (!committed) {2329            // A live-session storage failure rolls back the public value.  A2330            // stale epoch is already reset by lock()/the new session and must2331            // not be allowed to overwrite that safe state.2332            mutateIfCurrentEpoch(epoch) { _settings.value = prior }2333            throw IllegalStateException("settings_write_failed")2334        }2335    }23362337    // ---- Recovery words (vault metadata) ----------------------------------23382339    /** True once the user has confirmed their recovery words for this vault. */2340    fun isRecoveryWordsSet(): Boolean = mutateState { recoveryWordsSet }23412342    /**2343     * Record the BLAKE3 hash of the confirmed recovery words and mark them set.2344     * Persisted without bumping the version — recovery metadata is local-only and2345     * is not an entry mutation paired devices should sync against.2346     */2347    suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {2348        val epoch = requireUnlocked()2349        // H-03: hash + escrow-related state fields set under stateLock so a2350        // concurrent lock() cannot zero them in the middle of buildRecoveryEscrow.2351        // M-04: the flags have to be live before the escrows are built — both seal2352        // currentPayload() — so capture the prior pair and put it back if the write2353        // never lands. Otherwise the session reports words set against a slot A2354        // that still holds no escrow, and the recovery screen never offers a retry.2355        val prior = mutateCurrentSession(epoch) {2356            val priorPair = recoveryWordHash to recoveryWordsSet2357            recoveryWordHash = recoveryWordsHash(words)2358            recoveryWordsSet = true2359            priorPair2360        } ?: return@withLock false2361        // Seal TWO escrows (MF-1): the browser-byte-compatible root-key escrow2362        // (cross-platform recovery of the sync root key) and Android's whole-payload2363        // escrow (offline forgot-password restore of entries). Both derive their key2364        // from the same `wordsToRootKeyMaterial` IKM but use distinct AADs.2365        val persisted = runCatching {2366            persistSlotAWithEscrows(2367                buildRecoveryEscrow(words),2368                buildRootKeyEscrow(words),2369                expectedEpoch = epoch,2370            )2371        }.getOrDefault(false)2372        if (!persisted) {2373            mutateIfCurrentEpoch(epoch) {2374                recoveryWordHash = prior.first2375                recoveryWordsSet = prior.second2376            }2377        }2378        persisted2379    }23802381    /** Verify entered words against the stored recovery hash. */2382    fun verifyRecoveryWords(words: List<String>): Boolean {2383        return mutateState {2384            val stored = recoveryWordHash ?: return@mutateState false2385            MessageDigest.isEqual(2386                stored.toByteArray(Charsets.UTF_8),2387                recoveryWordsHash(words).toByteArray(Charsets.UTF_8),2388            )2389        }2390    }23912392    // ---- Recovery escrow (forgot-password) --------------------------------23932394    /** True at rest if this vault has any recovery escrow the recovery flow can use. */2395    fun hasRecoveryEscrow(): Boolean =2396        store.loadSlotA()?.let { it.recoveryEscrow != null || it.rootKeyEscrow != null } ?: false23972398    /**2399     * One-time self-heal: if this vault has a root key but no recovery escrow2400     * on disk (adopted vaults created before the escrow fix), build and persist2401     * it now. Called on every successful unlock; no-ops once the escrow exists.2402     */2403    private fun ensureRecoveryEscrow() {2404        if (hasRecoveryEscrow()) return2405        val rk = mutateState { rootKey?.copyOf() } ?: return2406        runCatching {2407            val words = rootKeyToWords(rk)2408            val escrow = buildRecoveryEscrow(words)2409            val rkEscrow = buildRootKeyEscrow(words)2410            if (escrow != null || rkEscrow != null) {2411                val prior = store.loadSlotA() ?: return@runCatching2412                store.writeSlotA(prior.copy(2413                    recoveryEscrow = escrow ?: prior.recoveryEscrow,2414                    rootKeyEscrow = rkEscrow ?: prior.rootKeyEscrow,2415                ))2416                mutateState {2417                    recoveryWordHash = recoveryWordsHash(words)2418                    recoveryWordsSet = true2419                }2420            }2421        }.also { VaultCrypto.zero(rk) }2422    }24232424    /**2425     * Attempt to unlock the vault using the 12 BIP39 recovery [words] instead of2426     * the master password. On success the slot-A plaintext sealed in the escrow is2427     * adopted as the live session (entries, rootKey, settings), but no Argon2id2428     * password key exists yet — call [resetPasswordWithRecoveryWords] next to set a2429     * new password and finish unlocking. Returns false when there is no escrow, the2430     * words fail the BIP39 checksum, or the words are wrong (GCM tag mismatch).2431     *2432     * Unlike the brief's `unlockWithRecoveryWords(): ByteArray?`, there is no2433     * detached vault key to return here — slot A is wrapped under the rotating2434     * Argon2id key — so this opens the escrowed payload directly.2435     */2436    suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {2437        val expectedEpoch = currentEpoch()2438        val slotA = store.loadSlotA() ?: return false2439        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false24402441        // Prefer Android's whole-payload escrow: a full offline restore of entries,2442        // root key, and settings. Present for Android-created vaults.2443        val fullEscrow = slotA.recoveryEscrow2444        if (fullEscrow != null) {2445            val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull()2446            if (material != null) {2447                var keyBytes: ByteArray? = null2448                var plaintext: ByteArray? = null2449                var candidateRoot: ByteArray? = null2450                var stateCommitStarted = false2451                try {2452                    keyBytes = deriveRecoveryKey(material, unb64(fullEscrow.salt)).encoded2453                    plaintext = VaultCrypto.decrypt(unb64(fullEscrow.blob), keyBytes!!, VaultCrypto.AAD_RECOVERY)2454                    val payload = VaultCodec.decode(plaintext)2455                    // Stage every fallible operation before touching live session2456                    // fields.  In particular, a settings/provider/decode failure2457                    // cannot leave entries, flags, or a root key resident while the2458                    // public session remains locked.2459                    val candidateSettings = store.loadSettings()2460                    candidateRoot = if (payload.rootKeyB64.isNotBlank()) {2461                        val decodedRoot = unb64(payload.rootKeyB64)2462                        if (decodedRoot.size != VaultCrypto.KEY_SIZE) {2463                            // Do not let a malformed authenticated payload abandon2464                            // this decoded root-key candidate before the outer2465                            // finally block owns it.2466                            VaultCrypto.zero(decodedRoot)2467                            throw IllegalArgumentException("invalid recovery root key")2468                        }2469                        decodedRoot2470                    } else {2471                        generateRecoverableRootKey()2472                    }2473                    stateCommitStarted = true2474                    val adopted = mutateIfCurrentEpoch(expectedEpoch) {2475                        clearSessionStateLocked()2476                        entryList = payload.entries.toMutableList()2477                        authenticatedDuressConfigured = payload.duressConfigured2478                        _duressConfigured.value = payload.duressConfigured2479                        recoveryWordHash = payload.recoveryWordHash2480                        recoveryWordsSet = payload.recoveryWordsSet2481                        rootKey = candidateRoot2482                        candidateRoot = null2483                        _settings.value = candidateSettings2484                        publish()2485                        // This is the authenticated recovery half-unlock boundary:2486                        // only set it after every candidate field is installed.2487                        sessionDataAvailable = true2488                        _isUnlocked.value = false2489                        true2490                    }2491                    if (adopted == true) return@withLock true2492                } catch (_: Exception) {2493                    // Wrong words, malformed payloads, provider failures, and2494                    // settings failures all fall through to the browser-compatible2495                    // root-key escrow.  If the state commit had started, invalidate2496                    // that epoch so no partial candidate survives.2497                    if (stateCommitStarted) {2498                        mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }2499                    }2500                } finally {2501                    plaintext?.let(VaultCrypto::zero)2502                    VaultCrypto.zero(material)2503                    keyBytes?.let(VaultCrypto::zero)2504                    candidateRoot?.let(VaultCrypto::zero)2505                }2506            }2507        }25082509        // Browser-format vault (only the root-key escrow): recover the 32-byte root2510        // key (sync identity) and reset the password; entries return via sync. This2511        // is exactly the browser's recovery semantics (`messages.ts:312-347`).2512        val rootEscrow = slotA.rootKeyEscrow2513        if (rootEscrow != null) {2514            var candidateRoot: ByteArray? = null2515            var stateCommitStarted = false2516            try {2517                candidateRoot = unsealRootKeyEscrow(words, rootEscrow) ?: return false2518                require(candidateRoot!!.size == VaultCrypto.KEY_SIZE) { "invalid recovery root key" }2519                val candidateSettings = store.loadSettings()2520                stateCommitStarted = true2521                val adopted = mutateIfCurrentEpoch(expectedEpoch) {2522                    clearSessionStateLocked()2523                    entryList = mutableListOf()2524                    authenticatedDuressConfigured = false2525                    _duressConfigured.value = false2526                    recoveryWordHash = recoveryWordsHash(words)2527                    recoveryWordsSet = true2528                    rootKey = candidateRoot2529                    candidateRoot = null2530                    _settings.value = candidateSettings2531                    publish()2532                    sessionDataAvailable = true2533                    _isUnlocked.value = false2534                    true2535                }2536                if (adopted == true) return@withLock true2537            } catch (_: Exception) {2538                if (stateCommitStarted) {2539                    mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }2540                }2541            } finally {2542                candidateRoot?.let(VaultCrypto::zero)2543            }2544        }2545        return false2546    }25472548    /**2549     * After [unlockWithRecoveryWords] succeeds, set a brand-new master password:2550     * re-seal slot A under a fresh Argon2id key, rotate the escrow under the same2551     * words, mark the session fully unlocked, and publish. Returns false if called2552     * without a prior successful recovery unlock (no in-memory root key).2553     *2554     * Folds the brief's `resetPasswordWithRecoveryKey(vaultKey, …)` + `unlock(…)`2555     * into one step, since there is no detached vault key here.2556     */2557    suspend fun resetPasswordWithRecoveryWords(2558        words: List<String>,2559        newPassword: String,2560    ): Boolean = mutex.withLock {2561        val expectedEpoch = currentEpoch()2562        // H-03: read rootKey + entryList under stateLock before computing the new2563        // plaintext, then re-publish + swap the derived key under stateLock so a2564        // concurrent lock() cannot straddle the two fences.2565        if (mutateIfCurrentEpoch(expectedEpoch) { rootKey != null } != true) return false2566        val priorA = store.loadSlotA() ?: return false2567        var newKey: ByteArray? = null2568        var plaintext: ByteArray? = null2569        return try {2570            val newSalt = VaultCrypto.generateSalt()2571            newKey = VaultCrypto.deriveKey(newPassword, newSalt)2572            plaintext = VaultCodec.encode(currentPayload())2573            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))2574            // Rebuild both escrows against the recovered session so their salts rotate2575            // with the password reset; fall back to the prior escrows if rebuild fails2576            // (e.g. a checksum-invalid phrase). The same 12 words keep working.2577            val valid = words.size == 12 && findInvalidWords(words).isEmpty()2578            val freshRecovery = if (valid) buildRecoveryEscrow(words) ?: priorA.recoveryEscrow else priorA.recoveryEscrow2579            val freshRootKey = if (valid) buildRootKeyEscrow(words) ?: priorA.rootKeyEscrow else priorA.rootKeyEscrow2580            val next = StoredVault(2581                version = priorA.version,2582                salt = b64(newSalt),2583                blob = blob,2584                recoveryEscrow = freshRecovery,2585                rootKeyEscrow = freshRootKey,2586            )2587            // H-01: see changePassword — both rotations share the same2588            // commit-or-keep-old-key contract so a partial write can't strand2589            // the session on a key that no longer matches disk.2590            val priorB = store.loadSlotB()2591            if (!commitVaultRotation(priorA, priorB, next, expectedEpoch)) return false2592            // H-03 (P1-2 codex): zero the old live key and install the new one2593            // inside the same stateLock critical section so a concurrent lock()2594            // can't observe the in-between.2595            if (mutateIfCurrentEpoch(expectedEpoch) {2596                derivedKey?.let(VaultCrypto::zero)2597                derivedKey = newKey; newKey = null2598                publish()2599                _isUnlocked.value = true2600            } == null) return false2601            VaultKeyRotationHooks.onRotated()2602            true2603        } catch (_: Exception) {2604            false2605        } finally {2606            newKey?.let(VaultCrypto::zero)2607            plaintext?.let(VaultCrypto::zero)2608        }2609    }26102611    /**2612     * Seal the current slot-A plaintext under a key derived from the 12 BIP392613     * recovery [words] (Android offline-restore escrow). IKM is the browser's2614     * `wordsToRootKeyMaterial` (MF-1), AAD is the string [VaultCrypto.AAD_RECOVERY].2615     * Returns null for a checksum-invalid phrase.2616     */2617    private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {2618        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null2619        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2620        var keyBytes: ByteArray? = null2621        var plaintext: ByteArray? = null2622        return try {2623            val salt = VaultCrypto.generateSalt()2624            val recoveryKey = deriveRecoveryKey(material, salt)2625            keyBytes = recoveryKey.encoded2626            plaintext = VaultCodec.encode(currentPayload())2627            val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)2628            RecoveryEscrow(salt = b64(salt), blob = b64(sealed))2629        } finally {2630            VaultCrypto.zero(material)2631            keyBytes?.let(VaultCrypto::zero)2632            plaintext?.let(VaultCrypto::zero)2633        }2634    }26352636    /**2637     * Seal ONLY the 32-byte root key under a key the recovery [words] derive,2638     * byte-for-byte the browser algorithm (MF-1): plaintext = lowercase ASCII hex2639     * of the root key, IKM = `wordsToRootKeyMaterial`, HKDF salt random-16,2640     * info `peach-recovery-v1`, AES-256-GCM AAD = 0x01. The same 12 words unwrap2641     * the same root key on the browser. Returns null with no in-memory root key or2642     * a checksum-invalid phrase.2643     */2644    private fun buildRootKeyEscrow(words: List<String>): RootKeyEscrow? {2645        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null2646        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2647        val rk = mutateState { rootKey?.copyOf() } ?: run {2648            VaultCrypto.zero(material)2649            return null2650        }2651        var keyBytes: ByteArray? = null2652        var plaintext: ByteArray? = null2653        return try {2654            val salt = VaultCrypto.generateSalt()2655            val recoveryKey = deriveRecoveryKey(material, salt)2656            keyBytes = recoveryKey.encoded2657            plaintext = rootKeyToHex(rk).toByteArray(Charsets.US_ASCII)2658            // combined = nonce(12) || ciphertext || tag(16)2659            val combined = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)2660            val nonce = combined.copyOfRange(0, VaultCrypto.NONCE_SIZE)2661            val ctTag = combined.copyOfRange(VaultCrypto.NONCE_SIZE, combined.size)2662            val tag = ctTag.copyOfRange(ctTag.size - 16, ctTag.size)2663            val ct = ctTag.copyOfRange(0, ctTag.size - 16)2664            RootKeyEscrow(salt = b64(salt), wrappedRootKey = b64(ct), nonce = b64(nonce), tag = b64(tag))2665        } finally {2666            VaultCrypto.zero(rk)2667            VaultCrypto.zero(material)2668            keyBytes?.let(VaultCrypto::zero)2669            plaintext?.let(VaultCrypto::zero)2670        }2671    }26722673    /** Unwrap the 32-byte root key from a browser-compatible [escrow]; null on wrong words. */2674    private fun unsealRootKeyEscrow(words: List<String>, escrow: RootKeyEscrow): ByteArray? {2675        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2676        var keyBytes: ByteArray? = null2677        var pt: ByteArray? = null2678        return try {2679            val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))2680            keyBytes = recoveryKey.encoded2681            val combined = unb64(escrow.nonce) + unb64(escrow.wrappedRootKey) + unb64(escrow.tag)2682            pt = VaultCrypto.decrypt(combined, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)2683            hexToRootKey(String(pt, Charsets.US_ASCII))2684        } catch (_: Exception) {2685            null2686        } finally {2687            // M-05: pt is the lowercase hex of the 32-byte root key — i.e. the2688            // IKM-equivalent of the vault identity. material+keyBytes were2689            // already zeroed; pt was leaking.2690            VaultCrypto.zero(material)2691            keyBytes?.let(VaultCrypto::zero)2692            pt?.let(VaultCrypto::zero)2693        }2694    }26952696    /**2697     * Re-seal slot A from the current in-memory state under the live key, carrying2698     * both [recoveryEscrow] and [rootKeyEscrow] onto the written record. Never runs2699     * in decoy mode (recovery is never offered for the decoy) and persists without2700     * a version bump, like the recovery-words metadata write it replaces.2701     */2702    private fun persistSlotAWithEscrows(2703        recoveryEscrow: RecoveryEscrow?,2704        rootKeyEscrow: RootKeyEscrow?,2705        expectedEpoch: Long? = null,2706    ): Boolean {2707        val snapshot = snapshotForPersist(expectedEpoch)2708            ?: throw IllegalStateException("vault_locked_or_stale")2709        if (snapshot.decoy) {2710            VaultCrypto.zero(snapshot.key)2711            return false2712        }2713        try {2714            val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")2715            val plaintext = VaultCodec.encode(snapshot.payload)2716            val blob = try {2717                b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))2718            } finally {2719                // The escrow path used to drop this reference before zeroing it;2720                // keep it live through the fill on both success and failure.2721                VaultCrypto.zero(plaintext)2722            }2723            val next = prior.copy(2724                blob = blob,2725                recoveryEscrow = recoveryEscrow ?: prior.recoveryEscrow,2726                rootKeyEscrow = rootKeyEscrow ?: prior.rootKeyEscrow,2727            )2728            beforeDurableCommit()2729            return withEpochCommit(snapshot.epoch) {2730                if (!store.writeSlotA(next)) return@withEpochCommit false2731                try {2732                    if (!writeMatchingNoiseSlotB(next)) throw java.io.IOException("noise_slot_b_commit_failed")2733                    // H-04: escrow rebuild changes slot A's plaintext size, so re-pad2734                    // the duress slot too. A real decoy is left alone; a fake is2735                    // re-sized to slot A's new ciphertext length.2736                    if (!writeCompanionDuressSlot(next)) throw java.io.IOException("duress_slot_commit_failed")2737                } catch (e: Exception) {2738                    store.writeSlotA(prior)2739                    throw e2740                }2741                true2742            } ?: false2743        } finally {2744            VaultCrypto.zero(snapshot.key)2745        }2746    }27472748    // ---- Internals --------------------------------------------------------27492750    private fun requireUnlocked(): Long {2751        // H-03: read derivedKey atomically with [lock]'s reset; without it,2752        // [lock] from a background lifecycle event can run between this read2753        // and the caller's first state touch.2754        stateLock.lock()2755        try {2756            if (derivedKey == null) throw IllegalStateException("vault_locked")2757            return sessionEpoch2758        } finally {2759            stateLock.unlock()2760        }2761    }27622763    /** A locked or half-adopted session must not expose secret-bearing fields. */2764    private fun isFullyUnlockedLocked(): Boolean = _isUnlocked.value && derivedKey != null27652766    private fun countDuplicateEntriesLocked(): Int {2767        val seen = mutableMapOf<String, VaultEntry>()2768        var duplicates = 02769        for (entry in entryList.filter { it.deletedAt == null }) {2770            val key = entry.duplicateKey()2771            val existing = seen[key]2772            if (existing == null) {2773                seen[key] = entry2774            } else {2775                duplicates++2776                val entryStamp = entry.modifiedAt.takeIf { it > 0 } ?: entry.createdAt2777                val existingStamp = existing.modifiedAt.takeIf { it > 0 } ?: existing.createdAt2778                if (entryStamp > existingStamp) seen[key] = entry2779            }2780        }2781        return duplicates2782    }27832784    private fun VaultEntry.duplicateKey(): String {2785        if (type == "note") return "note|${title.lowercase()}"2786        val passkeyData = passkey2787        if (passkeyData != null) {2788            return "passkey|${passkeyData.rpId.lowercase()}|${passkeyData.userName.lowercase()}"2789        }2790        return "login|${title.lowercase()}|${url.orEmpty().lowercase()}|${username.orEmpty().lowercase()}"2791    }27922793    /**2794     * Capture the current slot pair (and metadata) into the history list.2795     * Returns true when the history write landed, false when it didn't — callers2796     * that depend on the snapshot existing (notably [restoreVaultSnapshot])2797     * must check the result and roll back if it does not.2798     */2799    private fun takeVaultSnapshot(reason: String, expectedEpoch: Long? = null): Boolean {2800        val epoch = expectedEpoch ?: currentEpoch()2801        if (mutateIfCurrentEpoch(epoch) { true } != true) return false2802        val slotA = store.loadSlotA() ?: return false2803        val vaultA = VaultCodec.encodeSlot(slotA)2804        val vaultB = store.loadSlotB() ?: slotA.blob2805        // H-04: capture the duress slot so a restore preserves the at-rest2806        // triad, not just the A/B pair. The duress slot is always present2807        // (real or fake), so loadDecoySlot() returning null is a logic error2808        // — fall through to a fake duress in that case rather than silently2809        // losing the record from the snapshot.2810        val vaultD = store.loadDecoySlot()?.let(VaultCodec::encodeSlot) ?: run {2811            val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 162812            val fakeBlob = ByteArray(target).also(rng::nextBytes)2813            val fakeSalt = VaultCrypto.generateSalt()2814            VaultCodec.encodeSlot(StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob)))2815        }2816        val history = store.loadVaultHistory()2817        val latest = history.snapshots.firstOrNull()2818        if (latest?.vault_a == vaultA && latest.vault_b == vaultB && latest.vault_d == vaultD) return true2819        val entryCount = mutateIfCurrentEpoch(epoch) {2820            if (derivedKey != null && !decoyMode) {2821                bucketEntryCount(entryList.count { it.deletedAt == null })2822            } else {2823                null2824            }2825        } ?: return false2826        return try {2827            val snapshot = VaultSnapshot(2828                id = UUID.randomUUID().toString(),2829                savedAt = System.currentTimeMillis(),2830                reason = reason,2831                vault_a = vaultA,2832                vault_b = vaultB,2833                vault_d = vaultD,2834                entryCount = entryCount,2835            )2836            // P1-4 (codex): return the history-write boolean to callers so a2837            // false return no longer leaves the snapshot out of history while2838            // callers (notably restoreVaultSnapshot) proceed as if it succeeded.2839            withEpochCommit(epoch) {2840                store.writeVaultHistory(2841                    history.copy(snapshots = (listOf(snapshot) + history.snapshots).take(VAULT_HISTORY_MAX)),2842                )2843            } ?: false2844        } catch (_: Exception) {2845            false2846        }2847    }28482849    private fun bucketEntryCount(n: Int): Int = when {2850        n <= 0 -> 02851        n <= 10 -> 102852        n <= 25 -> 252853        n <= 50 -> 502854        n <= 100 -> 1002855        n <= 250 -> 2502856        n <= 500 -> 5002857        else -> ((n + 499) / 500) * 5002858    }28592860    /**2861     * Keep [VaultEntry.last4] in sync with the card number for card entries (MF-3),2862     * so it is stored explicitly and survives the sync wire format rather than being2863     * re-derived at render time. Non-card entries pass through unchanged.2864     *2865     * M-03: never overwrite a stored last4 with null. A card kept only as last42866     * (e.g. after a PeachScript import that had no PAN) must keep that value;2867     * re-deriving from an absent cardNumber would silently zero the field.2868     */2869    private fun withDerivedLast4(entry: VaultEntry): VaultEntry {2870        if (!entry.isCard()) return entry2871        val digits = entry.cardNumber?.filter { it.isDigit() } ?: ""2872        val derived = if (digits.length >= 4) digits.takeLast(4) else null2873        return entry.copy(last4 = derived ?: entry.last4)2874    }28752876    /**2877     * On unlock, hard-delete trashed entries older than the retention window.2878     * A null or non-positive [VaultSettings.trashRetentionDays] means "never"2879     * (the app's "Never" option), so nothing is purged. Persists without a2880     * version bump and without touching the publish state (caller publishes).2881     */2882    private fun autoPurgeExpiredTrash() {2883        val days = _settings.value.trashRetentionDays ?: return2884        if (days <= 0) return2885        val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L2886        val before = entryList.size2887        entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }2888        if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }2889    }28902891    /**2892     * Browser parity (P1): merge orphaned passkey-only entries into matching2893     * login entries that share the same registrable domain. A passkey-only2894     * entry has passkey fields (rpId + credentialId) but no password. Runs on2895     * unlock so consolidation is idempotent and cheap.2896     */2897    private fun consolidatePasskeyEntries() {2898        val passkeyOnly = entryList.filter { entry ->2899            entry.deletedAt == null &&2900                entry.isLogin() &&2901                entry.password.isNullOrBlank() &&2902                !entry.rpId.isNullOrBlank() &&2903                !entry.credentialId.isNullOrBlank()2904        }2905        if (passkeyOnly.isEmpty()) return2906        var changed = false2907        val now = System.currentTimeMillis()2908        for (pkEntry in passkeyOnly) {2909            val rpId = pkEntry.rpId ?: continue2910            val target = entryList.firstOrNull { candidate ->2911                candidate.deletedAt == null &&2912                    candidate.id != pkEntry.id &&2913                    candidate.isLogin() &&2914                    candidate.passkey == null &&2915                    candidate.credentialId.isNullOrBlank() &&2916                    !candidate.password.isNullOrBlank() &&2917                    listOfNotNull(candidate.url, *candidate.additionalUrls.orEmpty().toTypedArray())2918                        .any { com.peachpasswords.shared.extractDomain(it) == rpId }2919            } ?: continue2920            val idx = entryList.indexOfFirst { it.id == target.id }2921            if (idx < 0) continue2922            entryList[idx] = target.copy(2923                rpId = pkEntry.rpId,2924                rpName = pkEntry.rpName ?: target.rpName,2925                credentialId = pkEntry.credentialId,2926                publicKeyCose = pkEntry.publicKeyCose,2927                privateKeyJwk = pkEntry.privateKeyJwk,2928                userHandle = pkEntry.userHandle,2929                userName = pkEntry.userName,2930                userDisplayName = pkEntry.userDisplayName,2931                algorithm = pkEntry.algorithm,2932                signCount = pkEntry.signCount,2933                lastUsedAt = pkEntry.lastUsedAt,2934                modifiedAt = now,2935            )2936            // Soft-delete the orphan so it lands in trash (recoverable).2937            val pkIdx = entryList.indexOfFirst { it.id == pkEntry.id }2938            if (pkIdx >= 0) entryList[pkIdx] = pkEntry.copy(deletedAt = now)2939            changed = true2940        }2941        if (changed) runCatching { persistSlotA(bumpVersion = false) }2942    }29432944    /** The slot-A plaintext envelope for the current in-memory session. */2945    private fun currentPayload(): VaultPayload = mutateState { currentPayloadLocked() }29462947    private fun currentPayloadLocked(): VaultPayload =2948        VaultPayload(2949            entries = entryList.toList(),2950            duressConfigured = authenticatedDuressConfigured,2951            rootKeyB64 = rootKey?.let(::b64) ?: "",2952            recoveryWordHash = recoveryWordHash,2953            recoveryWordsSet = recoveryWordsSet,2954        )29552956    /**2957     * Adopt the payload's root key, lazily minting one for legacy payloads.2958     * A freshly-minted key is persisted WITHOUT bumping the version — adopting2959     * a root key is not a mutation paired devices should sync against.2960     */2961    private fun ensureRootKey(payload: VaultPayload) {2962        if (payload.rootKeyB64.isNotBlank()) {2963            rootKey = unb64(payload.rootKeyB64)2964            return2965        }2966        rootKey = generateRecoverableRootKey()2967        runCatching { persistSlotA(bumpVersion = false) }2968    }29692970    private fun publish() {2971        _entries.value = entryList.filter { it.deletedAt == null }2972    }29732974    private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {2975        var plaintext = VaultCodec.encode(currentPayload())2976        return try {2977            val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))2978            StoredVault(version = LEGACY_ANDROID_SLOT_VERSION, salt = b64(salt), blob = blob)2979        } finally {2980            // M-05: full vault plaintext is allocated here once per createVault.2981            // Zeroing in finally keeps the transient copy off the heap after the2982            // caller either succeeds or rolls back via lock().2983            VaultCrypto.zero(plaintext)2984        }2985    }29862987    private fun writeMatchingNoiseSlotB(slotA: StoredVault): Boolean {2988        // Size the noise so its base64 length matches slot A's blob (MN-1): with the2989        // plaintext now bucket-padded, an at-rest observer sees two equal-length slots2990        // and cannot pick the real one by size. b64(N bytes) ≈ N*4/3 chars.2991        val approxBytes = (slotA.blob.length * 3 / 4).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)2992        val noise = ByteArray(approxBytes).also(rng::nextBytes)2993        return store.writeSlotB(b64(noise))2994    }29952996    /** H-04: the ciphertext length slot A is using right now, so the duress2997     *  slot's blob can match it on disk. AES-GCM is a stream cipher — plaintext2998     *  length equals ciphertext length, so this also matches slot A's plaintext. */2999    private fun matchingCiphertextLength(slotA: StoredVault): Int =3000        (unb64(slotA.blob).size - VaultCrypto.NONCE_SIZE - 16).coerceAtLeast(0)30013002    /** H-04: a decoy-shaped StoredVault with a random blob of [matchingCiphertextLength]3003     *  bytes. Replaces a real decoy when the user clears duress, and is the3004     *  initial duress slot when no decoy is configured — so the record's3005     *  PRESENCE on disk is independent of authenticatedDuressConfigured, and its SIZE3006     *  matches slot A's blob length. */3007    private fun writeFakeDuressSlot(slotA: StoredVault): Boolean {3008        val blobSize = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 163009        val fakeBlob = ByteArray(blobSize).also(rng::nextBytes)3010        val fakeSalt = VaultCrypto.generateSalt()3011        return store.writeDecoySlot(StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob)))3012    }30133014    /** H-04: keep the duress record present on every persist. A real decoy is3015     *  left alone (it was padded at setDuressPassphrase time, and we don't have3016     *  the duress key here to re-seal it) — VaultStore re-pads both slot3017     *  records to the longer of the two on every write, which is what keeps the3018     *  pair the same length after slot A crosses a padding bucket3019     *  (PAI-2026-004). No real decoy → a fresh fake of slot A's size. */3020    private fun writeCompanionDuressSlot(slotA: StoredVault): Boolean {3021        val isConfigured = mutateState { authenticatedDuressConfigured }3022        return if (isConfigured) true else writeFakeDuressSlot(slotA)3023    }30243025    /**3026     * H-04: convert a browser-shaped duress slot to Android StoredVault3027     * without decrypting. The browser seals slot "b" under the duress3028     * passphrase; decrypting with the main password silently drops it.3029     * Concatenates nonce‖ciphertext‖tag into Android's blob and re-encodes3030     * the salt from hex to base64.3031     */3032    private fun browserDuressPassthrough(b: BrowserSlotA): StoredVault {3033        val salt = unhex(b.salt)3034        val nonce = unhex(b.nonce)3035        val ct = unhex(b.ciphertext)3036        val tag = unhex(b.tag)3037        val blob = ByteArray(nonce.size + ct.size + tag.size).also {3038            System.arraycopy(nonce, 0, it, 0, nonce.size)3039            System.arraycopy(ct, 0, it, nonce.size, ct.size)3040            System.arraycopy(tag, 0, it, nonce.size + ct.size, tag.size)3041        }3042        return StoredVault(version = LEGACY_ANDROID_SLOT_VERSION, salt = b64(salt), blob = b64(blob))3043    }3044    /** Re-seal slot A from the current in-memory state under the live key. */3045    private fun persistSlotA(3046        bumpVersion: Boolean,3047        snapshotReason: String? = "local_save",3048        expectedEpoch: Long? = null,3049    ): Boolean {3050        val snapshot = snapshotForPersist(expectedEpoch)3051            ?: throw IllegalStateException("vault_locked_or_stale")3052        return try {3053            // Decoy sessions persist to the decoy slot only — never touch the real slot A.3054            if (snapshot.decoy) {3055                val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")3056                val plaintext = VaultCodec.encode(snapshot.payload)3057                val blob = try {3058                    b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_B))3059                } finally {3060                    // Keep the last reference alive until the zero, including the3061                    // successful encrypt path (M-05).3062                    VaultCrypto.zero(plaintext)3063                }3064                beforeDurableCommit()3065                return withEpochCommit(snapshot.epoch) {3066                    store.writeDecoySlot(prior.copy(version = CURRENT_ANDROID_SLOT_VERSION, blob = blob))3067                } ?: false3068            }3069            val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")3070            // H-01: captured BEFORE the noise write so a stamp failure can restore3071            // the prior slot B alongside the prior slot A. Slot B is always3072            // overwritten by writeMatchingNoiseSlotB below, so a stamp failure3073            // leaves (new A, new B, old version) on disk — partial commit.3074            val priorB = store.loadSlotB()3075            beforeDurableCommit()3076            if (snapshotReason != null && !takeVaultSnapshot(snapshotReason, snapshot.epoch)) return false3077            val plaintext = VaultCodec.encode(snapshot.payload)3078            val blob = try {3079                b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))3080            } finally {3081                // Do not drop [plaintext] before fill(0): the serialized vault3082                // contains every entry password and is the primary M-05 target.3083                VaultCrypto.zero(plaintext)3084            }3085            val next = prior.copy(blob = blob)3086            // The epoch check and the entire A/B/D/version commit share one brief3087            // stateLock critical section. lock() either wins before this block or3088            // waits until the already-committed write is complete; it can never3089            // clear the session between the check and the durable write.3090            withEpochCommit(snapshot.epoch) {3091                if (!store.writeSlotA(next)) return@withEpochCommit false3092                try {3093                    if (!writeMatchingNoiseSlotB(next)) throw java.io.IOException("noise_slot_b_commit_failed")3094                    // H-04: duress slot stays present (real one untouched, fake one3095                    // re-padded to slot A's current size on every persist).3096                    if (!writeCompanionDuressSlot(next)) throw java.io.IOException("duress_slot_commit_failed")3097                    if (bumpVersion) store.stampLocalMutation()3098                } catch (e: Exception) {3099                    store.writeSlotA(prior)3100                    if (priorB != null) runCatching { store.writeSlotB(priorB) }3101                    throw e3102                }3103                true3104            } ?: false3105        } finally {3106            // Snapshot keys are copies, so lock() may zero the live key while this3107            // operation is still deriving/encrypting; always scrub our copy too.3108            VaultCrypto.zero(snapshot.key)3109        }3110    }31113112    /**3113     * H-01: durably commit a slot-A rotation by writing slot A, its3114     * size-matched noise slot B, and the local-mutation stamp in order. Any3115     * failure rolls the previously-committed steps back so the at-rest pair3116     * matches what was there before the call. Returns true only when every3117     * step succeeded — callers must NOT swap their session key on false.3118     */3119    private fun commitVaultRotation(3120        priorA: StoredVault,3121        priorB: String?,3122        nextA: StoredVault,3123        expectedEpoch: Long,3124    ): Boolean {3125        beforeDurableCommit()3126        return withEpochCommit(expectedEpoch) {3127            if (!store.writeSlotA(nextA)) return@withEpochCommit false3128            // P1-1 (codex): the noise write's boolean AND any thrown exception from3129            // it must trigger rollback; previously a throw from writeMatchingNoiseSlotB3130            // escaped the helper and left slot A committed.3131            try {3132                if (!writeMatchingNoiseSlotB(nextA)) throw java.io.IOException("noise_slot_b_commit_failed")3133                // H-04: a password rotation changes slot A's plaintext size (new3134                // salt → re-encrypted blob), so the duress slot must be re-padded3135                // alongside. writeCompanionDuressSlot leaves a real decoy alone3136                // and re-emits a fake of slot A's size otherwise.3137                if (!writeCompanionDuressSlot(nextA)) throw java.io.IOException("duress_slot_commit_failed")3138                store.stampLocalMutation()3139            } catch (_: Exception) {3140                rollbackRotation(priorA, priorB)3141                return@withEpochCommit false3142            }3143            true3144        } ?: false3145    }31463147    /**3148     * Best-effort undo of the writes [commitVaultRotation] may have committed.3149     * Each step runs independently — a failed rollback must not mask the3150     * original commit failure. Log is a throwing stub off-device.3151     */3152    private fun rollbackRotation(priorA: StoredVault, priorB: String?) {3153        val failures = mutableListOf<String>()3154        runCatching { if (!store.writeSlotA(priorA)) failures += "writeSlotA returned false" }3155            .onFailure { failures += "writeSlotA: $it" }3156        if (priorB != null) {3157            runCatching { if (!store.writeSlotB(priorB)) failures += "writeSlotB returned false" }3158                .onFailure { failures += "writeSlotB: $it" }3159        }3160        if (failures.isNotEmpty()) runCatching { Log.w("PeachVault", "vault rotation rollback incomplete: $failures") }3161    }31623163    /** Persist a local mutation, rolling the in-memory list back on failure. */3164    private fun persistOrRollback(rollback: MutableList<VaultEntry>, expectedEpoch: Long) {3165        try {3166            if (!persistSlotA(bumpVersion = true, expectedEpoch = expectedEpoch)) {3167                mutateIfCurrentEpoch(expectedEpoch) { entryList = rollback }3168                throw IllegalStateException("storage_write_failed")3169            }3170        } catch (e: Exception) {3171            mutateIfCurrentEpoch(expectedEpoch) { entryList = rollback }3172            throw e3173        }3174        // A lock can win in the small interval after the durable commit and3175        // before publication. The epoch check prevents pre-lock entries from3176        // being republished into a newly locked (or newly unlocked) session.3177        mutateIfCurrentEpoch(expectedEpoch) { publish() }3178        runCatching { LockedSyncSpoolHooks.refresh(this) }3179    }3180}